]> icculus.org git repositories - divverent/nexuiz.git/blob - data/qcsrc/server/cl_client.qc
accuracy stats spec fix
[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
421 #ifdef ALLOW_FORCEMODELS
422         if(other.cvar_cl_forceplayermodelsfromnexuiz)
423                 if not(self.modelindex_lod0_from_nexuiz)
424                         modelsource = other;
425         if(other.cvar_cl_forceplayermodels && sv_clforceplayermodels)
426                 modelsource = other;
427 #endif
428
429         self.skin = modelsource.skinindex;
430
431 #if 0
432         if(modelsource == self)
433                 self.skin = modelsource.skinindex;
434         else
435                 self.skin = mod(modelsource.skinindex, 3); // forbid the fbskins as forced skins
436 #endif
437
438         // self: me
439         // other: the player viewing me
440         float distance;
441         float f;
442
443         if(other.cvar_cl_playerdetailreduction <= 0)
444         {
445                 if(other.cvar_cl_playerdetailreduction <= -2)
446                         self.modelindex = modelsource.modelindex_lod2;
447                 else if(other.cvar_cl_playerdetailreduction <= -1)
448                         self.modelindex = modelsource.modelindex_lod1;
449                 else
450                         self.modelindex = modelsource.modelindex_lod0;
451         }
452         else
453         {
454                 distance = vlen(self.origin - other.origin);
455                 f = (distance + 100.0) * other.cvar_cl_playerdetailreduction;
456                 if(f > sv_loddistance2)
457                         self.modelindex = modelsource.modelindex_lod2;
458                 else if(f > sv_loddistance1)
459                         self.modelindex = modelsource.modelindex_lod1;
460                 else
461                         self.modelindex = modelsource.modelindex_lod0;
462         }
463
464 #ifdef PROFILING
465         float t1;
466         t1 = gettime(GETTIME_HIRES); // reference
467         client_cefc_accumulator += (t1 - t0);
468 #endif
469
470         return TRUE;
471 }
472
473 void UpdatePlayerSounds();
474 void setmodel_lod(entity e, string modelname)
475 {
476         string s;
477
478         if(sv_loddistance1)
479         {
480                 // FIXME: this only supports 3-letter extensions
481                 s = strcat(substring(modelname, 0, strlen(modelname)-4), "_lod1", substring(modelname, -4, 4));
482                 if(fexists(s))
483                 {
484                         setmodel(e, s); // players have high precision
485                         self.modelindex_lod1 = self.modelindex;
486                 }
487                 else
488                         self.modelindex_lod1 = -1;
489
490                 s = strcat(substring(modelname, 0, strlen(modelname)-4), "_lod2", substring(modelname, -4, 4));
491                 if(fexists(s))
492                 {
493                         setmodel(e, s); // players have high precision
494                         self.modelindex_lod2 = self.modelindex;
495                 }
496                 else
497                         self.modelindex_lod2 = -1;
498
499                 precache_model(modelname);
500                 setmodel(e, modelname); // players have high precision
501                 self.modelindex_lod0 = self.modelindex;
502
503                 if(self.modelindex_lod1 < 0)
504                         self.modelindex_lod1 = self.modelindex;
505
506                 if(self.modelindex_lod2 < 0)
507                         self.modelindex_lod2 = self.modelindex;
508         }
509         else
510         {
511                 precache_model(modelname);
512                 setmodel(e, modelname); // players have high precision
513                 self.modelindex_lod0 = self.modelindex;
514                         // save it for possible player model forcing
515         }
516
517         s = whichpack(self.model);
518         self.modelindex_lod0_from_nexuiz = ((s == "") || (substring(s, 0, 4) == "data"));
519
520         player_setupanimsformodel();
521         UpdatePlayerSounds();
522 }
523
524 /*
525 =============
526 PutObserverInServer
527
528 putting a client as observer in the server
529 =============
530 */
531 void FixPlayermodel();
532 void PutObserverInServer (void)
533 {
534         entity  spot;
535
536         race_PreSpawnObserver();
537
538         spot = SelectSpawnPoint (TRUE);
539         if(!spot)
540                 error("No spawnpoints for observers?!?\n");
541         RemoveGrapplingHook(self); // Wazat's Grappling Hook
542
543         if(clienttype(self) == CLIENTTYPE_REAL)
544         {
545                 msg_entity = self;
546                 WriteByte(MSG_ONE, SVC_SETVIEW);
547                 WriteEntity(MSG_ONE, self);
548         }
549
550         DropAllRunes(self);
551         kh_Key_DropAll(self, TRUE);
552
553         Portal_ClearAll(self);
554
555         if(self.flagcarried)
556                 DropFlag(self.flagcarried, world, world);
557         if(self.ballcarried)
558                 DropBall(self.ballcarried, self.origin + self.ballcarried.origin, self.velocity);
559
560         WaypointSprite_PlayerDead();
561         
562         if(self.killcount != -666)
563         {
564                 if(g_lms)
565                 {
566                         if(PlayerScore_Add(self, SP_LMS_RANK, 0) > 0)
567                                 bprint ("^4", self.netname, "^4 has no more lives left\n");
568                         else
569                                 bprint ("^4", self.netname, "^4 is spectating now\n"); // TODO turn this into a proper forfeit?
570                 }
571                 else
572                         bprint ("^4", self.netname, "^4 is spectating now\n");
573         }
574
575         PlayerScore_Clear(self); // clear scores when needed
576
577         self.spectatortime = time;
578         
579         self.classname = "observer";
580         self.iscreature = FALSE;
581         self.health = -666;
582         self.takedamage = DAMAGE_NO;
583         self.solid = SOLID_NOT;
584         self.movetype = MOVETYPE_NOCLIP;
585         self.flags = FL_CLIENT | FL_NOTARGET;
586         self.armorvalue = 666;
587         self.effects = 0;
588         self.armorvalue = cvar("g_balance_armor_start");
589         self.pauserotarmor_finished = 0;
590         self.pauserothealth_finished = 0;
591         self.pauseregen_finished = 0;
592         self.damageforcescale = 0;
593         self.death_time = 0;
594         self.dead_frame = 0;
595         self.alpha = 0;
596         self.scale = 0;
597         self.fade_time = 0;
598         self.pain_frame = 0;
599         self.pain_finished = 0;
600         self.strength_finished = 0;
601         self.invincible_finished = 0;
602         self.pushltime = 0;
603         self.think = SUB_Null;
604         self.nextthink = 0;
605         self.hook_time = 0;
606         self.runes = 0;
607         self.deadflag = DEAD_NO;
608         self.angles = spot.angles;
609         self.angles_z = 0;
610         self.fixangle = TRUE;
611         self.crouch = FALSE;
612
613         self.view_ofs = PL_VIEW_OFS;
614         setorigin (self, spot.origin);
615         setsize (self, '0 0 0', '0 0 0');
616         self.prevorigin = self.origin;
617         self.items = 0;
618         self.weapons = 0;
619         self.model = "";
620         FixPlayermodel();
621         self.model = "";
622         self.modelindex = 0;
623         self.weapon = 0;
624         self.weaponmodel = "";
625         self.weaponentity = world;
626         self.exteriorweaponentity = world;
627         self.killcount = -666;
628         self.velocity = '0 0 0';
629         self.avelocity = '0 0 0';
630         self.punchangle = '0 0 0';
631         self.punchvector = '0 0 0';
632         self.oldvelocity = self.velocity;
633
634         if(sv_loddistance1)
635                 SetCustomizer(self, Client_customizeentityforclient, Client_uncustomizeentityforclient);
636
637         self.team = -1;
638
639         if(g_arena)
640         {
641                 if(self.version_mismatch)
642                 {
643                         Spawnqueue_Unmark(self);
644                         Spawnqueue_Remove(self);
645                 }
646                 else
647                 {
648                         Spawnqueue_Insert(self);
649                 }
650         }
651         else if(g_lms)
652         {
653                 // Only if the player cannot play at all
654                 if(PlayerScore_Add(self, SP_LMS_RANK, 0) == 666)
655                         self.frags = FRAGS_SPECTATOR;
656                 else
657                         self.frags = FRAGS_LMS_LOSER;
658         }
659         else
660                 self.frags = FRAGS_SPECTATOR;
661 }
662
663 float RestrictSkin(float s)
664 {
665         if(!teams_matter)
666                 return s;
667         if(s == 6)
668                 return 6;
669         return mod(s, 3);
670 }
671
672 void FixPlayermodel()
673 {
674         local string defaultmodel;
675         local float defaultskin, chmdl, oldskin;
676         local vector m1, m2;
677
678         defaultmodel = "";
679
680         if(cvar("sv_defaultcharacter") == 1) {
681                 defaultskin = 0;
682
683                 if(teams_matter)
684                 {
685                         defaultmodel = cvar_string(strcat("sv_defaultplayermodel_", Team_ColorNameLowerCase(self.team)));
686                         defaultskin = cvar(strcat("sv_defaultplayerskin_", Team_ColorNameLowerCase(self.team)));
687                 }
688
689                 if(defaultmodel == "")
690                 {
691                         defaultmodel = cvar_string("sv_defaultplayermodel");
692                         defaultskin = cvar("sv_defaultplayerskin");
693                 }
694         }
695
696         if(self.modelindex == 0 && self.deadflag == DEAD_NO)
697         {
698                 if(self.model != "")
699                         bprint("\{1}^1Player ", self.netname, "^1 has a zero modelindex, trying to fix...\n");
700                 self.model = ""; // force the != checks to return true
701         }
702
703         if(defaultmodel != "")
704         {
705                 if (defaultmodel != self.model)
706                 {
707                         m1 = self.mins;
708                         m2 = self.maxs;
709                         setmodel_lod (self, defaultmodel);
710                         setsize (self, m1, m2);
711                         chmdl = TRUE;
712                 }
713
714                 oldskin = self.skinindex;
715                 self.skinindex = defaultskin;
716         } else {
717                 if (self.playermodel != self.model)
718                 {
719                         self.playermodel = CheckPlayerModel(self.playermodel);
720                         m1 = self.mins;
721                         m2 = self.maxs;
722                         setmodel_lod (self, self.playermodel);
723                         setsize (self, m1, m2);
724                         chmdl = TRUE;
725                 }
726
727                 oldskin = self.skinindex;
728                 self.skinindex = RestrictSkin(stof(self.playerskin));
729         }
730         
731         if(chmdl || oldskin != self.skinindex)
732                 self.species = player_getspecies(); // model or skin has changed
733
734         if(!teams_matter)
735                 if(strlen(cvar_string("sv_defaultplayercolors")))
736                         if(self.clientcolors != cvar("sv_defaultplayercolors"))
737                                 setcolor(self, cvar("sv_defaultplayercolors"));
738 }
739
740 void PlayerTouchExplode(entity p1, entity p2)
741 {
742         vector org;
743         org = (p1.origin + p2.origin) * 0.5;
744         org_z += (p1.mins_z + p2.mins_z) * 0.5;
745
746         te_explosion(org);
747
748         entity e;
749         e = spawn();
750         setorigin(e, org);
751         RadiusDamage(e, world, g_touchexplode_damage, g_touchexplode_edgedamage, g_touchexplode_radius, world, g_touchexplode_force, DEATH_TOUCHEXPLODE, world);
752         remove(e);
753 }
754
755 /*
756 =============
757 PutClientInServer
758
759 Called when a client spawns in the server
760 =============
761 */
762 //void() ctf_playerchanged;
763 void PutClientInServer (void)
764 {
765         if(clienttype(self) == CLIENTTYPE_BOT)
766         {
767                 self.classname = "player";
768         }
769         else if(clienttype(self) == CLIENTTYPE_REAL)
770         {
771                 msg_entity = self;
772                 WriteByte(MSG_ONE, SVC_SETVIEW);
773                 WriteEntity(MSG_ONE, self);
774         }
775
776         // player is dead and becomes observer
777         // FIXME fix LMS scoring for new system
778         if(g_lms)
779         {
780                 if(PlayerScore_Add(self, SP_LMS_RANK, 0) > 0)
781                         self.classname = "observer";
782         }
783
784         if(g_arena)
785         if(!self.spawned)
786                 self.classname = "observer";
787
788         if(self.classname == "player") {
789                 entity spot, oldself;
790
791                 if(self.team < 0)
792                         JoinBestTeam(self, FALSE, TRUE);
793
794                 race_PreSpawn();
795
796                 spot = SelectSpawnPoint (FALSE);
797                 if(!spot)
798                 {
799                         centerprint(self, "Sorry, no spawnpoints available!\nHope your team can fix it...");
800                         return; // spawn failed
801                 }
802
803                 RemoveGrapplingHook(self); // Wazat's Grappling Hook
804                 self.campingrifle_bulletcounter = cvar("g_balance_campingrifle_magazinecapacity");
805
806                 self.classname = "player";
807                 self.wasplayer = TRUE;
808                 self.iscreature = TRUE;
809                 self.movetype = MOVETYPE_WALK;
810                 self.solid = SOLID_SLIDEBOX;
811                 self.dphitcontentsmask = DPCONTENTS_SOLID | DPCONTENTS_BODY | DPCONTENTS_PLAYERCLIP;
812                 self.frags = FRAGS_PLAYER;
813                 if(independent_players)
814                         MAKE_INDEPENDENT_PLAYER(self);
815                 self.flags = FL_CLIENT;
816                 self.takedamage = DAMAGE_AIM;
817                 if(g_minstagib)
818                         self.effects = EF_FULLBRIGHT;
819                 else
820                         self.effects = 0;
821                 self.air_finished = time + 12;
822                 self.dmg = 2;
823
824                 if(inWarmupStage)
825                 {
826                         self.ammo_shells = warmup_start_ammo_shells;
827                         self.ammo_nails = warmup_start_ammo_nails;
828                         self.ammo_rockets = warmup_start_ammo_rockets;
829                         self.ammo_cells = warmup_start_ammo_cells;
830                         self.ammo_fuel = warmup_start_ammo_fuel;
831                         self.health = warmup_start_health;
832                         self.armorvalue = warmup_start_armorvalue;
833                         self.weapons = warmup_start_weapons;
834                 }
835                 else
836                 {
837                         self.ammo_shells = start_ammo_shells;
838                         self.ammo_nails = start_ammo_nails;
839                         self.ammo_rockets = start_ammo_rockets;
840                         self.ammo_cells = start_ammo_cells;
841                         self.ammo_fuel = start_ammo_fuel;
842                         self.health = start_health;
843                         self.armorvalue = start_armorvalue;
844                         self.weapons = start_weapons;
845                 }
846                 self.items = start_items;
847                 self.switchweapon = w_getbestweapon(self);
848                 self.cnt = self.switchweapon;
849                 self.weapon = 0;
850                 self.jump_interval = time;
851
852                 self.spawnshieldtime = time + cvar("g_spawnshieldtime");
853                 self.pauserotarmor_finished = time + cvar("g_balance_pause_armor_rot_spawn");
854                 self.pauserothealth_finished = time + cvar("g_balance_pause_health_rot_spawn");
855                 self.pauserotfuel_finished = time + cvar("g_balance_pause_fuel_rot_spawn");
856                 self.pauseregen_finished = time + cvar("g_balance_pause_health_regen_spawn");
857                 //extend the pause of rotting if client was reset at the beginning of the countdown
858                 if(!cvar("sv_ready_restart_after_countdown") && time < game_starttime) { // TODO why is this cvar NOTted?
859                         self.spawnshieldtime += game_starttime - time;
860                         self.pauserotarmor_finished += game_starttime - time;
861                         self.pauserothealth_finished += game_starttime - time;
862                         self.pauseregen_finished += game_starttime - time;
863                 }
864                 self.damageforcescale = 2;
865                 self.death_time = 0;
866                 self.dead_frame = 0;
867                 self.alpha = 0;
868                 self.scale = 0;
869                 self.fade_time = 0;
870                 self.pain_frame = 0;
871                 self.pain_finished = 0;
872                 self.strength_finished = 0;
873                 self.invincible_finished = 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         if(g_race_qualifying)
1130                 killtime = 0;
1131
1132         self.killindicator_teamchange = targetteam;
1133
1134         if(!self.killindicator)
1135         {
1136                 if(killtime <= 0 || !self.modelindex || self.deadflag != DEAD_NO)
1137                 {
1138                         ClientKill_Now();
1139                 }
1140                 else
1141                 {
1142                         self.killindicator = spawn();
1143                         self.killindicator.owner = self;
1144                         self.killindicator.scale = 0.5;
1145                         setattachment(self.killindicator, self, "");
1146                         setorigin(self.killindicator, '0 0 52');
1147                         self.killindicator.think = KillIndicator_Think;
1148                         self.killindicator.nextthink = time + (self.lip) * 0.05;
1149                         self.killindicator.cnt = ceil(killtime);
1150                         self.killindicator.count = bound(0, ceil(killtime), 10);
1151                         sprint(self, strcat("^1You'll be dead in ", ftos(self.killindicator.cnt), " seconds\n"));
1152
1153                         for(e = world; (e = find(e, classname, "body")) != world; )
1154                         {
1155                                 if(e.enemy != self)
1156                                         continue;
1157                                 e.killindicator = spawn();
1158                                 e.killindicator.owner = e;
1159                                 e.killindicator.scale = 0.5;
1160                                 setattachment(e.killindicator, e, "");
1161                                 setorigin(e.killindicator, '0 0 52');
1162                                 e.killindicator.think = KillIndicator_Think;
1163                                 e.killindicator.nextthink = time + (e.lip) * 0.05;
1164                                 e.killindicator.cnt = ceil(killtime);
1165                         }
1166                         self.lip = 0;
1167                 }
1168         }
1169         if(self.killindicator)
1170         {
1171                 if(targetteam)
1172                         self.killindicator.colormod = TeamColor(targetteam);
1173                 else
1174                         self.killindicator.colormod = '0 0 0';
1175         }
1176 }
1177
1178 void ClientKill (void)
1179 {
1180         ClientKill_TeamChange(0);
1181 }
1182
1183 void DoTeamChange(float destteam)
1184 {
1185         float t, c0;
1186         if(!teams_matter)
1187         {
1188                 if(destteam >= 0)
1189                         SetPlayerColors(self, destteam);
1190                 return;
1191         }
1192         if(self.classname == "player")
1193         if(destteam == -1)
1194         {
1195                 CheckAllowedTeams(self);
1196                 t = FindSmallestTeam(self, TRUE);
1197                 switch(self.team)
1198                 {
1199                         case COLOR_TEAM1: c0 = c1; break;
1200                         case COLOR_TEAM2: c0 = c2; break;
1201                         case COLOR_TEAM3: c0 = c3; break;
1202                         case COLOR_TEAM4: c0 = c4; break;
1203                         default:          c0 = 999;
1204                 }
1205                 switch(t)
1206                 {
1207                         case 1:
1208                                 if(c0 > c1)
1209                                         destteam = COLOR_TEAM1;
1210                                 break;
1211                         case 2:
1212                                 if(c0 > c2)
1213                                         destteam = COLOR_TEAM2;
1214                                 break;
1215                         case 3:
1216                                 if(c0 > c3)
1217                                         destteam = COLOR_TEAM3;
1218                                 break;
1219                         case 4:
1220                                 if(c0 > c4)
1221                                         destteam = COLOR_TEAM4;
1222                                 break;
1223                 }
1224                 if(destteam == -1)
1225                         return;
1226         }
1227         if(destteam == self.team && destteam >= 0 && !self.killindicator)
1228                 return;
1229         ClientKill_TeamChange(destteam);
1230 }
1231
1232 void FixClientCvars(entity e)
1233 {
1234         // send prediction settings to the client
1235         stuffcmd(e, "\nin_bindmap 0 0\n");
1236         /*
1237          * we no longer need to stuff this. Remove this comment block if you feel 
1238          * 2.3 and higher (or was it 2.2.3?) don't need these any more
1239         stuffcmd(e, strcat("cl_gravity ", ftos(cvar("sv_gravity")), "\n"));
1240         stuffcmd(e, strcat("cl_movement_accelerate ", ftos(cvar("sv_accelerate")), "\n"));
1241         stuffcmd(e, strcat("cl_movement_friction ", ftos(cvar("sv_friction")), "\n"));
1242         stuffcmd(e, strcat("cl_movement_maxspeed ", ftos(cvar("sv_maxspeed")), "\n"));
1243         stuffcmd(e, strcat("cl_movement_airaccelerate ", ftos(cvar("sv_airaccelerate")), "\n"));
1244         stuffcmd(e, strcat("cl_movement_maxairspeed ", ftos(cvar("sv_maxairspeed")), "\n"));
1245         stuffcmd(e, strcat("cl_movement_stopspeed ", ftos(cvar("sv_stopspeed")), "\n"));
1246         stuffcmd(e, strcat("cl_movement_jumpvelocity ", ftos(cvar("sv_jumpvelocity")), "\n"));
1247         stuffcmd(e, strcat("cl_movement_stepheight ", ftos(cvar("sv_stepheight")), "\n"));
1248         stuffcmd(e, strcat("set cl_movement_friction_on_land ", ftos(cvar("sv_friction_on_land")), "\n"));
1249         stuffcmd(e, strcat("set cl_movement_airaccel_qw ", ftos(cvar("sv_airaccel_qw")), "\n"));
1250         stuffcmd(e, strcat("set cl_movement_airaccel_sideways_friction ", ftos(cvar("sv_airaccel_sideways_friction")), "\n"));
1251         stuffcmd(e, "cl_movement_edgefriction 1\n");
1252          */
1253 }
1254
1255 /*
1256 =============
1257 ClientConnect
1258
1259 Called when a client connects to the server
1260 =============
1261 */
1262 //void ctf_clientconnect();
1263 string ColoredTeamName(float t);
1264 void DecodeLevelParms (void);
1265 //void dom_player_join_team(entity pl);
1266 void ClientConnect (void)
1267 {
1268         local string s;
1269         float t;
1270
1271         if(self.flags & FL_CLIENT)
1272         {
1273                 print("Warning: ClientConnect, but already connected!\n");
1274                 return;
1275         }
1276
1277         if(Ban_MaybeEnforceBan(self))
1278                 return;
1279
1280         DecodeLevelParms();
1281
1282         self.classname = "player_joining";
1283
1284         self.flags = FL_CLIENT;
1285         self.version_nagtime = time + 10 + random() * 10;
1286
1287         if(player_count<0)
1288         {
1289                 dprint("BUG player count is lower than zero, this cannot happen!\n");
1290                 player_count = 0;
1291         }
1292
1293         PlayerScore_Attach(self);
1294         ClientData_Attach();
1295
1296         bot_clientconnect();
1297
1298         race_PreSpawnObserver();
1299
1300         //if(g_domination)
1301         //      dom_player_join_team(self);
1302
1303         JoinBestTeam(self, FALSE, FALSE); // if the team number is valid, keep it
1304
1305         if((cvar("sv_spectate") == 1 && !g_lms) || cvar("g_campaign")) {
1306                 self.classname = "observer";
1307         } else {
1308                 if(teams_matter)
1309                 {
1310                         if(cvar("g_balance_teams") || cvar("g_balance_teams_force"))
1311                         {
1312                                 self.classname = "player";
1313                                 campaign_bots_may_start = 1;
1314                         }
1315                         else
1316                         {
1317                                 self.classname = "observer"; // do it anyway
1318                         }
1319                 }
1320                 else
1321                 {
1322                         self.classname = "player";
1323                         campaign_bots_may_start = 1;
1324                 }
1325         }
1326
1327         self.playerid = (playerid_last = playerid_last + 1);
1328         if(cvar("sv_eventlog"))
1329         {
1330                 if(clienttype(self) == CLIENTTYPE_REAL)
1331                         GameLogEcho(strcat(":join:", ftos(self.playerid), ":", ftos(num_for_edict(self)), ":", self.netaddress, ":", self.netname));
1332                 else
1333                         GameLogEcho(strcat(":join:", ftos(self.playerid), ":", ftos(num_for_edict(self)), ":bot:", self.netname));
1334                 s = strcat(":team:", ftos(self.playerid), ":");
1335                 s = strcat(s, ftos(self.team));
1336                 GameLogEcho(s);
1337         }
1338         self.netname_previous = strzone(self.netname);
1339
1340         //stuffcmd(self, "set tmpviewsize $viewsize \n");
1341
1342         bprint ("^4",self.netname);
1343         bprint ("^4 connected");
1344
1345         if(g_domination || g_ctf)
1346         {
1347                 bprint(" and joined the ");
1348                 bprint(ColoredTeamName(self.team));
1349         }
1350
1351         bprint("\n");
1352
1353         self.welcomemessage_time = 0;
1354
1355         stuffcmd(self, strcat(clientstuff, "\n"));
1356         stuffcmd(self, strcat("exec maps/", mapname, ".cfg\n"));
1357         stuffcmd(self, "cl_particles_reloadeffects\n");
1358
1359         FixClientCvars(self);
1360
1361         // spawnfunc_waypoint sprites
1362         WaypointSprite_InitClient(self);
1363
1364         // Wazat's grappling hook
1365         SetGrappleHookBindings();
1366
1367         // get autoswitch state from player when he toggles it
1368         stuffcmd(self, "alias autoswitch \"set cl_autoswitch $1 ; cmd autoswitch $1\"\n"); // default.cfg-ed in 2.4.1
1369
1370         // get version info from player
1371         stuffcmd(self, "cmd clientversion $gameversion\n");
1372
1373         // get other cvars from player
1374         GetCvars(0);
1375
1376         // set cvar for team scoreboard
1377         stuffcmd(self, strcat("set teamplay ", ftos(teamplay), "\n"));
1378
1379         // notify about available teams
1380         if(teams_matter)
1381         {
1382                 CheckAllowedTeams(self);
1383                 t = 0; if(c1 >= 0) t |= 1; if(c2 >= 0) t |= 2; if(c3 >= 0) t |= 4; if(c4 >= 0) t |= 8;
1384                 stuffcmd(self, strcat("set _teams_available ", ftos(t), "\n"));
1385         }
1386         else
1387                 stuffcmd(self, "set _teams_available 0\n");
1388
1389         stuffcmd(self, strcat("set gametype ", ftos(game), "\n"));
1390
1391         if(g_arena)
1392         {
1393                 self.classname = "observer";
1394                 Spawnqueue_Insert(self);
1395         }
1396         /*else if(g_ctf)
1397         {
1398                 ctf_clientconnect();
1399         }*/
1400
1401         if(teams_matter || sv_cheats)
1402                 attach_entcs();
1403
1404         bot_relinkplayerlist();
1405
1406         self.spectatortime = time;
1407         if(blockSpectators)
1408         {
1409                 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"));
1410         }
1411
1412         self.jointime = time;
1413         self.allowedTimeouts = cvar("sv_timeout_number");
1414
1415         if(clienttype(self) == CLIENTTYPE_REAL)
1416         {
1417                 if(cvar("g_bugrigs") || g_weaponarena == WEPBIT_TUBA)
1418                         stuffcmd(self, "cl_cmd settemp chase_active 1\n");
1419         }
1420
1421         if(g_lms)
1422         {
1423                 if(PlayerScore_Add(self, SP_LMS_LIVES, LMS_NewPlayerLives()) <= 0)
1424                 {
1425                         PlayerScore_Add(self, SP_LMS_RANK, 666);
1426                         self.frags = FRAGS_SPECTATOR;
1427                 }
1428         }
1429
1430         if(!sv_foginterval && world.fog != "")
1431                 stuffcmd(self, strcat("\nfog ", world.fog, "\nr_fog_exp2 0\nr_drawfog 1\n"));
1432
1433         SoundEntity_Attach(self);
1434
1435         if(cvar("g_hitplots"))
1436         {
1437                 self.hitplotfh = fopen(strcat("hits-", matchid, "-", ftos(self.playerid), ".plot"), FILE_WRITE);
1438                 fputs(self.hitplotfh, strcat("#name ", self.netname, "\n"));
1439         }
1440         else
1441                 self.hitplotfh = -1;
1442 }
1443
1444 /*
1445 =============
1446 ClientDisconnect
1447
1448 Called when a client disconnects from the server
1449 =============
1450 */
1451 .entity chatbubbleentity;
1452 .entity teambubbleentity;
1453 void ReadyCount();
1454 void ClientDisconnect (void)
1455 {
1456         if not(self.flags & FL_CLIENT)
1457         {
1458                 print("Warning: ClientDisconnect without ClientConnect\n");
1459                 return;
1460         }
1461
1462         if(self.hitplotfh >= 0)
1463         {
1464                 fclose(self.hitplotfh);
1465                 self.hitplotfh = -1;
1466         }
1467
1468         bot_clientdisconnect();
1469
1470         if(self.entcs)
1471                 detach_entcs();
1472         
1473         if(cvar("sv_eventlog"))
1474                 GameLogEcho(strcat(":part:", ftos(self.playerid)));
1475         bprint ("^4",self.netname);
1476         bprint ("^4 disconnected\n");
1477         
1478         SoundEntity_Detach(self);
1479
1480         DropAllRunes(self);
1481         kh_Key_DropAll(self, TRUE);
1482
1483         Portal_ClearAll(self);
1484
1485         if(self.flagcarried)
1486                 DropFlag(self.flagcarried, world, world);
1487         if(self.ballcarried)
1488                 DropBall(self.ballcarried, self.origin + self.ballcarried.origin, self.velocity);
1489
1490         // Here, everything has been done that requires this player to be a client.
1491
1492         self.flags &~= FL_CLIENT;
1493
1494         if (self.chatbubbleentity)
1495                 remove (self.chatbubbleentity);
1496
1497         if (self.teambubbleentity)
1498                 remove (self.teambubbleentity);
1499
1500         if (self.killindicator)
1501                 remove (self.killindicator);
1502
1503         WaypointSprite_PlayerGone();
1504
1505         bot_relinkplayerlist();
1506
1507         // remove laserdot
1508         if(self.weaponentity)
1509                 if(self.weaponentity.lasertarget)
1510                         remove(self.weaponentity.lasertarget);
1511
1512         if(g_arena)
1513         {
1514                 Spawnqueue_Unmark(self);
1515                 Spawnqueue_Remove(self);
1516         }
1517
1518         ClientData_Detach();
1519         PlayerScore_Detach(self);
1520
1521         if(self.netname_previous)
1522                 strunzone(self.netname_previous);
1523         if(self.clientstatus)
1524                 strunzone(self.clientstatus);
1525
1526         ClearPlayerSounds();
1527
1528         self.playerid = 0;
1529         ReadyCount();
1530
1531         // free cvars
1532         GetCvars(-1);
1533 }
1534
1535 .float BUTTON_CHAT;
1536 void ChatBubbleThink()
1537 {
1538         self.nextthink = time;
1539         if (!self.owner.modelindex || self.owner.chatbubbleentity != self)
1540         {
1541                 if(self.owner) // but why can that ever be world?
1542                         self.owner.chatbubbleentity = world;
1543                 remove(self);
1544                 return;
1545         }
1546         if (self.owner.BUTTON_CHAT && !self.owner.deadflag)
1547                 self.model = self.mdl;
1548         else
1549                 self.model = "";
1550 };
1551
1552 void UpdateChatBubble()
1553 {
1554         if (!self.modelindex)
1555                 return;
1556         // spawn a chatbubble entity if needed
1557         if (!self.chatbubbleentity)
1558         {
1559                 self.chatbubbleentity = spawn();
1560                 self.chatbubbleentity.owner = self;
1561                 self.chatbubbleentity.exteriormodeltoclient = self;
1562                 self.chatbubbleentity.think = ChatBubbleThink;
1563                 self.chatbubbleentity.nextthink = time;
1564                 setmodel(self.chatbubbleentity, "models/misc/chatbubble.spr"); // precision set below
1565                 //setorigin(self.chatbubbleentity, self.origin + '0 0 15' + self.maxs_z * '0 0 1');
1566                 setorigin(self.chatbubbleentity, '0 0 15' + self.maxs_z * '0 0 1');
1567                 setattachment(self.chatbubbleentity, self, "");  // sticks to moving player better, also conserves bandwidth
1568                 self.chatbubbleentity.mdl = self.chatbubbleentity.model;
1569                 self.chatbubbleentity.model = "";
1570                 self.chatbubbleentity.effects = EF_LOWPRECISION;
1571         }
1572 }
1573
1574
1575 void TeamBubbleThink()
1576 {
1577         self.nextthink = time;
1578         if (!self.owner.modelindex || self.owner.teambubbleentity != self)
1579         {
1580                 if(self.owner) // but why can that ever be world?
1581                         self.owner.teambubbleentity = world;
1582                 remove(self);
1583                 return;
1584         }
1585 //      setorigin(self, self.owner.origin + '0 0 15' + self.owner.maxs_z * '0 0 1');  // bandwidth hog. setattachment does this now
1586         if (self.owner.BUTTON_CHAT || self.owner.deadflag || self.owner.killindicator)
1587                 self.model = "";
1588         else
1589                 self.model = self.mdl;
1590
1591 };
1592
1593 float TeamBubble_customizeentityforclient()
1594 {
1595         return (self.owner != other && self.owner.team == other.team && other.killcount > -666);
1596 }
1597
1598 void UpdateTeamBubble()
1599 {
1600         if (!self.modelindex || !teams_matter)
1601                 return;
1602         // spawn a teambubble entity if needed
1603         if (!self.teambubbleentity && teams_matter)
1604         {
1605                 self.teambubbleentity = spawn();
1606                 self.teambubbleentity.owner = self;
1607                 self.teambubbleentity.exteriormodeltoclient = self;
1608                 self.teambubbleentity.think = TeamBubbleThink;
1609                 self.teambubbleentity.nextthink = time;
1610                 setmodel(self.teambubbleentity, "models/misc/teambubble.spr"); // precision set below
1611 //              setorigin(self.teambubbleentity, self.origin + '0 0 15' + self.maxs_z * '0 0 1');
1612                 setorigin(self.teambubbleentity, '0 0 15' + self.maxs_z * '0 0 1');
1613                 setattachment(self.teambubbleentity, self, "");  // sticks to moving player better, also conserves bandwidth
1614                 self.teambubbleentity.mdl = self.teambubbleentity.model;
1615                 self.teambubbleentity.model = self.teambubbleentity.mdl;
1616                 self.teambubbleentity.customizeentityforclient = TeamBubble_customizeentityforclient;
1617                 self.teambubbleentity.effects = EF_LOWPRECISION;
1618         }
1619 }
1620
1621 // LordHavoc: this hack will be removed when proper _pants/_shirt layers are
1622 // added to the model skins
1623 /*void UpdateColorModHack()
1624 {
1625         local float c;
1626         c = self.clientcolors & 15;
1627         // LordHavoc: only bothering to support white, green, red, yellow, blue
1628              if (!teams_matter) self.colormod = '0 0 0';
1629         else if (c ==  0) self.colormod = '1.00 1.00 1.00';
1630         else if (c ==  3) self.colormod = '0.10 1.73 0.10';
1631         else if (c ==  4) self.colormod = '1.73 0.10 0.10';
1632         else if (c == 12) self.colormod = '1.22 1.22 0.10';
1633         else if (c == 13) self.colormod = '0.10 0.10 1.73';
1634         else self.colormod = '1 1 1';
1635 };*/
1636
1637 void respawn(void)
1638 {
1639         CopyBody(1);
1640         self.effects |= EF_NODRAW; // prevent another CopyBody
1641         PutClientInServer();
1642 }
1643
1644 void play_countdown(float finished, string samp)
1645 {
1646         if(clienttype(self) == CLIENTTYPE_REAL)
1647                 if(floor(finished - time - frametime) != floor(finished - time))
1648                         if(finished - time < 6)
1649                                 sound (self, CHAN_AUTO, samp, VOL_BASE, ATTN_NORM);
1650 }
1651
1652 /**
1653  * When sv_timeout is used this function returs strings like
1654  * "Timeout begins in 2 seconds!\n" or "Timeout ends in 23 seconds!\n".
1655  * Called by centerprint functions
1656  * @param addOneSecond boolean, set to 1 if the welcome-message centerprint asks for the text
1657  */
1658 string getTimeoutText(float addOneSecond) {
1659         if (!cvar("sv_timeout") || !timeoutStatus)
1660                 return "";
1661
1662         local string retStr;
1663         if (timeoutStatus == 1) {
1664                 if (addOneSecond == 1) {
1665                         retStr = strcat("Timeout begins in ", ftos(remainingLeadTime + 1), " seconds!\n");
1666                 }
1667                 else {
1668                         retStr = strcat("Timeout begins in ", ftos(remainingLeadTime), " seconds!\n");
1669                 }
1670                 return retStr;
1671         }
1672         else if (timeoutStatus == 2) {
1673                 if (addOneSecond) {
1674                         retStr = strcat("Timeout ends in ", ftos(remainingTimeoutTime + 1), " seconds!\n");
1675                         //don't show messages like "Timeout ends in 0 seconds"...
1676                         if ((remainingTimeoutTime + 1) > 0)
1677                                 return retStr;
1678                         else
1679                                 return "";
1680                 }
1681                 else {
1682                         retStr = strcat("Timeout ends in ", ftos(remainingTimeoutTime), " seconds!\n");
1683                         //don't show messages like "Timeout ends in 0 seconds"...
1684                         if (remainingTimeoutTime > 0)
1685                                 return retStr;
1686                         else
1687                                 return "";
1688                 }
1689         }
1690         else return "";
1691 }
1692
1693 void player_powerups (void)
1694 {
1695         if((self.items & IT_USING_JETPACK) && !self.deadflag)
1696         {
1697                 SoundEntity_StartSound(self, CHAN_PLAYER, "misc/jetpack_fly.wav", VOL_BASE, cvar("g_jetpack_attenuation"));
1698                 self.modelflags |= MF_ROCKET;
1699         }
1700         else
1701         {
1702                 SoundEntity_StopSound(self, CHAN_PLAYER);
1703                 self.modelflags &~= MF_ROCKET;
1704         }
1705
1706         self.effects &~= (EF_RED | EF_BLUE | EF_ADDITIVE | EF_FULLBRIGHT);
1707
1708         if(!self.modelindex || self.deadflag) // don't apply the flags if the player is gibbed
1709                 return;
1710
1711         if (g_minstagib)
1712         {
1713                 self.effects |= EF_FULLBRIGHT;
1714
1715                 if (self.items & IT_STRENGTH)
1716                 {
1717                         play_countdown(self.strength_finished, "misc/poweroff.wav");
1718                         if (time > self.strength_finished)
1719                         {
1720                                 self.alpha = default_player_alpha;
1721                                 self.exteriorweaponentity.alpha = default_weapon_alpha;
1722                                 self.items &~= IT_STRENGTH;
1723                                 sprint(self, "^3Invisibility has worn off\n");
1724                         }
1725                 }
1726                 else
1727                 {
1728                         if (time < self.strength_finished)
1729                         {
1730                                 self.alpha = g_minstagib_invis_alpha;
1731                                 self.exteriorweaponentity.alpha = g_minstagib_invis_alpha;
1732                                 self.items |= IT_STRENGTH;
1733                                 sprint(self, "^3You are invisible\n");
1734                         }
1735                 }
1736
1737                 if (self.items & IT_INVINCIBLE)
1738                 {
1739                         play_countdown(self.invincible_finished, "misc/poweroff.wav");
1740                         if (time > self.invincible_finished)
1741                         {
1742                                 self.items = self.items - (self.items & IT_INVINCIBLE);
1743                                 sprint(self, "^3Speed has worn off\n");
1744                         }
1745                 }
1746                 else
1747                 {
1748                         if (time < self.invincible_finished)
1749                         {
1750                                 self.items = self.items | IT_INVINCIBLE;
1751                                 sprint(self, "^3You are on speed\n");
1752                         }
1753                 }
1754                 return;
1755         }
1756
1757         if (self.items & IT_STRENGTH)
1758         {
1759                 play_countdown(self.strength_finished, "misc/poweroff.wav");
1760                 self.effects = self.effects | (EF_BLUE | EF_ADDITIVE | EF_FULLBRIGHT);
1761                 if (time > self.strength_finished)
1762                 {
1763                         self.items = self.items - (self.items & IT_STRENGTH);
1764                         sprint(self, "^3Strength has worn off\n");
1765                 }
1766         }
1767         else
1768         {
1769                 if (time < self.strength_finished)
1770                 {
1771                         self.items = self.items | IT_STRENGTH;
1772                         sprint(self, "^3Strength infuses your weapons with devastating power\n");
1773                 }
1774         }
1775         if (self.items & IT_INVINCIBLE)
1776         {
1777                 play_countdown(self.invincible_finished, "misc/poweroff.wav");
1778                 self.effects = self.effects | (EF_RED | EF_ADDITIVE | EF_FULLBRIGHT);
1779                 if (time > self.invincible_finished)
1780                 {
1781                         self.items = self.items - (self.items & IT_INVINCIBLE);
1782                         sprint(self, "^3Shield has worn off\n");
1783                 }
1784         }
1785         else
1786         {
1787                 if (time < self.invincible_finished)
1788                 {
1789                         self.items = self.items | IT_INVINCIBLE;
1790                         sprint(self, "^3Shield surrounds you\n");
1791                 }
1792         }
1793
1794         if (cvar("g_fullbrightplayers"))
1795                 self.effects = self.effects | EF_FULLBRIGHT;
1796
1797         // midair gamemode: damage only while in the air
1798         // if in midair mode, being on ground grants temporary invulnerability
1799         // (this is so that multishot weapon don't clear the ground flag on the
1800         // first damage in the frame, leaving the player vulnerable to the
1801         // remaining hits in the same frame)
1802         if (self.flags & FL_ONGROUND)
1803         if (g_midair)
1804                 self.spawnshieldtime = max(self.spawnshieldtime, time + cvar("g_midair_shieldtime"));
1805
1806         if (time >= game_starttime)
1807         if (time < self.spawnshieldtime)
1808                 self.effects = self.effects | (EF_ADDITIVE | EF_FULLBRIGHT);
1809 }
1810
1811 float CalcRegen(float current, float stable, float regenfactor, float regenframetime)
1812 {
1813         if(current > stable)
1814                 return current;
1815         else if(current > stable - 0.25) // when close enough, "snap"
1816                 return stable;
1817         else
1818                 return min(stable, current + (stable - current) * regenfactor * regenframetime);
1819 }
1820
1821 float CalcRot(float current, float stable, float rotfactor, float rotframetime)
1822 {
1823         if(current < stable)
1824                 return current;
1825         else if(current < stable + 0.25) // when close enough, "snap"
1826                 return stable;
1827         else
1828                 return max(stable, current + (stable - current) * rotfactor * rotframetime);
1829 }
1830
1831 float CalcRotRegen(float current, float regenstable, float regenfactor, float regenlinear, float regenframetime, float rotstable, float rotfactor, float rotlinear, float rotframetime, float limit)
1832 {
1833         if(current > rotstable)
1834         {
1835                 if(rotframetime > 0)
1836                 {
1837                         current = CalcRot(current, rotstable, rotfactor, rotframetime);
1838                         current = max(rotstable, current - rotlinear * rotframetime);
1839                 }
1840         }
1841         else if(current < regenstable)
1842         {
1843                 if(regenframetime > 0)
1844                 {
1845                         current = CalcRegen(current, regenstable, regenfactor, regenframetime);
1846                         current = min(regenstable, current + regenlinear * regenframetime);
1847                 }
1848         }
1849
1850         if(current > limit)
1851                 current = limit;
1852
1853         return current;
1854 }
1855
1856 void player_regen (void)
1857 {
1858         float minh, mina, minf, maxh, maxa, maxf, limith, limita, limitf, max_mod, regen_mod, rot_mod, limit_mod;
1859         maxh = cvar("g_balance_health_rotstable");
1860         maxa = cvar("g_balance_armor_rotstable");
1861         maxf = cvar("g_balance_fuel_rotstable");
1862         minh = cvar("g_balance_health_regenstable");
1863         mina = cvar("g_balance_armor_regenstable");
1864         minf = cvar("g_balance_fuel_regenstable");
1865         limith = cvar("g_balance_health_limit");
1866         limita = cvar("g_balance_armor_limit");
1867         limitf = cvar("g_balance_fuel_limit");
1868
1869         max_mod = regen_mod = rot_mod = limit_mod = 1;
1870
1871         if (self.runes & RUNE_REGEN)
1872         {
1873                 if (self.runes & CURSE_VENOM) // do we have both rune/curse?
1874                 {
1875                         regen_mod = cvar("g_balance_rune_regen_combo_regenrate");
1876                         max_mod = cvar("g_balance_rune_regen_combo_hpmod");
1877                         limit_mod = cvar("g_balance_rune_regen_combo_limitmod");
1878                 }
1879                 else
1880                 {
1881                         regen_mod = cvar("g_balance_rune_regen_regenrate");
1882                         max_mod = cvar("g_balance_rune_regen_hpmod");
1883                         limit_mod = cvar("g_balance_rune_regen_limitmod");
1884                 }
1885         }
1886         else if (self.runes & CURSE_VENOM)
1887         {
1888                 max_mod = cvar("g_balance_curse_venom_hpmod");
1889                 if (self.runes & RUNE_REGEN) // do we have both rune/curse?
1890                         rot_mod = cvar("g_balance_rune_regen_combo_rotrate");
1891                 else
1892                         rot_mod = cvar("g_balance_curse_venom_rotrate");
1893                 limit_mod = cvar("g_balance_curse_venom_limitmod");
1894                 //if (!self.runes & RUNE_REGEN)
1895                 //      rot_mod = cvar("g_balance_curse_venom_rotrate");
1896         }
1897         maxh = maxh * max_mod;
1898         //maxa = maxa * max_mod;
1899         //maxf = maxf * max_mod;
1900         minh = minh * max_mod;
1901         //mina = mina * max_mod;
1902         //minf = minf * max_mod;
1903         limith = limith * limit_mod;
1904         limita = limita * limit_mod;
1905         //limitf = limitf * limit_mod;
1906
1907         if(g_lms)
1908                 rot_mod = 0;
1909
1910         if (!g_minstagib && (!g_lms || cvar("g_lms_regenerate")))
1911         {
1912                 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);
1913                 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);
1914
1915                 // if player rotted to death...  die!
1916                 if(self.health < 1)
1917                         self.event_damage(self, self, 1, DEATH_ROT, self.origin, '0 0 0');
1918         }
1919
1920         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);
1921 }
1922
1923 float zoomstate_set;
1924 void SetZoomState(float z)
1925 {
1926         if(z != self.zoomstate)
1927         {
1928                 self.zoomstate = z;
1929                 ClientData_Touch(self);
1930         }
1931         zoomstate_set = 1;
1932 }
1933
1934 void GetPressedKeys(void) {
1935         if (self.movement_x > 0) // get if movement keys are pressed
1936         {       // forward key pressed
1937                 self.pressedkeys |= KEY_FORWARD;
1938                 self.pressedkeys &~= KEY_BACKWARD;
1939         }
1940         else if (self.movement_x < 0)
1941         {       // backward key pressed
1942                 self.pressedkeys |= KEY_BACKWARD;
1943                 self.pressedkeys &~= KEY_FORWARD;
1944         }
1945         else
1946         {       // no x input
1947                 self.pressedkeys &~= KEY_FORWARD;
1948                 self.pressedkeys &~= KEY_BACKWARD;
1949         }
1950         
1951         if (self.movement_y > 0)
1952         {       // right key pressed
1953                 self.pressedkeys |= KEY_RIGHT;
1954                 self.pressedkeys &~= KEY_LEFT;
1955         }
1956         else if (self.movement_y < 0)
1957         {       // left key pressed
1958                 self.pressedkeys |= KEY_LEFT;
1959                 self.pressedkeys &~= KEY_RIGHT;
1960         }
1961         else
1962         {       // no y input
1963                 self.pressedkeys &~= KEY_RIGHT;
1964                 self.pressedkeys &~= KEY_LEFT;
1965         }
1966         
1967         if (self.BUTTON_JUMP) // get if jump and crouch keys are pressed
1968                 self.pressedkeys |= KEY_JUMP;
1969         else
1970                 self.pressedkeys &~= KEY_JUMP;
1971         if (self.BUTTON_CROUCH)
1972                 self.pressedkeys |= KEY_CROUCH;
1973         else
1974                 self.pressedkeys &~= KEY_CROUCH;
1975 }
1976
1977 /*
1978 ======================
1979 spectate mode routines
1980 ======================
1981 */
1982 void SpectateCopy(entity spectatee) {
1983         self.armortype = spectatee.armortype;
1984         self.armorvalue = spectatee.armorvalue;
1985         self.ammo_cells = spectatee.ammo_cells;
1986         self.ammo_shells = spectatee.ammo_shells;
1987         self.ammo_nails = spectatee.ammo_nails;
1988         self.ammo_rockets = spectatee.ammo_rockets;
1989         self.ammo_fuel = spectatee.ammo_fuel;
1990         self.effects = spectatee.effects & EFMASK_CHEAP; // eat performance
1991         self.health = spectatee.health;
1992         self.impulse = 0;
1993         self.items = spectatee.items;
1994         self.metertime = spectatee.metertime;
1995         self.strength_finished = spectatee.strength_finished;
1996         self.invincible_finished = spectatee.invincible_finished;
1997         self.pressedkeys = spectatee.pressedkeys;
1998         self.weapons = spectatee.weapons;
1999         self.switchweapon = spectatee.switchweapon;
2000         self.weapon = spectatee.weapon;
2001         self.punchangle = spectatee.punchangle;
2002         self.view_ofs = spectatee.view_ofs;
2003         self.v_angle = spectatee.v_angle;
2004         self.velocity = spectatee.velocity;
2005         self.dmg_take = spectatee.dmg_take;
2006         self.dmg_save = spectatee.dmg_save;
2007         self.dmg_inflictor = spectatee.dmg_inflictor;
2008         self.angles = spectatee.v_angle;
2009         self.fixangle = TRUE;
2010         setorigin(self, spectatee.origin);
2011         setsize(self, spectatee.mins, spectatee.maxs);
2012         SetZoomState(spectatee.zoomstate);
2013 }
2014
2015 float SpectateUpdate() {
2016         if(!self.enemy)
2017                 return 0;
2018
2019         if (self == self.enemy)
2020                 return 0;
2021         
2022         if(self.enemy.classname != "player")
2023                 return 0;
2024
2025         SpectateCopy(self.enemy);
2026
2027         return 1;
2028 }
2029
2030 float SpectateNext() {
2031         other = find(self.enemy, classname, "player");
2032         if (!other) {
2033                 other = find(other, classname, "player");
2034         }
2035         if (other) {
2036                 self.enemy = other;
2037         }
2038         if(self.enemy.classname == "player") {
2039                 msg_entity = self;
2040                 WriteByte(MSG_ONE, SVC_SETVIEW);
2041                 WriteEntity(MSG_ONE, self.enemy);
2042                 //stuffcmd(self, "set viewsize $tmpviewsize \n");
2043                 if(!SpectateUpdate())
2044                         PutObserverInServer();
2045                 return 1;
2046         } else {
2047                 return 0;
2048         }
2049 }
2050
2051 /*
2052 =============
2053 ShowRespawnCountdown()
2054
2055 Update a respawn countdown display.
2056 =============
2057 */
2058 void ShowRespawnCountdown()
2059 {
2060         float number;
2061         if(self.deadflag == DEAD_NO) // just respawned?
2062                 return;
2063         else
2064         {
2065                 number = ceil(self.death_time - time);
2066                 if(number <= 0)
2067                         return;
2068                 if(number <= self.respawn_countdown)
2069                 {
2070                         self.respawn_countdown = number - 1;
2071                         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
2072                                 announce(self, strcat("announcer/robotic/", ftos(number), ".wav"));
2073                 }
2074         }
2075 }
2076
2077 void LeaveSpectatorMode()
2078 {
2079         if(isJoinAllowed()) {
2080                 if(!teams_matter || cvar("g_campaign") || cvar("g_balance_teams") || (self.wasplayer && cvar("g_changeteam_banned"))) {
2081                         self.classname = "player";
2082                         if(cvar("g_campaign") || cvar("g_balance_teams") || cvar("g_balance_teams_force"))
2083                                 JoinBestTeam(self, FALSE, TRUE);
2084                         if(cvar("g_campaign"))
2085                                 campaign_bots_may_start = 1;
2086                         PutClientInServer();
2087                         if(self.classname == "player")
2088                                 bprint ("^4", self.netname, "^4 is playing now\n");
2089                         if(!cvar("g_campaign"))
2090                                 centerprint(self,""); // clear MOTD
2091                         return;
2092                 } else {
2093                         stuffcmd(self,"menu_showteamselect\n");
2094                         return;
2095                 }
2096         }
2097         else {
2098                 //player may not join because of g_maxplayers is set
2099                 centerprint_atprio(self, CENTERPRIO_MAPVOTE, PREVENT_JOIN_TEXT);
2100         }
2101 }
2102
2103 /**
2104  * Determines whether the player is allowed to join. This depends on cvar
2105  * g_maxplayers, if it isn't used this function always return TRUE, otherwise
2106  * it checks whether the number of currently playing players exceeds g_maxplayers.
2107  * @return bool TRUE if the player is allowed to join, false otherwise
2108  */
2109 float isJoinAllowed() {
2110         if (!cvar("g_maxplayers"))
2111                 return TRUE;
2112
2113         local entity e;
2114         local float currentlyPlaying;
2115         FOR_EACH_REALPLAYER(e) {
2116                 if(e.classname == "player")
2117                         currentlyPlaying += 1;
2118         }
2119         if(currentlyPlaying < cvar("g_maxplayers"))
2120                 return TRUE;
2121
2122         return FALSE;
2123 }
2124
2125 /**
2126  * Checks whether the client is an observer or spectator, if so, he will get kicked after
2127  * g_maxplayers_spectator_blocktime seconds
2128  */
2129 void checkSpectatorBlock() {
2130         if(self.classname == "spectator" || self.classname == "observer") {
2131                 if( time > (self.spectatortime + cvar("g_maxplayers_spectator_blocktime")) ) {
2132                         sprint(self, "^7You were kicked from the server because you are spectator and spectators aren't allowed at the moment.\n");
2133                         dropclient(self);
2134                 }
2135         }
2136 }
2137
2138 float vercmp_recursive(string v1, string v2)
2139 {
2140         float dot1, dot2;
2141         string s1, s2;
2142         float r;
2143
2144         dot1 = strstrofs(v1, ".", 0);
2145         dot2 = strstrofs(v2, ".", 0);
2146         if(dot1 == -1)
2147                 s1 = v1;
2148         else
2149                 s1 = substring(v1, 0, dot1);
2150         if(dot2 == -1)
2151                 s2 = v2;
2152         else
2153                 s2 = substring(v2, 0, dot2);
2154
2155         r = stof(s1) - stof(s2);
2156         if(r != 0)
2157                 return r;
2158
2159         r = strcasecmp(s1, s2);
2160         if(r != 0)
2161                 return r;
2162
2163         if(dot1 == -1)
2164                 if(dot2 == -1)
2165                         return 0;
2166                 else
2167                         return -1;
2168         else
2169                 if(dot2 == -1)
2170                         return 1;
2171                 else
2172                         return vercmp_recursive(substring(v1, dot1 + 1, 999), substring(v2, dot2 + 1, 999));
2173 }
2174
2175 float vercmp(string v1, string v2)
2176 {
2177         if(strcasecmp(v1, v2) == 0) // early out check
2178                 return 0;
2179         return vercmp_recursive(v1, v2);
2180 }
2181
2182 void ObserverThink()
2183 {
2184         if (self.flags & FL_JUMPRELEASED) {
2185                 if (self.BUTTON_JUMP && !self.version_mismatch) {
2186                         self.welcomemessage_time = 0;
2187                         self.flags &~= FL_JUMPRELEASED;
2188                         self.flags |= FL_SPAWNING;
2189                 } else if(self.BUTTON_ATCK && !self.version_mismatch) {
2190                         self.welcomemessage_time = 0;
2191                         self.flags &~= FL_JUMPRELEASED;
2192                         if(SpectateNext() == 1) {
2193                                 self.classname = "spectator";
2194                         }
2195                 }
2196         } else {
2197                 if (!(self.BUTTON_ATCK || self.BUTTON_JUMP)) {
2198                         self.flags |= FL_JUMPRELEASED;
2199                         if(self.flags & FL_SPAWNING)
2200                         {
2201                                 self.flags &~= FL_SPAWNING;
2202                                 LeaveSpectatorMode();
2203                                 return;
2204                         }
2205                 }
2206         }
2207         PrintWelcomeMessage(self);
2208 }
2209
2210 void SpectatorThink()
2211 {
2212         if (self.flags & FL_JUMPRELEASED) {
2213                 if (self.BUTTON_JUMP && !self.version_mismatch) {
2214                         self.welcomemessage_time = 0;
2215                         self.flags &~= FL_JUMPRELEASED;
2216                         self.flags |= FL_SPAWNING;
2217                 } else if(self.BUTTON_ATCK) {
2218                         self.welcomemessage_time = 0;
2219                         self.flags &~= FL_JUMPRELEASED;
2220                         if(SpectateNext() == 1) {
2221                                 self.classname = "spectator";
2222                         } else {
2223                                 self.classname = "observer";
2224                                 PutClientInServer();
2225                         }
2226                 } else if (self.BUTTON_ATCK2) {
2227                         self.welcomemessage_time = 0;
2228                         self.flags &~= FL_JUMPRELEASED;
2229                         self.classname = "observer";
2230                         PutClientInServer();
2231                 } else {
2232                         if(!SpectateUpdate())
2233                                 PutObserverInServer();
2234                 }
2235         } else {
2236                 if (!(self.BUTTON_ATCK || self.BUTTON_ATCK2)) {
2237                         self.flags |= FL_JUMPRELEASED;
2238                         if(self.flags & FL_SPAWNING)
2239                         {
2240                                 self.flags &~= FL_SPAWNING;
2241                                 LeaveSpectatorMode();
2242                                 return;
2243                         }
2244                 }
2245         }
2246         PrintWelcomeMessage(self);
2247         self.flags |= FL_CLIENT | FL_NOTARGET;
2248 }
2249
2250 .float touchexplode_time;
2251
2252 /*
2253 =============
2254 PlayerPreThink
2255
2256 Called every frame for each client before the physics are run
2257 =============
2258 */
2259 void() ctf_setstatus;
2260 void() nexball_setstatus;
2261 .float items_added;
2262 void PlayerPreThink (void)
2263 {
2264         self.stat_game_starttime = game_starttime;
2265         self.stat_allow_oldnexbeam = cvar("g_allow_oldnexbeam");
2266         self.stat_leadlimit = cvar("leadlimit");
2267
2268         if(blockSpectators && frametime)
2269                 // WORKAROUND: only use dropclient in server frames (frametime set). Never use it in cl_movement frames (frametime zero).
2270                 checkSpectatorBlock();
2271         
2272         zoomstate_set = 0;
2273
2274         if(self.netname_previous != self.netname)
2275         {
2276                 if(cvar("sv_eventlog"))
2277                         GameLogEcho(strcat(":name:", ftos(self.playerid), ":", self.netname));
2278                 if(self.netname_previous)
2279                         strunzone(self.netname_previous);
2280                 self.netname_previous = strzone(self.netname);
2281         }
2282
2283         // version nagging
2284         if(self.version_nagtime)
2285                 if(self.cvar_g_nexuizversion)
2286                         if(time > self.version_nagtime)
2287                         {
2288                                 if(strstr(self.cvar_g_nexuizversion, "svn", 0) < 0)
2289                                 {
2290                                         if(strstr(cvar_string("g_nexuizversion"), "svn", 0) >= 0)
2291                                         {
2292                                                 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");
2293                                                 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"));
2294                                         }
2295                                         else
2296                                         {
2297                                                 float r;
2298                                                 r = vercmp(self.cvar_g_nexuizversion, cvar_string("g_nexuizversion"));
2299                                                 if(r < 0)
2300                                                 {
2301                                                         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");
2302                                                         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"));
2303                                                 }
2304                                                 else if(r > 0)
2305                                                 {
2306                                                         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");
2307                                                         sprint(self, strcat("\{1}^1NOTE: ^7the server is running ^3Nexuiz ", cvar_string("g_nexuizversion"), "^7, you have ^3Nexuiz ", self.cvar_g_nexuizversion, "^1\n"));
2308                                                 }
2309                                         }
2310                                 }
2311                                 self.version_nagtime = 0;
2312                         }
2313
2314         // GOD MODE info
2315         if(!(self.flags & FL_GODMODE)) if(self.max_armorvalue)
2316         {
2317                 sprint(self, strcat("godmode saved you ", ftos(self.max_armorvalue), " units of damage, cheater!\n"));
2318                 self.max_armorvalue = 0;
2319         }
2320
2321         if(frametime)
2322                 antilag_record(self);
2323
2324         if(self.classname == "player") {
2325 //              if(self.netname == "Wazat")
2326 //                      bprint(self.classname, "\n");
2327
2328                 CheckRules_Player();
2329
2330                 PrintWelcomeMessage(self);
2331
2332                 if (intermission_running)
2333                 {
2334                         IntermissionThink ();   // otherwise a button could be missed between
2335                         return;                                 // the think tics
2336                 }
2337
2338                 if(self.teleport_time)
2339                 if(time > self.teleport_time)
2340                 {
2341                         self.teleport_time = 0;
2342                         self.effects = self.effects - (self.effects & EF_NODRAW);
2343                 }
2344
2345                 Nixnex_GiveCurrentWeapon();
2346
2347                 if(frametime > 0) // don't do this in cl_movement frames, just in server ticks
2348                         UpdateSelectedPlayer();
2349
2350                 //don't allow the player to turn around while game is paused!
2351                 if(timeoutStatus == 2) {
2352                         self.v_angle = self.lastV_angle;
2353                         self.angles = self.lastV_angle;
2354                         self.fixangle = TRUE;
2355                 }
2356
2357                 if(frametime)
2358                         player_powerups();
2359
2360                 if (self.deadflag != DEAD_NO)
2361                 {
2362                         float button_pressed, force_respawn;
2363                         if(frametime)
2364                                 player_anim();
2365                         button_pressed = (self.BUTTON_ATCK || self.BUTTON_JUMP || self.BUTTON_ATCK2 || self.BUTTON_HOOK || self.BUTTON_USE);
2366                         force_respawn = (g_lms || cvar("g_forced_respawn"));
2367                         if (self.deadflag == DEAD_DYING)
2368                         {
2369                                 if(force_respawn)
2370                                         self.deadflag = DEAD_RESPAWNING;
2371                                 else if(!button_pressed)
2372                                         self.deadflag = DEAD_DEAD;
2373                         }
2374                         else if (self.deadflag == DEAD_DEAD)
2375                         {
2376                                 if(button_pressed)
2377                                         self.deadflag = DEAD_RESPAWNABLE;
2378                         }
2379                         else if (self.deadflag == DEAD_RESPAWNABLE)
2380                         {
2381                                 if(!button_pressed)
2382                                         self.deadflag = DEAD_RESPAWNING;
2383                         }
2384                         else if (self.deadflag == DEAD_RESPAWNING)
2385                         {
2386                                 if(time > self.death_time)
2387                                 {
2388                                         self.death_time = time + 1; // only retry once a second
2389                                         respawn();
2390                                 }
2391                         }
2392                         ShowRespawnCountdown();
2393                         return;
2394                 }
2395
2396                 if(g_touchexplode)
2397                 if(time > self.touchexplode_time)
2398                 if(self.classname == "player")
2399                 if(self.deadflag == DEAD_NO)
2400                 if not(IS_INDEPENDENT_PLAYER(self))
2401                 FOR_EACH_PLAYER(other) if(self != other)
2402                 {
2403                         if(time > other.touchexplode_time)
2404                         if(other.classname == "player")
2405                         if(other.deadflag == DEAD_NO)
2406                         if not(IS_INDEPENDENT_PLAYER(other))
2407                         if(boxesoverlap(self.absmin, self.absmax, other.absmin, other.absmax))
2408                         {
2409                                 PlayerTouchExplode(self, other);
2410                                 self.touchexplode_time = other.touchexplode_time = time + 0.2;
2411                         }
2412                 }
2413
2414                 if(g_lms && !self.deadflag && cvar("g_lms_campcheck_interval"))
2415                 {
2416                         vector dist;
2417
2418                         // calculate player movement (in 2 dimensions only, so jumping on one spot doesn't count as movement)
2419                         dist = self.prevorigin - self.origin;
2420                         dist_z = 0;
2421                         self.lms_traveled_distance += fabs(vlen(dist));
2422
2423                         if((cvar("g_campaign") && !campaign_bots_may_start) || (time < game_starttime))
2424                         {
2425                                 self.lms_nextcheck = time + cvar("g_lms_campcheck_interval")*2;
2426                                 self.lms_traveled_distance = 0;
2427                         }
2428
2429                         if(time > self.lms_nextcheck)
2430                         {
2431                                 //sprint(self, "distance: ", ftos(self.lms_traveled_distance), "\n");
2432                                 if(self.lms_traveled_distance < cvar("g_lms_campcheck_distance"))
2433                                 {
2434                                         centerprint(self, cvar_string("g_lms_campcheck_message"));
2435                                         // FIXME KadaverJack: gibbing player here causes playermodel to bounce around, instead of eye.md3
2436                                         // I wasn't able to find out WHY that happens, so I put a workaround in place that shall prevent players from being gibbed :(
2437                                         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');
2438                                 }
2439                                 self.lms_nextcheck = time + cvar("g_lms_campcheck_interval");
2440                                 self.lms_traveled_distance = 0;
2441                         }
2442                 }
2443
2444                 self.prevorigin = self.origin;
2445
2446                 if ((self.BUTTON_CROUCH && !self.hook.state) || self.health <= g_bloodloss)
2447                 {
2448                         if (!self.crouch)
2449                         {
2450                                 self.crouch = TRUE;
2451                                 self.view_ofs = PL_CROUCH_VIEW_OFS;
2452                                 setsize (self, PL_CROUCH_MIN, PL_CROUCH_MAX);
2453                                 setanim(self, self.anim_duck, FALSE, TRUE, TRUE);
2454                         }
2455                 }
2456                 else
2457                 {
2458                         if (self.crouch)
2459                         {
2460                                 tracebox(self.origin, PL_MIN, PL_MAX, self.origin, FALSE, self);
2461                                 if (!trace_startsolid)
2462                                 {
2463                                         self.crouch = FALSE;
2464                                         self.view_ofs = PL_VIEW_OFS;
2465                                         setsize (self, PL_MIN, PL_MAX);
2466                                 }
2467                         }
2468                 }
2469                 
2470                 if(self.health <= g_bloodloss && self.deadflag == DEAD_NO)
2471                 {
2472                         if(self.bloodloss_timer < time)
2473                         {
2474                                 self.event_damage(self, self, 1, DEATH_ROT, self.origin, '0 0 0');
2475                                 self.bloodloss_timer = time + 0.5 + random() * 0.5;
2476                         }
2477                 }
2478
2479                 FixPlayermodel();
2480
2481                 GrapplingHookFrame();
2482
2483                 if(frametime)
2484                 {
2485                         self.items &~= self.items_added;
2486
2487                         W_WeaponFrame();
2488
2489                         self.items_added = 0;
2490                         if(self.items & IT_JETPACK)
2491                                 if(self.items & IT_FUEL_REGEN || self.ammo_fuel >= 0.01)
2492                                         self.items_added |= IT_FUEL;
2493
2494                         self.items |= self.items_added;
2495                 }
2496
2497                 player_regen();
2498                 if(frametime)
2499                         player_anim();
2500
2501                 if (g_minstagib)
2502                         minstagib_ammocheck();
2503
2504                 ctf_setstatus();
2505                 kh_setstatus();
2506                 nexball_setstatus();
2507
2508                 self.dmg_team = max(0, self.dmg_team - cvar("g_teamdamage_resetspeed") * frametime);
2509
2510                 //self.angles_y=self.v_angle_y + 90;   // temp
2511
2512                 //if (TetrisPreFrame()) return;
2513         } else if(gameover) {
2514                 if (intermission_running)
2515                         IntermissionThink ();   // otherwise a button could be missed between
2516                 return;
2517         } else if(self.classname == "observer") {
2518                 ObserverThink();
2519         } else if(self.classname == "spectator") {
2520                 SpectatorThink();
2521         }
2522
2523         if(!zoomstate_set)
2524                 SetZoomState(self.BUTTON_ZOOM || (self.BUTTON_ATCK2 && self.weapon == WEP_NEX));
2525
2526         float oldspectatee_status;
2527         oldspectatee_status = self.spectatee_status;
2528         if(self.classname == "spectator")
2529                 self.spectatee_status = num_for_edict(self.enemy);
2530         else if(self.classname == "observer")
2531                 self.spectatee_status = num_for_edict(self);
2532         else
2533                 self.spectatee_status = 0;
2534         if(self.spectatee_status != oldspectatee_status)
2535         {
2536                 ClientData_Touch(self);
2537                 if(g_race || g_cts)
2538                         race_InitSpectator();
2539         }
2540
2541         if(self.teamkill_soundtime)
2542         if(time > self.teamkill_soundtime)
2543         {
2544                 self.teamkill_soundtime = 0;
2545
2546                 entity oldpusher, oldself;
2547
2548                 oldself = self; self = self.teamkill_soundsource;
2549                 oldpusher = self.pusher; self.pusher = oldself;
2550
2551                 PlayerSound(playersound_teamshoot, CHAN_VOICE, VOICETYPE_LASTATTACKER_ONLY);
2552
2553                 self.pusher = oldpusher;
2554                 self = oldself;
2555         }
2556
2557         if(self.taunt_soundtime)
2558         if(time > self.taunt_soundtime)
2559         {
2560                 self.taunt_soundtime = 0;
2561                 PlayerSound(playersound_taunt, CHAN_VOICE, VOICETYPE_AUTOTAUNT);
2562         }
2563
2564         target_voicescript_next(self);
2565 }
2566
2567 // on dragger:
2568 .entity dragentity;
2569 .float draggravity;
2570 .float dragspeed; // speed of mouse wheel action
2571 .float dragdistance; // distance of dragentity's draglocalvector from view_ofs
2572 .vector draglocalvector; // local attachment vector of the dragentity
2573 .float draglocalangle;
2574 // on draggee:
2575 .entity draggedby;
2576 .float dragmovetype;
2577 void Drag_Begin(entity dragger, entity draggee, vector touchpoint)
2578 {
2579         float tagscale;
2580
2581         draggee.dragmovetype = draggee.movetype;
2582         draggee.draggravity = draggee.gravity;
2583         draggee.movetype = MOVETYPE_WALK;
2584         draggee.gravity = 0.00001;
2585         draggee.flags &~= FL_ONGROUND;
2586         draggee.draggedby = dragger;
2587
2588         dragger.dragentity = draggee;
2589
2590         dragger.dragdistance = vlen(touchpoint - dragger.origin - dragger.view_ofs);
2591         dragger.draglocalangle = draggee.angles_y - dragger.v_angle_y;
2592         touchpoint = touchpoint - gettaginfo(draggee, 0);
2593         tagscale = pow(vlen(v_forward), -2);
2594         dragger.draglocalvector_x = touchpoint * v_forward * tagscale;
2595         dragger.draglocalvector_y = touchpoint * v_right * tagscale;
2596         dragger.draglocalvector_z = touchpoint * v_up * tagscale;
2597
2598         dragger.dragspeed = 64;
2599 }
2600
2601 void Drag_Finish(entity dragger)
2602 {
2603         entity draggee;
2604         draggee = dragger.dragentity;
2605         if(dragger)
2606                 dragger.dragentity = world;
2607         draggee.draggedby = world;
2608         draggee.movetype = draggee.dragmovetype;
2609         draggee.gravity = draggee.draggravity;
2610
2611         switch(draggee.movetype)
2612         {
2613                 case MOVETYPE_TOSS:
2614                 case MOVETYPE_WALK:
2615                 case MOVETYPE_STEP:
2616                 case MOVETYPE_FLYMISSILE:
2617                 case MOVETYPE_BOUNCE:
2618                 case MOVETYPE_BOUNCEMISSILE:
2619                         break;
2620                 default:
2621                         draggee.velocity = '0 0 0';
2622                         break;
2623         }
2624
2625         if((draggee.flags & FL_ITEM) && (vlen(draggee.velocity) < 32))
2626         {
2627                 draggee.velocity = '0 0 0';
2628                 draggee.flags |= FL_ONGROUND; // floating items are FUN
2629         }
2630 }
2631
2632 float Drag_IsDraggable(entity draggee)
2633 {
2634         // TODO add more checks for bad stuff here
2635         if(draggee.classname == "func_bobbing")
2636                 return FALSE;
2637         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)
2638                 return FALSE;
2639         if(draggee.classname == "plat")
2640                 return FALSE;
2641         if(draggee.classname == "func_button")
2642                 return FALSE;
2643         if(draggee.model == "")
2644                 return FALSE;
2645         if(draggee.classname == "spectator")
2646                 return FALSE;
2647         if(draggee.classname == "observer")
2648                 return FALSE;
2649         if(draggee.classname == "exteriorweaponentity")
2650                 return FALSE;
2651
2652         return TRUE;
2653 }
2654
2655 float Drag_MayChangeAngles(entity draggee)
2656 {
2657         // TODO add more checks for bad stuff here
2658         if(substring(draggee.model, 0, 1) == "*")
2659                 return FALSE;
2660         return TRUE;
2661 }
2662
2663 void Drag_MoveForward(entity dragger)
2664 {
2665         dragger.dragdistance += dragger.dragspeed;
2666 }
2667
2668 void Drag_SetSpeed(entity dragger, float s)
2669 {
2670         dragger.dragspeed = pow(2, s);
2671 }
2672
2673 void Drag_MoveBackward(entity dragger)
2674 {
2675         dragger.dragdistance = max(0, dragger.dragdistance - dragger.dragspeed);
2676 }
2677
2678 void Drag_Update(entity dragger)
2679 {
2680         vector curorigin, neworigin, goodvelocity;
2681         float f;
2682         entity draggee;
2683
2684         draggee = dragger.dragentity;
2685         draggee.flags &~= FL_ONGROUND;
2686
2687         curorigin = gettaginfo(draggee, 0);
2688         curorigin = curorigin + v_forward * dragger.draglocalvector_x + v_right * dragger.draglocalvector_y + v_up * dragger.draglocalvector_z;
2689         makevectors(dragger.v_angle);
2690         neworigin = dragger.origin + dragger.view_ofs + v_forward * dragger.dragdistance;
2691         goodvelocity = (neworigin - curorigin) * (1 / frametime);
2692
2693         while(draggee.angles_y - dragger.v_angle_y - dragger.draglocalangle > 180)
2694                 dragger.draglocalangle += 360;
2695         while(draggee.angles_y - dragger.v_angle_y - dragger.draglocalangle <= -180)
2696                 dragger.draglocalangle -= 360;
2697
2698         f = min(frametime * 10, 1);
2699         draggee.velocity = draggee.velocity * (1 - f) + goodvelocity * f;
2700
2701         if(Drag_MayChangeAngles(draggee))
2702                 draggee.angles_y = draggee.angles_y * (1 - f) + (dragger.v_angle_y + dragger.draglocalangle) * f;
2703         
2704         draggee.ltime = max(servertime + serverframetime, draggee.ltime); // fixes func_train breakage
2705
2706         te_lightning1(dragger, dragger.origin + dragger.view_ofs, curorigin);
2707 }
2708
2709 float Drag_CanDrag(entity dragger)
2710 {
2711         return (dragger.deadflag == DEAD_NO) || (dragger.classname == "player");
2712 }
2713
2714 float Drag_IsDragging(entity dragger)
2715 {
2716         if(!dragger.dragentity)
2717                 return FALSE;
2718         if(wasfreed(dragger.dragentity) || dragger.dragentity.draggedby != dragger)
2719         {
2720                 dragger.dragentity = world;
2721                 return FALSE;
2722         }
2723         if(!Drag_CanDrag(dragger) || !Drag_IsDraggable(dragger.dragentity))
2724         {
2725                 Drag_Finish(dragger);
2726                 return FALSE;
2727         }
2728         return TRUE;
2729 }
2730
2731 void Drag_MoveDrag(entity from, entity to)
2732 {
2733         if(from.draggedby)
2734         {
2735                 to.draggedby = from.draggedby;
2736                 to.draggedby.dragentity = to;
2737                 from.draggedby = world;
2738         }
2739 }
2740
2741 /*
2742 =============
2743 PlayerPostThink
2744
2745 Called every frame for each client after the physics are run
2746 =============
2747 */
2748 .float idlekick_lasttimeleft;
2749 void PlayerPostThink (void)
2750 {
2751         // Savage: Check for nameless players
2752         if (strlen(self.netname) < 1) {
2753                 self.netname = "Player";
2754                 stuffcmd(self, "seta _cl_name Player\n");
2755         }
2756
2757         if(sv_maxidle && frametime)
2758         {
2759                 // WORKAROUND: only use dropclient in server frames (frametime set). Never use it in cl_movement frames (frametime zero).
2760                 float timeleft;
2761                 timeleft = ceil(sv_maxidle - (time - self.parm_idlesince));
2762                 if(timeleft <= 0)
2763                 {
2764                         bprint("^3", self.netname, "^3 was kicked for idling.\n");
2765                         announce(self, "announcer/robotic/terminated.wav");
2766                         dropclient(self);
2767                         return;
2768                 }
2769                 else if(timeleft <= 10)
2770                 {
2771                         if(timeleft != self.idlekick_lasttimeleft)
2772                         {
2773                                 centerprint_atprio(self, CENTERPRIO_IDLEKICK, strcat("^3Stop idling!\n^3Disconnecting in ", ftos(timeleft), "..."));
2774                                 announce(self, strcat("announcer/robotic/", ftos(timeleft), ".wav"));
2775                         }
2776                 }
2777                 else
2778                 {
2779                         centerprint_expire(self, CENTERPRIO_IDLEKICK);
2780                 }
2781                 self.idlekick_lasttimeleft = timeleft;
2782         }
2783
2784         if(sv_cheats || self.maycheat)
2785                 if(Drag_CanDrag(self))
2786                         if(self.BUTTON_DRAG)
2787                                 if(!self.dragentity)
2788                                         if(self.cursor_trace_ent)
2789                                                 if(Drag_IsDraggable(self.cursor_trace_ent))
2790                                                 {
2791                                                         if(self.cursor_trace_ent.draggedby)
2792                                                                 Drag_Finish(self.cursor_trace_ent.draggedby);
2793                                                         if(self.cursor_trace_ent.tag_entity)
2794                                                                 detach_sameorigin(self.cursor_trace_ent);
2795                                                         Drag_Begin(self, self.cursor_trace_ent, self.cursor_trace_endpos);
2796                                                 }
2797         
2798         if(Drag_IsDragging(self))
2799         {
2800                 if(self.BUTTON_DRAG)
2801                 {
2802                         if(self.impulse == 10 || self.impulse == 15 || self.impulse == 18)
2803                         {
2804                                 Drag_MoveForward(self);
2805                                 self.impulse = 0;
2806                         }
2807                         else if(self.impulse == 12 || self.impulse == 16 || self.impulse == 19)
2808                         {
2809                                 Drag_MoveBackward(self);
2810                                 self.impulse = 0;
2811                         }
2812                         else if(self.impulse >= 1 && self.impulse <= 9)
2813                         {
2814                                 Drag_SetSpeed(self, self.impulse - 1);
2815                         }
2816                         else if(self.impulse == 14)
2817                         {
2818                                 Drag_SetSpeed(self, 9);
2819                         }
2820
2821                         if(frametime)
2822                                 Drag_Update(self);
2823                 }
2824                 else
2825                 {
2826                         Drag_Finish(self);
2827                 }
2828         }
2829
2830         if(self.classname == "player") {
2831                 CheckRules_Player();
2832                 UpdateChatBubble();
2833                 UpdateTeamBubble();
2834                 if (self.impulse)
2835                         ImpulseCommands();
2836                 if (intermission_running)
2837                         return;         // intermission or finale
2838
2839                 //if (TetrisPostFrame()) return;
2840
2841                 GetPressedKeys();
2842         } else if (self.classname == "observer") {
2843                 //do nothing
2844         } else if (self.classname == "spectator") {
2845                 //do nothing
2846         }
2847
2848         /*
2849         float i;
2850         for(i = 0; i < 1000; ++i)
2851         {
2852                 vector end;
2853                 end = self.origin + '0 0 1024' + 512 * randomvec();
2854                 tracebox(self.origin, self.mins, self.maxs, end, MOVE_NORMAL, self);
2855                 if(trace_fraction < 1)
2856                 if(!(trace_dphitq3surfaceflags & Q3SURFACEFLAG_NOIMPACT))
2857                 {
2858                         print("I HIT SOLID: ", vtos(self.origin), " -> ", vtos(end), "\n");
2859                         break;
2860                 }
2861         }
2862         */
2863
2864         Arena_Warmup();
2865
2866         //pointparticles(particleeffectnum("machinegun_impact"), self.origin + self.view_ofs + '0 0 7', '0 0 0', 1);
2867
2868         if(self.waypointsprite_attachedforcarrier)
2869                 WaypointSprite_UpdateHealth(self.waypointsprite_attachedforcarrier, '1 0 0' * healtharmor_maxdamage(self.health, self.armorvalue, cvar("g_balance_armor_blockpercent")));
2870 }