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