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