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