]> git.xonotic.org Git - xonotic/xonotic-data.pk3dir.git/blob - qcsrc/server/client.qc
Some more defs.qh cleanup, update gameplay hash
[xonotic/xonotic-data.pk3dir.git] / qcsrc / server / client.qc
1 #include "client.qh"
2
3 #include <server/defs.qh>
4 #include <server/miscfunctions.qh>
5 #include <common/effects/all.qh>
6 #include "anticheat.qh"
7 #include "impulse.qh"
8 #include "player.qh"
9 #include "ipban.qh"
10 #include "miscfunctions.qh"
11 #include "portals.qh"
12 #include "teamplay.qh"
13 #include "spawnpoints.qh"
14 #include "resources.qh"
15 #include "g_damage.qh"
16 #include "handicap.qh"
17 #include "g_hook.qh"
18 #include "command/common.qh"
19 #include "command/vote.qh"
20 #include "clientkill.qh"
21 #include "cheats.qh"
22 #include "g_world.qh"
23 #include <server/gamelog.qh>
24 #include "race.qh"
25 #include <server/sv_main.qh>
26 #include "antilag.qh"
27 #include "campaign.qh"
28 #include "command/common.qh"
29 #include "scores_rules.qh"
30 #include "weapons/common.qh"
31
32 #include "bot/api.qh"
33
34 #include "../common/ent_cs.qh"
35 #include "../common/wepent.qh"
36 #include <common/state.qh>
37
38 #include "compat/quake3.qh"
39
40 #include <common/effects/qc/globalsound.qh>
41
42 #include "../common/mapobjects/func/conveyor.qh"
43 #include <common/mapobjects/func/ladder.qh>
44 #include "../common/mapobjects/teleporters.qh"
45 #include "../common/mapobjects/target/spawnpoint.qh"
46 #include <common/mapobjects/trigger/counter.qh>
47 #include <common/mapobjects/trigger/swamp.qh>
48
49 #include "../common/vehicles/all.qh"
50
51 #include "weapons/hitplot.qh"
52 #include "weapons/weaponsystem.qh"
53
54 #include "../common/net_notice.qh"
55 #include "../common/net_linked.qh"
56 #include "../common/physics/player.qh"
57
58 #include <common/vehicles/sv_vehicles.qh>
59
60 #include "../common/items/_mod.qh"
61
62 #include "../common/mutators/mutator/waypoints/all.qh"
63 #include "../common/mutators/mutator/instagib/sv_instagib.qh"
64 #include <common/gamemodes/_mod.qh>
65
66 #include "../common/mapobjects/subs.qh"
67 #include "../common/mapobjects/triggers.qh"
68 #include "../common/mapobjects/trigger/secret.qh"
69
70 #include "../common/minigames/sv_minigames.qh"
71
72 #include "../common/items/inventory.qh"
73
74 #include "../common/monsters/sv_monsters.qh"
75
76 #include "../lib/warpzone/server.qh"
77
78 #include <common/mutators/mutator/overkill/oknex.qh>
79
80 STATIC_METHOD(Client, Add, void(Client this, int _team))
81 {
82     ClientConnect(this);
83     TRANSMUTE(Player, this);
84     this.frame = 12; // 7
85     this.team = _team;
86     PutClientInServer(this);
87 }
88
89 STATIC_METHOD(Client, Remove, void(Client this))
90 {
91     TRANSMUTE(Observer, this);
92     PutClientInServer(this);
93     ClientDisconnect(this);
94 }
95
96 void send_CSQC_teamnagger() {
97         WriteHeader(MSG_BROADCAST, TE_CSQC_TEAMNAGGER);
98 }
99
100 int CountSpectators(entity player, entity to)
101 {
102         if(!player) { return 0; } // not sure how, but best to be safe
103
104         int spec_count = 0;
105
106         FOREACH_CLIENT(IS_REAL_CLIENT(it) && IS_SPEC(it) && it != to && it.enemy == player,
107         {
108                 spec_count++;
109         });
110
111         return spec_count;
112 }
113
114 void WriteSpectators(entity player, entity to)
115 {
116         if(!player) { return; } // not sure how, but best to be safe
117
118         FOREACH_CLIENT(IS_REAL_CLIENT(it) && IS_SPEC(it) && it != to && it.enemy == player,
119         {
120                 WriteByte(MSG_ENTITY, num_for_edict(it));
121         });
122 }
123
124 bool ClientData_Send(entity this, entity to, int sf)
125 {
126         assert(to == this.owner, return false);
127
128         entity e = to;
129         if (IS_SPEC(e)) e = e.enemy;
130
131         sf = 0;
132         if (CS(e).race_completed)       sf |= BIT(0); // forced scoreboard
133         if (CS(to).spectatee_status)    sf |= BIT(1); // spectator ent number follows
134         if (CS(e).zoomstate)            sf |= BIT(2); // zoomed
135         if (autocvar_sv_showspectators) sf |= BIT(4); // show spectators
136
137         WriteHeader(MSG_ENTITY, ENT_CLIENT_CLIENTDATA);
138         WriteByte(MSG_ENTITY, sf);
139
140         if (sf & BIT(1))
141                 WriteByte(MSG_ENTITY, CS(to).spectatee_status);
142
143         if(sf & BIT(4))
144         {
145                 float specs = CountSpectators(e, to);
146                 WriteByte(MSG_ENTITY, specs);
147                 WriteSpectators(e, to);
148         }
149
150         return true;
151 }
152
153 void ClientData_Attach(entity this)
154 {
155         Net_LinkEntity(CS(this).clientdata = new_pure(clientdata), false, 0, ClientData_Send);
156         CS(this).clientdata.drawonlytoclient = this;
157         CS(this).clientdata.owner = this;
158 }
159
160 void ClientData_Detach(entity this)
161 {
162         delete(CS(this).clientdata);
163         CS(this).clientdata = NULL;
164 }
165
166 void ClientData_Touch(entity e)
167 {
168         entity cd = CS(e).clientdata;
169         if (cd) { cd.SendFlags = 1; }
170
171         // make it spectatable
172         FOREACH_CLIENT(IS_REAL_CLIENT(it) && it != e && IS_SPEC(it) && it.enemy == e,
173         {
174                 entity cd = CS(it).clientdata;
175                 if (cd) { cd.SendFlags = 1; }
176         });
177 }
178
179
180 /*
181 =============
182 CheckPlayerModel
183
184 Checks if the argument string can be a valid playermodel.
185 Returns a valid one in doubt.
186 =============
187 */
188 string FallbackPlayerModel;
189 string CheckPlayerModel(string plyermodel) {
190         if(FallbackPlayerModel != cvar_defstring("_cl_playermodel"))
191         {
192                 // note: we cannot summon Don Strunzone here, some player may
193                 // still have the model string set. In case anyone manages how
194                 // to change a cvar default, we'll have a small leak here.
195                 FallbackPlayerModel = strzone(cvar_defstring("_cl_playermodel"));
196         }
197         // only in right path
198         if( substring(plyermodel,0,14) != "models/player/")
199                 return FallbackPlayerModel;
200         // only good file extensions
201         if(substring(plyermodel,-4,4) != ".zym")
202         if(substring(plyermodel,-4,4) != ".dpm")
203         if(substring(plyermodel,-4,4) != ".iqm")
204         if(substring(plyermodel,-4,4) != ".md3")
205         if(substring(plyermodel,-4,4) != ".psk")
206                 return FallbackPlayerModel;
207         // forbid the LOD models
208         if(substring(plyermodel, -9,5) == "_lod1")
209                 return FallbackPlayerModel;
210         if(substring(plyermodel, -9,5) == "_lod2")
211                 return FallbackPlayerModel;
212         if(plyermodel != strtolower(plyermodel))
213                 return FallbackPlayerModel;
214         // also, restrict to server models
215         if(autocvar_sv_servermodelsonly)
216         {
217                 if(!fexists(plyermodel))
218                         return FallbackPlayerModel;
219         }
220         return plyermodel;
221 }
222
223 void setplayermodel(entity e, string modelname)
224 {
225         precache_model(modelname);
226         _setmodel(e, modelname);
227         player_setupanimsformodel(e);
228         if(!autocvar_g_debug_globalsounds)
229                 UpdatePlayerSounds(e);
230 }
231
232 /** putting a client as observer in the server */
233 void PutObserverInServer(entity this)
234 {
235     bool mutator_returnvalue = MUTATOR_CALLHOOK(MakePlayerObserver, this);
236         PlayerState_detach(this);
237
238         if (IS_PLAYER(this))
239         {
240                 if(GetResource(this, RES_HEALTH) >= 1)
241                 {
242                         // despawn effect
243                         Send_Effect(EFFECT_SPAWN_NEUTRAL, this.origin, '0 0 0', 1);
244                 }
245
246                 // was a player, recount votes and ready status
247                 if(IS_REAL_CLIENT(this))
248                 {
249                         if (vote_called) { VoteCount(false); }
250                         ReadyCount();
251                 }
252     }
253
254     {
255         entity spot = SelectSpawnPoint(this, true);
256         if (!spot) LOG_FATAL("No spawnpoints for observers?!?");
257         this.angles = vec2(spot.angles);
258         this.fixangle = true;
259         // offset it so that the spectator spawns higher off the ground, looks better this way
260         setorigin(this, spot.origin + STAT(PL_VIEW_OFS, this));
261         if (IS_REAL_CLIENT(this))
262         {
263             msg_entity = this;
264             WriteByte(MSG_ONE, SVC_SETVIEW);
265             WriteEntity(MSG_ONE, this);
266         }
267         // give the spectator some space between walls for MOVETYPE_FLY_WORLDONLY
268         // so that your view doesn't go into the ceiling with MOVETYPE_FLY_WORLDONLY, previously "PL_VIEW_OFS"
269         if(!autocvar_g_debug_globalsounds)
270         {
271                 // needed for player sounds
272                 this.model = "";
273                 FixPlayermodel(this);
274         }
275         setmodel(this, MDL_Null);
276         setsize(this, STAT(PL_CROUCH_MIN, this), STAT(PL_CROUCH_MAX, this));
277         this.view_ofs = '0 0 0';
278     }
279
280     RemoveGrapplingHooks(this);
281         Portal_ClearAll(this);
282         Unfreeze(this, false);
283         SetSpectatee(this, NULL);
284
285         if (this.alivetime)
286         {
287                 if (!warmup_stage)
288                         PlayerStats_GameReport_Event_Player(this, PLAYERSTATS_ALIVETIME, time - this.alivetime);
289                 this.alivetime = 0;
290         }
291
292         if (this.vehicle) vehicles_exit(this.vehicle, VHEF_RELEASE);
293
294         WaypointSprite_PlayerDead(this);
295
296         if (CS(this).killcount != FRAGS_SPECTATOR)
297         {
298                 if(!game_stopped)
299                 if(autocvar_g_chat_nospectators == 1 || (!warmup_stage && autocvar_g_chat_nospectators == 2))
300                         Send_Notification(NOTIF_ONE_ONLY, this, MSG_INFO, INFO_CHAT_NOSPECTATORS);
301         }
302
303         accuracy_resend(this);
304
305         CS(this).spectatortime = time;
306         if(this.bot_attack)
307                 IL_REMOVE(g_bot_targets, this);
308         this.bot_attack = false;
309         if(this.monster_attack)
310                 IL_REMOVE(g_monster_targets, this);
311         this.monster_attack = false;
312     STAT(HUD, this) = HUD_NORMAL;
313         TRANSMUTE(Observer, this);
314         this.iscreature = false;
315         this.teleportable = TELEPORT_SIMPLE;
316         if(this.damagedbycontents)
317                 IL_REMOVE(g_damagedbycontents, this);
318         this.damagedbycontents = false;
319         SetResourceExplicit(this, RES_HEALTH, FRAGS_SPECTATOR);
320         SetSpectatee_status(this, etof(this));
321         this.takedamage = DAMAGE_NO;
322         this.solid = SOLID_NOT;
323         set_movetype(this, MOVETYPE_FLY_WORLDONLY); // user preference is controlled by playerprethink
324         this.flags = FL_CLIENT | FL_NOTARGET;
325         this.effects = 0;
326         SetResourceExplicit(this, RES_ARMOR, autocvar_g_balance_armor_start); // was 666?!
327         this.pauserotarmor_finished = 0;
328         this.pauserothealth_finished = 0;
329         this.pauseregen_finished = 0;
330         this.damageforcescale = 0;
331         this.death_time = 0;
332         this.respawn_flags = 0;
333         this.respawn_time = 0;
334         STAT(RESPAWN_TIME, this) = 0;
335         this.alpha = 0;
336         this.scale = 0;
337         this.fade_time = 0;
338         this.pain_frame = 0;
339         this.pain_finished = 0;
340         STAT(STRENGTH_FINISHED, this) = 0;
341         STAT(INVINCIBLE_FINISHED, this) = 0;
342         STAT(SUPERWEAPONS_FINISHED, this) = 0;
343         STAT(AIR_FINISHED, this) = 0;
344         //this.dphitcontentsmask = 0;
345         this.dphitcontentsmask = DPCONTENTS_SOLID;
346         if (autocvar_g_playerclip_collisions)
347                 this.dphitcontentsmask |= DPCONTENTS_PLAYERCLIP;
348         this.pushltime = 0;
349         this.istypefrag = 0;
350         setthink(this, func_null);
351         this.nextthink = 0;
352         this.deadflag = DEAD_NO;
353         UNSET_DUCKED(this);
354         STAT(REVIVE_PROGRESS, this) = 0;
355         this.revival_time = 0;
356         this.draggable = drag_undraggable;
357
358         this.items = 0;
359         STAT(WEAPONS, this) = '0 0 0';
360         this.drawonlytoclient = this;
361
362         this.viewloc = NULL;
363
364         //this.spawnpoint_targ = NULL; // keep it so they can return to where they were?
365
366         this.weaponmodel = "";
367         for (int slot = 0; slot < MAX_WEAPONSLOTS; ++slot)
368         {
369                 this.weaponentities[slot] = NULL;
370         }
371         this.exteriorweaponentity = NULL;
372         CS(this).killcount = FRAGS_SPECTATOR;
373         this.velocity = '0 0 0';
374         this.avelocity = '0 0 0';
375         this.punchangle = '0 0 0';
376         this.punchvector = '0 0 0';
377         this.oldvelocity = this.velocity;
378         this.fire_endtime = -1;
379         this.event_damage = func_null;
380         this.event_heal = func_null;
381
382         for(int slot = 0; slot < MAX_AXH; ++slot)
383         {
384                 entity axh = this.(AuxiliaryXhair[slot]);
385                 this.(AuxiliaryXhair[slot]) = NULL;
386
387                 if(axh.owner == this && axh != NULL && !wasfreed(axh))
388                         delete(axh);
389         }
390
391         if (mutator_returnvalue)
392         {
393                 // mutator prevents resetting teams+score
394         }
395         else
396         {
397                 SetPlayerTeam(this, -1, TEAM_CHANGE_SPECTATOR);
398                 this.frags = FRAGS_SPECTATOR;
399         }
400         if (CS(this).just_joined)
401                 CS(this).just_joined = false;
402 }
403
404 int player_getspecies(entity this)
405 {
406         get_model_parameters(this.model, this.skin);
407         int s = get_model_parameters_species;
408         get_model_parameters(string_null, 0);
409         if (s < 0) return SPECIES_HUMAN;
410         return s;
411 }
412
413 .float model_randomizer;
414 void FixPlayermodel(entity player)
415 {
416         string defaultmodel = "";
417         int defaultskin = 0;
418         if(autocvar_sv_defaultcharacter)
419         {
420                 if(teamplay)
421                 {
422                         switch(player.team)
423                         {
424                                 case NUM_TEAM_1: defaultmodel = autocvar_sv_defaultplayermodel_red; defaultskin = autocvar_sv_defaultplayerskin_red; break;
425                                 case NUM_TEAM_2: defaultmodel = autocvar_sv_defaultplayermodel_blue; defaultskin = autocvar_sv_defaultplayerskin_blue; break;
426                                 case NUM_TEAM_3: defaultmodel = autocvar_sv_defaultplayermodel_yellow; defaultskin = autocvar_sv_defaultplayerskin_yellow; break;
427                                 case NUM_TEAM_4: defaultmodel = autocvar_sv_defaultplayermodel_pink; defaultskin = autocvar_sv_defaultplayerskin_pink; break;
428                         }
429                 }
430
431                 if(defaultmodel == "")
432                 {
433                         defaultmodel = autocvar_sv_defaultplayermodel;
434                         defaultskin = autocvar_sv_defaultplayerskin;
435                 }
436
437                 int n = tokenize_console(defaultmodel);
438                 if(n > 0)
439                 {
440                         defaultmodel = argv(floor(n * CS(player).model_randomizer));
441                         // However, do NOT randomize if the player-selected model is in the list.
442                         for (int i = 0; i < n; ++i)
443                                 if ((argv(i) == player.playermodel && defaultskin == stof(player.playerskin)) || argv(i) == strcat(player.playermodel, ":", player.playerskin))
444                                         defaultmodel = argv(i);
445                 }
446
447                 int i = strstrofs(defaultmodel, ":", 0);
448                 if(i >= 0)
449                 {
450                         defaultskin = stof(substring(defaultmodel, i+1, -1));
451                         defaultmodel = substring(defaultmodel, 0, i);
452                 }
453         }
454         if(autocvar_sv_defaultcharacterskin && !defaultskin)
455         {
456                 if(teamplay)
457                 {
458                         switch(player.team)
459                         {
460                                 case NUM_TEAM_1: defaultskin = autocvar_sv_defaultplayerskin_red; break;
461                                 case NUM_TEAM_2: defaultskin = autocvar_sv_defaultplayerskin_blue; break;
462                                 case NUM_TEAM_3: defaultskin = autocvar_sv_defaultplayerskin_yellow; break;
463                                 case NUM_TEAM_4: defaultskin = autocvar_sv_defaultplayerskin_pink; break;
464                         }
465                 }
466
467                 if(!defaultskin)
468                         defaultskin = autocvar_sv_defaultplayerskin;
469         }
470
471         MUTATOR_CALLHOOK(FixPlayermodel, defaultmodel, defaultskin, player);
472         defaultmodel = M_ARGV(0, string);
473         defaultskin = M_ARGV(1, int);
474
475         bool chmdl = false;
476         int oldskin;
477         if(defaultmodel != "")
478         {
479                 if (defaultmodel != player.model)
480                 {
481                         vector m1 = player.mins;
482                         vector m2 = player.maxs;
483                         setplayermodel (player, defaultmodel);
484                         setsize (player, m1, m2);
485                         chmdl = true;
486                 }
487
488                 oldskin = player.skin;
489                 player.skin = defaultskin;
490         } else {
491                 if (player.playermodel != player.model || player.playermodel == "")
492                 {
493                         player.playermodel = CheckPlayerModel(player.playermodel); // this is never "", so no endless loop
494                         vector m1 = player.mins;
495                         vector m2 = player.maxs;
496                         setplayermodel (player, player.playermodel);
497                         setsize (player, m1, m2);
498                         chmdl = true;
499                 }
500
501                 if(!autocvar_sv_defaultcharacterskin)
502                 {
503                         oldskin = player.skin;
504                         player.skin = stof(player.playerskin);
505                 }
506                 else
507                 {
508                         oldskin = player.skin;
509                         player.skin = defaultskin;
510                 }
511         }
512
513         if(chmdl || oldskin != player.skin) // model or skin has changed
514         {
515                 player.species = player_getspecies(player); // update species
516                 if(!autocvar_g_debug_globalsounds)
517                         UpdatePlayerSounds(player); // update skin sounds
518         }
519
520         if(!teamplay)
521                 if(strlen(autocvar_sv_defaultplayercolors))
522                         if(player.clientcolors != stof(autocvar_sv_defaultplayercolors))
523                                 setcolor(player, stof(autocvar_sv_defaultplayercolors));
524 }
525
526 void PutPlayerInServer(entity this)
527 {
528         if (this.vehicle) vehicles_exit(this.vehicle, VHEF_RELEASE);
529
530         PlayerState_attach(this);
531         accuracy_resend(this);
532
533         if (this.team < 0)
534                 TeamBalance_JoinBestTeam(this);
535
536         entity spot = SelectSpawnPoint(this, false);
537         if (!spot) {
538                 Send_Notification(NOTIF_ONE_ONLY, this, MSG_CENTER, CENTER_JOIN_NOSPAWNS);
539                 return; // spawn failed
540         }
541
542         TRANSMUTE(Player, this);
543
544         CS(this).wasplayer = true;
545         this.iscreature = true;
546         this.teleportable = TELEPORT_NORMAL;
547         if(!this.damagedbycontents)
548                 IL_PUSH(g_damagedbycontents, this);
549         this.damagedbycontents = true;
550         set_movetype(this, MOVETYPE_WALK);
551         this.solid = SOLID_SLIDEBOX;
552         this.dphitcontentsmask = DPCONTENTS_BODY | DPCONTENTS_SOLID;
553         if (autocvar_g_playerclip_collisions)
554                 this.dphitcontentsmask |= DPCONTENTS_PLAYERCLIP;
555         if (IS_BOT_CLIENT(this) && autocvar_g_botclip_collisions)
556                 this.dphitcontentsmask |= DPCONTENTS_BOTCLIP;
557         this.frags = FRAGS_PLAYER;
558         if (INDEPENDENT_PLAYERS) MAKE_INDEPENDENT_PLAYER(this);
559         this.flags = FL_CLIENT | FL_PICKUPITEMS;
560         if (autocvar__notarget)
561                 this.flags |= FL_NOTARGET;
562         this.takedamage = DAMAGE_AIM;
563         this.effects = EF_TELEPORT_BIT | EF_RESTARTANIM_BIT;
564
565         if (warmup_stage) {
566                 SetResource(this, RES_SHELLS, warmup_start_ammo_shells);
567                 SetResource(this, RES_BULLETS, warmup_start_ammo_nails);
568                 SetResource(this, RES_ROCKETS, warmup_start_ammo_rockets);
569                 SetResource(this, RES_CELLS, warmup_start_ammo_cells);
570                 SetResource(this, RES_PLASMA, warmup_start_ammo_plasma);
571                 SetResource(this, RES_FUEL, warmup_start_ammo_fuel);
572                 SetResource(this, RES_HEALTH, warmup_start_health);
573                 SetResource(this, RES_ARMOR, warmup_start_armorvalue);
574                 STAT(WEAPONS, this) = WARMUP_START_WEAPONS;
575         } else {
576                 SetResource(this, RES_SHELLS, start_ammo_shells);
577                 SetResource(this, RES_BULLETS, start_ammo_nails);
578                 SetResource(this, RES_ROCKETS, start_ammo_rockets);
579                 SetResource(this, RES_CELLS, start_ammo_cells);
580                 SetResource(this, RES_PLASMA, start_ammo_plasma);
581                 SetResource(this, RES_FUEL, start_ammo_fuel);
582                 SetResource(this, RES_HEALTH, start_health);
583                 SetResource(this, RES_ARMOR, start_armorvalue);
584                 STAT(WEAPONS, this) = start_weapons;
585                 if (MUTATOR_CALLHOOK(ForbidRandomStartWeapons, this) == false)
586                 {
587                         GiveRandomWeapons(this, random_start_weapons_count,
588                                 autocvar_g_random_start_weapons, random_start_ammo);
589                 }
590         }
591         SetSpectatee_status(this, 0);
592
593         PS(this).dual_weapons = '0 0 0';
594
595         STAT(SUPERWEAPONS_FINISHED, this) = (STAT(WEAPONS, this) & WEPSET_SUPERWEAPONS) ? time + autocvar_g_balance_superweapons_time : 0;
596
597         this.items = start_items;
598
599         this.spawnshieldtime = time + autocvar_g_spawnshieldtime;
600         this.pauserotarmor_finished = time + autocvar_g_balance_pause_armor_rot_spawn;
601         this.pauserothealth_finished = time + autocvar_g_balance_pause_health_rot_spawn;
602         this.pauserotfuel_finished = time + autocvar_g_balance_pause_fuel_rot_spawn;
603         this.pauseregen_finished = time + autocvar_g_balance_pause_health_regen_spawn;
604         if (!sv_ready_restart_after_countdown && time < game_starttime)
605         {
606                 float f = game_starttime - time;
607                 this.spawnshieldtime += f;
608                 this.pauserotarmor_finished += f;
609                 this.pauserothealth_finished += f;
610                 this.pauseregen_finished += f;
611         }
612
613         this.damageforcescale = autocvar_g_player_damageforcescale;
614         this.death_time = 0;
615         this.respawn_flags = 0;
616         this.respawn_time = 0;
617         STAT(RESPAWN_TIME, this) = 0;
618         bool q3dfcompat = autocvar_sv_q3defragcompat && autocvar_sv_q3defragcompat_changehitbox;
619         this.scale = ((q3dfcompat) ? 0.9 : autocvar_sv_player_scale);
620         this.fade_time = 0;
621         this.pain_frame = 0;
622         this.pain_finished = 0;
623         this.pushltime = 0;
624         setthink(this, func_null); // players have no think function
625         this.nextthink = 0;
626         this.dmg_team = 0;
627         PS(this).ballistics_density = autocvar_g_ballistics_density_player;
628
629         this.deadflag = DEAD_NO;
630
631         this.angles = spot.angles;
632         this.angles_z = 0; // never spawn tilted even if the spot says to
633         if (IS_BOT_CLIENT(this))
634         {
635                 this.v_angle = this.angles;
636                 bot_aim_reset(this);
637         }
638         this.fixangle = true; // turn this way immediately
639         this.oldvelocity = this.velocity = '0 0 0';
640         this.avelocity = '0 0 0';
641         this.punchangle = '0 0 0';
642         this.punchvector = '0 0 0';
643
644         STAT(STRENGTH_FINISHED, this) = 0;
645         STAT(INVINCIBLE_FINISHED, this) = 0;
646         this.fire_endtime = -1;
647         STAT(REVIVE_PROGRESS, this) = 0;
648         this.revival_time = 0;
649
650         // TODO: we can't set these in the PlayerSpawn hook since the target code is called before it!
651         STAT(BUFFS, this) = 0;
652         STAT(BUFF_TIME, this) = 0;
653
654         STAT(AIR_FINISHED, this) = 0;
655         this.waterlevel = WATERLEVEL_NONE;
656         this.watertype = CONTENT_EMPTY;
657
658         entity spawnevent = new_pure(spawnevent);
659         spawnevent.owner = this;
660         Net_LinkEntity(spawnevent, false, 0.5, SpawnEvent_Send);
661
662         // Cut off any still running player sounds.
663         stopsound(this, CH_PLAYER_SINGLE);
664
665         this.model = "";
666         FixPlayermodel(this);
667         this.drawonlytoclient = NULL;
668
669         this.viewloc = NULL;
670
671         for(int slot = 0; slot < MAX_AXH; ++slot)
672         {
673                 entity axh = this.(AuxiliaryXhair[slot]);
674                 this.(AuxiliaryXhair[slot]) = NULL;
675
676                 if(axh.owner == this && axh != NULL && !wasfreed(axh))
677                         delete(axh);
678         }
679
680         this.spawnpoint_targ = NULL;
681
682         UNSET_DUCKED(this);
683         this.view_ofs = STAT(PL_VIEW_OFS, this);
684         setsize(this, STAT(PL_MIN, this), STAT(PL_MAX, this));
685         this.spawnorigin = spot.origin;
686         setorigin(this, spot.origin + '0 0 1' * (1 - this.mins.z - 24));
687         // don't reset back to last position, even if new position is stuck in solid
688         this.oldorigin = this.origin;
689         if(this.conveyor)
690                 IL_REMOVE(g_conveyed, this);
691         this.conveyor = NULL; // prevent conveyors at the previous location from moving a freshly spawned player
692         if(this.swampslug)
693                 IL_REMOVE(g_swamped, this);
694         this.swampslug = NULL;
695         this.swamp_interval = 0;
696         if(this.ladder_entity)
697                 IL_REMOVE(g_ladderents, this);
698         this.ladder_entity = NULL;
699         IL_EACH(g_counters, it.realowner == this,
700         {
701                 delete(it);
702         });
703         STAT(HUD, this) = HUD_NORMAL;
704
705         this.event_damage = PlayerDamage;
706         this.event_heal = PlayerHeal;
707
708         this.draggable = func_null;
709
710         if(!this.bot_attack)
711                 IL_PUSH(g_bot_targets, this);
712         this.bot_attack = true;
713         if(!this.monster_attack)
714                 IL_PUSH(g_monster_targets, this);
715         this.monster_attack = true;
716         navigation_dynamicgoal_init(this, false);
717
718         PHYS_INPUT_BUTTON_ATCK(this) = PHYS_INPUT_BUTTON_JUMP(this) = PHYS_INPUT_BUTTON_ATCK2(this) = false;
719
720         // player was spectator
721         if (CS(this).killcount == FRAGS_SPECTATOR) {
722                 PlayerScore_Clear(this);
723                 CS(this).killcount = 0;
724                 CS(this).startplaytime = time;
725         }
726
727         for (int slot = 0; slot < MAX_WEAPONSLOTS; ++slot)
728         {
729                 .entity weaponentity = weaponentities[slot];
730                 CL_SpawnWeaponentity(this, weaponentity);
731         }
732         this.alpha = default_player_alpha;
733         this.colormod = '1 1 1' * autocvar_g_player_brightness;
734         this.exteriorweaponentity.alpha = default_weapon_alpha;
735
736         this.speedrunning = false;
737
738         this.counter_cnt = 0;
739         this.fragsfilter_cnt = 0;
740
741         target_voicescript_clear(this);
742
743         // reset fields the weapons may use
744         FOREACH(Weapons, true, {
745                 it.wr_resetplayer(it, this);
746                         // reload all reloadable weapons
747                 if (it.spawnflags & WEP_FLAG_RELOADABLE) {
748                         for(int slot = 0; slot < MAX_WEAPONSLOTS; ++slot)
749                         {
750                                 .entity weaponentity = weaponentities[slot];
751                                 this.(weaponentity).weapon_load[it.m_id] = it.reloading_ammo;
752                         }
753                 }
754         });
755
756         {
757                 string s = spot.target;
758                 if(g_assault || g_race) // TODO: make targeting work in assault & race without this hack
759                         spot.target = string_null;
760                 SUB_UseTargets(spot, this, NULL);
761                 if(g_assault || g_race)
762                         spot.target = s;
763         }
764
765         Unfreeze(this, false);
766
767         MUTATOR_CALLHOOK(PlayerSpawn, this, spot);
768
769         if (autocvar_spawn_debug)
770         {
771                 sprint(this, strcat("spawnpoint origin:  ", vtos(spot.origin), "\n"));
772                 delete(spot); // usefull for checking if there are spawnpoints, that let drop through the floor
773         }
774
775         for(int slot = 0; slot < MAX_WEAPONSLOTS; ++slot)
776         {
777                 .entity weaponentity = weaponentities[slot];
778                 if(slot == 0 || autocvar_g_weaponswitch_debug == 1)
779                         this.(weaponentity).m_switchweapon = w_getbestweapon(this, weaponentity);
780                 else
781                         this.(weaponentity).m_switchweapon = WEP_Null;
782                 this.(weaponentity).m_weapon = WEP_Null;
783                 this.(weaponentity).weaponname = "";
784                 this.(weaponentity).m_switchingweapon = WEP_Null;
785                 this.(weaponentity).cnt = -1;
786         }
787
788         MUTATOR_CALLHOOK(PlayerWeaponSelect, this);
789
790         if (CS(this).impulse) ImpulseCommands(this);
791
792         W_ResetGunAlign(this, CS(this).cvar_cl_gunalign);
793         for(int slot = 0; slot < MAX_WEAPONSLOTS; ++slot)
794         {
795                 .entity weaponentity = weaponentities[slot];
796                 W_WeaponFrame(this, weaponentity);
797         }
798
799         if (!warmup_stage && !this.alivetime)
800                 this.alivetime = time;
801
802         antilag_clear(this, CS(this));
803 }
804
805 /** Called when a client spawns in the server */
806 void PutClientInServer(entity this)
807 {
808         if (IS_BOT_CLIENT(this)) {
809                 TRANSMUTE(Player, this);
810         } else if (IS_REAL_CLIENT(this)) {
811                 msg_entity = this;
812                 WriteByte(MSG_ONE, SVC_SETVIEW);
813                 WriteEntity(MSG_ONE, this);
814         }
815         if (game_stopped)
816                 TRANSMUTE(Observer, this);
817
818         SetSpectatee(this, NULL);
819
820         // reset player keys
821         if(PS(this))
822                 PS(this).itemkeys = 0;
823
824         MUTATOR_CALLHOOK(PutClientInServer, this);
825
826         if (IS_OBSERVER(this)) {
827                 PutObserverInServer(this);
828         } else if (IS_PLAYER(this)) {
829                 PutPlayerInServer(this);
830         }
831 }
832
833 // TODO do we need all these fields, or should we stop autodetecting runtime
834 // changes and just have a console command to update this?
835 bool ClientInit_SendEntity(entity this, entity to, int sf)
836 {
837         WriteHeader(MSG_ENTITY, _ENT_CLIENT_INIT);
838         return = true;
839         msg_entity = to;
840         // MSG_INIT replacement
841         // TODO: make easier to use
842         Registry_send_all();
843         W_PROP_reload(MSG_ONE, to);
844         ClientInit_misc(this);
845         MUTATOR_CALLHOOK(Ent_Init);
846 }
847 void ClientInit_misc(entity this)
848 {
849         int channel = MSG_ONE;
850         WriteHeader(channel, ENT_CLIENT_INIT);
851         WriteByte(channel, g_nexball_meter_period * 32);
852         WriteInt24_t(channel, compressShotOrigin(hook_shotorigin[0]));
853         WriteInt24_t(channel, compressShotOrigin(hook_shotorigin[1]));
854         WriteInt24_t(channel, compressShotOrigin(hook_shotorigin[2]));
855         WriteInt24_t(channel, compressShotOrigin(hook_shotorigin[3]));
856         WriteInt24_t(channel, compressShotOrigin(arc_shotorigin[0]));
857         WriteInt24_t(channel, compressShotOrigin(arc_shotorigin[1]));
858         WriteInt24_t(channel, compressShotOrigin(arc_shotorigin[2]));
859         WriteInt24_t(channel, compressShotOrigin(arc_shotorigin[3]));
860
861         if(sv_foginterval && world.fog != "")
862                 WriteString(channel, world.fog);
863         else
864                 WriteString(channel, "");
865         WriteByte(channel, this.count * 255.0); // g_balance_armor_blockpercent
866         WriteByte(channel, this.cnt * 255.0); // g_balance_damagepush_speedfactor
867         WriteByte(channel, serverflags);
868         WriteCoord(channel, autocvar_g_trueaim_minrange);
869 }
870
871 void ClientInit_CheckUpdate(entity this)
872 {
873         this.nextthink = time;
874         if(this.count != autocvar_g_balance_armor_blockpercent)
875         {
876                 this.count = autocvar_g_balance_armor_blockpercent;
877                 this.SendFlags |= 1;
878         }
879         if(this.cnt != autocvar_g_balance_damagepush_speedfactor)
880         {
881                 this.cnt = autocvar_g_balance_damagepush_speedfactor;
882                 this.SendFlags |= 1;
883         }
884 }
885
886 void ClientInit_Spawn()
887 {
888         entity e = new_pure(clientinit);
889         setthink(e, ClientInit_CheckUpdate);
890         Net_LinkEntity(e, false, 0, ClientInit_SendEntity);
891
892         ClientInit_CheckUpdate(e);
893 }
894
895 /*
896 =============
897 SetNewParms
898 =============
899 */
900 void SetNewParms ()
901 {
902         // initialize parms for a new player
903         parm1 = -(86400 * 366);
904
905         MUTATOR_CALLHOOK(SetNewParms);
906 }
907
908 /*
909 =============
910 SetChangeParms
911 =============
912 */
913 void SetChangeParms (entity this)
914 {
915         // save parms for level change
916         parm1 = CS(this).parm_idlesince - time;
917
918         MUTATOR_CALLHOOK(SetChangeParms);
919 }
920
921 /*
922 =============
923 DecodeLevelParms
924 =============
925 */
926 void DecodeLevelParms(entity this)
927 {
928         // load parms
929         CS(this).parm_idlesince = parm1;
930         if (CS(this).parm_idlesince == -(86400 * 366))
931                 CS(this).parm_idlesince = time;
932
933         // whatever happens, allow 60 seconds of idling directly after connect for map loading
934         CS(this).parm_idlesince = max(CS(this).parm_idlesince, time - sv_maxidle + 60);
935
936         MUTATOR_CALLHOOK(DecodeLevelParms);
937 }
938
939 void FixClientCvars(entity e)
940 {
941         // send prediction settings to the client
942         stuffcmd(e, "\nin_bindmap 0 0\n");
943         if(autocvar_g_antilag == 3) // client side hitscan
944                 stuffcmd(e, "cl_cmd settemp cl_prydoncursor_notrace 0\n");
945         if(autocvar_sv_gentle)
946                 stuffcmd(e, "cl_cmd settemp cl_gentle 1\n");
947
948         stuffcmd(e, sprintf("\ncl_jumpspeedcap_min \"%s\"\n", autocvar_sv_jumpspeedcap_min));
949         stuffcmd(e, sprintf("\ncl_jumpspeedcap_max \"%s\"\n", autocvar_sv_jumpspeedcap_max));
950
951         stuffcmd(e, sprintf("\ncl_shootfromfixedorigin \"%s\"\n", autocvar_g_shootfromfixedorigin));
952
953         MUTATOR_CALLHOOK(FixClientCvars, e);
954 }
955
956 bool findinlist_abbrev(string tofind, string list)
957 {
958         if(list == "" || tofind == "")
959                 return false; // empty list or search, just return
960
961         // this function allows abbreviated strings!
962         FOREACH_WORD(list, it == substring(tofind, 0, strlen(it)),
963         {
964                 return true;
965         });
966
967         return false;
968 }
969
970 bool PlayerInIPList(entity p, string iplist)
971 {
972         // some safety checks (never allow local?)
973         if(p.netaddress == "local" || p.netaddress == "" || !IS_REAL_CLIENT(p))
974                 return false;
975
976         return findinlist_abbrev(p.netaddress, iplist);
977 }
978
979 bool PlayerInIDList(entity p, string idlist)
980 {
981         // NOTE: we do NOT check crypto_idfp_signed here, an unsigned ID is fine too for this
982         if(!p.crypto_idfp)
983                 return false;
984
985         return findinlist_abbrev(p.crypto_idfp, idlist);
986 }
987
988 bool PlayerInList(entity player, string list)
989 {
990         return boolean(PlayerInIDList(player, list) || PlayerInIPList(player, list));
991 }
992
993 #ifdef DP_EXT_PRECONNECT
994 /*
995 =============
996 ClientPreConnect
997
998 Called once (not at each match start) when a client begins a connection to the server
999 =============
1000 */
1001 void ClientPreConnect(entity this)
1002 {
1003         if(autocvar_sv_eventlog)
1004         {
1005                 GameLogEcho(sprintf(":connect:%d:%d:%s",
1006                         this.playerid,
1007                         etof(this),
1008                         ((IS_REAL_CLIENT(this)) ? this.netaddress : "bot")
1009                 ));
1010         }
1011 }
1012 #endif
1013
1014 string GetClientVersionMessage(entity this)
1015 {
1016         if (CS(this).version_mismatch) {
1017                 if(CS(this).version < autocvar_gameversion) {
1018                         return strcat("This is Xonotic ", autocvar_g_xonoticversion,
1019                                 "\n^3Your client version is outdated.\n\n\n### YOU WON'T BE ABLE TO PLAY ON THIS SERVER ###\n\n\nPlease update!!!^8");
1020                 } else {
1021                         return strcat("This is Xonotic ", autocvar_g_xonoticversion,
1022                                 "\n^3This server is using an outdated Xonotic version.\n\n\n ### THIS SERVER IS INCOMPATIBLE AND THUS YOU CANNOT JOIN ###.^8");
1023                 }
1024         } else {
1025                 return strcat("Welcome to Xonotic ", autocvar_g_xonoticversion);
1026         }
1027 }
1028
1029 string getwelcomemessage(entity this)
1030 {
1031         MUTATOR_CALLHOOK(BuildMutatorsPrettyString, "");
1032         string modifications = M_ARGV(0, string);
1033
1034         if(g_weaponarena)
1035         {
1036                 if(g_weaponarena_random)
1037                         modifications = strcat(modifications, ", ", ftos(g_weaponarena_random), " of ", g_weaponarena_list, " Arena");
1038                 else
1039                         modifications = strcat(modifications, ", ", g_weaponarena_list, " Arena");
1040         }
1041         else if(cvar("g_balance_blaster_weaponstartoverride") == 0)
1042                 modifications = strcat(modifications, ", No start weapons");
1043         if(cvar("sv_gravity") < stof(cvar_defstring("sv_gravity")))
1044                 modifications = strcat(modifications, ", Low gravity");
1045         if(g_weapon_stay && !g_cts)
1046                 modifications = strcat(modifications, ", Weapons stay");
1047         if(g_jetpack)
1048                 modifications = strcat(modifications, ", Jet pack");
1049         if(autocvar_g_powerups == 0)
1050                 modifications = strcat(modifications, ", No powerups");
1051         if(autocvar_g_powerups > 0)
1052                 modifications = strcat(modifications, ", Powerups");
1053         modifications = substring(modifications, 2, strlen(modifications) - 2);
1054
1055         string versionmessage = GetClientVersionMessage(this);
1056         string s = strcat(versionmessage, "^8\n^8\nhost is ^9", autocvar_hostname, "^8\n");
1057
1058         s = strcat(s, "^8\nmatch type is ^1", gamemode_name, "^8\n");
1059
1060         if(modifications != "")
1061                 s = strcat(s, "^8\nactive modifications: ^3", modifications, "^8\n");
1062
1063         if(cache_lastmutatormsg != autocvar_g_mutatormsg)
1064         {
1065                 strcpy(cache_lastmutatormsg, autocvar_g_mutatormsg);
1066                 strcpy(cache_mutatormsg, cache_lastmutatormsg);
1067         }
1068
1069         if (cache_mutatormsg != "") {
1070                 s = strcat(s, "\n\n^8special gameplay tips: ^7", cache_mutatormsg);
1071         }
1072
1073         string mutator_msg = "";
1074         MUTATOR_CALLHOOK(BuildGameplayTipsString, mutator_msg);
1075         mutator_msg = M_ARGV(0, string);
1076
1077         s = strcat(s, mutator_msg); // trust that the mutator will do proper formatting
1078
1079         string motd = autocvar_sv_motd;
1080         if (motd != "") {
1081                 s = strcat(s, "\n\n^8MOTD: ^7", strreplace("\\n", "\n", motd));
1082         }
1083         return s;
1084 }
1085
1086 bool autocvar_sv_qcphysics = true; // TODO this is for testing - remove when qcphysics work
1087
1088 /**
1089 =============
1090 ClientConnect
1091
1092 Called when a client connects to the server
1093 =============
1094 */
1095 void ClientConnect(entity this)
1096 {
1097         if (Ban_MaybeEnforceBanOnce(this)) return;
1098         assert(!IS_CLIENT(this), return);
1099         this.flags |= FL_CLIENT;
1100         assert(player_count >= 0, player_count = 0);
1101
1102 #ifdef WATERMARK
1103         Send_Notification(NOTIF_ONE_ONLY, this, MSG_INFO, INFO_WATERMARK, WATERMARK);
1104 #endif
1105         TRANSMUTE(Client, this);
1106         CS(this).version_nagtime = time + 10 + random() * 10;
1107
1108         Send_Notification(NOTIF_ALL, NULL, MSG_INFO, INFO_JOIN_CONNECT, this.netname);
1109
1110         bot_clientconnect(this);
1111
1112         Player_DetermineForcedTeam(this);
1113
1114         TRANSMUTE(Observer, this);
1115
1116         PlayerStats_GameReport_AddEvent(sprintf("kills-%d", this.playerid));
1117
1118         // always track bots, don't ask for cl_allow_uidtracking
1119         if (IS_BOT_CLIENT(this))
1120                 PlayerStats_GameReport_AddPlayer(this);
1121         else
1122                 CS(this).allowed_timeouts = autocvar_sv_timeout_number;
1123
1124         if (autocvar_sv_eventlog)
1125                 GameLogEcho(strcat(":join:", ftos(this.playerid), ":", ftos(etof(this)), ":", ((IS_REAL_CLIENT(this)) ? GameLog_ProcessIP(this.netaddress) : "bot"), ":", playername(this, false)));
1126
1127         CS(this).just_joined = true;  // stop spamming the eventlog with additional lines when the client connects
1128
1129         stuffcmd(this, clientstuff, "\n");
1130         stuffcmd(this, "cl_particles_reloadeffects\n"); // TODO do we still need this?
1131
1132         FixClientCvars(this);
1133
1134         // get version info from player
1135         stuffcmd(this, "cmd clientversion $gameversion\n");
1136
1137         // notify about available teams
1138         if (teamplay)
1139         {
1140                 entity balance = TeamBalance_CheckAllowedTeams(this);
1141                 int t = TeamBalance_GetAllowedTeams(balance);
1142                 TeamBalance_Destroy(balance);
1143                 stuffcmd(this, sprintf("set _teams_available %d\n", t));
1144         }
1145         else
1146         {
1147                 stuffcmd(this, "set _teams_available 0\n");
1148         }
1149
1150         bot_relinkplayerlist();
1151
1152         CS(this).spectatortime = time;
1153         if (blockSpectators)
1154         {
1155                 Send_Notification(NOTIF_ONE_ONLY, this, MSG_INFO, INFO_SPECTATE_WARNING, autocvar_g_maxplayers_spectator_blocktime);
1156         }
1157
1158         CS(this).jointime = time;
1159
1160         if (IS_REAL_CLIENT(this))
1161         {
1162                 if (g_weaponarena_weapons == WEPSET(TUBA))
1163                         stuffcmd(this, "cl_cmd settemp chase_active 1\n");
1164         }
1165
1166         if (!sv_foginterval && world.fog != "")
1167                 stuffcmd(this, strcat("\nfog ", world.fog, "\nr_fog_exp2 0\nr_drawfog 1\n"));
1168
1169         if (autocvar_sv_teamnagger && !(autocvar_bot_vs_human && AvailableTeams() == 2))
1170                 if(!MUTATOR_CALLHOOK(HideTeamNagger, this))
1171                         send_CSQC_teamnagger();
1172
1173         CSQCMODEL_AUTOINIT(this);
1174
1175         CS(this).model_randomizer = random();
1176
1177         if (IS_REAL_CLIENT(this))
1178                 sv_notice_join(this);
1179
1180         this.move_qcphysics = autocvar_sv_qcphysics;
1181
1182         // update physics stats (players can spawn before physics runs)
1183         Physics_UpdateStats(this);
1184
1185         IL_EACH(g_initforplayer, it.init_for_player, {
1186                 it.init_for_player(it, this);
1187         });
1188
1189         Handicap_Initialize(this);
1190
1191         MUTATOR_CALLHOOK(ClientConnect, this);
1192
1193         if (IS_REAL_CLIENT(this))
1194         {
1195                 if (!autocvar_g_campaign && !IS_PLAYER(this))
1196                 {
1197                         CS(this).motd_actived_time = -1;
1198                         Send_Notification(NOTIF_ONE_ONLY, this, MSG_CENTER, CENTER_MOTD, getwelcomemessage(this));
1199                 }
1200         }
1201 }
1202 /*
1203 =============
1204 ClientDisconnect
1205
1206 Called when a client disconnects from the server
1207 =============
1208 */
1209 .entity chatbubbleentity;
1210 void ClientDisconnect(entity this)
1211 {
1212         assert(IS_CLIENT(this), return);
1213
1214         PlayerStats_GameReport_FinalizePlayer(this);
1215         if (this.vehicle) vehicles_exit(this.vehicle, VHEF_RELEASE);
1216         if (CS(this).active_minigame) part_minigame(this);
1217         if (IS_PLAYER(this)) Send_Effect(EFFECT_SPAWN_NEUTRAL, this.origin, '0 0 0', 1);
1218
1219         if (autocvar_sv_eventlog)
1220                 GameLogEcho(strcat(":part:", ftos(this.playerid)));
1221
1222         Send_Notification(NOTIF_ALL, NULL, MSG_INFO, INFO_QUIT_DISCONNECT, this.netname);
1223
1224         if(IS_SPEC(this))
1225                 SetSpectatee(this, NULL);
1226
1227     MUTATOR_CALLHOOK(ClientDisconnect, this);
1228
1229         strfree(CS(this).netname_previous); // needs to be before the CS entity is removed!
1230         strfree(CS(this).weaponorder_byimpulse);
1231         ClientState_detach(this);
1232
1233         Portal_ClearAll(this);
1234
1235         Unfreeze(this, false);
1236
1237         RemoveGrapplingHooks(this);
1238
1239         // Here, everything has been done that requires this player to be a client.
1240
1241         this.flags &= ~FL_CLIENT;
1242
1243         if (this.chatbubbleentity) delete(this.chatbubbleentity);
1244         if (this.killindicator) delete(this.killindicator);
1245
1246         IL_EACH(g_counters, it.realowner == this,
1247         {
1248                 delete(it);
1249         });
1250
1251         WaypointSprite_PlayerGone(this);
1252
1253         bot_relinkplayerlist();
1254
1255         strfree(this.clientstatus);
1256         if (this.personal) delete(this.personal);
1257
1258         this.playerid = 0;
1259         ReadyCount();
1260         if (vote_called && IS_REAL_CLIENT(this)) VoteCount(false);
1261
1262         ONREMOVE(this);
1263 }
1264
1265 void ChatBubbleThink(entity this)
1266 {
1267         this.nextthink = time;
1268         if ((this.owner.alpha < 0) || this.owner.chatbubbleentity != this)
1269         {
1270                 if(this.owner) // but why can that ever be NULL?
1271                         this.owner.chatbubbleentity = NULL;
1272                 delete(this);
1273                 return;
1274         }
1275
1276         this.mdl = "";
1277
1278         if ( !IS_DEAD(this.owner) && IS_PLAYER(this.owner) )
1279         {
1280                 if ( CS(this.owner).active_minigame && PHYS_INPUT_BUTTON_MINIGAME(this.owner) )
1281                         this.mdl = "models/sprites/minigame_busy.iqm";
1282                 else if (PHYS_INPUT_BUTTON_CHAT(this.owner))
1283                         this.mdl = "models/misc/chatbubble.spr";
1284         }
1285
1286         if ( this.model != this.mdl )
1287                 _setmodel(this, this.mdl);
1288
1289 }
1290
1291 void UpdateChatBubble(entity this)
1292 {
1293         if (this.alpha < 0)
1294                 return;
1295         // spawn a chatbubble entity if needed
1296         if (!this.chatbubbleentity)
1297         {
1298                 this.chatbubbleentity = new(chatbubbleentity);
1299                 this.chatbubbleentity.owner = this;
1300                 this.chatbubbleentity.exteriormodeltoclient = this;
1301                 setthink(this.chatbubbleentity, ChatBubbleThink);
1302                 this.chatbubbleentity.nextthink = time;
1303                 setmodel(this.chatbubbleentity, MDL_CHAT); // precision set below
1304                 //setorigin(this.chatbubbleentity, this.origin + '0 0 15' + this.maxs_z * '0 0 1');
1305                 setorigin(this.chatbubbleentity, '0 0 15' + this.maxs_z * '0 0 1');
1306                 setattachment(this.chatbubbleentity, this, "");  // sticks to moving player better, also conserves bandwidth
1307                 this.chatbubbleentity.mdl = this.chatbubbleentity.model;
1308                 //this.chatbubbleentity.model = "";
1309                 this.chatbubbleentity.effects = EF_LOWPRECISION;
1310         }
1311 }
1312
1313 void calculate_player_respawn_time(entity this)
1314 {
1315         if(MUTATOR_CALLHOOK(CalculateRespawnTime, this))
1316                 return;
1317
1318         float gametype_setting_tmp;
1319         float sdelay_max = GAMETYPE_DEFAULTED_SETTING(respawn_delay_max);
1320         float sdelay_small = GAMETYPE_DEFAULTED_SETTING(respawn_delay_small);
1321         float sdelay_large = GAMETYPE_DEFAULTED_SETTING(respawn_delay_large);
1322         float sdelay_small_count = GAMETYPE_DEFAULTED_SETTING(respawn_delay_small_count);
1323         float sdelay_large_count = GAMETYPE_DEFAULTED_SETTING(respawn_delay_large_count);
1324         float waves = GAMETYPE_DEFAULTED_SETTING(respawn_waves);
1325
1326         float pcount = 1;  // Include myself whether or not team is already set right and I'm a "player".
1327         if (teamplay)
1328         {
1329                 FOREACH_CLIENT(IS_PLAYER(it) && it != this, {
1330                         if(it.team == this.team)
1331                                 ++pcount;
1332                 });
1333                 if (sdelay_small_count == 0)
1334                         sdelay_small_count = 1;
1335                 if (sdelay_large_count == 0)
1336                         sdelay_large_count = 1;
1337         }
1338         else
1339         {
1340                 FOREACH_CLIENT(IS_PLAYER(it) && it != this, {
1341                         ++pcount;
1342                 });
1343                 if (sdelay_small_count == 0)
1344                 {
1345                         if (IS_INDEPENDENT_PLAYER(this))
1346                         {
1347                                 // Players play independently. No point in requiring enemies.
1348                                 sdelay_small_count = 1;
1349                         }
1350                         else
1351                         {
1352                                 // Players play AGAINST each other. Enemies required.
1353                                 sdelay_small_count = 2;
1354                         }
1355                 }
1356                 if (sdelay_large_count == 0)
1357                 {
1358                         if (IS_INDEPENDENT_PLAYER(this))
1359                         {
1360                                 // Players play independently. No point in requiring enemies.
1361                                 sdelay_large_count = 1;
1362                         }
1363                         else
1364                         {
1365                                 // Players play AGAINST each other. Enemies required.
1366                                 sdelay_large_count = 2;
1367                         }
1368                 }
1369         }
1370
1371         float sdelay;
1372
1373         if (pcount <= sdelay_small_count)
1374                 sdelay = sdelay_small;
1375         else if (pcount >= sdelay_large_count)
1376                 sdelay = sdelay_large;
1377         else  // NOTE: this case implies sdelay_large_count > sdelay_small_count.
1378                 sdelay = sdelay_small + (sdelay_large - sdelay_small) * (pcount - sdelay_small_count) / (sdelay_large_count - sdelay_small_count);
1379
1380         if(waves)
1381                 this.respawn_time = ceil((time + sdelay) / waves) * waves;
1382         else
1383                 this.respawn_time = time + sdelay;
1384
1385         if(sdelay < sdelay_max)
1386                 this.respawn_time_max = time + sdelay_max;
1387         else
1388                 this.respawn_time_max = this.respawn_time;
1389
1390         if((sdelay + waves >= 5.0) && (this.respawn_time - time > 1.75))
1391                 this.respawn_countdown = 10; // first number to count down from is 10
1392         else
1393                 this.respawn_countdown = -1; // do not count down
1394
1395         if(autocvar_g_forced_respawn)
1396                 this.respawn_flags = this.respawn_flags | RESPAWN_FORCE;
1397 }
1398
1399 // LordHavoc: this hack will be removed when proper _pants/_shirt layers are
1400 // added to the model skins
1401 /*void UpdateColorModHack()
1402 {
1403         float c;
1404         c = this.clientcolors & 15;
1405         // LordHavoc: only bothering to support white, green, red, yellow, blue
1406              if (!teamplay) this.colormod = '0 0 0';
1407         else if (c ==  0) this.colormod = '1.00 1.00 1.00';
1408         else if (c ==  3) this.colormod = '0.10 1.73 0.10';
1409         else if (c ==  4) this.colormod = '1.73 0.10 0.10';
1410         else if (c == 12) this.colormod = '1.22 1.22 0.10';
1411         else if (c == 13) this.colormod = '0.10 0.10 1.73';
1412         else this.colormod = '1 1 1';
1413 }*/
1414
1415 void respawn(entity this)
1416 {
1417         bool damagedbycontents_prev = this.damagedbycontents;
1418         if(this.alpha >= 0)
1419         {
1420                 if(autocvar_g_respawn_ghosts)
1421                 {
1422                         this.solid = SOLID_NOT;
1423                         this.takedamage = DAMAGE_NO;
1424                         this.damagedbycontents = false;
1425                         set_movetype(this, MOVETYPE_FLY);
1426                         this.velocity = '0 0 1' * autocvar_g_respawn_ghosts_speed;
1427                         this.avelocity = randomvec() * autocvar_g_respawn_ghosts_speed * 3 - randomvec() * autocvar_g_respawn_ghosts_speed * 3;
1428                         this.effects |= CSQCMODEL_EF_RESPAWNGHOST;
1429                         this.alpha = min(this.alpha, autocvar_g_respawn_ghosts_alpha);
1430                         Send_Effect(EFFECT_RESPAWN_GHOST, this.origin, '0 0 0', 1);
1431                         if(autocvar_g_respawn_ghosts_time > 0)
1432                                 SUB_SetFade(this, time + autocvar_g_respawn_ghosts_time, autocvar_g_respawn_ghosts_fadetime);
1433                 }
1434                 else
1435                         SUB_SetFade (this, time, 1); // fade out the corpse immediately
1436         }
1437
1438         CopyBody(this, 1);
1439         this.damagedbycontents = damagedbycontents_prev;
1440
1441         this.effects |= EF_NODRAW; // prevent another CopyBody
1442         PutClientInServer(this);
1443 }
1444
1445 ERASEABLE
1446 void PrintToChat(entity client, string text)
1447 {
1448         text = strcat("\{1}^7", text, "\n");
1449         sprint(client, text);
1450 }
1451
1452 ERASEABLE
1453 void DebugPrintToChat(entity client, string text)
1454 {
1455         if (autocvar_developer > 0)
1456         {
1457                 PrintToChat(client, text);
1458         }
1459 }
1460
1461 ERASEABLE
1462 void PrintToChatAll(string text)
1463 {
1464         text = strcat("\{1}^7", text, "\n");
1465         bprint(text);
1466 }
1467
1468 ERASEABLE
1469 void DebugPrintToChatAll(string text)
1470 {
1471         if (autocvar_developer > 0)
1472         {
1473                 PrintToChatAll(text);
1474         }
1475 }
1476
1477 ERASEABLE
1478 void PrintToChatTeam(int team_num, string text)
1479 {
1480         text = strcat("\{1}^7", text, "\n");
1481         FOREACH_CLIENT(IS_REAL_CLIENT(it),
1482         {
1483                 if (it.team == team_num)
1484                 {
1485                         sprint(it, text);
1486                 }
1487         });
1488 }
1489
1490 ERASEABLE
1491 void DebugPrintToChatTeam(int team_num, string text)
1492 {
1493         if (autocvar_developer > 0)
1494         {
1495                 PrintToChatTeam(team_num, text);
1496         }
1497 }
1498
1499 void play_countdown(entity this, float finished, Sound samp)
1500 {
1501         TC(Sound, samp);
1502         if(IS_REAL_CLIENT(this))
1503                 if(floor(finished - time - frametime) != floor(finished - time))
1504                         if(finished - time < 6)
1505                                 sound (this, CH_INFO, samp, VOL_BASE, ATTEN_NORM);
1506 }
1507
1508 void player_powerups(entity this)
1509 {
1510         if((this.items & IT_USING_JETPACK) && !IS_DEAD(this) && !game_stopped)
1511                 this.modelflags |= MF_ROCKET;
1512         else
1513                 this.modelflags &= ~MF_ROCKET;
1514
1515         this.effects &= ~(EF_RED | EF_BLUE | EF_ADDITIVE | EF_FULLBRIGHT | EF_FLAME | EF_NODEPTHTEST);
1516
1517         if (IS_DEAD(this))
1518         {
1519                 if (this.items & (ITEM_Strength.m_itemid | ITEM_Shield.m_itemid | IT_SUPERWEAPON))
1520                 {
1521                         sound(this, CH_INFO, SND_POWEROFF, VOL_BASE, ATTEN_NORM);
1522                         stopsound(this, CH_TRIGGER_SINGLE); // get rid of the pickup sound
1523                         this.items &= ~ITEM_Strength.m_itemid;
1524                         this.items &= ~ITEM_Shield.m_itemid;
1525                         this.items -= (this.items & IT_SUPERWEAPON);
1526                 }
1527         }
1528
1529         if((this.alpha < 0 || IS_DEAD(this)) && !this.vehicle) // don't apply the flags if the player is gibbed
1530                 return;
1531
1532         // add a way to see what the items were BEFORE all of these checks for the mutator hook
1533         int items_prev = this.items;
1534
1535         Fire_ApplyDamage(this);
1536         Fire_ApplyEffect(this);
1537
1538         if (!MUTATOR_IS_ENABLED(mutator_instagib))
1539         {
1540                 if (this.items & ITEM_Strength.m_itemid)
1541                 {
1542                         play_countdown(this, STAT(STRENGTH_FINISHED, this), SND_POWEROFF);
1543                         this.effects = this.effects | (EF_BLUE | EF_ADDITIVE | EF_FULLBRIGHT);
1544                         if (time > STAT(STRENGTH_FINISHED, this))
1545                         {
1546                                 this.items = this.items - (this.items & ITEM_Strength.m_itemid);
1547                                 //Send_Notification(NOTIF_ALL, NULL, MSG_INFO, INFO_POWERDOWN_STRENGTH, this.netname);
1548                                 Send_Notification(NOTIF_ONE, this, MSG_CENTER, CENTER_POWERDOWN_STRENGTH);
1549                         }
1550                 }
1551                 else
1552                 {
1553                         if (time < STAT(STRENGTH_FINISHED, this))
1554                         {
1555                                 this.items = this.items | ITEM_Strength.m_itemid;
1556                                 if(!g_cts)
1557                                         Send_Notification(NOTIF_ALL, NULL, MSG_INFO, INFO_POWERUP_STRENGTH, this.netname);
1558                                 Send_Notification(NOTIF_ONE, this, MSG_CENTER, CENTER_POWERUP_STRENGTH);
1559                         }
1560                 }
1561                 if (this.items & ITEM_Shield.m_itemid)
1562                 {
1563                         play_countdown(this, STAT(INVINCIBLE_FINISHED, this), SND_POWEROFF);
1564                         this.effects = this.effects | (EF_RED | EF_ADDITIVE | EF_FULLBRIGHT);
1565                         if (time > STAT(INVINCIBLE_FINISHED, this))
1566                         {
1567                                 this.items = this.items - (this.items & ITEM_Shield.m_itemid);
1568                                 //Send_Notification(NOTIF_ALL, NULL, MSG_INFO, INFO_POWERDOWN_SHIELD, this.netname);
1569                                 Send_Notification(NOTIF_ONE, this, MSG_CENTER, CENTER_POWERDOWN_SHIELD);
1570                         }
1571                 }
1572                 else
1573                 {
1574                         if (time < STAT(INVINCIBLE_FINISHED, this))
1575                         {
1576                                 this.items = this.items | ITEM_Shield.m_itemid;
1577                                 if(!g_cts)
1578                                         Send_Notification(NOTIF_ALL, NULL, MSG_INFO, INFO_POWERUP_SHIELD, this.netname);
1579                                 Send_Notification(NOTIF_ONE, this, MSG_CENTER, CENTER_POWERUP_SHIELD);
1580                         }
1581                 }
1582                 if (this.items & IT_SUPERWEAPON)
1583                 {
1584                         if (!(STAT(WEAPONS, this) & WEPSET_SUPERWEAPONS))
1585                         {
1586                                 STAT(SUPERWEAPONS_FINISHED, this) = 0;
1587                                 this.items = this.items - (this.items & IT_SUPERWEAPON);
1588                                 //Send_Notification(NOTIF_ALL, NULL, MSG_INFO, INFO_SUPERWEAPON_LOST, this.netname);
1589                                 Send_Notification(NOTIF_ONE, this, MSG_CENTER, CENTER_SUPERWEAPON_LOST);
1590                         }
1591                         else if (this.items & IT_UNLIMITED_SUPERWEAPONS)
1592                         {
1593                                 // don't let them run out
1594                         }
1595                         else
1596                         {
1597                                 play_countdown(this, STAT(SUPERWEAPONS_FINISHED, this), SND_POWEROFF);
1598                                 if (time > STAT(SUPERWEAPONS_FINISHED, this))
1599                                 {
1600                                         this.items = this.items - (this.items & IT_SUPERWEAPON);
1601                                         STAT(WEAPONS, this) &= ~WEPSET_SUPERWEAPONS;
1602                                         //Send_Notification(NOTIF_ALL, NULL, MSG_INFO, INFO_SUPERWEAPON_BROKEN, this.netname);
1603                                         Send_Notification(NOTIF_ONE, this, MSG_CENTER, CENTER_SUPERWEAPON_BROKEN);
1604                                 }
1605                         }
1606                 }
1607                 else if(STAT(WEAPONS, this) & WEPSET_SUPERWEAPONS)
1608                 {
1609                         if (time < STAT(SUPERWEAPONS_FINISHED, this) || (this.items & IT_UNLIMITED_SUPERWEAPONS))
1610                         {
1611                                 this.items = this.items | IT_SUPERWEAPON;
1612                                 if(!(this.items & IT_UNLIMITED_SUPERWEAPONS))
1613                                 {
1614                                         if(!g_cts)
1615                                                 Send_Notification(NOTIF_ALL, NULL, MSG_INFO, INFO_SUPERWEAPON_PICKUP, this.netname);
1616                                         Send_Notification(NOTIF_ONE, this, MSG_CENTER, CENTER_SUPERWEAPON_PICKUP);
1617                                 }
1618                         }
1619                         else
1620                         {
1621                                 STAT(SUPERWEAPONS_FINISHED, this) = 0;
1622                                 STAT(WEAPONS, this) &= ~WEPSET_SUPERWEAPONS;
1623                         }
1624                 }
1625                 else
1626                 {
1627                         STAT(SUPERWEAPONS_FINISHED, this) = 0;
1628                 }
1629         }
1630
1631         if(autocvar_g_nodepthtestplayers)
1632                 this.effects = this.effects | EF_NODEPTHTEST;
1633
1634         if(autocvar_g_fullbrightplayers)
1635                 this.effects = this.effects | EF_FULLBRIGHT;
1636
1637         if (time >= game_starttime)
1638         if (time < this.spawnshieldtime)
1639                 this.effects = this.effects | (EF_ADDITIVE | EF_FULLBRIGHT);
1640
1641         MUTATOR_CALLHOOK(PlayerPowerups, this, items_prev);
1642 }
1643
1644 float CalcRegen(float current, float stable, float regenfactor, float regenframetime)
1645 {
1646         if(current > stable)
1647                 return current;
1648         else if(current > stable - 0.25) // when close enough, "snap"
1649                 return stable;
1650         else
1651                 return min(stable, current + (stable - current) * regenfactor * regenframetime);
1652 }
1653
1654 float CalcRot(float current, float stable, float rotfactor, float rotframetime)
1655 {
1656         if(current < stable)
1657                 return current;
1658         else if(current < stable + 0.25) // when close enough, "snap"
1659                 return stable;
1660         else
1661                 return max(stable, current + (stable - current) * rotfactor * rotframetime);
1662 }
1663
1664 void RotRegen(entity this, int res, float regenstable, float regenfactor, float regenlinear, float regenframetime, float rotstable, float rotfactor, float rotlinear, float rotframetime, float limit_mod)
1665 {
1666         float old = GetResource(this, res);
1667         float current = old;
1668         if(current > rotstable)
1669         {
1670                 if(rotframetime > 0)
1671                 {
1672                         current = CalcRot(current, rotstable, rotfactor, rotframetime);
1673                         current = max(rotstable, current - rotlinear * rotframetime);
1674                 }
1675         }
1676         else if(current < regenstable)
1677         {
1678                 if(regenframetime > 0)
1679                 {
1680                         current = CalcRegen(current, regenstable, regenfactor, regenframetime);
1681                         current = min(regenstable, current + regenlinear * regenframetime);
1682                 }
1683         }
1684
1685         float limit = GetResourceLimit(this, res) * limit_mod;
1686         if(current > limit)
1687                 current = limit;
1688
1689         if (current != old)
1690                 SetResource(this, res, current);
1691 }
1692
1693 void player_regen(entity this)
1694 {
1695         float max_mod, regen_mod, rot_mod, limit_mod;
1696         max_mod = regen_mod = rot_mod = limit_mod = 1;
1697
1698         float regen_health = autocvar_g_balance_health_regen;
1699         float regen_health_linear = autocvar_g_balance_health_regenlinear;
1700         float regen_health_rot = autocvar_g_balance_health_rot;
1701         float regen_health_rotlinear = autocvar_g_balance_health_rotlinear;
1702         float regen_health_stable = autocvar_g_balance_health_regenstable;
1703         float regen_health_rotstable = autocvar_g_balance_health_rotstable;
1704         bool mutator_returnvalue = MUTATOR_CALLHOOK(PlayerRegen, this, max_mod, regen_mod, rot_mod, limit_mod, regen_health, regen_health_linear, regen_health_rot,
1705                 regen_health_rotlinear, regen_health_stable, regen_health_rotstable);
1706         max_mod = M_ARGV(1, float);
1707         regen_mod = M_ARGV(2, float);
1708         rot_mod = M_ARGV(3, float);
1709         limit_mod = M_ARGV(4, float);
1710         regen_health = M_ARGV(5, float);
1711         regen_health_linear = M_ARGV(6, float);
1712         regen_health_rot = M_ARGV(7, float);
1713         regen_health_rotlinear = M_ARGV(8, float);
1714         regen_health_stable = M_ARGV(9, float);
1715         regen_health_rotstable = M_ARGV(10, float);
1716
1717         if(!mutator_returnvalue)
1718         if(!STAT(FROZEN, this))
1719         {
1720                 float maxa = autocvar_g_balance_armor_rotstable;
1721                 float mina = autocvar_g_balance_armor_regenstable;
1722
1723                 RotRegen(this, RES_ARMOR, mina, autocvar_g_balance_armor_regen, autocvar_g_balance_armor_regenlinear,
1724                         regen_mod * frametime * (time > this.pauseregen_finished), maxa, autocvar_g_balance_armor_rot, autocvar_g_balance_armor_rotlinear,
1725                         rot_mod * frametime * (time > this.pauserotarmor_finished), limit_mod);
1726
1727                 RotRegen(this, RES_HEALTH, regen_health_stable * max_mod, regen_health, regen_health_linear,
1728                         regen_mod * frametime * (time > this.pauseregen_finished), regen_health_rotstable * max_mod, regen_health_rot, regen_health_rotlinear,
1729                         rot_mod * frametime * (time > this.pauserothealth_finished), limit_mod);
1730         }
1731
1732         // if player rotted to death...  die!
1733         // check this outside above checks, as player may still be able to rot to death
1734         if(GetResource(this, RES_HEALTH) < 1)
1735         {
1736                 if(this.vehicle)
1737                         vehicles_exit(this.vehicle, VHEF_RELEASE);
1738                 if(this.event_damage)
1739                         this.event_damage(this, this, this, 1, DEATH_ROT.m_id, DMG_NOWEP, this.origin, '0 0 0');
1740         }
1741
1742         if (!(this.items & IT_UNLIMITED_AMMO))
1743         {
1744                 float maxf = autocvar_g_balance_fuel_rotstable;
1745                 float minf = autocvar_g_balance_fuel_regenstable;
1746
1747                 RotRegen(this, RES_FUEL, minf, autocvar_g_balance_fuel_regen, autocvar_g_balance_fuel_regenlinear,
1748                         frametime * (time > this.pauseregen_finished) * ((this.items & ITEM_JetpackRegen.m_itemid) != 0),
1749                         maxf, autocvar_g_balance_fuel_rot, autocvar_g_balance_fuel_rotlinear, frametime * (time > this.pauserotfuel_finished), 1);
1750         }
1751 }
1752
1753 bool zoomstate_set;
1754 void SetZoomState(entity this, float newzoom)
1755 {
1756         if(newzoom != CS(this).zoomstate)
1757         {
1758                 CS(this).zoomstate = newzoom;
1759                 ClientData_Touch(this);
1760         }
1761         zoomstate_set = true;
1762 }
1763
1764 void GetPressedKeys(entity this)
1765 {
1766         MUTATOR_CALLHOOK(GetPressedKeys, this);
1767         int keys = STAT(PRESSED_KEYS, this);
1768         keys = BITSET(keys, KEY_FORWARD,        CS(this).movement.x > 0);
1769         keys = BITSET(keys, KEY_BACKWARD,       CS(this).movement.x < 0);
1770         keys = BITSET(keys, KEY_RIGHT,          CS(this).movement.y > 0);
1771         keys = BITSET(keys, KEY_LEFT,           CS(this).movement.y < 0);
1772
1773         keys = BITSET(keys, KEY_JUMP,           PHYS_INPUT_BUTTON_JUMP(this));
1774         keys = BITSET(keys, KEY_CROUCH,         IS_DUCKED(this)); // workaround: player can't un-crouch until their path is clear, so we keep the button held here
1775         keys = BITSET(keys, KEY_ATCK,           PHYS_INPUT_BUTTON_ATCK(this));
1776         keys = BITSET(keys, KEY_ATCK2,          PHYS_INPUT_BUTTON_ATCK2(this));
1777         CS(this).pressedkeys = keys; // store for other users
1778
1779         STAT(PRESSED_KEYS, this) = keys;
1780 }
1781
1782 /*
1783 ======================
1784 spectate mode routines
1785 ======================
1786 */
1787
1788 void SpectateCopy(entity this, entity spectatee)
1789 {
1790         TC(Client, this); TC(Client, spectatee);
1791
1792         MUTATOR_CALLHOOK(SpectateCopy, spectatee, this);
1793         PS(this) = PS(spectatee);
1794         this.armortype = spectatee.armortype;
1795         SetResourceExplicit(this, RES_ARMOR, GetResource(spectatee, RES_ARMOR));
1796         SetResourceExplicit(this, RES_CELLS, GetResource(spectatee, RES_CELLS));
1797         SetResourceExplicit(this, RES_PLASMA, GetResource(spectatee, RES_PLASMA));
1798         SetResourceExplicit(this, RES_SHELLS, GetResource(spectatee, RES_SHELLS));
1799         SetResourceExplicit(this, RES_BULLETS, GetResource(spectatee, RES_BULLETS));
1800         SetResourceExplicit(this, RES_ROCKETS, GetResource(spectatee, RES_ROCKETS));
1801         SetResourceExplicit(this, RES_FUEL, GetResource(spectatee, RES_FUEL));
1802         this.effects = spectatee.effects & EFMASK_CHEAP; // eat performance
1803         SetResourceExplicit(this, RES_HEALTH, GetResource(spectatee, RES_HEALTH));
1804         CS(this).impulse = 0;
1805         this.disableclientprediction = 1; // no need to run prediction on a spectator
1806         this.items = spectatee.items;
1807         STAT(LAST_PICKUP, this) = STAT(LAST_PICKUP, spectatee);
1808         STAT(HIT_TIME, this) = STAT(HIT_TIME, spectatee);
1809         STAT(STRENGTH_FINISHED, this) = STAT(STRENGTH_FINISHED, spectatee);
1810         STAT(INVINCIBLE_FINISHED, this) = STAT(INVINCIBLE_FINISHED, spectatee);
1811         STAT(SUPERWEAPONS_FINISHED, this) = STAT(SUPERWEAPONS_FINISHED, spectatee);
1812         STAT(AIR_FINISHED, this) = STAT(AIR_FINISHED, spectatee);
1813         STAT(PRESSED_KEYS, this) = STAT(PRESSED_KEYS, spectatee);
1814         STAT(WEAPONS, this) = STAT(WEAPONS, spectatee);
1815         this.punchangle = spectatee.punchangle;
1816         this.view_ofs = spectatee.view_ofs;
1817         this.velocity = spectatee.velocity;
1818         this.dmg_take = spectatee.dmg_take;
1819         this.dmg_save = spectatee.dmg_save;
1820         this.dmg_inflictor = spectatee.dmg_inflictor;
1821         this.v_angle = spectatee.v_angle;
1822         this.angles = spectatee.v_angle;
1823         STAT(FROZEN, this) = STAT(FROZEN, spectatee);
1824         STAT(REVIVE_PROGRESS, this) = STAT(REVIVE_PROGRESS, spectatee);
1825         this.viewloc = spectatee.viewloc;
1826         if(!PHYS_INPUT_BUTTON_USE(this) && STAT(CAMERA_SPECTATOR, this) != 2)
1827                 this.fixangle = true;
1828         setorigin(this, spectatee.origin);
1829         setsize(this, spectatee.mins, spectatee.maxs);
1830         SetZoomState(this, CS(spectatee).zoomstate);
1831
1832     anticheat_spectatecopy(this, spectatee);
1833         STAT(HUD, this) = STAT(HUD, spectatee);
1834         if(spectatee.vehicle)
1835     {
1836         this.angles = spectatee.v_angle;
1837
1838         //this.fixangle = false;
1839         //this.velocity = spectatee.vehicle.velocity;
1840         this.vehicle_health = spectatee.vehicle_health;
1841         this.vehicle_shield = spectatee.vehicle_shield;
1842         this.vehicle_energy = spectatee.vehicle_energy;
1843         this.vehicle_ammo1 = spectatee.vehicle_ammo1;
1844         this.vehicle_ammo2 = spectatee.vehicle_ammo2;
1845         this.vehicle_reload1 = spectatee.vehicle_reload1;
1846         this.vehicle_reload2 = spectatee.vehicle_reload2;
1847
1848         //msg_entity = this;
1849
1850        // WriteByte (MSG_ONE, SVC_SETVIEWANGLES);
1851             //WriteAngle(MSG_ONE,  spectatee.v_angle.x);
1852            // WriteAngle(MSG_ONE,  spectatee.v_angle.y);
1853            // WriteAngle(MSG_ONE,  spectatee.v_angle.z);
1854
1855         //WriteByte (MSG_ONE, SVC_SETVIEW);
1856         //    WriteEntity(MSG_ONE, this);
1857         //makevectors(spectatee.v_angle);
1858         //setorigin(this, spectatee.origin - v_forward * 400 + v_up * 300);*/
1859     }
1860 }
1861
1862 bool SpectateUpdate(entity this)
1863 {
1864         if(!this.enemy)
1865                 return false;
1866
1867         if(!IS_PLAYER(this.enemy) || this == this.enemy)
1868         {
1869                 SetSpectatee(this, NULL);
1870                 return false;
1871         }
1872
1873         SpectateCopy(this, this.enemy);
1874
1875         return true;
1876 }
1877
1878 bool SpectateSet(entity this)
1879 {
1880         if(!IS_PLAYER(this.enemy))
1881                 return false;
1882
1883         ClientData_Touch(this.enemy);
1884
1885         msg_entity = this;
1886         WriteByte(MSG_ONE, SVC_SETVIEW);
1887         WriteEntity(MSG_ONE, this.enemy);
1888         set_movetype(this, MOVETYPE_NONE);
1889         accuracy_resend(this);
1890
1891         if(!SpectateUpdate(this))
1892                 PutObserverInServer(this);
1893
1894         return true;
1895 }
1896
1897 void SetSpectatee_status(entity this, int spectatee_num)
1898 {
1899         int oldspectatee_status = CS(this).spectatee_status;
1900         CS(this).spectatee_status = spectatee_num;
1901
1902         if (CS(this).spectatee_status != oldspectatee_status)
1903         {
1904                 if (STAT(PRESSED_KEYS, this))
1905                 {
1906                         CS(this).pressedkeys = 0;
1907                         STAT(PRESSED_KEYS, this) = 0;
1908                 }
1909                 ClientData_Touch(this);
1910                 if (g_race || g_cts) race_InitSpectator();
1911         }
1912 }
1913
1914 void SetSpectatee(entity this, entity spectatee)
1915 {
1916         if(IS_BOT_CLIENT(this))
1917                 return; // bots abuse .enemy, this code is useless to them
1918
1919         entity old_spectatee = this.enemy;
1920
1921         this.enemy = spectatee;
1922
1923         // WEAPONTODO
1924         // these are required to fix the spectator bug with arc
1925         if(old_spectatee)
1926         {
1927                 for(int slot = 0; slot < MAX_WEAPONSLOTS; ++slot)
1928                 {
1929                         .entity weaponentity = weaponentities[slot];
1930                         if(old_spectatee.(weaponentity).arc_beam)
1931                                 old_spectatee.(weaponentity).arc_beam.SendFlags |= ARC_SF_SETTINGS;
1932                 }
1933         }
1934         if(this.enemy)
1935         {
1936                 for(int slot = 0; slot < MAX_WEAPONSLOTS; ++slot)
1937                 {
1938                         .entity weaponentity = weaponentities[slot];
1939                         if(this.enemy.(weaponentity).arc_beam)
1940                                 this.enemy.(weaponentity).arc_beam.SendFlags |= ARC_SF_SETTINGS;
1941                 }
1942         }
1943
1944         if (this.enemy)
1945                 SetSpectatee_status(this, etof(this.enemy));
1946
1947         // needed to update spectator list
1948         if(old_spectatee) { ClientData_Touch(old_spectatee); }
1949 }
1950
1951 bool Spectate(entity this, entity pl)
1952 {
1953         if(MUTATOR_CALLHOOK(SpectateSet, this, pl))
1954                 return false;
1955         pl = M_ARGV(1, entity);
1956
1957         SetSpectatee(this, pl);
1958         return SpectateSet(this);
1959 }
1960
1961 bool SpectateNext(entity this)
1962 {
1963         entity ent = find(this.enemy, classname, STR_PLAYER);
1964
1965         if (MUTATOR_CALLHOOK(SpectateNext, this, ent))
1966                 ent = M_ARGV(1, entity);
1967         else if (!ent)
1968                 ent = find(ent, classname, STR_PLAYER);
1969
1970         if(ent) { SetSpectatee(this, ent); }
1971
1972         return SpectateSet(this);
1973 }
1974
1975 bool SpectatePrev(entity this)
1976 {
1977         // NOTE: chain order is from the highest to the lower entnum (unlike find)
1978         entity ent = findchain(classname, STR_PLAYER);
1979         if (!ent) // no player
1980                 return false;
1981
1982         entity first = ent;
1983         // skip players until current spectated player
1984         if(this.enemy)
1985         while(ent && ent != this.enemy)
1986                 ent = ent.chain;
1987
1988         switch (MUTATOR_CALLHOOK(SpectatePrev, this, ent, first))
1989         {
1990                 case MUT_SPECPREV_FOUND:
1991                     ent = M_ARGV(1, entity);
1992                     break;
1993                 case MUT_SPECPREV_RETURN:
1994                     return true;
1995                 case MUT_SPECPREV_CONTINUE:
1996                 default:
1997                 {
1998                         if(ent.chain)
1999                                 ent = ent.chain;
2000                         else
2001                                 ent = first;
2002                         break;
2003                 }
2004         }
2005
2006         SetSpectatee(this, ent);
2007         return SpectateSet(this);
2008 }
2009
2010 /*
2011 =============
2012 ShowRespawnCountdown()
2013
2014 Update a respawn countdown display.
2015 =============
2016 */
2017 void ShowRespawnCountdown(entity this)
2018 {
2019         float number;
2020         if(!IS_DEAD(this)) // just respawned?
2021                 return;
2022         else
2023         {
2024                 number = ceil(this.respawn_time - time);
2025                 if(number <= 0)
2026                         return;
2027                 if(number <= this.respawn_countdown)
2028                 {
2029                         this.respawn_countdown = number - 1;
2030                         if(ceil(this.respawn_time - (time + 0.5)) == number) // only say it if it is the same number even in 0.5s; to prevent overlapping sounds
2031                                 { Send_Notification(NOTIF_ONE, this, MSG_ANNCE, Announcer_PickNumber(CNT_RESPAWN, number)); }
2032                 }
2033         }
2034 }
2035
2036 .bool team_selected;
2037 bool ShowTeamSelection(entity this)
2038 {
2039         if (!teamplay || autocvar_g_campaign || autocvar_g_balance_teams || this.team_selected || (CS(this).wasplayer && autocvar_g_changeteam_banned) || Player_HasRealForcedTeam(this))
2040                 return false;
2041         stuffcmd(this, "menu_showteamselect\n");
2042         return true;
2043 }
2044 void Join(entity this)
2045 {
2046         TRANSMUTE(Player, this);
2047
2048         if(!this.team_selected)
2049         if(autocvar_g_campaign || autocvar_g_balance_teams)
2050                 TeamBalance_JoinBestTeam(this);
2051
2052         if(autocvar_g_campaign)
2053                 campaign_bots_may_start = true;
2054
2055         Kill_Notification(NOTIF_ONE_ONLY, this, MSG_CENTER, CPID_PREVENT_JOIN);
2056
2057         PutClientInServer(this);
2058
2059         if(IS_PLAYER(this))
2060         if(teamplay && this.team != -1)
2061         {
2062         }
2063         else
2064                 Send_Notification(NOTIF_ALL, NULL, MSG_INFO, INFO_JOIN_PLAY, this.netname);
2065         this.team_selected = false;
2066 }
2067
2068 int GetPlayerLimit()
2069 {
2070         if(g_duel)
2071                 return 2; // TODO: this workaround is needed since the mutator hook from duel can't be activated before the gametype is loaded (e.g. switching modes via gametype vote screen)
2072         int player_limit = autocvar_g_maxplayers;
2073         MUTATOR_CALLHOOK(GetPlayerLimit, player_limit);
2074         player_limit = M_ARGV(0, int);
2075         return player_limit;
2076 }
2077
2078 /**
2079  * Determines whether the player is allowed to join. This depends on cvar
2080  * g_maxplayers, if it isn't used this function always return true, otherwise
2081  * it checks whether the number of currently playing players exceeds g_maxplayers.
2082  * @return int number of free slots for players, 0 if none
2083  */
2084 int nJoinAllowed(entity this, entity ignore)
2085 {
2086         if(!ignore)
2087         // this is called that way when checking if anyone may be able to join (to build qcstatus)
2088         // so report 0 free slots if restricted
2089         {
2090                 if(autocvar_g_forced_team_otherwise == "spectate")
2091                         return 0;
2092                 if(autocvar_g_forced_team_otherwise == "spectator")
2093                         return 0;
2094         }
2095
2096         if(this && (Player_GetForcedTeamIndex(this) == TEAM_FORCE_SPECTATOR))
2097                 return 0; // forced spectators can never join
2098
2099         // TODO simplify this
2100         int totalClients = 0;
2101         int currentlyPlaying = 0;
2102         FOREACH_CLIENT(true, {
2103                 if(it != ignore)
2104                         ++totalClients;
2105                 if(IS_REAL_CLIENT(it))
2106                 if(IS_PLAYER(it) || it.caplayer)
2107                         ++currentlyPlaying;
2108         });
2109
2110         int player_limit = GetPlayerLimit();
2111
2112         int free_slots = 0;
2113         if (!player_limit)
2114                 free_slots = maxclients - totalClients;
2115         else if(player_limit > 0 && currentlyPlaying < player_limit)
2116                 free_slots = min(maxclients - totalClients, player_limit - currentlyPlaying);
2117
2118         static float msg_time = 0;
2119         if(this && !this.caplayer && ignore && !free_slots && time > msg_time)
2120         {
2121                 Send_Notification(NOTIF_ONE_ONLY, this, MSG_CENTER, CENTER_JOIN_PREVENT);
2122                 msg_time = time + 0.5;
2123         }
2124
2125         return free_slots;
2126 }
2127
2128 /**
2129  * Checks whether the client is an observer or spectator, if so, he will get kicked after
2130  * g_maxplayers_spectator_blocktime seconds
2131  */
2132 void checkSpectatorBlock(entity this)
2133 {
2134         if(IS_SPEC(this) || IS_OBSERVER(this))
2135         if(!this.caplayer)
2136         if(IS_REAL_CLIENT(this))
2137         {
2138                 if( time > (CS(this).spectatortime + autocvar_g_maxplayers_spectator_blocktime) ) {
2139                         Send_Notification(NOTIF_ONE_ONLY, this, MSG_INFO, INFO_QUIT_KICK_SPECTATING);
2140                         dropclient(this);
2141                 }
2142         }
2143 }
2144
2145 void PrintWelcomeMessage(entity this)
2146 {
2147         if(CS(this).motd_actived_time == 0)
2148         {
2149                 if (autocvar_g_campaign) {
2150                         if ((IS_PLAYER(this) && PHYS_INPUT_BUTTON_INFO(this)) || (!IS_PLAYER(this))) {
2151                                 CS(this).motd_actived_time = time;
2152                                 Send_Notification(NOTIF_ONE_ONLY, this, MSG_CENTER, CENTER_CAMPAIGN_MESSAGE, Campaign_GetMessage(), Campaign_GetLevelNum());
2153                         }
2154                 } else {
2155                         if (PHYS_INPUT_BUTTON_INFO(this)) {
2156                                 CS(this).motd_actived_time = time;
2157                                 Send_Notification(NOTIF_ONE_ONLY, this, MSG_CENTER, CENTER_MOTD, getwelcomemessage(this));
2158                         }
2159                 }
2160         }
2161         else if(CS(this).motd_actived_time > 0) // showing MOTD or campaign message
2162         {
2163                 if (autocvar_g_campaign) {
2164                         if (PHYS_INPUT_BUTTON_INFO(this))
2165                                 CS(this).motd_actived_time = time;
2166                         else if ((time - CS(this).motd_actived_time > 2) && IS_PLAYER(this)) { // hide it some seconds after BUTTON_INFO has been released
2167                                 CS(this).motd_actived_time = 0;
2168                                 Kill_Notification(NOTIF_ONE_ONLY, this, MSG_CENTER, CPID_CAMPAIGN_MESSAGE);
2169                         }
2170                 } else {
2171                         if (PHYS_INPUT_BUTTON_INFO(this))
2172                                 CS(this).motd_actived_time = time;
2173                         else if (time - CS(this).motd_actived_time > 2) { // hide it some seconds after BUTTON_INFO has been released
2174                                 CS(this).motd_actived_time = 0;
2175                                 Kill_Notification(NOTIF_ONE_ONLY, this, MSG_CENTER, CPID_MOTD);
2176                         }
2177                 }
2178         }
2179         else //if(CS(this).motd_actived_time < 0) // just connected, motd is active
2180         {
2181                 if(PHYS_INPUT_BUTTON_INFO(this)) // BUTTON_INFO hides initial MOTD
2182                         CS(this).motd_actived_time = -2; // wait until BUTTON_INFO gets released
2183                 else if (CS(this).motd_actived_time == -2)
2184                 {
2185                         // instantly hide MOTD
2186                         CS(this).motd_actived_time = 0;
2187                         if (autocvar_g_campaign)
2188                                 Kill_Notification(NOTIF_ONE_ONLY, this, MSG_CENTER, CPID_CAMPAIGN_MESSAGE);
2189                         else
2190                                 Kill_Notification(NOTIF_ONE_ONLY, this, MSG_CENTER, CPID_MOTD);
2191                 }
2192                 else if (IS_PLAYER(this) || IS_SPEC(this))
2193                 {
2194                         // FIXME occasionally for some reason MOTD never goes away
2195                         // delay MOTD removal a little bit in the hope it fixes this bug
2196                         if (CS(this).motd_actived_time == -1) // MOTD marked to fade away as soon as client becomes player or spectator
2197                                 CS(this).motd_actived_time = -(5 + floor(random() * 10)); // add small delay
2198                         else //if (CS(this).motd_actived_time < -2)
2199                                 CS(this).motd_actived_time++;
2200                 }
2201         }
2202 }
2203
2204 bool joinAllowed(entity this)
2205 {
2206         if (CS(this).version_mismatch) return false;
2207         if (time < CS(this).jointime + MIN_SPEC_TIME) return false;
2208         if (!nJoinAllowed(this, this)) return false;
2209         if (teamplay && lockteams) return false;
2210         if (MUTATOR_CALLHOOK(ForbidSpawn, this)) return false;
2211         if (ShowTeamSelection(this)) return false;
2212         return true;
2213 }
2214
2215 .string shootfromfixedorigin;
2216 .bool dualwielding_prev;
2217 bool PlayerThink(entity this)
2218 {
2219         if (game_stopped || intermission_running) {
2220                 this.modelflags &= ~MF_ROCKET;
2221                 if(intermission_running)
2222                         IntermissionThink(this);
2223                 return false;
2224         }
2225
2226         if (timeout_status == TIMEOUT_ACTIVE) {
2227         // don't allow the player to turn around while game is paused
2228                 // FIXME turn this into CSQC stuff
2229                 this.v_angle = this.lastV_angle;
2230                 this.angles = this.lastV_angle;
2231                 this.fixangle = true;
2232         }
2233
2234         if (frametime) player_powerups(this);
2235
2236         if (IS_DEAD(this)) {
2237                 if (this.personal && g_race_qualifying) {
2238                         if (time > this.respawn_time) {
2239                                 STAT(RESPAWN_TIME, this) = this.respawn_time = time + 1; // only retry once a second
2240                                 respawn(this);
2241                                 CS(this).impulse = CHIMPULSE_SPEEDRUN.impulse;
2242                         }
2243                 } else {
2244                         if (frametime) player_anim(this);
2245
2246                         if (this.respawn_flags & RESPAWN_DENY)
2247                         {
2248                                 STAT(RESPAWN_TIME, this) = 0;
2249                                 return false;
2250                         }
2251
2252                         bool button_pressed = (PHYS_INPUT_BUTTON_ATCK(this) || PHYS_INPUT_BUTTON_JUMP(this) || PHYS_INPUT_BUTTON_ATCK2(this) || PHYS_INPUT_BUTTON_HOOK(this) || PHYS_INPUT_BUTTON_USE(this));
2253
2254                         switch(this.deadflag)
2255                         {
2256                                 case DEAD_DYING:
2257                                 {
2258                                         if ((this.respawn_flags & RESPAWN_FORCE) && !(this.respawn_time < this.respawn_time_max))
2259                                                 this.deadflag = DEAD_RESPAWNING;
2260                                         else if (!button_pressed || (time >= this.respawn_time_max && (this.respawn_flags & RESPAWN_FORCE)))
2261                                                 this.deadflag = DEAD_DEAD;
2262                                         break;
2263                                 }
2264                                 case DEAD_DEAD:
2265                                 {
2266                                         if (button_pressed)
2267                                                 this.deadflag = DEAD_RESPAWNABLE;
2268                                         else if (time >= this.respawn_time_max && (this.respawn_flags & RESPAWN_FORCE))
2269                                                 this.deadflag = DEAD_RESPAWNING;
2270                                         break;
2271                                 }
2272                                 case DEAD_RESPAWNABLE:
2273                                 {
2274                                         if (!button_pressed || (this.respawn_flags & RESPAWN_FORCE))
2275                                                 this.deadflag = DEAD_RESPAWNING;
2276                                         break;
2277                                 }
2278                                 case DEAD_RESPAWNING:
2279                                 {
2280                                         if (time > this.respawn_time)
2281                                         {
2282                                                 this.respawn_time = time + 1; // only retry once a second
2283                                                 this.respawn_time_max = this.respawn_time;
2284                                                 respawn(this);
2285                                         }
2286                                         break;
2287                                 }
2288                         }
2289
2290                         ShowRespawnCountdown(this);
2291
2292                         if (this.respawn_flags & RESPAWN_SILENT)
2293                                 STAT(RESPAWN_TIME, this) = 0;
2294                         else if ((this.respawn_flags & RESPAWN_FORCE) && this.respawn_time < this.respawn_time_max)
2295                         {
2296                                 if (time < this.respawn_time)
2297                                         STAT(RESPAWN_TIME, this) = this.respawn_time;
2298                                 else if (this.deadflag != DEAD_RESPAWNING)
2299                                         STAT(RESPAWN_TIME, this) = -this.respawn_time_max;
2300                         }
2301                         else
2302                                 STAT(RESPAWN_TIME, this) = this.respawn_time;
2303                 }
2304
2305                 // if respawning, invert stat_respawn_time to indicate this, the client translates it
2306                 if (this.deadflag == DEAD_RESPAWNING && STAT(RESPAWN_TIME, this) > 0)
2307                         STAT(RESPAWN_TIME, this) *= -1;
2308
2309                 return false;
2310         }
2311
2312         FixPlayermodel(this);
2313
2314         if (this.shootfromfixedorigin != autocvar_g_shootfromfixedorigin) {
2315                 this.shootfromfixedorigin = autocvar_g_shootfromfixedorigin;
2316                 stuffcmd(this, sprintf("\ncl_shootfromfixedorigin \"%s\"\n", autocvar_g_shootfromfixedorigin));
2317         }
2318
2319         // reset gun alignment when dual wielding status changes
2320         // to ensure guns are always aligned right and left
2321         bool dualwielding = W_DualWielding(this);
2322         if(this.dualwielding_prev != dualwielding)
2323         {
2324                 W_ResetGunAlign(this, CS(this).cvar_cl_gunalign);
2325                 this.dualwielding_prev = dualwielding;
2326         }
2327
2328         // LordHavoc: allow firing on move frames (sub-ticrate), this gives better timing on slow servers
2329         //if(frametime)
2330         {
2331                 for(int slot = 0; slot < MAX_WEAPONSLOTS; ++slot)
2332                 {
2333                         .entity weaponentity = weaponentities[slot];
2334                         if(WEP_CVAR(vortex, charge_always))
2335                                 W_Vortex_Charge(this, weaponentity, frametime);
2336                         W_WeaponFrame(this, weaponentity);
2337                 }
2338         }
2339
2340         if (frametime)
2341         {
2342                 // WEAPONTODO: Add a weapon request for this
2343                 // rot vortex charge to the charge limit
2344                 for(int slot = 0; slot < MAX_WEAPONSLOTS; ++slot)
2345                 {
2346                         .entity weaponentity = weaponentities[slot];
2347                         if (WEP_CVAR(vortex, charge_rot_rate) && this.(weaponentity).vortex_charge > WEP_CVAR(vortex, charge_limit) && this.(weaponentity).vortex_charge_rottime < time)
2348                                 this.(weaponentity).vortex_charge = bound(WEP_CVAR(vortex, charge_limit), this.(weaponentity).vortex_charge - WEP_CVAR(vortex, charge_rot_rate) * frametime / W_TICSPERFRAME, 1);
2349                 }
2350
2351                 player_regen(this);
2352                 player_anim(this);
2353                 this.dmg_team = max(0, this.dmg_team - autocvar_g_teamdamage_resetspeed * frametime);
2354         }
2355
2356         monsters_setstatus(this);
2357
2358         return true;
2359 }
2360
2361 .bool would_spectate;
2362 void ObserverOrSpectatorThink(entity this)
2363 {
2364         bool is_spec = IS_SPEC(this);
2365         if ( CS(this).impulse )
2366         {
2367                 int r = MinigameImpulse(this, CS(this).impulse);
2368                 if (!is_spec || r)
2369                         CS(this).impulse = 0;
2370
2371                 if (is_spec && CS(this).impulse == IMP_weapon_drop.impulse)
2372                 {
2373                         STAT(CAMERA_SPECTATOR, this) = (STAT(CAMERA_SPECTATOR, this) + 1) % 3;
2374                         CS(this).impulse = 0;
2375                         return;
2376                 }
2377         }
2378
2379         if (this.flags & FL_JUMPRELEASED) {
2380                 if (PHYS_INPUT_BUTTON_JUMP(this) && (joinAllowed(this) || time < CS(this).jointime + MIN_SPEC_TIME)) {
2381                         this.flags &= ~FL_JUMPRELEASED;
2382                         this.flags |= FL_SPAWNING;
2383                 } else if((is_spec && (PHYS_INPUT_BUTTON_ATCK(this) || CS(this).impulse == 10 || CS(this).impulse == 15 || CS(this).impulse == 18 || (CS(this).impulse >= 200 && CS(this).impulse <= 209)))
2384                         || (!is_spec && ((PHYS_INPUT_BUTTON_ATCK(this) && !CS(this).version_mismatch) || this.would_spectate))) {
2385                         this.flags &= ~FL_JUMPRELEASED;
2386                         if(SpectateNext(this)) {
2387                                 TRANSMUTE(Spectator, this);
2388                         } else if (is_spec) {
2389                                 TRANSMUTE(Observer, this);
2390                                 PutClientInServer(this);
2391                         }
2392                         if (is_spec)
2393                                 CS(this).impulse = 0;
2394                 } else if (is_spec) {
2395                         if(CS(this).impulse == 12 || CS(this).impulse == 16  || CS(this).impulse == 19 || (CS(this).impulse >= 220 && CS(this).impulse <= 229)) {
2396                                 this.flags &= ~FL_JUMPRELEASED;
2397                                 if(SpectatePrev(this)) {
2398                                         TRANSMUTE(Spectator, this);
2399                                 } else {
2400                                         TRANSMUTE(Observer, this);
2401                                         PutClientInServer(this);
2402                                 }
2403                                 CS(this).impulse = 0;
2404                         } else if(PHYS_INPUT_BUTTON_ATCK2(this)) {
2405                                 this.would_spectate = false;
2406                                 this.flags &= ~FL_JUMPRELEASED;
2407                                 TRANSMUTE(Observer, this);
2408                                 PutClientInServer(this);
2409                         } else if(!SpectateUpdate(this) && !SpectateNext(this)) {
2410                                 PutObserverInServer(this);
2411                                 this.would_spectate = true;
2412                         }
2413                 }
2414                 else {
2415                         int preferred_movetype = ((!PHYS_INPUT_BUTTON_USE(this) ? CS(this).cvar_cl_clippedspectating : !CS(this).cvar_cl_clippedspectating) ? MOVETYPE_FLY_WORLDONLY : MOVETYPE_NOCLIP);
2416                         set_movetype(this, preferred_movetype);
2417                 }
2418         } else {
2419                 if ((is_spec && !(PHYS_INPUT_BUTTON_ATCK(this) || PHYS_INPUT_BUTTON_ATCK2(this)))
2420                         || (!is_spec && !(PHYS_INPUT_BUTTON_ATCK(this) || PHYS_INPUT_BUTTON_JUMP(this)))) {
2421                         this.flags |= FL_JUMPRELEASED;
2422                         if(this.flags & FL_SPAWNING)
2423                         {
2424                                 this.flags &= ~FL_SPAWNING;
2425                                 if(joinAllowed(this))
2426                                         Join(this);
2427                                 else if(time < CS(this).jointime + MIN_SPEC_TIME)
2428                                         CS(this).autojoin_checked = -1;
2429                                 return;
2430                         }
2431                 }
2432                 if(is_spec && !SpectateUpdate(this))
2433                         PutObserverInServer(this);
2434         }
2435         if (is_spec)
2436                 this.flags |= FL_CLIENT | FL_NOTARGET;
2437 }
2438
2439 void PlayerUseKey(entity this)
2440 {
2441         if (!IS_PLAYER(this))
2442                 return;
2443
2444         if(this.vehicle)
2445         {
2446                 if(!game_stopped)
2447                 {
2448                         vehicles_exit(this.vehicle, VHEF_NORMAL);
2449                         return;
2450                 }
2451         }
2452         else if(autocvar_g_vehicles_enter)
2453         {
2454                 if(!game_stopped && !STAT(FROZEN, this) && !IS_DEAD(this) && !IS_INDEPENDENT_PLAYER(this))
2455                 {
2456                         entity head, closest_target = NULL;
2457                         head = WarpZone_FindRadius(this.origin, autocvar_g_vehicles_enter_radius, true);
2458
2459                         while(head) // find the closest acceptable target to enter
2460                         {
2461                                 if(IS_VEHICLE(head) && !IS_DEAD(head) && head.takedamage != DAMAGE_NO)
2462                                 if(!head.owner || ((head.vehicle_flags & VHF_MULTISLOT) && SAME_TEAM(head.owner, this)))
2463                                 {
2464                                         if(closest_target)
2465                                         {
2466                                                 if(vlen2(this.origin - head.origin) < vlen2(this.origin - closest_target.origin))
2467                                                 { closest_target = head; }
2468                                         }
2469                                         else { closest_target = head; }
2470                                 }
2471
2472                                 head = head.chain;
2473                         }
2474
2475                         if(closest_target) { vehicles_enter(this, closest_target); return; }
2476                 }
2477         }
2478
2479         // a use key was pressed; call handlers
2480         MUTATOR_CALLHOOK(PlayerUseKey, this);
2481 }
2482
2483
2484 /*
2485 =============
2486 PlayerPreThink
2487
2488 Called every frame for each client before the physics are run
2489 =============
2490 */
2491 .float last_vehiclecheck;
2492 void PlayerPreThink (entity this)
2493 {
2494         STAT(GUNALIGN, this) = CS(this).cvar_cl_gunalign; // TODO
2495         STAT(MOVEVARS_CL_TRACK_CANJUMP, this) = CS(this).cvar_cl_movement_track_canjump;
2496
2497         WarpZone_PlayerPhysics_FixVAngle(this);
2498
2499         if (frametime) {
2500                 // physics frames: update anticheat stuff
2501                 anticheat_prethink(this);
2502         }
2503
2504         if (blockSpectators && frametime) {
2505                 // WORKAROUND: only use dropclient in server frames (frametime set).
2506                 // Never use it in cl_movement frames (frametime zero).
2507                 checkSpectatorBlock(this);
2508         }
2509
2510         zoomstate_set = false;
2511
2512         // Check for nameless players
2513         if (this.netname == "" || this.netname != CS(this).netname_previous)
2514         {
2515                 bool assume_unchanged = (CS(this).netname_previous == "");
2516                 if (autocvar_sv_name_maxlength > 0 && strlennocol(this.netname) > autocvar_sv_name_maxlength)
2517                 {
2518                         int new_length = textLengthUpToLength(this.netname, autocvar_sv_name_maxlength, strlennocol);
2519                         this.netname = strzone(strcat(substring(this.netname, 0, new_length), "^7"));
2520                         sprint(this, sprintf("Warning: your name is longer than %d characters, it has been truncated.\n", autocvar_sv_name_maxlength));
2521                         assume_unchanged = false;
2522                         // stuffcmd(this, strcat("name ", this.netname, "\n")); // maybe?
2523                 }
2524                 if (isInvisibleString(this.netname))
2525                 {
2526                         this.netname = strzone(sprintf("Player#%d", this.playerid));
2527                         sprint(this, "Warning: invisible names are not allowed.\n");
2528                         assume_unchanged = false;
2529                         // stuffcmd(this, strcat("name ", this.netname, "\n")); // maybe?
2530                 }
2531                 if (!assume_unchanged && autocvar_sv_eventlog)
2532                         GameLogEcho(strcat(":name:", ftos(this.playerid), ":", playername(this, false)));
2533                 strcpy(CS(this).netname_previous, this.netname);
2534         }
2535
2536         // version nagging
2537         if (CS(this).version_nagtime && CS(this).cvar_g_xonoticversion && time > CS(this).version_nagtime) {
2538         CS(this).version_nagtime = 0;
2539         if (strstrofs(CS(this).cvar_g_xonoticversion, "git", 0) >= 0 || strstrofs(CS(this).cvar_g_xonoticversion, "autobuild", 0) >= 0) {
2540             // git client
2541         } else if (strstrofs(autocvar_g_xonoticversion, "git", 0) >= 0 || strstrofs(autocvar_g_xonoticversion, "autobuild", 0) >= 0) {
2542             // git server
2543             Send_Notification(NOTIF_ONE_ONLY, this, MSG_INFO, INFO_VERSION_BETA, autocvar_g_xonoticversion, CS(this).cvar_g_xonoticversion);
2544         } else {
2545             int r = vercmp(CS(this).cvar_g_xonoticversion, autocvar_g_xonoticversion);
2546             if (r < 0) { // old client
2547                 Send_Notification(NOTIF_ONE_ONLY, this, MSG_INFO, INFO_VERSION_OUTDATED, autocvar_g_xonoticversion, CS(this).cvar_g_xonoticversion);
2548             } else if (r > 0) { // old server
2549                 Send_Notification(NOTIF_ONE_ONLY, this, MSG_INFO, INFO_VERSION_OLD, autocvar_g_xonoticversion, CS(this).cvar_g_xonoticversion);
2550             }
2551         }
2552     }
2553
2554         // GOD MODE info
2555         if (!(this.flags & FL_GODMODE) && this.max_armorvalue)
2556         {
2557                 Send_Notification(NOTIF_ONE_ONLY, this, MSG_INFO, INFO_GODMODE_OFF, this.max_armorvalue);
2558                 this.max_armorvalue = 0;
2559         }
2560
2561         if (frametime && IS_PLAYER(this))
2562         {
2563                 if (STAT(FROZEN, this) == FROZEN_TEMP_REVIVING)
2564                 {
2565                         STAT(REVIVE_PROGRESS, this) = bound(0, STAT(REVIVE_PROGRESS, this) + frametime * this.revive_speed, 1);
2566                         SetResourceExplicit(this, RES_HEALTH, max(1, STAT(REVIVE_PROGRESS, this) * start_health));
2567                         if (this.iceblock)
2568                                 this.iceblock.alpha = bound(0.2, 1 - STAT(REVIVE_PROGRESS, this), 1);
2569
2570                         if (STAT(REVIVE_PROGRESS, this) >= 1)
2571                                 Unfreeze(this, false);
2572                 }
2573                 else if (STAT(FROZEN, this) == FROZEN_TEMP_DYING)
2574                 {
2575                         STAT(REVIVE_PROGRESS, this) = bound(0, STAT(REVIVE_PROGRESS, this) - frametime * this.revive_speed, 1);
2576                         SetResourceExplicit(this, RES_HEALTH, max(0, autocvar_g_nades_ice_health + (start_health-autocvar_g_nades_ice_health) * STAT(REVIVE_PROGRESS, this)));
2577
2578                         if (GetResource(this, RES_HEALTH) < 1)
2579                         {
2580                                 if (this.vehicle)
2581                                         vehicles_exit(this.vehicle, VHEF_RELEASE);
2582                                 if(this.event_damage)
2583                                         this.event_damage(this, this, this.frozen_by, 1, DEATH_NADE_ICE_FREEZE.m_id, DMG_NOWEP, this.origin, '0 0 0');
2584                         }
2585                         else if (STAT(REVIVE_PROGRESS, this) <= 0)
2586                                 Unfreeze(this, false);
2587                 }
2588         }
2589
2590         MUTATOR_CALLHOOK(PlayerPreThink, this);
2591
2592         if(autocvar_g_vehicles_enter && (time > this.last_vehiclecheck) && !game_stopped && !this.vehicle)
2593         if(IS_PLAYER(this) && !STAT(FROZEN, this) && !IS_DEAD(this) && !IS_INDEPENDENT_PLAYER(this))
2594         {
2595                 FOREACH_ENTITY_RADIUS(this.origin, autocvar_g_vehicles_enter_radius, IS_VEHICLE(it) && !IS_DEAD(it) && it.takedamage != DAMAGE_NO,
2596                 {
2597                         if(!it.owner)
2598                         {
2599                                 if(!it.team || SAME_TEAM(this, it))
2600                                         Send_Notification(NOTIF_ONE, this, MSG_CENTER, CENTER_VEHICLE_ENTER);
2601                                 else if(autocvar_g_vehicles_steal)
2602                                         Send_Notification(NOTIF_ONE, this, MSG_CENTER, CENTER_VEHICLE_ENTER_STEAL);
2603                         }
2604                         else if((it.vehicle_flags & VHF_MULTISLOT) && SAME_TEAM(it.owner, this))
2605                         {
2606                                 Send_Notification(NOTIF_ONE, this, MSG_CENTER, CENTER_VEHICLE_ENTER_GUNNER);
2607                         }
2608                 });
2609
2610                 this.last_vehiclecheck = time + 1;
2611         }
2612
2613         if(!CS(this).cvar_cl_newusekeysupported) // FIXME remove this - it was a stupid idea to begin with, we can JUST use the button
2614         {
2615                 if(PHYS_INPUT_BUTTON_USE(this) && !CS(this).usekeypressed)
2616                         PlayerUseKey(this);
2617                 CS(this).usekeypressed = PHYS_INPUT_BUTTON_USE(this);
2618         }
2619
2620         if (IS_REAL_CLIENT(this))
2621                 PrintWelcomeMessage(this);
2622
2623         if (IS_PLAYER(this)) {
2624                 if (IS_REAL_CLIENT(this) && time < CS(this).jointime + MIN_SPEC_TIME)
2625                         error("Client can't be spawned as player on connection!");
2626                 if(!PlayerThink(this))
2627                         return;
2628         }
2629         else if (game_stopped || intermission_running) {
2630                 if(intermission_running)
2631                         IntermissionThink(this);
2632                 return;
2633         }
2634         else if (IS_REAL_CLIENT(this) && CS(this).autojoin_checked <= 0 && time >= CS(this).jointime + MIN_SPEC_TIME)
2635         {
2636                 bool early_join_requested = (CS(this).autojoin_checked < 0);
2637                 CS(this).autojoin_checked = 1;
2638                 // don't do this in ClientConnect
2639                 // many things can go wrong if a client is spawned as player on connection
2640                 if (early_join_requested || MUTATOR_CALLHOOK(AutoJoinOnConnection, this)
2641                         || (!(autocvar_sv_spectate || autocvar_g_campaign || (Player_GetForcedTeamIndex(this) == TEAM_FORCE_SPECTATOR))
2642                                 && (!teamplay || autocvar_g_balance_teams)))
2643                 {
2644                         campaign_bots_may_start = true;
2645                         if(joinAllowed(this))
2646                                 Join(this);
2647                         return;
2648                 }
2649         }
2650         else if (IS_OBSERVER(this) || IS_SPEC(this)) {
2651                 ObserverOrSpectatorThink(this);
2652         }
2653
2654         // WEAPONTODO: Add weapon request for this
2655         if (!zoomstate_set) {
2656                 bool wep_zoomed = false;
2657                 for(int slot = 0; slot < MAX_WEAPONSLOTS; ++slot)
2658                 {
2659                         .entity weaponentity = weaponentities[slot];
2660                         Weapon thiswep = this.(weaponentity).m_weapon;
2661                         if(thiswep != WEP_Null && thiswep.wr_zoom)
2662                                 wep_zoomed += thiswep.wr_zoom(thiswep, this);
2663                 }
2664                 SetZoomState(this, PHYS_INPUT_BUTTON_ZOOM(this) || PHYS_INPUT_BUTTON_ZOOMSCRIPT(this) || wep_zoomed);
2665         }
2666
2667         if (CS(this).teamkill_soundtime && time > CS(this).teamkill_soundtime)
2668         {
2669                 CS(this).teamkill_soundtime = 0;
2670
2671                 entity e = CS(this).teamkill_soundsource;
2672                 entity oldpusher = e.pusher;
2673                 e.pusher = this;
2674                 PlayerSound(e, playersound_teamshoot, CH_VOICE, VOL_BASEVOICE, VOICETYPE_LASTATTACKER_ONLY);
2675                 e.pusher = oldpusher;
2676         }
2677
2678         if (CS(this).taunt_soundtime && time > CS(this).taunt_soundtime) {
2679                 CS(this).taunt_soundtime = 0;
2680                 PlayerSound(this, playersound_taunt, CH_VOICE, VOL_BASEVOICE, VOICETYPE_AUTOTAUNT);
2681         }
2682
2683         target_voicescript_next(this);
2684
2685         // WEAPONTODO: Move into weaponsystem somehow
2686         // if a player goes unarmed after holding a loaded weapon, empty his clip size and remove the crosshair ammo ring
2687         for(int slot = 0; slot < MAX_WEAPONSLOTS; ++slot)
2688         {
2689                 .entity weaponentity = weaponentities[slot];
2690                 if(this.(weaponentity).m_weapon == WEP_Null)
2691                         this.(weaponentity).clip_load = this.(weaponentity).clip_size = 0;
2692         }
2693 }
2694
2695 void DrownPlayer(entity this)
2696 {
2697         if(IS_DEAD(this) || game_stopped || time < game_starttime || this.vehicle
2698                 || STAT(FROZEN, this) || this.watertype != CONTENT_WATER)
2699         {
2700                 STAT(AIR_FINISHED, this) = 0;
2701                 return;
2702         }
2703
2704         if (this.waterlevel != WATERLEVEL_SUBMERGED)
2705         {
2706                 if(STAT(AIR_FINISHED, this) && STAT(AIR_FINISHED, this) < time)
2707                         PlayerSound(this, playersound_gasp, CH_PLAYER, VOL_BASE, VOICETYPE_PLAYERSOUND);
2708                 STAT(AIR_FINISHED, this) = 0;
2709         }
2710         else
2711         {
2712                 if (!STAT(AIR_FINISHED, this))
2713                         STAT(AIR_FINISHED, this) = time + autocvar_g_balance_contents_drowndelay;
2714                 if (STAT(AIR_FINISHED, this) < time)
2715                 {       // drown!
2716                         if (this.pain_finished < time)
2717                         {
2718                                 Damage (this, NULL, NULL, autocvar_g_balance_contents_playerdamage_drowning * autocvar_g_balance_contents_damagerate, DEATH_DROWN.m_id, DMG_NOWEP, this.origin, '0 0 0');
2719                                 this.pain_finished = time + 0.5;
2720                         }
2721                 }
2722         }
2723 }
2724
2725 .bool move_qcphysics;
2726
2727 void Player_Physics(entity this)
2728 {
2729         this.movetype = (this.move_qcphysics) ? MOVETYPE_QCPLAYER : this.move_movetype;
2730
2731         if(!this.move_qcphysics)
2732                 return;
2733
2734         if(!frametime && !CS(this).pm_frametime)
2735                 return;
2736
2737         Movetype_Physics_NoMatchTicrate(this, CS(this).pm_frametime, true);
2738
2739         CS(this).pm_frametime = 0;
2740 }
2741
2742 /*
2743 =============
2744 PlayerPostThink
2745
2746 Called every frame for each client after the physics are run
2747 =============
2748 */
2749 void PlayerPostThink (entity this)
2750 {
2751         Player_Physics(this);
2752
2753         if (sv_maxidle > 0)
2754         if (frametime) // WORKAROUND: only use dropclient in server frames (frametime set). Never use it in cl_movement frames (frametime zero).
2755         if (IS_REAL_CLIENT(this))
2756         if (IS_PLAYER(this) || sv_maxidle_spectatorsareidle)
2757         {
2758                 int totalClients = 0;
2759                 if(sv_maxidle_slots > 0)
2760                 {
2761                         FOREACH_CLIENT(IS_REAL_CLIENT(it) || sv_maxidle_slots_countbots,
2762                         {
2763                                 ++totalClients;
2764                         });
2765                 }
2766
2767                 if (sv_maxidle_slots > 0 && (maxclients - totalClients) > sv_maxidle_slots)
2768                 { /* do nothing */ }
2769                 else if (time - CS(this).parm_idlesince < 1) // instead of (time == this.parm_idlesince) to support sv_maxidle <= 10
2770                 {
2771                         if (CS(this).idlekick_lasttimeleft)
2772                         {
2773                                 CS(this).idlekick_lasttimeleft = 0;
2774                                 Kill_Notification(NOTIF_ONE_ONLY, this, MSG_CENTER, CPID_IDLING);
2775                         }
2776                 }
2777                 else
2778                 {
2779                         float timeleft = ceil(sv_maxidle - (time - CS(this).parm_idlesince));
2780                         if (timeleft == min(10, sv_maxidle - 1)) { // - 1 to support sv_maxidle <= 10
2781                                 if (!CS(this).idlekick_lasttimeleft)
2782                                         Send_Notification(NOTIF_ONE_ONLY, this, MSG_CENTER, CENTER_DISCONNECT_IDLING, timeleft);
2783                         }
2784                         if (timeleft <= 0) {
2785                                 Send_Notification(NOTIF_ALL, NULL, MSG_INFO, INFO_QUIT_KICK_IDLING, this.netname);
2786                                 dropclient(this);
2787                                 return;
2788                         }
2789                         else if (timeleft <= 10) {
2790                                 if (timeleft != CS(this).idlekick_lasttimeleft) {
2791                                     Send_Notification(NOTIF_ONE, this, MSG_ANNCE, Announcer_PickNumber(CNT_IDLE, timeleft));
2792                 }
2793                                 CS(this).idlekick_lasttimeleft = timeleft;
2794                         }
2795                 }
2796         }
2797
2798         CheatFrame(this);
2799
2800         if (game_stopped)
2801         {
2802                 this.solid = SOLID_NOT;
2803                 this.takedamage = DAMAGE_NO;
2804                 set_movetype(this, MOVETYPE_NONE);
2805                 CS(this).teamkill_complain = 0;
2806                 CS(this).teamkill_soundtime = 0;
2807                 CS(this).teamkill_soundsource = NULL;
2808         }
2809
2810         if (IS_PLAYER(this)) {
2811                 if(this.death_time == time && IS_DEAD(this))
2812                 {
2813                         // player's bbox gets resized now, instead of in the damage event that killed the player,
2814                         // once all the damage events of this frame have been processed with normal size
2815                         this.maxs.z = 5;
2816                         setsize(this, this.mins, this.maxs);
2817                 }
2818                 DrownPlayer(this);
2819                 UpdateChatBubble(this);
2820                 if (CS(this).impulse) ImpulseCommands(this);
2821                 if (game_stopped)
2822                 {
2823                         CSQCMODEL_AUTOUPDATE(this);
2824                         return;
2825                 }
2826                 GetPressedKeys(this);
2827         }
2828         else if (IS_OBSERVER(this) && STAT(PRESSED_KEYS, this))
2829         {
2830                 CS(this).pressedkeys = 0;
2831                 STAT(PRESSED_KEYS, this) = 0;
2832         }
2833
2834         if (this.waypointsprite_attachedforcarrier) {
2835                 float hp = healtharmor_maxdamage(GetResource(this, RES_HEALTH), GetResource(this, RES_ARMOR), autocvar_g_balance_armor_blockpercent, DEATH_WEAPON.m_id).x;
2836                 WaypointSprite_UpdateHealth(this.waypointsprite_attachedforcarrier, hp);
2837         }
2838
2839         CSQCMODEL_AUTOUPDATE(this);
2840 }
2841
2842 /**
2843  * message "": do not say, just test flood control
2844  * return value:
2845  *   1 = accept
2846  *   0 = reject
2847  *  -1 = fake accept
2848  */
2849 int Say(entity source, int teamsay, entity privatesay, string msgin, bool floodcontrol)
2850 {
2851         if (!teamsay && !privatesay && substring(msgin, 0, 1) == " ")
2852                 msgin = substring(msgin, 1, -1); // work around DP say bug (say_team does not have this!)
2853
2854         if (source)
2855                 msgin = formatmessage(source, msgin);
2856
2857         string colorstr;
2858         if (!(IS_PLAYER(source) || source.caplayer))
2859                 colorstr = "^0"; // black for spectators
2860         else if(teamplay)
2861                 colorstr = Team_ColorCode(source.team);
2862         else
2863         {
2864                 colorstr = "";
2865                 teamsay = false;
2866         }
2867
2868         if (!source) {
2869                 colorstr = "";
2870                 teamsay = false;
2871         }
2872
2873         if(msgin != "")
2874                 msgin = trigger_magicear_processmessage_forallears(source, teamsay, privatesay, msgin);
2875
2876         /*
2877          * using bprint solves this... me stupid
2878         // how can we prevent the message from appearing in a listen server?
2879         // for now, just give "say" back and only handle say_team
2880         if(!teamsay)
2881         {
2882                 clientcommand(source, strcat("say ", msgin));
2883                 return;
2884         }
2885         */
2886
2887         string namestr = "";
2888         if (source)
2889                 namestr = playername(source, autocvar_g_chat_teamcolors);
2890
2891         string colorprefix = (strdecolorize(namestr) == namestr) ? "^3" : "^7";
2892
2893         string msgstr = "", cmsgstr = "";
2894         string privatemsgprefix = string_null;
2895         int privatemsgprefixlen = 0;
2896         if (msgin != "")
2897         {
2898                 bool found_me = false;
2899                 if(strstrofs(msgin, "/me", 0) >= 0)
2900                 {
2901                         string newmsgin = "";
2902                         string newnamestr = ((teamsay) ? strcat(colorstr, "(", colorprefix, namestr, colorstr, ")", "^7") : strcat(colorprefix, namestr, "^7"));
2903                         FOREACH_WORD(msgin, true,
2904                         {
2905                                 if(strdecolorize(it) == "/me")
2906                                 {
2907                                         found_me = true;
2908                                         newmsgin = cons(newmsgin, newnamestr);
2909                                 }
2910                                 else
2911                                         newmsgin = cons(newmsgin, it);
2912                         });
2913                         msgin = newmsgin;
2914                 }
2915
2916                 if(privatesay)
2917                 {
2918                         msgstr = strcat("\{1}\{13}* ", colorprefix, namestr, "^3 tells you: ^7");
2919                         privatemsgprefixlen = strlen(msgstr);
2920                         msgstr = strcat(msgstr, msgin);
2921                         cmsgstr = strcat(colorstr, colorprefix, namestr, "^3 tells you:\n^7", msgin);
2922                         privatemsgprefix = strcat("\{1}\{13}* ^3You tell ", playername(privatesay, autocvar_g_chat_teamcolors), ": ^7");
2923                 }
2924                 else if(teamsay)
2925                 {
2926                         if(found_me)
2927                         {
2928                                 //msgin = strreplace("/me", "", msgin);
2929                                 //msgin = substring(msgin, 3, strlen(msgin));
2930                                 //msgin = strreplace("/me", strcat(colorstr, "(", colorprefix, namestr, colorstr, ")^7"), msgin);
2931                                 msgstr = strcat("\{1}\{13}^4* ", "^7", msgin);
2932                         }
2933                         else
2934                                 msgstr = strcat("\{1}\{13}", colorstr, "(", colorprefix, namestr, colorstr, ") ^7", msgin);
2935                         cmsgstr = strcat(colorstr, "(", colorprefix, namestr, colorstr, ")\n^7", msgin);
2936                 }
2937                 else
2938                 {
2939                         if(found_me)
2940                         {
2941                                 //msgin = strreplace("/me", "", msgin);
2942                                 //msgin = substring(msgin, 3, strlen(msgin));
2943                                 //msgin = strreplace("/me", strcat(colorprefix, namestr), msgin);
2944                                 msgstr = strcat("\{1}^4* ^7", msgin);
2945                         }
2946                         else {
2947                                 msgstr = "\{1}";
2948                                 msgstr = strcat(msgstr, (namestr != "") ? strcat(colorprefix, namestr, "^7: ") : "^7");
2949                                 msgstr = strcat(msgstr, msgin);
2950                         }
2951                         cmsgstr = "";
2952                 }
2953                 msgstr = strcat(strreplace("\n", " ", msgstr), "\n"); // newlines only are good for centerprint
2954         }
2955
2956         string fullmsgstr = msgstr;
2957         string fullcmsgstr = cmsgstr;
2958
2959         // FLOOD CONTROL
2960         int flood = 0;
2961         var .float flood_field = floodcontrol_chat;
2962         if(floodcontrol && source)
2963         {
2964                 float flood_spl;
2965                 float flood_burst;
2966                 float flood_lmax;
2967                 float lines;
2968                 if(privatesay)
2969                 {
2970                         flood_spl = autocvar_g_chat_flood_spl_tell;
2971                         flood_burst = autocvar_g_chat_flood_burst_tell;
2972                         flood_lmax = autocvar_g_chat_flood_lmax_tell;
2973                         flood_field = floodcontrol_chattell;
2974                 }
2975                 else if(teamsay)
2976                 {
2977                         flood_spl = autocvar_g_chat_flood_spl_team;
2978                         flood_burst = autocvar_g_chat_flood_burst_team;
2979                         flood_lmax = autocvar_g_chat_flood_lmax_team;
2980                         flood_field = floodcontrol_chatteam;
2981                 }
2982                 else
2983                 {
2984                         flood_spl = autocvar_g_chat_flood_spl;
2985                         flood_burst = autocvar_g_chat_flood_burst;
2986                         flood_lmax = autocvar_g_chat_flood_lmax;
2987                         flood_field = floodcontrol_chat;
2988                 }
2989                 flood_burst = max(0, flood_burst - 1);
2990                 // to match explanation in default.cfg, a value of 3 must allow three-line bursts and not four!
2991
2992                 // do flood control for the default line size
2993                 if(msgstr != "")
2994                 {
2995                         getWrappedLine_remaining = msgstr;
2996                         msgstr = "";
2997                         lines = 0;
2998                         while(getWrappedLine_remaining && (!flood_lmax || lines <= flood_lmax))
2999                         {
3000                                 msgstr = strcat(msgstr, " ", getWrappedLineLen(82.4289758859709, strlennocol)); // perl averagewidth.pl < gfx/vera-sans.width
3001                                 ++lines;
3002                         }
3003                         msgstr = substring(msgstr, 1, strlen(msgstr) - 1);
3004
3005                         if(getWrappedLine_remaining != "")
3006                         {
3007                                 msgstr = strcat(msgstr, "\n");
3008                                 flood = 2;
3009                         }
3010
3011                         if (time >= source.(flood_field))
3012                         {
3013                                 source.(flood_field) = max(time - flood_burst * flood_spl, source.(flood_field)) + lines * flood_spl;
3014                         }
3015                         else
3016                         {
3017                                 flood = 1;
3018                                 msgstr = fullmsgstr;
3019                         }
3020                 }
3021                 else
3022                 {
3023                         if (time >= source.(flood_field))
3024                                 source.(flood_field) = max(time - flood_burst * flood_spl, source.(flood_field)) + flood_spl;
3025                         else
3026                                 flood = 1;
3027                 }
3028
3029                 if (timeout_status == TIMEOUT_ACTIVE) // when game is paused, no flood protection
3030                         source.(flood_field) = flood = 0;
3031         }
3032
3033         string sourcemsgstr, sourcecmsgstr;
3034         if(flood == 2) // cannot happen for empty msgstr
3035         {
3036                 if(autocvar_g_chat_flood_notify_flooder)
3037                 {
3038                         sourcemsgstr = strcat(msgstr, "\n^3FLOOD CONTROL: ^7message too long, trimmed\n");
3039                         sourcecmsgstr = "";
3040                 }
3041                 else
3042                 {
3043                         sourcemsgstr = fullmsgstr;
3044                         sourcecmsgstr = fullcmsgstr;
3045                 }
3046                 cmsgstr = "";
3047         }
3048         else
3049         {
3050                 sourcemsgstr = msgstr;
3051                 sourcecmsgstr = cmsgstr;
3052         }
3053
3054         if (!privatesay && source && !(IS_PLAYER(source) || source.caplayer))
3055         {
3056                 if (!game_stopped)
3057                 if (teamsay || (autocvar_g_chat_nospectators == 1) || (autocvar_g_chat_nospectators == 2 && !warmup_stage))
3058                         teamsay = -1; // spectators
3059         }
3060
3061         if(flood)
3062                 LOG_INFO("NOTE: ", playername(source, true), "^7 is flooding.");
3063
3064         // build sourcemsgstr by cutting off a prefix and replacing it by the other one
3065         if(privatesay)
3066                 sourcemsgstr = strcat(privatemsgprefix, substring(sourcemsgstr, privatemsgprefixlen, -1));
3067
3068         int ret;
3069         if(source && CS(source).muted)
3070         {
3071                 // always fake the message
3072                 ret = -1;
3073         }
3074         else if(flood == 1)
3075         {
3076                 if (autocvar_g_chat_flood_notify_flooder)
3077                 {
3078                         sprint(source, strcat("^3FLOOD CONTROL: ^7wait ^1", ftos(source.(flood_field) - time), "^3 seconds\n"));
3079                         ret = 0;
3080                 }
3081                 else
3082                         ret = -1;
3083         }
3084         else
3085         {
3086                 ret = 1;
3087         }
3088
3089         if (privatesay && source && !(IS_PLAYER(source) || source.caplayer))
3090         {
3091                 if (!game_stopped)
3092                 if ((privatesay && (IS_PLAYER(privatesay) || privatesay.caplayer)) && ((autocvar_g_chat_nospectators == 1) || (autocvar_g_chat_nospectators == 2 && !warmup_stage)))
3093                         ret = -1; // just hide the message completely
3094         }
3095
3096         MUTATOR_CALLHOOK(ChatMessage, source, ret);
3097         ret = M_ARGV(1, int);
3098
3099         string event_log_msg = "";
3100
3101         if(sourcemsgstr != "" && ret != 0)
3102         {
3103                 if(ret < 0) // faked message, because the player is muted
3104                 {
3105                         sprint(source, sourcemsgstr);
3106                         if(sourcecmsgstr != "" && !privatesay)
3107                                 centerprint(source, sourcecmsgstr);
3108                 }
3109                 else if(privatesay) // private message, between 2 people only
3110                 {
3111                         sprint(source, sourcemsgstr);
3112                         if (!autocvar_g_chat_tellprivacy) { dedicated_print(msgstr); } // send to server console too if "tellprivacy" is disabled
3113                         if(!MUTATOR_CALLHOOK(ChatMessageTo, privatesay, source))
3114                         {
3115                                 sprint(privatesay, msgstr);
3116                                 if(cmsgstr != "")
3117                                         centerprint(privatesay, cmsgstr);
3118                         }
3119                 }
3120                 else if ( teamsay && CS(source).active_minigame )
3121                 {
3122                         sprint(source, sourcemsgstr);
3123                         dedicated_print(msgstr); // send to server console too
3124                         FOREACH_CLIENT(IS_REAL_CLIENT(it) && it != source && CS(it).active_minigame == CS(source).active_minigame && !MUTATOR_CALLHOOK(ChatMessageTo, it, source), {
3125                                 sprint(it, msgstr);
3126                         });
3127                         event_log_msg = sprintf(":chat_minigame:%d:%s:%s", source.playerid, CS(source).active_minigame.netname, msgin);
3128
3129                 }
3130                 else if(teamsay > 0) // team message, only sent to team mates
3131                 {
3132                         sprint(source, sourcemsgstr);
3133                         dedicated_print(msgstr); // send to server console too
3134                         if(sourcecmsgstr != "")
3135                                 centerprint(source, sourcecmsgstr);
3136                         FOREACH_CLIENT((IS_PLAYER(it) || it.caplayer) && IS_REAL_CLIENT(it) && it != source && it.team == source.team && !MUTATOR_CALLHOOK(ChatMessageTo, it, source), {
3137                                 sprint(it, msgstr);
3138                                 if(cmsgstr != "")
3139                                         centerprint(it, cmsgstr);
3140                         });
3141                         event_log_msg = sprintf(":chat_team:%d:%d:%s", source.playerid, source.team, strreplace("\n", " ", msgin));
3142                 }
3143                 else if(teamsay < 0) // spectator message, only sent to spectators
3144                 {
3145                         sprint(source, sourcemsgstr);
3146                         dedicated_print(msgstr); // send to server console too
3147                         FOREACH_CLIENT(!(IS_PLAYER(it) || it.caplayer) && IS_REAL_CLIENT(it) && it != source && !MUTATOR_CALLHOOK(ChatMessageTo, it, source), {
3148                                 sprint(it, msgstr);
3149                         });
3150                         event_log_msg = sprintf(":chat_spec:%d:%s", source.playerid, strreplace("\n", " ", msgin));
3151                 }
3152                 else
3153                 {
3154                         if (source) {
3155                                 sprint(source, sourcemsgstr);
3156                                 dedicated_print(msgstr); // send to server console too
3157                                 MX_Say(strcat(playername(source, true), "^7: ", msgin));
3158                         }
3159                         FOREACH_CLIENT(IS_REAL_CLIENT(it) && it != source && !MUTATOR_CALLHOOK(ChatMessageTo, it, source), {
3160                                 sprint(it, msgstr);
3161                         });
3162                         event_log_msg = sprintf(":chat:%d:%s", source.playerid, strreplace("\n", " ", msgin));
3163                 }
3164         }
3165
3166         if (autocvar_sv_eventlog && (event_log_msg != "")) {
3167                 GameLogEcho(event_log_msg);
3168         }
3169
3170         return ret;
3171 }
3172
3173 // hack to copy the button fields from the client entity to the Client State
3174 void PM_UpdateButtons(entity this, entity store)
3175 {
3176         if(this.impulse)
3177                 store.impulse = this.impulse;
3178         this.impulse = 0;
3179
3180         bool typing = this.buttonchat || this.button12;
3181
3182         store.button0 = (typing) ? 0 : this.button0;
3183         //button1?!
3184         store.button2 = (typing) ? 0 : this.button2;
3185         store.button3 = (typing) ? 0 : this.button3;
3186         store.button4 = this.button4;
3187         store.button5 = (typing) ? 0 : this.button5;
3188         store.button6 = this.button6;
3189         store.button7 = this.button7;
3190         store.button8 = this.button8;
3191         store.button9 = this.button9;
3192         store.button10 = this.button10;
3193         store.button11 = this.button11;
3194         store.button12 = this.button12;
3195         store.button13 = this.button13;
3196         store.button14 = this.button14;
3197         store.button15 = this.button15;
3198         store.button16 = this.button16;
3199         store.buttonuse = this.buttonuse;
3200         store.buttonchat = this.buttonchat;
3201
3202         store.cursor_active = this.cursor_active;
3203         store.cursor_screen = this.cursor_screen;
3204         store.cursor_trace_start = this.cursor_trace_start;
3205         store.cursor_trace_endpos = this.cursor_trace_endpos;
3206         store.cursor_trace_ent = this.cursor_trace_ent;
3207
3208         store.ping = this.ping;
3209         store.ping_packetloss = this.ping_packetloss;
3210         store.ping_movementloss = this.ping_movementloss;
3211
3212         store.v_angle = this.v_angle;
3213         store.movement = this.movement;
3214 }
3215
3216 NET_HANDLE(fpsreport, bool)
3217 {
3218         int fps = ReadShort();
3219         PlayerScore_Set(sender, SP_FPS, fps);
3220         return true;
3221 }