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