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