]> icculus.org git repositories - divverent/nexuiz.git/blob - data/qcsrc/server/cl_player.qc
fix a file handle leak in per-model gibs
[divverent/nexuiz.git] / data / qcsrc / server / cl_player.qc
1
2 // changes by LordHavoc on 03/29/04 and 03/30/04 at Vermeulen's request
3 // merged player_run and player_stand to player_anim
4 // added death animations to player_anim
5 // can now spawn thrown weapons from anywhere, not just from players
6 // thrown weapons now fade out after 20 seconds
7 // created PlayerGib function
8 // PlayerDie no longer uses hitloc or damage
9 // PlayerDie now supports dying animations as well as gibbing
10 // cleaned up PlayerDie a lot
11 // added CopyBody
12
13 .entity pusher;
14 .float pushltime;
15
16 void CopyBody(float keepvelocity)
17 {
18         local entity oldself;
19         if (self.effects & EF_NODRAW)
20                 return;
21         oldself = self;
22         self = spawn();
23         self.enemy = oldself;
24         self.lip = oldself.lip;
25         self.colormap = oldself.colormap;
26         self.iscreature = oldself.iscreature;
27         self.angles = oldself.angles;
28         self.avelocity = oldself.avelocity;
29         self.classname = "body";
30         self.damageforcescale = oldself.damageforcescale;
31         self.effects = oldself.effects;
32         self.event_damage = oldself.event_damage;
33         self.animstate_startframe = oldself.animstate_startframe;
34         self.animstate_numframes = oldself.animstate_numframes;
35         self.animstate_framerate = oldself.animstate_framerate;
36         self.animstate_starttime = oldself.animstate_starttime;
37         self.animstate_endtime = oldself.animstate_endtime;
38         self.animstate_override = oldself.animstate_override;
39         self.animstate_looping = oldself.animstate_looping;
40         self.frame = oldself.frame;
41         self.dead_frame = oldself.dead_frame;
42         self.pain_finished = oldself.pain_finished;
43         self.health = oldself.health;
44         self.armorvalue = oldself.armorvalue;
45         self.armortype = oldself.armortype;
46         self.model = oldself.model;
47         self.modelindex = oldself.modelindex;
48         self.species = oldself.species;
49         self.movetype = oldself.movetype;
50         self.nextthink = oldself.nextthink;
51         self.skin = oldself.skin;
52         self.solid = oldself.solid;
53         self.takedamage = oldself.takedamage;
54         self.think = oldself.think;
55         self.customizeentityforclient = oldself.customizeentityforclient;
56         if (keepvelocity == 1)
57                 self.velocity = oldself.velocity;
58         self.oldvelocity = self.velocity;
59         self.fade_time = oldself.fade_time;
60         self.fade_rate = oldself.fade_rate;
61         //self.weapon = oldself.weapon;
62         setorigin(self, oldself.origin);
63         setsize(self, oldself.mins, oldself.maxs);
64         self.prevorigin = oldself.origin;
65         self.reset = SUB_Remove;
66
67         Drag_MoveDrag(oldself, self);
68
69         self = oldself;
70 }
71
72 float player_getspecies()
73 {
74         local float glob, i, j, fh, len, s, sk;
75         local string fn, l;
76
77         s = -1;
78
79         glob = search_begin("models/player/*.txt", TRUE, TRUE);
80         if(glob < 0)
81                 return s;
82         for(j = 0; j <= 1; ++j)
83         {
84                 for(i = 0; i < search_getsize(glob); ++i)
85                 {
86                         fn = search_getfilename(glob, i);
87                         fh = fopen(fn, FILE_READ);
88                         if(fh < 0)
89                                 continue;
90                         fgets(fh); fgets(fh);
91                         sk = stof(fgets(fh));
92                         if(sk == (j ? 0 : self.skin)) // 2nd pass skips the skin test
93                         if(fgets(fh) == self.model)
94                         {
95                                 l = fgets(fh);
96                                 len = tokenize_console(l);
97                                 if (len != 2)
98                                         goto nospecies;
99                                 if (argv(0) != "species")
100                                         goto nospecies;
101                                 switch(argv(1))
102                                 {
103                                         case "human":       s = SPECIES_HUMAN;       break;
104                                         case "alien":       s = SPECIES_ALIEN;       break;
105                                         case "robot_shiny": s = SPECIES_ROBOT_SHINY; break;
106                                         case "robot_rusty": s = SPECIES_ROBOT_RUSTY; break;
107                                         case "animal":      s = SPECIES_ANIMAL;      break;
108                                         case "reserved":    s = SPECIES_RESERVED;    break;
109                                 }
110                         }
111 :nospecies
112                         fclose(fh);
113                 }
114                 if (s >= 0)
115                         break;
116         }
117         search_end(glob);
118
119         if (s < 0)
120                 s = SPECIES_HUMAN;
121
122         return s;
123 }
124
125 void player_setupanimsformodel()
126 {
127         local string animfilename;
128         local float animfile;
129         // defaults for legacy .zym models without animinfo files
130         self.anim_die1 = '0 1 0.5'; // 2 seconds
131         self.anim_die2 = '1 1 0.5'; // 2 seconds
132         self.anim_draw = '2 1 3'; // TODO: analyze models and set framerate
133         self.anim_duck = '3 1 100'; // this anim seems bogus in most models, so make it play VERY briefly!
134         self.anim_duckwalk = '4 1 1';
135         self.anim_duckjump = '5 1 100'; // zym anims keep playing until changed, so this only has to start the anim, landing will end it
136         self.anim_duckidle = '6 1 1';
137         self.anim_idle = '7 1 1';
138         self.anim_jump = '8 1 100'; // zym anims keep playing until changed, so this only has to start the anim, landing will end it
139         self.anim_pain1 = '9 1 2'; // 0.5 seconds
140         self.anim_pain2 = '10 1 2'; // 0.5 seconds
141         self.anim_shoot = '11 1 5'; // TODO: analyze models and set framerate
142         self.anim_taunt = '12 1 1'; // FIXME?  there is no code using this anim
143         self.anim_run = '13 1 1';
144         self.anim_runbackwards = '14 1 1';
145         self.anim_strafeleft = '15 1 1';
146         self.anim_straferight = '16 1 1';
147         self.anim_dead1 = '17 1 1';
148         self.anim_dead2 = '18 1 1';
149         self.anim_forwardright = '19 1 1';
150         self.anim_forwardleft = '20 1 1';
151         self.anim_backright = '21 1 1';
152         self.anim_backleft  = '22 1 1';
153         animparseerror = FALSE;
154         animfilename = strcat(self.model, ".animinfo");
155         animfile = fopen(animfilename, FILE_READ);
156         if (animfile >= 0)
157         {
158                 self.anim_die1         = animparseline(animfile);
159                 self.anim_die2         = animparseline(animfile);
160                 self.anim_draw         = animparseline(animfile);
161                 self.anim_duck         = animparseline(animfile);
162                 self.anim_duckwalk     = animparseline(animfile);
163                 self.anim_duckjump     = animparseline(animfile);
164                 self.anim_duckidle     = animparseline(animfile);
165                 self.anim_idle         = animparseline(animfile);
166                 self.anim_jump         = animparseline(animfile);
167                 self.anim_pain1        = animparseline(animfile);
168                 self.anim_pain2        = animparseline(animfile);
169                 self.anim_shoot        = animparseline(animfile);
170                 self.anim_taunt        = animparseline(animfile);
171                 self.anim_run          = animparseline(animfile);
172                 self.anim_runbackwards = animparseline(animfile);
173                 self.anim_strafeleft   = animparseline(animfile);
174                 self.anim_straferight  = animparseline(animfile);
175                 self.anim_forwardright = animparseline(animfile);
176                 self.anim_forwardleft  = animparseline(animfile);
177                 self.anim_backright    = animparseline(animfile);
178                 self.anim_backleft     = animparseline(animfile);
179                 fclose(animfile);
180
181                 // derived anims
182                 self.anim_dead1 = '0 1 1' + '1 0 0' * (self.anim_die1_x + self.anim_die1_y - 1);
183                 self.anim_dead2 = '0 1 1' + '1 0 0' * (self.anim_die2_x + self.anim_die2_y - 1);
184
185                 if (animparseerror)
186                         print("Parse error in ", animfilename, ", some player animations are broken\n");
187         }
188         else
189                 dprint("File ", animfilename, " not found, assuming legacy .zym model animation timings\n");
190         // reset animstate now
191         setanim(self, self.anim_idle, TRUE, FALSE, TRUE);
192 };
193
194 void player_anim (void)
195 {
196         updateanim(self);
197         if (self.weaponentity)
198                 updateanim(self.weaponentity);
199
200         if (self.deadflag != DEAD_NO)
201         {
202                 if (time > self.animstate_endtime)
203                 {
204                         if (self.maxs_z > 5)
205                         {
206                                 self.maxs_z = 5;
207                                 setsize(self, self.mins, self.maxs);
208                         }
209                         self.frame = self.dead_frame;
210                 }
211                 return;
212         }
213
214         if (!self.animstate_override)
215         {
216                 if (!(self.flags & FL_ONGROUND))
217                 {
218                         if (self.crouch)
219                                 setanim(self, self.anim_duckjump, FALSE, TRUE, FALSE);
220                         else
221                                 setanim(self, self.anim_jump, FALSE, TRUE, FALSE);
222                 }
223                 else if (self.crouch)
224                 {
225                         if (self.movement_x * self.movement_x + self.movement_y * self.movement_y > 20)
226                                 setanim(self, self.anim_duckwalk, TRUE, FALSE, FALSE);
227                         else
228                                 setanim(self, self.anim_duckidle, TRUE, FALSE, FALSE);
229                 }
230                 else if ((self.movement_x * self.movement_x + self.movement_y * self.movement_y) > 20)
231                 {
232                         if (self.movement_x > 0 && self.movement_y == 0)
233                                 setanim(self, self.anim_run, TRUE, FALSE, FALSE);
234                         else if (self.movement_x < 0 && self.movement_y == 0)
235                                 setanim(self, self.anim_runbackwards, TRUE, FALSE, FALSE);
236                         else if (self.movement_x == 0 && self.movement_y > 0)
237                                 setanim(self, self.anim_straferight, TRUE, FALSE, FALSE);
238                         else if (self.movement_x == 0 && self.movement_y < 0)
239                                 setanim(self, self.anim_strafeleft, TRUE, FALSE, FALSE);
240                         else if (self.movement_x > 0 && self.movement_y > 0)
241                                 setanim(self, self.anim_forwardright, TRUE, FALSE, FALSE);
242                         else if (self.movement_x > 0 && self.movement_y < 0)
243                                 setanim(self, self.anim_forwardleft, TRUE, FALSE, FALSE);
244                         else if (self.movement_x < 0 && self.movement_y > 0)
245                                 setanim(self, self.anim_backright, TRUE, FALSE, FALSE);
246                         else if (self.movement_x < 0 && self.movement_y < 0)
247                                 setanim(self, self.anim_backleft, TRUE, FALSE, FALSE);
248                         else
249                                 setanim(self, self.anim_run, TRUE, FALSE, FALSE);
250                 }
251                 else
252                         setanim(self, self.anim_idle, TRUE, FALSE, FALSE);
253         }
254
255         if (self.weaponentity)
256         if (!self.weaponentity.animstate_override)
257                 setanim(self.weaponentity, self.weaponentity.anim_idle, TRUE, FALSE, FALSE);
258 }
259
260 void SpawnThrownWeapon (vector org, float w)
261 {
262         if(g_pinata)
263         {
264                 float j;
265                 for(j = WEP_FIRST; j <= WEP_LAST; ++j)
266                 {
267                         if(self.weapons & W_WeaponBit(j))
268                                 if(W_IsWeaponThrowable(j))
269                                         W_ThrowNewWeapon(self, j, FALSE, self.origin, randomvec() * 175 + '0 0 325');
270                 }
271         }
272         else
273                 W_ThrowWeapon(randomvec() * 125 + '0 0 200', org - self.origin, FALSE);
274 }
275
276 void PlayerCorpseDamage (entity inflictor, entity attacker, float damage, float deathtype, vector hitloc, vector force)
277 {
278         local float take, save;
279         Violence_GibSplash_At(hitloc, force, 2, bound(0, damage, 200) / 16);
280
281         // damage resistance (ignore most of the damage from a bullet or similar)
282         damage = max(damage - 5, 1);
283
284         save = bound(0, damage * cvar("g_balance_armor_blockpercent"), self.armorvalue);
285         take = bound(0, damage - save, damage);
286
287         if (save > 10)
288                 sound (self, CHAN_PROJECTILE, "misc/armorimpact.wav", VOL_BASE, ATTN_NORM);
289         else if (take > 30)
290                 sound (self, CHAN_PROJECTILE, "misc/bodyimpact2.wav", VOL_BASE, ATTN_NORM);
291         else if (take > 10)
292                 sound (self, CHAN_PROJECTILE, "misc/bodyimpact1.wav", VOL_BASE, ATTN_NORM);
293
294         if (take > 50)
295                 Violence_GibSplash_At(hitloc, force * -0.1, 3, 1);
296         if (take > 100)
297                 Violence_GibSplash_At(hitloc, force * -0.2, 3, 1);
298
299         if (!(self.flags & FL_GODMODE))
300         {
301                 self.armorvalue = self.armorvalue - save;
302                 self.health = self.health - take;
303                 // pause regeneration for 5 seconds
304                 self.pauseregen_finished = max(self.pauseregen_finished, time + cvar("g_balance_pause_health_regen"));
305         }
306         self.dmg_save = self.dmg_save + save;//max(save - 10, 0);
307         self.dmg_take = self.dmg_take + take;//max(take - 10, 0);
308         self.dmg_inflictor = inflictor;
309
310         if (self.health <= -75 && self.modelindex != 0)
311         {
312                 // don't use any animations as a gib
313                 self.frame = 0;
314                 self.dead_frame = 0;
315                 // view just above the floor
316                 self.view_ofs = '0 0 4';
317
318                 Violence_GibSplash(self, 1, 1);
319                 self.modelindex = 0; // restore later
320                 self.solid = SOLID_NOT; // restore later
321         }
322 }
323
324 void ClientKill_Now_TeamChange();
325
326 void PlayerDamage (entity inflictor, entity attacker, float damage, float deathtype, vector hitloc, vector force)
327 {
328         local float take, save, waves, sdelay;
329
330         if(!DEATH_ISSPECIAL(deathtype))
331         {
332                 damage *= sqrt(bound(1.0, self.cvar_cl_handicap, 100.0));
333                 if(self != attacker)
334                         damage /= sqrt(bound(1.0, attacker.cvar_cl_handicap, 100.0));
335         }
336
337         Violence_GibSplash_At(hitloc, force, 2, bound(0, damage, 200) / 16);
338
339         if(g_arena)
340         if(numspawned < 2)
341                 return;
342
343         if (!g_minstagib)
344         {
345                 save = bound(0, damage * cvar("g_balance_armor_blockpercent"), self.armorvalue);
346                 take = bound(0, damage - save, damage);
347         }
348         else
349         {
350                 save = 0;
351                 take = damage;
352         }
353
354         if (save > 10)
355                 sound (self, CHAN_PROJECTILE, "misc/armorimpact.wav", VOL_BASE, ATTN_NORM);
356         else if (take > 30)
357                 sound (self, CHAN_PROJECTILE, "misc/bodyimpact2.wav", VOL_BASE, ATTN_NORM);
358         else if (take > 10)
359                 sound (self, CHAN_PROJECTILE, "misc/bodyimpact1.wav", VOL_BASE, ATTN_NORM); // FIXME possibly remove them?
360
361         if (take > 50)
362                 Violence_GibSplash_At(hitloc, force * -0.1, 3, 1);
363         if (take > 100)
364                 Violence_GibSplash_At(hitloc, force * -0.2, 3, 1);
365
366         if (time > self.spawnshieldtime)
367         {
368                 if (!(self.flags & FL_GODMODE))
369                 {
370                         self.armorvalue = self.armorvalue - save;
371                         self.health = self.health - take;
372                         // pause regeneration for 5 seconds
373                         self.pauseregen_finished = max(self.pauseregen_finished, time + cvar("g_balance_pause_health_regen"));
374
375                         if (time > self.pain_finished)          //Don't switch pain sequences like crazy
376                         {
377                                 self.pain_finished = time + 0.5;        //Supajoe
378
379                                 if(sv_gentle < 1) {             
380                                         if (random() > 0.5)
381                                                 setanim(self, self.anim_pain1, FALSE, TRUE, TRUE);
382                                         else
383                                                 setanim(self, self.anim_pain2, FALSE, TRUE, TRUE);
384
385                                         if(!DEATH_ISWEAPON(deathtype, WEP_LASER) || attacker != self || self.health < 2 * cvar("g_balance_laser_primary_damage") * cvar("g_balance_selfdamagepercent") + 1)
386                                         // exclude pain sounds for laserjumps as long as you aren't REALLY low on health and would die of the next two
387                                         {
388                                                 if(self.health > 75) // TODO make a "gentle" version?
389                                                         PlayerSound(playersound_pain100, CHAN_PAIN, VOICETYPE_PLAYERSOUND);
390                                                 else if(self.health > 50)
391                                                         PlayerSound(playersound_pain75, CHAN_PAIN, VOICETYPE_PLAYERSOUND);
392                                                 else if(self.health > 25)
393                                                         PlayerSound(playersound_pain50, CHAN_PAIN, VOICETYPE_PLAYERSOUND);
394                                                 else if(self.health > 1)
395                                                         PlayerSound(playersound_pain25, CHAN_PAIN, VOICETYPE_PLAYERSOUND);
396                                         }
397                                 }
398
399                                 // throw off bot aim temporarily
400                                 local float shake;
401                                 shake = damage * 5 / (bound(0,skill,100) + 1);
402                                 self.v_angle_x = self.v_angle_x + (random() * 2 - 1) * shake;
403                                 self.v_angle_y = self.v_angle_y + (random() * 2 - 1) * shake;
404                         }
405                 }
406                 else
407                         self.max_armorvalue += (save + take);
408         }
409         self.dmg_save = self.dmg_save + save;//max(save - 10, 0);
410         self.dmg_take = self.dmg_take + take;//max(take - 10, 0);
411         self.dmg_inflictor = inflictor;
412
413         if(attacker == self)
414         {
415                 // don't reset pushltime for self damage as it may be an attempt to
416                 // escape a lava pit or similar
417                 //self.pushltime = 0;
418         }
419         else if(attacker.classname == "player" || attacker.classname == "gib")
420         {
421                 self.pusher = attacker;
422                 self.pushltime = time + cvar("g_maxpushtime");
423         }
424         else if(time < self.pushltime)
425         {
426                 attacker = self.pusher;
427                 self.pushltime = max(self.pushltime, time + 0.6);
428         }
429         else
430                 self.pushltime = 0;
431
432         if (self.health < 1)
433         {
434                 float defer_ClientKill_Now_TeamChange;
435                 defer_ClientKill_Now_TeamChange = FALSE;
436
437                 if(sv_gentle < 1) // TODO make a "gentle" version?
438                 {
439                         if(deathtype == DEATH_DROWN)
440                                 PlayerSound(playersound_drown, CHAN_PAIN, VOICETYPE_PLAYERSOUND);
441                         else
442                                 PlayerSound(playersound_death, CHAN_PAIN, VOICETYPE_PLAYERSOUND);
443                 }
444
445                 // get rid of kill indicator
446                 if(self.killindicator)
447                 {
448                         remove(self.killindicator);
449                         self.killindicator = world;
450                         if(self.killindicator_teamchange)
451                                 defer_ClientKill_Now_TeamChange = TRUE;
452
453                         if(self.classname == "body")
454                         if(deathtype == DEATH_KILL)
455                         {
456                                 // for the lemmings fans, a small harmless explosion
457                                 pointparticles(particleeffectnum("rocket_explode"), self.origin, '0 0 0', 1);
458                         }
459                 }
460
461                 // become fully visible
462                 self.alpha = 1;
463                 // clear selected player display
464                 ClearSelectedPlayer();
465                 // throw a weapon
466                 SpawnThrownWeapon (self.origin + (self.mins + self.maxs) * 0.5, self.switchweapon);
467                 // print an obituary message
468                 Obituary (attacker, inflictor, self, deathtype);
469                 race_PreDie();
470                 DropAllRunes(self);
471                 if(self == attacker)
472                         kh_Key_DropAll(self, TRUE);
473                 else if(attacker.classname == "player" || attacker.classname == "gib")
474                         kh_Key_DropAll(self, FALSE);
475                 else
476                         kh_Key_DropAll(self, TRUE);
477                 if(self.flagcarried)
478                 {
479                         if(attacker.classname != "player" && attacker.classname != "gib")
480                                 DropFlag(self.flagcarried, self, attacker); // penalty for flag loss by suicide
481                         else if(attacker.team == self.team)
482                                 DropFlag(self.flagcarried, attacker, attacker); // penalty for flag loss by suicide/teamkill
483                         else
484                                 DropFlag(self.flagcarried, world, attacker);
485                 }
486                 if(self.ballcarried)
487                         DropBall(self.ballcarried, self.origin, self.velocity);
488                 Portal_ClearAllLater(self);
489                 // clear waypoints
490                 WaypointSprite_PlayerDead();
491                 // make the corpse upright (not tilted)
492                 self.angles_x = 0;
493                 self.angles_z = 0;
494                 // don't spin
495                 self.avelocity = '0 0 0';
496                 // view from the floor
497                 self.view_ofs = '0 0 -8';
498                 // toss the corpse
499                 self.movetype = MOVETYPE_TOSS;
500                 // shootable corpse
501                 self.solid = SOLID_CORPSE;
502                 // don't stick to the floor
503                 self.flags &~= FL_ONGROUND;
504                 // dying animation
505                 self.deadflag = DEAD_DYING;
506                 // when to allow respawn
507                 sdelay = 0;
508                 waves = 0;
509                 if(cvar("g_respawn_mapsettings"))
510                 {
511                         sdelay = cvar("g_respawn_mapsettings_delay");
512                         waves = cvar("g_respawn_mapsettings_waves");
513                 }
514                 if(!sdelay)
515                         sdelay = cvar(strcat("g_", GetGametype(), "_respawn_delay"));
516                 if(!sdelay)
517                         sdelay = cvar("g_respawn_delay");
518                 if(!waves)
519                         waves = cvar(strcat("g_", GetGametype(), "_respawn_waves"));
520                 if(!waves)
521                         waves = cvar("g_respawn_waves");
522                 if(waves)
523                         self.death_time = ceil((time + sdelay) / waves) * waves;
524                 else
525                         self.death_time = time + sdelay;
526                 if((sdelay + waves >= 5.0) && (self.death_time - time > 1.75))
527                         self.respawn_countdown = 10; // first number to count down from is 10
528                 else
529                         self.respawn_countdown = -1; // do not count down
530                 if (random() < 0.5)
531                 {
532                         setanim(self, self.anim_die1, FALSE, TRUE, TRUE);
533                         self.dead_frame = self.anim_dead1_x;
534                 }
535                 else
536                 {
537                         setanim(self, self.anim_die2, FALSE, TRUE, TRUE);
538                         self.dead_frame = self.anim_dead2_x;
539                 }
540                 // set damage function to corpse damage
541                 self.event_damage = PlayerCorpseDamage;
542                 // call the corpse damage function just in case it wants to gib
543                 self.event_damage(inflictor, attacker, 0, deathtype, hitloc, force);
544                 // set up to fade out later
545                 SUB_SetFade (self, time + 12 + random () * 4, 1);
546
547                 // remove laserdot
548                 if(self.weaponentity)
549                         if(self.weaponentity.lasertarget)
550                                 remove(self.weaponentity.lasertarget);
551
552                 if(clienttype(self) == CLIENTTYPE_REAL)
553                 {
554                         self.fixangle = TRUE;
555                         //msg_entity = self;
556                         //WriteByte (MSG_ONE, SVC_SETANGLE);
557                         //WriteAngle (MSG_ONE, self.v_angle_x);
558                         //WriteAngle (MSG_ONE, self.v_angle_y);
559                         //WriteAngle (MSG_ONE, 80);
560                 }
561
562                 if(g_arena)
563                         Spawnqueue_Unmark(self);
564
565                 if(defer_ClientKill_Now_TeamChange)
566                         ClientKill_Now_TeamChange();
567
568                 if(sv_gentle > 0) {
569                         // remove corpse
570                         PlayerCorpseDamage (inflictor, attacker, 100.0, deathtype, hitloc, force);
571                 }
572         }
573 }
574
575 float UpdateSelectedPlayer_countvalue(float v)
576 {
577         return max(0, (v - 1.0) / 0.5);
578 }
579
580 // returns: -2 if no hit, otherwise cos of the angle
581 // uses the global v_angle
582 float UpdateSelectedPlayer_canSee(entity p, float mincosangle, float maxdist)
583 {
584         vector so, d;
585         float c;
586
587         if(p == self)
588                 return -2;
589
590         if(p.deadflag)
591                 return -2;
592
593         so = self.origin + self.view_ofs;
594         d = p.origin - so;
595
596         // misaimed?
597         if(dist_point_line(d, '0 0 0', v_forward) > maxdist)
598                 return -2;
599
600         // now find the cos of the angle...
601         c = normalize(d) * v_forward;
602
603         if(c <= mincosangle)
604                 return -2;
605
606         // not visible in any way? forget it
607         if(!checkpvs(so, p))
608                 return -2;
609
610         traceline(so, p.origin, MOVE_NOMONSTERS, self);
611         if(trace_fraction < 1)
612                 return -2;
613
614         return c;
615 }
616
617 void ClearSelectedPlayer()
618 {
619         if(self.selected_player)
620         {
621                 centerprint_expire(self, CENTERPRIO_POINT);
622                 self.selected_player = world;
623                 self.selected_player_display_needs_update = FALSE;
624         }
625 }
626
627 void UpdateSelectedPlayer()
628 {
629         entity selected;
630         float selected_score;
631         selected = world;
632         selected_score = 0.95; // 18 degrees
633
634         if(!cvar("sv_allow_shownames"))
635                 return;
636
637         if(clienttype(self) != CLIENTTYPE_REAL)
638                 return;
639
640         if(self.cvar_cl_shownames == 0)
641                 return;
642
643         if(self.cvar_cl_shownames == 1 && !teams_matter)
644                 return;
645
646         makevectors(self.v_angle); // sets v_forward
647
648         // 1. cursor trace is always right
649         if(self.cursor_trace_ent && self.cursor_trace_ent.classname == "player" && !self.cursor_trace_ent.deadflag)
650         {
651                 selected = self.cursor_trace_ent;
652         }
653         else
654         {
655                 // 2. if we don't have a cursor trace, find the player which is least
656                 //    mis-aimed at
657                 entity p;
658                 FOR_EACH_PLAYER(p)
659                 {
660                         float c;
661                         c = UpdateSelectedPlayer_canSee(p, selected_score, 100); // 100 = 2.5 meters
662                         if(c >= -1)
663                         {
664                                 selected = p;
665                                 selected_score = c;
666                         }
667                 }
668         }
669
670         if(selected)
671         {
672                 self.selected_player_display_timeout = time + self.cvar_scr_centertime;
673         }
674         else
675         {
676                 if(time < self.selected_player_display_timeout)
677                         if(UpdateSelectedPlayer_canSee(self.selected_player, 0.7, 200) >= -1) // 5 meters, 45 degrees
678                                 selected = self.selected_player;
679         }
680
681         if(selected)
682         {
683                 if(selected == self.selected_player)
684                 {
685                         float save;
686                         save = UpdateSelectedPlayer_countvalue(self.selected_player_count);
687                         self.selected_player_count = self.selected_player_count + frametime;
688                         if(save != UpdateSelectedPlayer_countvalue(self.selected_player_count))
689                         {
690                                 string namestr, healthstr;
691                                 namestr = playername(selected);
692                                 if(teams_matter)
693                                 {
694                                         healthstr = ftos(floor(selected.health));
695                                         if(self.team == selected.team)
696                                         {
697                                                 namestr = strcat(namestr, " (", healthstr, "%)");
698                                                 self.selected_player_display_needs_update = TRUE;
699                                         }
700                                 }
701                                 centerprint_atprio(self, CENTERPRIO_POINT, namestr);
702                         }
703                 }
704                 else
705                 {
706                         ClearSelectedPlayer();
707                         self.selected_player = selected;
708                         self.selected_player_time = time;
709                         self.selected_player_count = 0;
710                         self.selected_player_display_needs_update = FALSE;
711                 }
712         }
713         else
714         {
715                 ClearSelectedPlayer();
716         }
717
718         if(self.selected_player)
719                 self.last_selected_player = self.selected_player;
720 }
721
722 .float muted; // to be used by prvm_edictset server playernumber muted 1
723 void Say(entity source, float teamsay, entity privatesay, string msgin, float floodcontrol)
724 {
725         string msgstr, colorstr, cmsgstr, namestr, fullmsgstr, sourcemsgstr, fullcmsgstr, sourcecmsgstr, privatemsgprefix;
726         float flood, privatemsgprefixlen;
727         entity head;
728
729         if(Ban_MaybeEnforceBan(source))
730                 return;
731         
732         if(!teamsay && !privatesay)
733                 if(substring(msgin, 0, 1) == " ")
734                         msgin = substring(msgin, 1, strlen(msgin) - 1); // work around DP say bug (say_team does not have this!)
735
736         msgin = formatmessage(msgin);
737
738         if(msgin == "")
739                 return;
740
741         if(source.classname != "player")
742                 colorstr = "^0"; // black for spectators
743         else if(teams_matter)
744                 colorstr = Team_ColorCode(source.team);
745         else
746                 teamsay = FALSE;
747
748         if(intermission_running)
749                 teamsay = FALSE;
750
751         /*
752          * using bprint solves this... me stupid
753         // how can we prevent the message from appearing in a listen server?
754         // for now, just give "say" back and only handle say_team
755         if(!teamsay)
756         {
757                 clientcommand(self, strcat("say ", msgin));
758                 return;
759         }
760         */
761
762         if(cvar("g_chat_teamcolors"))
763                 namestr = playername(source);
764         else
765                 namestr = source.netname;
766
767         if(privatesay)
768         {
769                 msgstr = strcat("\{1}\{13}* ^3", namestr, "^3 tells you: ^7");
770                 privatemsgprefixlen = strlen(msgstr);
771                 msgstr = strcat(msgstr, msgin);
772                 cmsgstr = strcat(colorstr, "^3", namestr, "^3 tells you:\n^7", msgin);
773                 if(cvar("g_chat_teamcolors"))
774                         privatemsgprefix = strcat("\{1}\{13}* ^3You tell ", playername(privatesay), ": ^7");
775                 else
776                         privatemsgprefix = strcat("\{1}\{13}* ^3You tell ", privatesay.netname, ": ^7");
777         }
778         else if(teamsay)
779         {
780                 msgstr = strcat("\{1}\{13}", colorstr, "(^3", namestr, colorstr, ") ^7", msgin);
781                 cmsgstr = strcat(colorstr, "(^3", namestr, colorstr, ")\n^7", msgin);
782         }
783         else
784         {
785                 msgstr = strcat("\{1}", namestr, "^7: ", msgin);
786                 cmsgstr = "";
787         }
788         
789         msgstr = strcat(strreplace("\n", " ", msgstr), "\n"); // newlines only are good for centerprint
790         fullmsgstr = msgstr;
791         fullcmsgstr = cmsgstr;
792
793         // FLOOD CONTROL
794         flood = 0;
795         if(floodcontrol)
796         {
797                 float flood_spl;
798                 float flood_burst;
799                 float flood_lmax;
800                 var .float flood_field;
801                 float lines;
802                 if(privatesay)
803                 {
804                         flood_spl = cvar("g_chat_flood_spl_tell");
805                         flood_burst = cvar("g_chat_flood_burst_tell");
806                         flood_lmax = cvar("g_chat_flood_lmax_tell");
807                         flood_field = floodcontrol_chattell;
808                 }
809                 else if(teamsay)
810                 {
811                         flood_spl = cvar("g_chat_flood_spl_team");
812                         flood_burst = cvar("g_chat_flood_burst_team");
813                         flood_lmax = cvar("g_chat_flood_lmax_team");
814                         flood_field = floodcontrol_chatteam;
815                 }
816                 else
817                 {
818                         flood_spl = cvar("g_chat_flood_spl");
819                         flood_burst = cvar("g_chat_flood_burst");
820                         flood_lmax = cvar("g_chat_flood_lmax");
821                         flood_field = floodcontrol_chat;
822                 }
823                 flood_burst = max(0, flood_burst - 1);
824                 // to match explanation in default.cfg, a value of 3 must allow three-line bursts and not four!
825
826                 // do flood control for the default line size
827                 getWrappedLine_remaining = msgstr;
828                 msgstr = "";
829                 lines = 0;
830                 while(getWrappedLine_remaining && (!flood_lmax || lines <= flood_lmax))
831                 {
832                         msgstr = strcat(msgstr, " ", getWrappedLine(82.4289758859709, strlennocol)); // perl averagewidth.pl < gfx/vera-sans.width
833                         ++lines;
834                 }
835                 msgstr = substring(msgstr, 1, strlen(msgstr) - 1);
836
837                 if(getWrappedLine_remaining != "")
838                 {
839                         msgstr = strcat(msgstr, "\n");
840                         flood = 2;
841                 }
842
843                 if(time >= source.flood_field)
844                 {
845                         source.flood_field = max(time - flood_burst * flood_spl, source.flood_field) + lines * flood_spl;
846                 }
847                 else
848                 {
849                         flood = 1;
850                         msgstr = fullmsgstr;
851                 }
852         }
853         
854         if (timeoutStatus == 2) //when game is paused, no flood protection
855                 source.flood_field = flood = 0;
856
857         if(flood == 2)
858         {
859                 if(cvar("g_chat_flood_notify_flooder"))
860                 {
861                         sourcemsgstr = strcat(msgstr, "\n^3FLOOD CONTROL: ^7message too long, trimmed\n");
862                         sourcecmsgstr = "";
863                 }
864                 else
865                 {
866                         sourcemsgstr = fullmsgstr;
867                         sourcecmsgstr = fullcmsgstr;
868                 }
869                 cmsgstr = "";
870         }
871         else
872         {
873                 sourcemsgstr = msgstr;
874                 sourcecmsgstr = cmsgstr;
875         }
876
877         if(!privatesay)
878         if(source.classname != "player")
879         {
880                 if(teamsay || (cvar("g_chat_nospectators") == 1) || (cvar("g_chat_nospectators") == 2 && !inWarmupStage))
881                         teamsay = -1; // spectators
882         }
883
884         if(flood)
885                 print("NOTE: ", playername(source), "^7 is flooding.\n");
886         
887         // build sourcemsgstr by cutting off a prefix and replacing it by the other one
888         if(privatesay)
889                 sourcemsgstr = strcat(privatemsgprefix, substring(sourcemsgstr, privatemsgprefixlen, -1));
890
891         if(source.muted)
892         {
893                 // always fake the message
894                 sprint(source, sourcemsgstr);
895                 if(cmsgstr != "" && !privatesay)
896                         centerprint(source, sourcecmsgstr);
897         }
898         else if(flood == 1)
899         {
900                 if(cvar("g_chat_flood_notify_flooder"))
901                         sprint(source, strcat("^3FLOOD CONTROL: ^7wait ^1", ftos(source.flood_field - time), "^3 seconds\n"));
902                 else
903                 {
904                         sprint(source, sourcemsgstr);
905                         if(cmsgstr != "" && !privatesay)
906                                 centerprint(source, sourcecmsgstr);
907                 }
908         }
909         else if(privatesay)
910         {
911                 sprint(source, sourcemsgstr);
912                 sprint(privatesay, msgstr);
913                 if(cmsgstr != "")
914                         centerprint(privatesay, cmsgstr);
915         }
916         else if(teamsay > 0)
917         {
918                 sprint(source, sourcemsgstr);
919                 if(sourcecmsgstr != "")
920                         centerprint(source, sourcecmsgstr);
921                 FOR_EACH_REALPLAYER(head) if(head.team == source.team)
922                         if(head != source)
923                         {
924                                 sprint(head, msgstr);
925                                 if(cmsgstr != "")
926                                         centerprint(head, cmsgstr);
927                         }
928         }
929         else if(teamsay < 0)
930         {
931                 sprint(source, sourcemsgstr);
932                 FOR_EACH_REALCLIENT(head) if(head.classname != "player")
933                         if(head != source)
934                                 sprint(head, msgstr);
935         }
936         else if(sourcemsgstr != msgstr)
937         {
938                 sprint(source, sourcemsgstr);
939                 FOR_EACH_REALCLIENT(head)
940                         if(head != source)
941                                 sprint(head, msgstr);
942         }
943         else
944                 bprint(msgstr);
945 }
946
947 float GetVoiceMessageVoiceType(string type)
948 {
949         if(type == "taunt")
950                 return VOICETYPE_TAUNT;
951         if(type == "teamshoot")
952                 return VOICETYPE_LASTATTACKER;
953         return VOICETYPE_TEAMRADIO;
954 }
955
956 string allvoicesamples;
957 float GetPlayerSoundSampleField_notFound;
958 float GetPlayerSoundSampleField_fixed;
959 .string GetVoiceMessageSampleField(string type)
960 {
961         GetPlayerSoundSampleField_notFound = 0;
962         GetPlayerSoundSampleField_fixed = 0;
963         switch(type)
964         {
965 #define _VOICEMSG(m) case #m: return playersound_##m;
966                 ALLVOICEMSGS
967 #undef _VOICEMSG
968         }
969         GetPlayerSoundSampleField_notFound = 1;
970         return playersound_taunt;
971 }
972
973 .string GetPlayerSoundSampleField(string type)
974 {
975         GetPlayerSoundSampleField_notFound = 0;
976         GetPlayerSoundSampleField_fixed = 0;
977         switch(type)
978         {
979 #define _VOICEMSG(m) case #m: return playersound_##m;
980                 ALLPLAYERSOUNDS
981 #undef _VOICEMSG
982         }
983         GetPlayerSoundSampleField_notFound = 1;
984         return playersound_taunt;
985 }
986
987 void PrecacheGlobalSound(string samplestring)
988 {
989         float n, i;
990         tokenize_console(samplestring);
991         n = stof(argv(1));
992         if(n > 0)
993         {
994                 for(i = 1; i <= n; ++i)
995                         precache_sound(strcat(argv(0), ftos(i), ".wav"));
996         }
997         else
998         {
999                 precache_sound(strcat(argv(0), ".wav"));
1000         }
1001 }
1002
1003 void PrecachePlayerSounds(string f)
1004 {
1005         float fh;
1006         string s;
1007         fh = fopen(f, FILE_READ);
1008         if(fh < 0)
1009                 return;
1010         while((s = fgets(fh)))
1011         {
1012                 if(tokenize_console(s) != 3)
1013                 {
1014                         dprint("Invalid sound info line: ", s, "\n");
1015                         continue;
1016                 }
1017                 PrecacheGlobalSound(strcat(argv(1), " ", argv(2)));
1018         }
1019         fclose(fh);
1020
1021         if not(allvoicesamples)
1022         {
1023 #define _VOICEMSG(m) allvoicesamples = strcat(allvoicesamples, " ", #m);
1024                 ALLVOICEMSGS
1025 #undef _VOICEMSG
1026                 allvoicesamples = strzone(substring(allvoicesamples, 1, strlen(allvoicesamples) - 1));
1027         }
1028 }
1029
1030 void ClearPlayerSounds()
1031 {
1032 #define _VOICEMSG(m) if(self.playersound_##m) { strunzone(self.playersound_##m); self.playersound_##m = string_null; }
1033         ALLPLAYERSOUNDS
1034         ALLVOICEMSGS
1035 #undef _VOICEMSG
1036 }
1037
1038 void LoadPlayerSounds(string f, float first)
1039 {
1040         float fh;
1041         string s;
1042         var .string field;
1043         fh = fopen(f, FILE_READ);
1044         if(fh < 0)
1045                 return;
1046         while((s = fgets(fh)))
1047         {
1048                 if(tokenize_console(s) != 3)
1049                         continue;
1050                 field = GetPlayerSoundSampleField(argv(0));
1051                 if(GetPlayerSoundSampleField_notFound)
1052                         field = GetVoiceMessageSampleField(argv(0));
1053                 if(GetPlayerSoundSampleField_notFound)
1054                         continue;
1055                 if(GetPlayerSoundSampleField_fixed)
1056                         if not(first)
1057                                 continue;
1058                 if(self.field)
1059                         strunzone(self.field);
1060                 self.field = strzone(strcat(argv(1), " ", argv(2)));
1061         }
1062         fclose(fh);
1063 }
1064
1065 .float modelindex_for_playersound;
1066 void UpdatePlayerSounds()
1067 {
1068         if(self.modelindex == self.modelindex_for_playersound)
1069                 return;
1070         self.modelindex_for_playersound = self.modelindex;
1071         ClearPlayerSounds();
1072         LoadPlayerSounds("sound/player/default.sounds", 1);
1073         LoadPlayerSounds(strcat(self.model, ".sounds"), 0);
1074 }
1075
1076 void GlobalSound(string sample, float chan, float voicetype)
1077 {
1078         float n;
1079         float tauntrand;
1080
1081         if(sample == "")
1082                 return;
1083
1084         tokenize_console(sample);
1085         n = stof(argv(1));
1086         if(n > 0)
1087                 sample = strcat(argv(0), ftos(floor(random() * n + 1)), ".wav"); // randomization
1088         else
1089                 sample = strcat(argv(0), ".wav"); // randomization
1090         
1091         switch(voicetype)
1092         {
1093                 case VOICETYPE_LASTATTACKER_ONLY:
1094                         if(self.pusher)
1095                                 if(self.pusher.team == self.team)
1096                                 {
1097                                         msg_entity = self.pusher;
1098                                         if(clienttype(msg_entity) == CLIENTTYPE_REAL)
1099                                         {
1100                                                 if(msg_entity.cvar_cl_voice_directional == 1)
1101                                                         soundto(MSG_ONE, self, chan, sample, VOL_BASEVOICE, ATTN_MIN);
1102                                                 else
1103                                                         soundto(MSG_ONE, self, chan, sample, VOL_BASEVOICE, ATTN_NONE);
1104                                         }
1105                                 }
1106                         break;
1107                 case VOICETYPE_LASTATTACKER:
1108                         if(self.pusher)
1109                                 if(self.pusher.team == self.team)
1110                                 {
1111                                         msg_entity = self.pusher;
1112                                         if(clienttype(msg_entity) == CLIENTTYPE_REAL)
1113                                         {
1114                                                 if(msg_entity.cvar_cl_voice_directional == 1)
1115                                                         soundto(MSG_ONE, self, chan, sample, VOL_BASEVOICE, ATTN_MIN);
1116                                                 else
1117                                                         soundto(MSG_ONE, self, chan, sample, VOL_BASEVOICE, ATTN_NONE);
1118                                         }
1119                                         msg_entity = self;
1120                                         if(clienttype(msg_entity) == CLIENTTYPE_REAL)
1121                                                 soundto(MSG_ONE, self, chan, sample, VOL_BASE, ATTN_NONE);
1122                                 }
1123                         break;
1124                 case VOICETYPE_TEAMRADIO:
1125                         FOR_EACH_REALCLIENT(msg_entity)
1126                                 if(!teams_matter || msg_entity.team == self.team)
1127                                 {
1128                                         if(msg_entity.cvar_cl_voice_directional == 1)
1129                                                 soundto(MSG_ONE, self, chan, sample, VOL_BASEVOICE, ATTN_MIN);
1130                                         else
1131                                                 soundto(MSG_ONE, self, chan, sample, VOL_BASEVOICE, ATTN_NONE);
1132                                 }
1133                         break;
1134                 case VOICETYPE_AUTOTAUNT:
1135                         tauntrand = random();
1136                         FOR_EACH_REALCLIENT(msg_entity)
1137                                 if (tauntrand < msg_entity.cvar_cl_autotaunt)
1138                                 {
1139                                         if (msg_entity.cvar_cl_voice_directional >= 1)
1140                                                 soundto(MSG_ONE, self, chan, sample, VOL_BASEVOICE, bound(ATTN_MIN, msg_entity.cvar_cl_voice_directional_taunt_attenuation, ATTN_MAX));
1141                                         else
1142                                                 soundto(MSG_ONE, self, chan, sample, VOL_BASEVOICE, ATTN_NONE);
1143                                 }
1144                         break;
1145                 case VOICETYPE_TAUNT:
1146                         FOR_EACH_REALCLIENT(msg_entity)
1147                         {
1148                                 if (msg_entity.cvar_cl_voice_directional >= 1)
1149                                         soundto(MSG_ONE, self, chan, sample, VOL_BASEVOICE, bound(ATTN_MIN, msg_entity.cvar_cl_voice_directional_taunt_attenuation, ATTN_MAX));
1150                                 else
1151                                         soundto(MSG_ONE, self, chan, sample, VOL_BASEVOICE, ATTN_NONE);
1152                         }
1153                 case VOICETYPE_PLAYERSOUND:
1154                         sound(self, chan, sample, VOL_BASE, ATTN_NORM);
1155                         break;
1156                 default:
1157                         backtrace("Invalid voice type!");
1158                         break;
1159         }
1160 }
1161
1162 void PlayerSound(.string samplefield, float chan, float voicetype)
1163 {
1164         string sample;
1165         sample = self.samplefield;
1166         GlobalSound(sample, chan, voicetype);
1167 }
1168
1169 void VoiceMessage(string type, string msg)
1170 {
1171         var .string sample;
1172         var float voicetype, ownteam;
1173         sample = GetVoiceMessageSampleField(type);
1174
1175         if(GetPlayerSoundSampleField_notFound)
1176         {
1177                 sprint(self, strcat("Invalid voice. Use one of: ", allvoicesamples, "\n"));
1178                 return;
1179         }
1180
1181         voicetype = GetVoiceMessageVoiceType(type);
1182         ownteam = (voicetype == VOICETYPE_TEAMRADIO);
1183
1184         float flood;
1185         float flood_spv;
1186         var .float flood_field;
1187
1188         flood = 0;
1189         if(ownteam)
1190         {
1191                 flood_spv = cvar("g_voice_flood_spv_team");
1192                 flood_field = floodcontrol_voiceteam;
1193         }
1194         else
1195         {
1196                 flood_spv = cvar("g_voice_flood_spv");
1197                 flood_field = floodcontrol_voice;
1198         }
1199
1200         if(time >= self.flood_field)
1201                 self.flood_field = max(time, self.flood_field) + flood_spv;
1202         else
1203                 flood = 1;
1204                 
1205         if (timeoutStatus == 2) //when game is paused, no flood protection
1206                 self.flood_field = flood = 0;
1207
1208         if (msg != "")
1209                 Say(self, ownteam, world, msg, 0);
1210
1211         if (!flood)
1212                 PlayerSound(sample, CHAN_VOICE, voicetype);
1213 }