Merge branch 'master' into martin-t/mg-solidpen
[xonotic/xonotic-data.pk3dir.git] / qcsrc / server / weapons / tracing.qc
1 #include "tracing.qh"
2
3 #include <common/effects/all.qh>
4
5 #include "accuracy.qh"
6 #include "common.qh"
7 #include "hitplot.qh"
8 #include "weaponsystem.qh"
9
10 #include "../g_damage.qh"
11 #include "../antilag.qh"
12
13 #include <common/constants.qh>
14 #include <common/net_linked.qh>
15 #include <common/util.qh>
16
17 #include <common/weapons/_all.qh>
18 #include <common/wepent.qh>
19 #include <common/state.qh>
20
21 #include <lib/warpzone/common.qh>
22
23 // this function calculates w_shotorg and w_shotdir based on the weapon model
24 // offset, trueaim and antilag, and won't put w_shotorg inside a wall.
25 // make sure you call makevectors first (FIXME?)
26 void W_SetupShot_Dir_ProjectileSize_Range(entity ent, .entity weaponentity, vector s_forward, vector mi, vector ma, float antilag, float recoil, Sound snd, float chan, float maxdamage, float range, int deathtype)
27 {
28         TC(Sound, snd);
29         float nudge = 1; // added to traceline target and subtracted from result  TOOD(divVerent): do we still need this? Doesn't the engine do this now for us?
30         float oldsolid = ent.dphitcontentsmask;
31         Weapon wep = DEATH_WEAPONOF(deathtype);
32         if(!IS_CLIENT(ent))
33                 antilag = false; // no antilag for non-clients!
34         if (IS_PLAYER(ent) && (wep.spawnflags & WEP_FLAG_PENETRATEWALLS))
35         {
36                 // This is the reason rifle, MG, OKMG and other fireBullet weapons don't hit the crosshair when shooting at walls.
37                 // This is intentional, otherwise if you stand too close to a (glass) wall and attempt to shoot an enemy through it,
38                 // trueaim will cause the shot to hit the wall exactly but then miss the enemy (unless shooting from eye/center).
39                 // TODO for fireBullet, find how far the shot will penetrate and aim at that
40                 //      for fireRailgunbullet, find the farthest target and aim at that
41                 //      this will avoid issues when another player is passing in front of you when you shoot
42                 //      (currently such a shot will hit him but then miss the original target)
43                 ent.dphitcontentsmask = DPCONTENTS_BODY | DPCONTENTS_CORPSE;
44         }
45         else
46                 ent.dphitcontentsmask = DPCONTENTS_SOLID | DPCONTENTS_BODY | DPCONTENTS_CORPSE;
47         if(antilag)
48                 WarpZone_traceline_antilag(NULL, ent.origin + ent.view_ofs, ent.origin + ent.view_ofs + s_forward * range, MOVE_NORMAL, ent, ANTILAG_LATENCY(ent));
49                 // passing NULL, because we do NOT want it to touch dphitcontentsmask
50         else
51                 WarpZone_TraceLine(ent.origin + ent.view_ofs, ent.origin + ent.view_ofs + s_forward * range, MOVE_NOMONSTERS, ent);
52         ent.dphitcontentsmask = DPCONTENTS_SOLID | DPCONTENTS_BODY | DPCONTENTS_CORPSE;
53
54         vector vf, vr, vu;
55         vf = v_forward;
56         vr = v_right;
57         vu = v_up;
58         w_shotend = WarpZone_UnTransformOrigin(WarpZone_trace_transform, trace_endpos); // warpzone support
59         v_forward = vf;
60         v_right = vr;
61         v_up = vu;
62
63         // un-adjust trueaim if shotend is too close
64         if(vdist(w_shotend - (ent.origin + ent.view_ofs), <, autocvar_g_trueaim_minrange))
65                 w_shotend = ent.origin + ent.view_ofs + s_forward * autocvar_g_trueaim_minrange;
66
67         // track max damage
68         if (IS_PLAYER(ent) && accuracy_canbegooddamage(ent))
69                 accuracy_add(ent, wep, maxdamage, 0);
70
71         if(IS_PLAYER(ent))
72                 W_HitPlotAnalysis(ent, wep, v_forward, v_right, v_up);
73
74         vector md = ent.(weaponentity).movedir;
75         vector vecs = ((md.x > 0) ? md : '0 0 0');
76
77         // TODO this is broken - see 637056bea7bf7f5c9c0fc6113e94731a2767476 for an attempted fix
78         // which fixes issue #1957 but causes #2129
79         vector dv = v_right * -vecs.y + v_up * vecs.z;
80         w_shotorg = ent.origin + ent.view_ofs + dv;
81
82         // now move the shotorg forward as much as requested if possible
83         if(antilag)
84         {
85                 if(CS(ent).antilag_debug)
86                         tracebox_antilag(ent, w_shotorg, mi, ma, w_shotorg + v_forward * (vecs.x + nudge), MOVE_NORMAL, ent, CS(ent).antilag_debug);
87                 else
88                         tracebox_antilag(ent, w_shotorg, mi, ma, w_shotorg + v_forward * (vecs.x + nudge), MOVE_NORMAL, ent, ANTILAG_LATENCY(ent));
89         }
90         else
91                 tracebox(w_shotorg, mi, ma, w_shotorg + v_forward * (vecs.x + nudge), MOVE_NORMAL, ent);
92         w_shotorg = trace_endpos - v_forward * nudge;
93         // calculate the shotdir from the chosen shotorg
94         if(W_DualWielding(ent))
95                 w_shotdir = s_forward;
96         else
97                 w_shotdir = normalize(w_shotend - w_shotorg);
98
99         //vector prevdir = w_shotdir;
100         //vector prevorg = w_shotorg;
101         //vector prevend = w_shotend;
102
103         if (antilag)
104         if (!CS(ent).cvar_cl_noantilag)
105         {
106                 if (autocvar_g_antilag == 1) // switch to "ghost" if not hitting original
107                 {
108                         traceline(w_shotorg, w_shotorg + w_shotdir * range, MOVE_NORMAL, ent);
109                         if (!trace_ent.takedamage)
110                         {
111                                 traceline_antilag_force (ent, w_shotorg, w_shotorg + w_shotdir * range, MOVE_NORMAL, ent, ANTILAG_LATENCY(ent));
112                                 if (trace_ent.takedamage && IS_PLAYER(trace_ent))
113                                 {
114                                         entity e;
115                                         e = trace_ent;
116                                         traceline(w_shotorg, e.origin, MOVE_NORMAL, ent);
117                                         if(trace_ent == e)
118                                                 w_shotdir = normalize(trace_ent.origin - w_shotorg);
119                                 }
120                         }
121                 }
122                 else if(autocvar_g_antilag == 3) // client side hitscan
123                 {
124                         // this part MUST use prydon cursor
125                         if (CS(ent).cursor_trace_ent)                 // client was aiming at someone
126                         if (CS(ent).cursor_trace_ent != ent)         // just to make sure
127                         if (CS(ent).cursor_trace_ent.takedamage)      // and that person is killable
128                         if (IS_PLAYER(CS(ent).cursor_trace_ent)) // and actually a player
129                         {
130                                 // verify that the shot would miss without antilag
131                                 // (avoids an issue where guns would always shoot at their origin)
132                                 traceline(w_shotorg, w_shotorg + w_shotdir * range, MOVE_NORMAL, ent);
133                                 if (!trace_ent.takedamage)
134                                 {
135                                         // verify that the shot would hit if altered
136                                         traceline(w_shotorg, CS(ent).cursor_trace_ent.origin, MOVE_NORMAL, ent);
137                                         if (trace_ent == CS(ent).cursor_trace_ent)
138                                                 w_shotdir = normalize(CS(ent).cursor_trace_ent.origin - w_shotorg);
139                                         else
140                                                 LOG_INFO("antilag fail");
141                                 }
142                         }
143                 }
144         }
145
146         ent.dphitcontentsmask = oldsolid; // restore solid type (generally SOLID_SLIDEBOX)
147
148         if (!autocvar_g_norecoil)
149                 ent.punchangle_x = recoil * -1;
150
151         if (snd != SND_Null) {
152                 sound(ent, chan, snd, (W_DualWielding(ent) ? VOL_BASE * 0.7 : VOL_BASE), ATTN_NORM);
153                 W_PlayStrengthSound(ent);
154         }
155
156         // nudge w_shotend so a trace to w_shotend hits
157         w_shotend = w_shotend + normalize(w_shotend - w_shotorg) * nudge;
158         //if(w_shotend != prevend) { printf("SERVER: shotEND differs: %s - %s\n", vtos(w_shotend), vtos(prevend)); }
159         //if(w_shotorg != prevorg) { printf("SERVER: shotORG differs: %s - %s\n", vtos(w_shotorg), vtos(prevorg)); }
160         //if(w_shotdir != prevdir) { printf("SERVER: shotDIR differs: %s - %s\n", vtos(w_shotdir), vtos(prevdir)); }
161 }
162
163 vector W_CalculateProjectileVelocity(entity actor, vector pvelocity, vector mvelocity, float forceAbsolute)
164 {
165         vector mdirection;
166         float mspeed;
167         vector outvelocity;
168
169         mvelocity = mvelocity * W_WeaponSpeedFactor(actor);
170
171         mdirection = normalize(mvelocity);
172         mspeed = vlen(mvelocity);
173
174         outvelocity = get_shotvelocity(pvelocity, mdirection, mspeed, (forceAbsolute ? 0 : autocvar_g_projectiles_newton_style), autocvar_g_projectiles_newton_style_2_minfactor, autocvar_g_projectiles_newton_style_2_maxfactor);
175
176         return outvelocity;
177 }
178
179 void W_SetupProjVelocity_Explicit(entity proj, vector dir, vector upDir, float pSpeed, float pUpSpeed, float pZSpeed, float spread, float forceAbsolute)
180 {
181         if(proj.owner == NULL)
182                 error("Unowned missile");
183
184         dir = dir + upDir * (pUpSpeed / pSpeed);
185         dir.z += pZSpeed / pSpeed;
186         pSpeed *= vlen(dir);
187         dir = normalize(dir);
188
189         #if 0
190         if(autocvar_g_projectiles_spread_style != mspercallsstyle)
191         {
192                 mspercallsum = mspercallcount = 0;
193                 mspercallsstyle = autocvar_g_projectiles_spread_style;
194         }
195         mspercallsum -= gettime(GETTIME_HIRES);
196         #endif
197
198         dir = W_CalculateSpread(dir, spread, g_weaponspreadfactor, autocvar_g_projectiles_spread_style);
199
200         #if 0
201         mspercallsum += gettime(GETTIME_HIRES);
202         mspercallcount += 1;
203         LOG_INFO("avg: ", ftos(mspercallcount / mspercallsum), " per sec");
204         #endif
205
206         proj.velocity = W_CalculateProjectileVelocity(proj.owner, proj.owner.velocity, pSpeed * dir, forceAbsolute);
207 }
208
209
210 // ====================
211 //  Ballistics Tracing
212 // ====================
213
214 void FireRailgunBullet (entity this, .entity weaponentity, vector start, vector end, float bdamage, float bforce, float mindist, float maxdist, float halflifedist, float forcehalflifedist, int deathtype)
215 {
216         entity pseudoprojectile = NULL;
217
218         vector dir = normalize(end - start);
219         float length = vlen(end - start);
220         vector force = dir * bforce;
221
222         // go a little bit into the wall because we need to hit this wall later
223         end = end + dir;
224
225         float totaldmg = 0;
226
227         // trace multiple times until we hit a wall, each obstacle will be made
228         // non-solid so we can hit the next, while doing this we spawn effects and
229         // note down which entities were hit so we can damage them later
230         entity o = this;
231         while (1)
232         {
233                 if(CS(this).antilag_debug)
234                         WarpZone_traceline_antilag (this, start, end, false, o, CS(this).antilag_debug);
235                 else
236                         WarpZone_traceline_antilag (this, start, end, false, o, ANTILAG_LATENCY(this));
237                 if(o && WarpZone_trace_firstzone)
238                 {
239                         o = NULL;
240                         continue;
241                 }
242
243                 if(trace_ent.solid == SOLID_BSP || trace_ent.solid == SOLID_SLIDEBOX)
244                         Damage_DamageInfo(trace_endpos, bdamage, 0, 0, force, deathtype, trace_ent.species, this);
245
246                 // if it is NULL we can't hurt it so stop now
247                 if (trace_ent == NULL || trace_fraction == 1)
248                         break;
249
250                 // make the entity non-solid so we can hit the next one
251                 IL_PUSH(g_railgunhit, trace_ent);
252                 trace_ent.railgunhit = true;
253                 trace_ent.railgunhitloc = end;
254                 trace_ent.railgunhitsolidbackup = trace_ent.solid;
255                 trace_ent.railgundistance = vlen(WarpZone_UnTransformOrigin(WarpZone_trace_transform, trace_endpos) - start);
256                 trace_ent.railgunforce = WarpZone_TransformVelocity(WarpZone_trace_transform, force);
257
258                 // stop if this is a wall
259                 if (trace_ent.solid == SOLID_BSP)
260                         break;
261
262                 // make the entity non-solid
263                 trace_ent.solid = SOLID_NOT;
264         }
265
266         vector endpoint = trace_endpos;
267         entity endent = trace_ent;
268         float endq3surfaceflags = trace_dphitq3surfaceflags;
269
270         // find all the entities the railgun hit and restore their solid state
271         IL_EACH(g_railgunhit, it.railgunhit,
272         {
273                 it.solid = it.railgunhitsolidbackup;
274         });
275
276         // spawn a temporary explosion entity for RadiusDamage calls
277         //explosion = spawn();
278
279         // Find all non-hit players the beam passed close by
280         if(deathtype == WEP_VAPORIZER.m_id || deathtype == WEP_VORTEX.m_id) // WEAPONTODO
281         {
282                 FOREACH_CLIENT(IS_REAL_CLIENT(it) && it != this, {
283                         if(!it.railgunhit)
284                         if(!(IS_SPEC(it) && it.enemy == this))
285                         {
286                                 msg_entity = it;
287                                 // nearest point on the beam
288                                 vector beampos = start + dir * bound(0, (msg_entity.origin - start) * dir, length);
289
290                                 float f = bound(0, 1 - vlen(beampos - msg_entity.origin) / 512, 1);
291                                 if(f <= 0)
292                                         continue;
293
294                                 if(!pseudoprojectile)
295                                         pseudoprojectile = spawn(); // we need this so the sound uses the "entchannel4" volume
296                                 soundtoat(MSG_ONE, pseudoprojectile, beampos, CH_SHOTS, SND(NEXWHOOSH_RANDOM()), VOL_BASE * f, ATTEN_NONE);
297                         }
298                 });
299
300                 if(pseudoprojectile)
301                         delete(pseudoprojectile);
302         }
303
304         // find all the entities the railgun hit and hurt them
305         IL_EACH(g_railgunhit, it.railgunhit,
306         {
307                 // removal from the list is handled below
308
309                 // get the details we need to call the damage function
310                 vector hitloc = it.railgunhitloc;
311
312                 float foff = ExponentialFalloff(mindist, maxdist, halflifedist, it.railgundistance);
313                 float ffs = ExponentialFalloff(mindist, maxdist, forcehalflifedist, it.railgundistance);
314
315                 if(accuracy_isgooddamage(this, it))
316                         totaldmg += bdamage * foff;
317
318                 // apply the damage
319                 if (it.takedamage)
320                         Damage (it, this, this, bdamage * foff, deathtype, weaponentity, hitloc, it.railgunforce * ffs);
321
322                 // create a small explosion to throw gibs around (if applicable)
323                 //setorigin(explosion, hitloc);
324                 //RadiusDamage (explosion, this, 10, 0, 50, NULL, NULL, 300, deathtype);
325
326                 it.railgunhitloc = '0 0 0';
327                 it.railgunhitsolidbackup = SOLID_NOT;
328                 it.railgunhit = false;
329                 it.railgundistance = 0;
330         });
331
332         IL_CLEAR(g_railgunhit);
333
334         // calculate hits and fired shots for hitscan
335         if(this.(weaponentity))
336                 accuracy_add(this, this.(weaponentity).m_weapon, 0, min(bdamage, totaldmg));
337
338         trace_endpos = endpoint;
339         trace_ent = endent;
340         trace_dphitq3surfaceflags = endq3surfaceflags;
341 }
342
343 void fireBullet_trace_callback(vector start, vector hit, vector end)
344 {
345         if(vdist(hit - start, >, 16))
346                 trailparticles(NULL, fireBullet_trace_callback_eff, start, hit);
347         WarpZone_trace_forent = NULL;
348         fireBullet_last_hit = NULL;
349 }
350
351 void fireBullet(entity this, .entity weaponentity, vector start, vector dir, float spread, float max_solid_penetration, float damage, float force, float dtype, entity tracer_effect)
352 {
353         dir = normalize(dir + randomvec() * spread);
354         vector end = start + dir * max_shot_distance;
355
356         fireBullet_last_hit = NULL;
357         fireBullet_trace_callback_eff = tracer_effect;
358
359         float solid_penetration_fraction = 1;
360         float damage_fraction = 1;
361         float total_damage = 0;
362
363         float lag = ((IS_REAL_CLIENT(this)) ? ANTILAG_LATENCY(this) : 0);
364         if(lag < 0.001)
365                 lag = 0;
366         bool noantilag = ((IS_CLIENT(this)) ? CS(this).cvar_cl_noantilag : false);
367         if(autocvar_g_antilag == 0 || noantilag)
368                 lag = 0; // only do hitscan, but no antilag
369         if(lag)
370                 antilag_takeback_all(this, lag);
371
372         // change shooter to SOLID_BBOX so the shot can hit corpses
373         int oldsolid = this.dphitcontentsmask;
374         if(this)
375                 this.dphitcontentsmask = DPCONTENTS_SOLID | DPCONTENTS_BODY | DPCONTENTS_CORPSE;
376
377         WarpZone_trace_forent = this;
378
379         for (;;)
380         {
381                 WarpZone_TraceBox_ThroughZone(start, '0 0 0', '0 0 0', end, false, WarpZone_trace_forent, NULL, fireBullet_trace_callback);
382                 dir = WarpZone_TransformVelocity(WarpZone_trace_transform, dir);
383                 end = WarpZone_TransformOrigin(WarpZone_trace_transform, end);
384                 start = trace_endpos;
385                 entity hit = trace_ent;
386
387                 // traced up to max_shot_distance and didn't hit anything at all
388                 if (trace_fraction == 1.0)
389                         break;
390
391                 // When hitting sky, stop.
392                 if (trace_dphitq3surfaceflags & Q3SURFACEFLAG_SKY)
393                         break;
394
395                 // can't use noimpact, as we need to pass through walls
396                 //if (trace_dphitq3surfaceflags & Q3SURFACEFLAG_NOIMPACT)
397                         //break;
398
399                 // if we hit "weapclip", bail out
400                 //
401                 // rationale of this check:
402                 //
403                 // any shader that is solid, nodraw AND trans is meant to clip weapon
404                 // shots and players, but has no other effect!
405                 //
406                 // if it is not trans, it is caulk and should not have this side effect
407                 //
408                 // matching shaders:
409                 //   common/weapclip (intended)
410                 //   common/noimpact (is supposed to eat projectiles, but is erased anyway)
411                 bool is_weapclip = false;
412                 if(trace_dphitq3surfaceflags & Q3SURFACEFLAG_NODRAW)
413                 if (!(trace_dphitq3surfaceflags & Q3SURFACEFLAG_NONSOLID))
414                 if (!(trace_dphitcontents & DPCONTENTS_OPAQUE))
415                         is_weapclip = true;
416
417                 if(!hit || hit.solid == SOLID_BSP || hit.solid == SOLID_SLIDEBOX)
418                         Damage_DamageInfo(start, damage * damage_fraction, 0, 0, max(1, force) * dir * damage_fraction, dtype, hit.species, this);
419
420                 if (hit && hit != WarpZone_trace_forent && hit != fireBullet_last_hit)  // Avoid self-damage (except after going through a warp); avoid hitting the same entity twice (engine bug).
421                 {
422                         fireBullet_last_hit = hit;
423                         yoda = 0;
424                         MUTATOR_CALLHOOK(FireBullet_Hit, this, hit, start, end, damage, this.(weaponentity));
425                         damage = M_ARGV(4, float);
426                         bool gooddamage = accuracy_isgooddamage(this, hit);
427                         Damage(hit, this, this, damage * damage_fraction, dtype, weaponentity, start, force * dir * damage_fraction);
428                         // calculate hits for ballistic weapons
429                         if(gooddamage)
430                         {
431                                 // do not exceed 100%
432                                 float added_damage = min(damage - total_damage, damage * damage_fraction);
433                                 total_damage += damage * damage_fraction;
434                                 accuracy_add(this, this.(weaponentity).m_weapon, 0, added_damage);
435                         }
436                 }
437
438                 if (is_weapclip && !autocvar_g_ballistics_penetrate_clips)
439                         break;
440
441                 // go through solid!
442                 // outside the world? forget it
443                 if(start.x > world.maxs.x || start.y > world.maxs.y || start.z > world.maxs.z || start.x < world.mins.x || start.y < world.mins.y || start.z < world.mins.z)
444                         break;
445
446                 float maxdist;
447                 entity hitstore = IS_PLAYER(hit) ? PS(hit) : hit;
448                 if(max_solid_penetration < 0)
449                         break;
450                 else if(hitstore.ballistics_density < -1)
451                         break; // -2: no solid penetration, ever
452                 else if(hitstore.ballistics_density < 0)
453                         maxdist = vlen(hit.maxs - hit.mins) + 1; // -1: infinite travel distance
454                 else if(hitstore.ballistics_density == 0)
455                         maxdist = max_solid_penetration * solid_penetration_fraction;
456                 else
457                         maxdist = max_solid_penetration * solid_penetration_fraction / hitstore.ballistics_density;
458
459                 if(maxdist <= autocvar_g_ballistics_mindistance)
460                         break;
461
462                 // move the entity along its velocity until it's out of solid, then let it resume
463                 // The previously hit entity is ignored here!
464                 traceline_inverted (start, start + dir * maxdist, MOVE_NORMAL, WarpZone_trace_forent, true, hit);
465                 if(trace_fraction == 1) // 1: we never got out of solid
466                         break;
467
468                 float dist_taken = max(autocvar_g_ballistics_mindistance, vlen(trace_endpos - start));
469                 float fraction_used_of_what_is_left = dist_taken / maxdist;
470                 solid_penetration_fraction -= solid_penetration_fraction * fraction_used_of_what_is_left;
471                 solid_penetration_fraction = max(solid_penetration_fraction, 0);
472                 damage_fraction = pow(solid_penetration_fraction, autocvar_g_ballistics_solidpenetration_exponent);
473
474                 // Only show effect when going through a player (invisible otherwise)
475                 if (hit && (hit.solid != SOLID_BSP))
476                         if(vdist(trace_endpos - start, >, 4))
477                                 trailparticles(this, fireBullet_trace_callback_eff, start, trace_endpos);
478
479                 start = trace_endpos;
480
481                 if(hit.solid == SOLID_BSP)
482                         Damage_DamageInfo(start, 0, 0, 0, max(1, force) * normalize(dir) * -damage_fraction, dtype, 0, this);
483         }
484
485         if(lag)
486                 antilag_restore_all(this);
487
488         // restore shooter solid type
489         if(this)
490                 this.dphitcontentsmask = oldsolid;
491 }