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