properly draw the hook through warpzones again too; fix interpolation issues
[xonotic/xonotic-data.pk3dir.git] / qcsrc / server / cl_weaponsystem.qc
1 /*
2 ===========================================================================
3
4   CLIENT WEAPONSYSTEM CODE
5   Bring back W_Weaponframe
6
7 ===========================================================================
8 */
9
10 .float weapon_frametime;
11
12 float W_WeaponRateFactor()
13 {
14         float t;
15         t = 1.0 / g_weaponratefactor;
16
17         if(g_runematch)
18         {
19                 if(self.runes & RUNE_SPEED)
20                 {
21                         if(self.runes & CURSE_SLOW)
22                                 t = t * cvar("g_balance_rune_speed_combo_atkrate");
23                         else
24                                 t = t * cvar("g_balance_rune_speed_atkrate");
25                 }
26                 else if(self.runes & CURSE_SLOW)
27                 {
28                         t = t * cvar("g_balance_curse_slow_atkrate");
29                 }
30         }
31
32         return t;
33 }
34
35 void W_SwitchWeapon_Force(entity e, float w)
36 {
37         e.cnt = e.switchweapon;
38         e.switchweapon = w;
39         e.selectweapon = w;
40 }
41
42 .float antilag_debug;
43
44 // VorteX: static frame globals
45 float WFRAME_DONTCHANGE = -1;
46 float WFRAME_FIRE1 = 0;
47 float WFRAME_FIRE2 = 1;
48 float WFRAME_IDLE = 2;
49 float WFRAME_RELOAD = 3;
50 .float wframe;
51
52 void(float fr, float t, void() func) weapon_thinkf;
53
54 vector W_HitPlotUnnormalizedUntransform(vector screenforward, vector screenright, vector screenup, vector v)
55 {
56         vector ret;
57         ret_x = screenright * v;
58         ret_y = screenup * v;
59         ret_z = screenforward * v;
60         return ret;
61 }
62
63 vector W_HitPlotNormalizedUntransform(vector org, entity targ, vector screenforward, vector screenright, vector screenup, vector v)
64 {
65         float i, j, k;
66         vector mi, ma, thisv, myv, ret;
67
68         myv = W_HitPlotUnnormalizedUntransform(screenforward, screenright, screenup, org);
69
70         // x = 0..1 relative to hitbox; y = 0..1 relative to hitbox; z = distance
71
72         for(i = 0; i < 2; ++i) for(j = 0; j < 2; ++j) for(k = 0; k < 2; ++k)
73         {
74                 thisv = targ.origin;
75                 if(i) thisv_x += targ.maxs_x; else thisv_x += targ.mins_x;
76                 if(j) thisv_y += targ.maxs_y; else thisv_y += targ.mins_y;
77                 if(k) thisv_z += targ.maxs_z; else thisv_z += targ.mins_z;
78                 thisv = W_HitPlotUnnormalizedUntransform(screenforward, screenright, screenup, thisv);
79                 if(i || j || k)
80                 {
81                         if(mi_x > thisv_x) mi_x = thisv_x; if(ma_x < thisv_x) ma_x = thisv_x;
82                         if(mi_y > thisv_y) mi_y = thisv_y; if(ma_y < thisv_y) ma_y = thisv_y;
83                         //if(mi_z > thisv_z) mi_z = thisv_z; if(ma_z < thisv_z) ma_y = thisv_z;
84                 }
85                 else
86                 {
87                         // first run
88                         mi = ma = thisv;
89                 }
90         }
91
92         thisv = W_HitPlotUnnormalizedUntransform(screenforward, screenright, screenup, v);
93         ret_x = (thisv_x - mi_x) / (ma_x - mi_x);
94         ret_y = (thisv_y - mi_y) / (ma_y - mi_y);
95         ret_z = thisv_z - myv_z;
96         return ret;
97 }
98
99 void W_HitPlotAnalysis(entity player, vector screenforward, vector screenright, vector screenup)
100 {
101         vector hitplot;
102         vector org;
103         float lag;
104
105         if(player.hitplotfh >= 0)
106         {
107                 lag = ANTILAG_LATENCY(player);
108                 if(lag < 0.001)
109                         lag = 0;
110                 if(clienttype(player) != CLIENTTYPE_REAL)
111                         lag = 0; // only antilag for clients
112
113                 org = player.origin + player.view_ofs;
114                 traceline_antilag_force(player, org, org + screenforward * MAX_SHOT_DISTANCE, MOVE_NORMAL, player, lag);
115                 if(trace_ent.flags & FL_CLIENT)
116                 {
117                         antilag_takeback(trace_ent, time - lag);
118                         hitplot = W_HitPlotNormalizedUntransform(org, trace_ent, screenforward, screenright, screenup, trace_endpos);
119                         antilag_restore(trace_ent);
120                         fputs(player.hitplotfh, strcat(ftos(hitplot_x), " ", ftos(hitplot_y), " ", ftos(hitplot_z), " ", ftos(player.switchweapon), "\n"));
121                         //print(strcat(ftos(hitplot_x), " ", ftos(hitplot_y), " ", ftos(hitplot_z), "\n"));
122                 }
123         }
124 }
125
126 vector w_shotorg;
127 vector w_shotdir;
128
129 // this function calculates w_shotorg and w_shotdir based on the weapon model
130 // offset, trueaim and antilag, and won't put w_shotorg inside a wall.
131 // make sure you call makevectors first (FIXME?)
132 void W_SetupShot_Dir_ProjectileSize(entity ent, vector s_forward, vector mi, vector ma, float antilag, float recoil, string snd, float maxdamage)
133 {
134         float nudge = 1; // added to traceline target and subtracted from result
135         local vector trueaimpoint;
136         local float oldsolid;
137         vector vecs, dv;
138         oldsolid = ent.dphitcontentsmask;
139         if(ent.weapon == WEP_CAMPINGRIFLE)
140                 ent.dphitcontentsmask = DPCONTENTS_BODY | DPCONTENTS_CORPSE;
141         else
142                 ent.dphitcontentsmask = DPCONTENTS_SOLID | DPCONTENTS_BODY | DPCONTENTS_CORPSE;
143         if(antilag)
144                 WarpZone_traceline_antilag(world, ent.origin + ent.view_ofs, ent.origin + ent.view_ofs + s_forward * MAX_SHOT_DISTANCE, MOVE_NORMAL, ent, ANTILAG_LATENCY(ent));
145                 // passing world, because we do NOT want it to touch dphitcontentsmask
146         else
147                 WarpZone_TraceLine(ent.origin + ent.view_ofs, ent.origin + ent.view_ofs + s_forward * MAX_SHOT_DISTANCE, MOVE_NOMONSTERS, ent);
148         ent.dphitcontentsmask = DPCONTENTS_SOLID | DPCONTENTS_BODY | DPCONTENTS_CORPSE;
149
150         vector vf, vr, vu;
151         vf = v_forward;
152         vr = v_right;
153         vu = v_up;
154         trueaimpoint = WarpZone_UnTransformOrigin(WarpZone_trace_transform, trace_endpos); // warpzone support
155         v_forward = vf;
156         v_right = vr;
157         v_up = vu;
158
159         // track max damage
160         if not(inWarmupStage) {
161                 entity w;
162                 w = get_weaponinfo(ent.weapon);
163                 if(w.spawnflags & WEP_TYPE_SPLASH) {  // splash damage
164                         ent.stats_fired[ent.weapon - 1] += maxdamage;
165                         ent.stat_fired = ent.weapon + 64 * floor(ent.stats_fired[ent.weapon - 1]);
166                 }
167         }
168
169         W_HitPlotAnalysis(ent, v_forward, v_right, v_up);
170
171         if(ent.weaponentity.movedir_x > 0)
172                 vecs = ent.weaponentity.movedir;
173         else
174                 vecs = '0 0 0';
175         if(debug_shotorg != '0 0 0')
176                 vecs = debug_shotorg;
177
178         dv = v_right * -vecs_y + v_up * vecs_z;
179         w_shotorg = ent.origin + ent.view_ofs + dv;
180
181         // now move the shotorg forward as much as requested if possible
182         if(antilag)
183         {
184                 if(ent.antilag_debug)
185                         tracebox_antilag(ent, w_shotorg, mi, ma, w_shotorg + v_forward * (vecs_x + nudge), MOVE_NORMAL, ent, ent.antilag_debug);
186                 else
187                         tracebox_antilag(ent, w_shotorg, mi, ma, w_shotorg + v_forward * (vecs_x + nudge), MOVE_NORMAL, ent, ANTILAG_LATENCY(ent));
188         }
189         else
190                 tracebox(w_shotorg, mi, ma, w_shotorg + v_forward * (vecs_x + nudge), MOVE_NORMAL, ent);
191         w_shotorg = trace_endpos - v_forward * nudge;
192         // calculate the shotdir from the chosen shotorg
193         w_shotdir = normalize(trueaimpoint - w_shotorg);
194
195         if (antilag)
196         if (!ent.cvar_cl_noantilag)
197         {
198                 if (cvar("g_antilag") == 1) // switch to "ghost" if not hitting original
199                 {
200                         traceline(w_shotorg, w_shotorg + w_shotdir * MAX_SHOT_DISTANCE, MOVE_NORMAL, ent);
201                         if (!trace_ent.takedamage)
202                         {
203                                 traceline_antilag_force (ent, w_shotorg, w_shotorg + w_shotdir * MAX_SHOT_DISTANCE, MOVE_NORMAL, ent, ANTILAG_LATENCY(ent));
204                                 if (trace_ent.takedamage && trace_ent.classname == "player")
205                                 {
206                                         entity e;
207                                         e = trace_ent;
208                                         traceline(w_shotorg, e.origin, MOVE_NORMAL, ent);
209                                         if(trace_ent == e)
210                                                 w_shotdir = normalize(trace_ent.origin - w_shotorg);
211                                 }
212                         }
213                 }
214                 else if(cvar("g_antilag") == 3) // client side hitscan
215                 {
216                         // this part MUST use prydon cursor
217                         if (ent.cursor_trace_ent)                 // client was aiming at someone
218                         if (ent.cursor_trace_ent != ent)         // just to make sure
219                         if (ent.cursor_trace_ent.takedamage)      // and that person is killable
220                         if (ent.cursor_trace_ent.classname == "player") // and actually a player
221                         {
222                                 // verify that the shot would miss without antilag
223                                 // (avoids an issue where guns would always shoot at their origin)
224                                 traceline(w_shotorg, w_shotorg + w_shotdir * MAX_SHOT_DISTANCE, MOVE_NORMAL, ent);
225                                 if (!trace_ent.takedamage)
226                                 {
227                                         // verify that the shot would hit if altered
228                                         traceline(w_shotorg, ent.cursor_trace_ent.origin, MOVE_NORMAL, ent);
229                                         if (trace_ent == ent.cursor_trace_ent)
230                                                 w_shotdir = normalize(ent.cursor_trace_ent.origin - w_shotorg);
231                                         else
232                                                 print("antilag fail\n");
233                                 }
234                         }
235                 }
236         }
237
238         ent.dphitcontentsmask = oldsolid; // restore solid type (generally SOLID_SLIDEBOX)
239
240         if (!g_norecoil)
241                 ent.punchangle_x = recoil * -1;
242
243         if (snd != "")
244         {
245                 sound (ent, CHAN_WEAPON, snd, VOL_BASE, ATTN_NORM);
246         }
247
248         if (ent.items & IT_STRENGTH)
249         if (!g_minstagib)
250                 sound (ent, CHAN_AUTO, "weapons/strength_fire.wav", VOL_BASE, ATTN_NORM);
251 };
252
253 #define W_SetupShot_ProjectileSize(ent,mi,ma,antilag,recoil,snd,maxdamage) W_SetupShot_Dir_ProjectileSize(ent, v_forward, mi, ma, antilag, recoil, snd, maxdamage)
254 #define W_SetupShot_Dir(ent,s_forward,antilag,recoil,snd,maxdamage) W_SetupShot_Dir_ProjectileSize(ent, s_forward, '0 0 0', '0 0 0', antilag, recoil, snd, maxdamage)
255 #define W_SetupShot(ent,antilag,recoil,snd,maxdamage) W_SetupShot_ProjectileSize(ent, '0 0 0', '0 0 0', antilag, recoil, snd, maxdamage)
256
257 void LaserTarget_Think()
258 {
259         entity e;
260         vector offset;
261         float uselaser;
262         uselaser = 0;
263
264         // list of weapons that will use the laser, and the options that enable it
265         if(self.owner.laser_on && self.owner.weapon == WEP_ROCKET_LAUNCHER && g_laserguided_missile)
266                 uselaser = 1;
267         // example
268         //if(self.owner.weapon == WEP_ELECTRO && cvar("g_laserguided_electro"))
269         //      uselaser = 1;
270
271
272
273         // if a laser-enabled weapon isn't selected, delete any existing laser and quit
274         if(!uselaser)
275         {
276                 // rocket launcher isn't selected, so no laser target.
277                 if(self.lasertarget != world)
278                 {
279                         remove(self.lasertarget);
280                         self.lasertarget = world;
281                 }
282                 return;
283         }
284
285         if(!self.lasertarget)
286         {
287                 // we don't have a lasertarget entity, so spawn one
288                 //bprint("create laser target\n");
289                 e = self.lasertarget = spawn();
290                 e.owner = self.owner;                   // Its owner is my owner
291                 e.classname = "laser_target";
292                 e.movetype = MOVETYPE_NOCLIP;   // don't touch things
293                 setmodel(e, "models/laser_dot.mdl");    // what it looks like, precision set below
294                 e.scale = 1.25;                         // make it larger
295                 e.alpha = 0.25;                         // transparency
296                 e.colormod = '255 0 0' * (1/255) * 8;   // change colors
297                 e.effects = EF_FULLBRIGHT | EF_LOWPRECISION;
298                 // make it dynamically glow
299                 // you should avoid over-using this, as it can slow down the player's computer.
300                 e.glow_color = 251; // red color
301                 e.glow_size = 12;
302         }
303         else
304                 e = self.lasertarget;
305
306         // move the laser dot to where the player is looking
307
308         makevectors(self.owner.v_angle); // set v_forward etc to the direction the player is looking
309         offset = '0 0 26' + v_right*3;
310         traceline(self.owner.origin + offset, self.owner.origin + offset + v_forward * MAX_SHOT_DISTANCE, FALSE, self); // trace forward until you hit something, like a player or wall
311         setorigin(e, trace_endpos + v_forward*8); // move me to where the traceline ended
312         if(trace_plane_normal != '0 0 0')
313                 e.angles = vectoangles(trace_plane_normal);
314         else
315                 e.angles = vectoangles(v_forward);
316 }
317
318 float CL_Weaponentity_CustomizeEntityForClient()
319 {
320         self.viewmodelforclient = self.owner;
321         if(other.classname == "spectator")
322                 if(other.enemy == self.owner)
323                         self.viewmodelforclient = other;
324         return TRUE;
325 }
326
327 float qcweaponanimation;
328 vector weapon_offset = '0 -10 0';
329 vector weapon_adjust = '10 0 -15';
330 .vector weapon_morph0origin;
331 .vector weapon_morph0angles;
332 .float  weapon_morph0time;
333 .vector weapon_morph1origin;
334 .vector weapon_morph1angles;
335 .float  weapon_morph1time;
336 .vector weapon_morph2origin;
337 .vector weapon_morph2angles;
338 .float  weapon_morph2time;
339 .vector weapon_morph3origin;
340 .vector weapon_morph3angles;
341 .float  weapon_morph3time;
342 .vector weapon_morph4origin;
343 .vector weapon_morph4angles;
344 .float  weapon_morph4time;
345 .string weaponname;
346 #define QCWEAPONANIMATION_ORIGIN(e) ((weapon_offset_x + e.view_ofs_x) * v_forward - (weapon_offset_y + e.view_ofs_y) * v_right + (weapon_offset_z + e.view_ofs_z) * v_up + weapon_adjust)
347
348 /*
349  * supported formats:
350  *
351  * 1. simple animated model, muzzle flash handling on h_ model:
352  *    h_tuba.dpm, h_tuba.dpm.framegroups - invisible model controlling the animation
353  *      tags:
354  *        shot = muzzle end (shot origin, also used for muzzle flashes)
355  *        shell = casings ejection point (must be on the right hand side of the gun)
356  *        weapon = attachment for v_tuba.md3
357  *    v_tuba.md3 - first and third person model
358  *    g_tuba.md3 - pickup model
359  *
360  * 2. simple animated model, muzzle flash handling on v_ model:
361  *    h_tuba.dpm, h_tuba.dpm.framegroups - invisible model controlling the animation
362  *      tags:
363  *        weapon = attachment for v_tuba.md3
364  *    v_tuba.md3 - first and third person model
365  *      tags:
366  *        shot = muzzle end (shot origin, also used for muzzle flashes)
367  *        shell = casings ejection point (must be on the right hand side of the gun)
368  *    g_tuba.md3 - pickup model
369  *
370  * 3. fully animated model, muzzle flash handling on h_ model:
371  *    h_tuba.dpm, h_tuba.dpm.framegroups - animated first person model
372  *      tags:
373  *        shot = muzzle end (shot origin, also used for muzzle flashes)
374  *        shell = casings ejection point (must be on the right hand side of the gun)
375  *        handle = corresponding to the origin of v_tuba.md3 (used for muzzle flashes)
376  *    v_tuba.md3 - third person model
377  *    g_tuba.md3 - pickup model
378  *
379  * 4. fully animated model, muzzle flash handling on v_ model:
380  *    h_tuba.dpm, h_tuba.dpm.framegroups - animated first person model
381  *      tags:
382  *        shot = muzzle end (shot origin)
383  *        shell = casings ejection point (must be on the right hand side of the gun)
384  *    v_tuba.md3 - third person model
385  *      tags:
386  *        shot = muzzle end (for muzzle flashes)
387  *    g_tuba.md3 - pickup model
388  */
389
390 // writes:
391 //   self.origin, self.angles
392 //   self.weaponentity
393 //   self.movedir, self.view_ofs
394 //   attachment stuff
395 //   anim stuff
396 // to free:
397 //   call again with ""
398 //   remove the ent
399 void CL_WeaponEntity_SetModel(string name)
400 {
401         string animfilename;
402         float animfile;
403         float v_shot_idx;
404         if (name != "")
405         {
406                 // if there is a child entity, hide it until we're sure we use it
407                 if (self.weaponentity)
408                         self.weaponentity.model = "";
409                 setmodel(self, strcat("models/weapons/v_", name, ".md3")); // precision set below
410                 v_shot_idx = gettagindex(self, "shot"); // used later
411                 if(!v_shot_idx)
412                         v_shot_idx = gettagindex(self, "tag_shot");
413
414                 if(qcweaponanimation)
415                 {
416                         self.angles = '0 0 0';
417                         makevectors(self.angles_x * '-1 0 0' + self.angles_y * '0 1 0' + self.angles_z * '0 0 1');
418                         self.movedir = weapon_offset_x * v_forward - weapon_offset_y * v_right + weapon_offset_z * v_up + weapon_adjust;
419                         self.movedir_x += 32;
420                         self.spawnorigin = self.movedir;
421                         // oldorigin - not calculated here
422                 }
423                 else
424                 {
425                         setmodel(self, strcat("models/weapons/h_", name, ".iqm")); // precision set below
426                         animfilename = strcat("models/weapons/h_", name, ".iqm.animinfo");
427                         animfile = fopen(animfilename, FILE_READ);
428                         // preset some defaults that work great for renamed zym files (which don't need an animinfo)
429                         self.anim_fire1  = '0 1 0.01';
430                         self.anim_fire2  = '1 1 0.01';
431                         self.anim_idle   = '2 1 0.01';
432                         self.anim_reload = '3 1 0.01';
433                         if (animfile >= 0)
434                         {
435                                 animparseerror = FALSE;
436                                 self.anim_fire1  = animparseline(animfile);
437                                 self.anim_fire2  = animparseline(animfile);
438                                 self.anim_idle   = animparseline(animfile);
439                                 self.anim_reload = animparseline(animfile);
440                                 fclose(animfile);
441                                 if (animparseerror)
442                                         print("Parse error in ", animfilename, ", some player animations are broken\n");
443                         }
444
445                         // if we have a "weapon" tag, let's attach the v_ model to it ("invisible hand" style model)
446                         // if we don't, this is a "real" animated model
447                         if(gettagindex(self, "weapon"))
448                         {
449                                 if (!self.weaponentity)
450                                         self.weaponentity = spawn();
451                                 setmodel(self.weaponentity, strcat("models/weapons/v_", name, ".md3")); // precision does not matter
452                                 setattachment(self.weaponentity, self, "weapon");
453                         }
454                         else if(gettagindex(self, "tag_weapon"))
455                         {
456                                 if (!self.weaponentity)
457                                         self.weaponentity = spawn();
458                                 setmodel(self.weaponentity, strcat("models/weapons/v_", name, ".md3")); // precision does not matter
459                                 setattachment(self.weaponentity, self, "tag_weapon");
460                         }
461                         else
462                         {
463                                 if(self.weaponentity)
464                                         remove(self.weaponentity);
465                                 self.weaponentity = world;
466                         }
467
468                         setorigin(self,'0 0 0');
469                         self.angles = '0 0 0';
470                         self.frame = 0;
471                         self.viewmodelforclient = world;
472
473                         float idx;
474
475                         if(v_shot_idx) // v_ model attached to invisible h_ model
476                         {
477                                 self.movedir = gettaginfo(self.weaponentity, v_shot_idx);
478                         }
479                         else
480                         {
481                                 idx = gettagindex(self, "shot");
482                                 if(!idx)
483                                         idx = gettagindex(self, "tag_shot");
484                                 if(idx)
485                                         self.movedir = gettaginfo(self, idx);
486                                 else
487                                 {
488                                         print("WARNING: weapon model ", self.model, " does not support the 'shot' tag, will display shots TOTALLY wrong\n");
489                                         self.movedir = '0 0 0';
490                                 }
491                         }
492
493                         if(self.weaponentity) // v_ model attached to invisible h_ model
494                         {
495                                 idx = gettagindex(self.weaponentity, "shell");
496                                 if(!idx)
497                                         idx = gettagindex(self.weaponentity, "tag_shell");
498                                 if(idx)
499                                         self.spawnorigin = gettaginfo(self.weaponentity, idx);
500                         }
501                         else
502                                 idx = 0;
503                         if(!idx)
504                         {
505                                 idx = gettagindex(self, "shell");
506                                 if(!idx)
507                                         idx = gettagindex(self, "tag_shell");
508                                 if(idx)
509                                         self.spawnorigin = gettaginfo(self, idx);
510                                 else
511                                 {
512                                         print("WARNING: weapon model ", self.model, " does not support the 'shell' tag, will display casings wrong\n");
513                                         self.spawnorigin = self.movedir;
514                                 }
515                         }
516
517                         if(v_shot_idx)
518                         {
519                                 self.oldorigin = '0 0 0'; // use regular attachment
520                         }
521                         else
522                         {
523                                 if(self.weaponentity)
524                                 {
525                                         idx = gettagindex(self, "weapon");
526                                         if(!idx)
527                                                 idx = gettagindex(self, "tag_weapon");
528                                 }
529                                 else
530                                 {
531                                         idx = gettagindex(self, "handle");
532                                         if(!idx)
533                                                 idx = gettagindex(self, "tag_handle");
534                                 }
535                                 if(idx)
536                                 {
537                                         self.oldorigin = self.movedir - gettaginfo(self, idx);
538                                 }
539                                 else
540                                 {
541                                         print("WARNING: weapon model ", self.model, " does not support the 'handle' tag and neither does the v_ model support the 'shot' tag, will display muzzle flashes TOTALLY wrong\n");
542                                         self.oldorigin = '0 0 0'; // there is no way to recover from this
543                                 }
544                         }
545
546                         self.viewmodelforclient = self.owner;
547                 }
548         }
549         else
550         {
551                 self.model = "";
552                 if(self.weaponentity)
553                         remove(self.weaponentity);
554                 self.weaponentity = world;
555                 self.movedir = '0 0 0';
556                 self.spawnorigin = '0 0 0';
557                 self.oldorigin = '0 0 0';
558                 self.anim_fire1  = '0 1 0.01';
559                 self.anim_fire2  = '0 1 0.01';
560                 self.anim_idle   = '0 1 0.01';
561                 self.anim_reload = '0 1 0.01';
562         }
563
564         self.view_ofs = '0 0 0';
565
566         if(self.movedir_x >= 0)
567         {
568                 vector v0;
569                 v0 = self.movedir;
570                 self.movedir = shotorg_adjust(v0, FALSE, FALSE);
571                 self.view_ofs = shotorg_adjust(v0, FALSE, TRUE) - v0;
572         }
573         self.owner.stat_shotorg = compressShotOrigin(self.movedir);
574         self.movedir = decompressShotOrigin(self.owner.stat_shotorg); // make them match perfectly
575
576         self.spawnorigin += self.view_ofs; // offset the casings origin by the same amount
577
578         // check if an instant weapon switch occurred
579         if (qcweaponanimation)
580         {
581                 if (self.state == WS_READY)
582                 {
583                         self.angles = '0 0 0';
584                         makevectors(self.angles_x * '-1 0 0' + self.angles_y * '0 1 0' + self.angles_z * '0 0 1');
585                         setorigin(self, QCWEAPONANIMATION_ORIGIN(self));
586                 }
587         }
588         else
589                 setorigin(self, self.view_ofs);
590         // reset animstate now
591         self.wframe = WFRAME_IDLE;
592         self.weapon_morph0time = 0;
593         self.weapon_morph1time = 0;
594         self.weapon_morph2time = 0;
595         self.weapon_morph3time = 0;
596         self.weapon_morph4time = 0;
597         setanim(self, self.anim_idle, TRUE, FALSE, TRUE);
598 }
599
600 vector CL_Weapon_GetShotOrg(float wpn)
601 {
602         entity wi, oldself;
603         vector ret;
604         wi = get_weaponinfo(wpn);
605         oldself = self;
606         self = spawn();
607         CL_WeaponEntity_SetModel(wi.mdl);
608         ret = self.movedir;
609         CL_WeaponEntity_SetModel("");
610         remove(self);
611         self = oldself;
612         return ret;
613 }
614
615 void CL_Weaponentity_Think()
616 {
617         float tb;
618         self.nextthink = time;
619         if (intermission_running)
620                 self.frame = self.anim_idle_x;
621         if (self.owner.weaponentity != self)
622         {
623                 if (self.weaponentity)
624                         remove(self.weaponentity);
625                 remove(self);
626                 return;
627         }
628         if (self.owner.deadflag != DEAD_NO)
629         {
630                 self.model = "";
631                 if (self.weaponentity)
632                         self.weaponentity.model = "";
633                 return;
634         }
635         if (self.cnt != self.owner.weapon || self.dmg != self.owner.modelindex || self.deadflag != self.owner.deadflag)
636         {
637                 self.cnt = self.owner.weapon;
638                 self.dmg = self.owner.modelindex;
639                 self.deadflag = self.owner.deadflag;
640
641                 CL_WeaponEntity_SetModel(self.owner.weaponname);
642         }
643
644         tb = (self.effects & (EF_TELEPORT_BIT | EF_RESTARTANIM_BIT));
645         self.effects = self.owner.effects & EFMASK_CHEAP;
646         self.effects &~= EF_LOWPRECISION;
647         self.effects &~= EF_FULLBRIGHT; // can mask team color, so get rid of it
648         self.effects &~= EF_TELEPORT_BIT;
649         self.effects &~= EF_RESTARTANIM_BIT;
650         self.effects |= tb;
651
652         if(self.owner.alpha == default_player_alpha)
653                 self.alpha = default_weapon_alpha;
654         else if(self.owner.alpha != 0)
655                 self.alpha = self.owner.alpha;
656         else
657                 self.alpha = 1;
658
659         self.colormap = self.owner.colormap;
660         if (self.weaponentity)
661         {
662                 self.weaponentity.effects = self.effects;
663                 self.weaponentity.alpha = self.alpha;
664                 self.weaponentity.colormap = self.colormap;
665         }
666
667         self.angles = '0 0 0';
668         local float f;
669         f = 0;
670         if (self.state == WS_RAISE && !intermission_running)
671         {
672                 f = (self.owner.weapon_nextthink - time) * g_weaponratefactor / cvar("g_balance_weaponswitchdelay");
673                 self.angles_x = -90 * f * f;
674                 if (qcweaponanimation)
675                 {
676                         makevectors(self.angles_x * '-1 0 0' + self.angles_y * '0 1 0' + self.angles_z * '0 0 1');
677                         setorigin(self, QCWEAPONANIMATION_ORIGIN(self));
678                 }
679         }
680         else if (self.state == WS_DROP && !intermission_running)
681         {
682                 f = 1 - (self.owner.weapon_nextthink - time) * g_weaponratefactor / cvar("g_balance_weaponswitchdelay");
683                 self.angles_x = -90 * f * f;
684                 if (qcweaponanimation)
685                 {
686                         makevectors(self.angles_x * '-1 0 0' + self.angles_y * '0 1 0' + self.angles_z * '0 0 1');
687                         setorigin(self, QCWEAPONANIMATION_ORIGIN(self));
688                 }
689         }
690         else if (self.state == WS_CLEAR)
691         {
692                 f = 1;
693                 self.angles_x = -90 * f * f;
694                 if (qcweaponanimation)
695                 {
696                         makevectors(self.angles_x * '-1 0 0' + self.angles_y * '0 1 0' + self.angles_z * '0 0 1');
697                         setorigin(self, QCWEAPONANIMATION_ORIGIN(self));
698                 }
699         }
700         else if (qcweaponanimation && time < self.owner.weapon_morph1time)
701         {
702                 f = (time - self.owner.weapon_morph0time) / (self.owner.weapon_morph1time - self.owner.weapon_morph0time);
703                 f = 1 - pow(1 - f, 3);
704                 self.angles = self.owner.weapon_morph0angles * (1 - f) + self.owner.weapon_morph1angles * f;
705                 setorigin(self, self.owner.weapon_morph0origin * (1 - f) + self.owner.weapon_morph1origin * f);
706         }
707         else if (qcweaponanimation && time < self.owner.weapon_morph2time)
708         {
709                 f = (time - self.owner.weapon_morph1time) / (self.owner.weapon_morph2time - self.owner.weapon_morph1time);
710                 f = 1 - pow(1 - f, 3);
711                 self.angles = self.owner.weapon_morph1angles * (1 - f) + self.owner.weapon_morph2angles * f;
712                 setorigin(self, self.owner.weapon_morph1origin * (1 - f) + self.owner.weapon_morph2origin * f);
713         }
714         else if (qcweaponanimation && time < self.owner.weapon_morph3time)
715         {
716                 f = (time - self.owner.weapon_morph2time) / (self.owner.weapon_morph3time - self.owner.weapon_morph2time);
717                 f = 1 - pow(1 - f, 3);
718                 self.angles = self.owner.weapon_morph2angles * (1 - f) + self.owner.weapon_morph3angles * f;
719                 setorigin(self, self.owner.weapon_morph2origin * (1 - f) + self.owner.weapon_morph3origin * f);
720         }
721         else if (qcweaponanimation && time < self.owner.weapon_morph4time)
722         {
723                 f = (time - self.owner.weapon_morph3time) / (self.owner.weapon_morph4time - self.owner.weapon_morph3time);
724                 f = 1 - pow(1 - f, 3);
725                 self.angles = self.owner.weapon_morph3angles * (1 - f) + self.owner.weapon_morph4angles * f;
726                 setorigin(self, self.owner.weapon_morph3origin * (1 - f) + self.owner.weapon_morph4origin * f);
727         }
728         else if (qcweaponanimation)
729         {
730                 // begin a new idle morph
731                 self.owner.weapon_morph0time   = time;
732                 self.owner.weapon_morph0angles = self.angles;
733                 self.owner.weapon_morph0origin = self.origin;
734
735                 float r;
736                 float t;
737
738                 r = random();
739                 if (r < 0.1)
740                 {
741                         // turn gun to the left to look at it
742                         t = 2;
743                         self.owner.weapon_morph1time   = time + t * 0.2;
744                         self.owner.weapon_morph1angles = randomvec() * 3 + '-5 30 0';
745                         makevectors(self.owner.weapon_morph1angles_x * '-1 0 0' + self.owner.weapon_morph1angles_y * '0 1 0' + self.owner.weapon_morph1angles_z * '0 0 1');
746                         self.owner.weapon_morph1origin = QCWEAPONANIMATION_ORIGIN(self);
747
748                         self.owner.weapon_morph2time   = time + t * 0.6;
749                         self.owner.weapon_morph2angles = randomvec() * 3 + '-5 30 0';
750                         makevectors(self.owner.weapon_morph2angles_x * '-1 0 0' + self.owner.weapon_morph2angles_y * '0 1 0' + self.owner.weapon_morph2angles_z * '0 0 1');
751                         self.owner.weapon_morph2origin = QCWEAPONANIMATION_ORIGIN(self);
752
753                         self.owner.weapon_morph3time   = time + t;
754                         self.owner.weapon_morph3angles = '0 0 0';
755                         makevectors(self.owner.weapon_morph3angles_x * '-1 0 0' + self.owner.weapon_morph3angles_y * '0 1 0' + self.owner.weapon_morph3angles_z * '0 0 1');
756                         self.owner.weapon_morph3origin = QCWEAPONANIMATION_ORIGIN(self);
757                 }
758                 else if (r < 0.2)
759                 {
760                         // raise the gun a bit
761                         t = 2;
762                         self.owner.weapon_morph1time   = time + t * 0.2;
763                         self.owner.weapon_morph1angles = randomvec() * 3 + '30 -10 0';
764                         makevectors(self.owner.weapon_morph1angles_x * '-1 0 0' + self.owner.weapon_morph1angles_y * '0 1 0' + self.owner.weapon_morph1angles_z * '0 0 1');
765                         self.owner.weapon_morph1origin = QCWEAPONANIMATION_ORIGIN(self);
766
767                         self.owner.weapon_morph2time   = time + t * 0.5;
768                         self.owner.weapon_morph2angles = randomvec() * 3 + '30 -10 5';
769                         makevectors(self.owner.weapon_morph2angles_x * '-1 0 0' + self.owner.weapon_morph2angles_y * '0 1 0' + self.owner.weapon_morph2angles_z * '0 0 1');
770                         self.owner.weapon_morph2origin = QCWEAPONANIMATION_ORIGIN(self);
771
772                         self.owner.weapon_morph3time   = time + t;
773                         self.owner.weapon_morph3angles = '0 0 0';
774                         makevectors(self.owner.weapon_morph3angles_x * '-1 0 0' + self.owner.weapon_morph3angles_y * '0 1 0' + self.owner.weapon_morph3angles_z * '0 0 1');
775                         self.owner.weapon_morph3origin = QCWEAPONANIMATION_ORIGIN(self);
776                 }
777                 else if (r < 0.3)
778                 {
779                         // tweak it a bit
780                         t = 5;
781                         self.owner.weapon_morph1time   = time + t * 0.3;
782                         self.owner.weapon_morph1angles = randomvec() * 6;
783                         makevectors(self.owner.weapon_morph1angles_x * '-1 0 0' + self.owner.weapon_morph1angles_y * '0 1 0' + self.owner.weapon_morph1angles_z * '0 0 1');
784                         self.owner.weapon_morph1origin = QCWEAPONANIMATION_ORIGIN(self);
785
786                         self.owner.weapon_morph2time   = time + t * 0.7;
787                         self.owner.weapon_morph2angles = randomvec() * 6;
788                         makevectors(self.owner.weapon_morph2angles_x * '-1 0 0' + self.owner.weapon_morph2angles_y * '0 1 0' + self.owner.weapon_morph2angles_z * '0 0 1');
789                         self.owner.weapon_morph2origin = QCWEAPONANIMATION_ORIGIN(self);
790
791                         self.owner.weapon_morph3time   = time + t;
792                         self.owner.weapon_morph3angles = '0 0 0';
793                         makevectors(self.owner.weapon_morph3angles_x * '-1 0 0' + self.owner.weapon_morph3angles_y * '0 1 0' + self.owner.weapon_morph3angles_z * '0 0 1');
794                         self.owner.weapon_morph3origin = QCWEAPONANIMATION_ORIGIN(self);
795                 }
796                 else
797                 {
798                         // hold it mostly steady
799                         t = random() * 6 + 4;
800                         self.owner.weapon_morph1time   = time + t * 0.2;
801                         self.owner.weapon_morph1angles = randomvec() * 1;
802                         makevectors(self.owner.weapon_morph1angles_x * '-1 0 0' + self.owner.weapon_morph1angles_y * '0 1 0' + self.owner.weapon_morph1angles_z * '0 0 1');
803                         self.owner.weapon_morph1origin = QCWEAPONANIMATION_ORIGIN(self);
804
805                         self.owner.weapon_morph2time   = time + t * 0.5;
806                         self.owner.weapon_morph2angles = randomvec() * 1;
807                         makevectors(self.owner.weapon_morph2angles_x * '-1 0 0' + self.owner.weapon_morph2angles_y * '0 1 0' + self.owner.weapon_morph2angles_z * '0 0 1');
808                         self.owner.weapon_morph2origin = QCWEAPONANIMATION_ORIGIN(self);
809
810                         self.owner.weapon_morph3time   = time + t * 0.7;
811                         self.owner.weapon_morph3angles = randomvec() * 1;
812                         makevectors(self.owner.weapon_morph3angles_x * '-1 0 0' + self.owner.weapon_morph3angles_y * '0 1 0' + self.owner.weapon_morph3angles_z * '0 0 1');
813                         self.owner.weapon_morph3origin = QCWEAPONANIMATION_ORIGIN(self);
814                 }
815
816                 self.owner.weapon_morph4time   = time + t;
817                 self.owner.weapon_morph4angles = '0 0 0';
818                 makevectors(self.owner.weapon_morph4angles_x * '-1 0 0' + self.owner.weapon_morph4angles_y * '0 1 0' + self.owner.weapon_morph4angles_z * '0 0 1');
819                 self.owner.weapon_morph4origin = QCWEAPONANIMATION_ORIGIN(self);
820
821         }
822
823         // create or update the lasertarget entity
824         LaserTarget_Think();
825 };
826
827 void CL_ExteriorWeaponentity_Think()
828 {
829         float tag_found;
830         vector ang;
831         self.nextthink = time;
832         if (self.owner.exteriorweaponentity != self)
833         {
834                 remove(self);
835                 return;
836         }
837         if (self.owner.deadflag != DEAD_NO)
838         {
839                 self.model = "";
840                 return;
841         }
842         if (self.cnt != self.owner.weapon || self.dmg != self.owner.modelindex || self.deadflag != self.owner.deadflag)
843         {
844                 self.cnt = self.owner.weapon;
845                 self.dmg = self.owner.modelindex;
846                 self.deadflag = self.owner.deadflag;
847                 if (self.owner.weaponname != "")
848                         setmodel(self, strcat("models/weapons/v_", self.owner.weaponname, ".md3")); // precision set below
849                 else
850                         self.model = "";
851
852                 if((tag_found = gettagindex(self.owner, "tag_weapon")))
853                 {
854                         self.tag_index = tag_found;
855                         self.tag_entity = self.owner;
856                 }
857                 else
858                         setattachment(self, self.owner, "bip01 r hand");
859
860                 // if that didn't find a tag, hide the exterior weapon model
861                 if (!self.tag_index)
862                         self.model = "";
863         }
864         self.effects = self.owner.effects;
865         if(sv_pitch_min == sv_pitch_max)
866                 self.effects |= EF_LOWPRECISION;
867         else
868                 self.effects &~= EF_LOWPRECISION;
869         self.effects = self.effects & EFMASK_CHEAP; // eat performance
870         if(self.owner.alpha == default_player_alpha)
871                 self.alpha = default_weapon_alpha;
872         else if(self.owner.alpha != 0)
873                 self.alpha = self.owner.alpha;
874         else
875                 self.alpha = 1;
876
877         ang_x = bound(sv_pitch_min, self.owner.v_angle_x, sv_pitch_max);
878         ang_y = 0;
879         ang_z = 0;
880
881         if(sv_pitch_fixyaw) // workaround for stupid player models that don't aim forward
882         {
883                 ang_y = self.owner.v_angle_y;
884                 makevectors(ang);
885                 var vector v = v_forward;
886                 var float t = self.tag_entity.frame1time;
887                 var float f = self.tag_entity.frame;
888                 self.tag_entity.frame1time = time;
889                 self.tag_entity.frame = self.tag_entity.anim_idle_x;
890                 gettaginfo(self.tag_entity, self.tag_index);
891                 self.tag_entity.frame1time = t;
892                 self.tag_entity.frame = f;
893                 // untransform v according to this coordinate space
894                 vector w;
895                 w_x = v_forward * v;
896                 w_y = -v_right * v;
897                 w_z = v_up * v;
898                 self.angles = vectoangles(w);
899         }
900         else
901         {
902                 ang_x = -/* don't ask */ang_x;
903                 self.angles = ang;
904         }
905
906         self.colormap = self.owner.colormap;
907 };
908
909 // spawning weaponentity for client
910 void CL_SpawnWeaponentity()
911 {
912         self.weaponentity = spawn();
913         self.weaponentity.classname = "weaponentity";
914         self.weaponentity.solid = SOLID_NOT;
915         self.weaponentity.owner = self;
916         setmodel(self.weaponentity, ""); // precision set when changed
917         setorigin(self.weaponentity, '0 0 0');
918         self.weaponentity.angles = '0 0 0';
919         self.weaponentity.viewmodelforclient = self;
920         self.weaponentity.flags = 0;
921         self.weaponentity.think = CL_Weaponentity_Think;
922         self.weaponentity.customizeentityforclient = CL_Weaponentity_CustomizeEntityForClient;
923         self.weaponentity.nextthink = time;
924
925         self.exteriorweaponentity = spawn();
926         self.exteriorweaponentity.classname = "exteriorweaponentity";
927         self.exteriorweaponentity.solid = SOLID_NOT;
928         self.exteriorweaponentity.exteriorweaponentity = self.exteriorweaponentity;
929         self.exteriorweaponentity.owner = self;
930         setorigin(self.exteriorweaponentity, '0 0 0');
931         self.exteriorweaponentity.angles = '0 0 0';
932         self.exteriorweaponentity.think = CL_ExteriorWeaponentity_Think;
933         self.exteriorweaponentity.nextthink = time;
934 };
935
936 void Send_WeaponComplain (entity e, float wpn, string wpnname, float type)
937 {
938         msg_entity = e;
939         WriteByte(MSG_ONE, SVC_TEMPENTITY);
940         WriteByte(MSG_ONE, TE_CSQC_WEAPONCOMPLAIN);
941         WriteByte(MSG_ONE, wpn);
942         WriteString(MSG_ONE, wpnname);
943         WriteByte(MSG_ONE, type);
944 }
945
946 .float hasweapon_complain_spam;
947
948 float client_hasweapon(entity cl, float wpn, float andammo, float complain)
949 {
950         local float weaponbit, f;
951         local entity oldself;
952
953         if(time < self.hasweapon_complain_spam)
954                 complain = 0;
955         if(complain)
956                 self.hasweapon_complain_spam = time + 0.2;
957
958         if (wpn < WEP_FIRST || wpn > WEP_LAST)
959         {
960                 if (complain)
961                         sprint(self, "Invalid weapon\n");
962                 return FALSE;
963         }
964         weaponbit = W_WeaponBit(wpn);
965         if (cl.weapons & weaponbit)
966         {
967                 if (andammo)
968                 {
969                         if(cl.items & IT_UNLIMITED_WEAPON_AMMO)
970                         {
971                                 f = 1;
972                         }
973                         else
974                         {
975                                 oldself = self;
976                                 self = cl;
977                                 f = weapon_action(wpn, WR_CHECKAMMO1);
978                                 f = f + weapon_action(wpn, WR_CHECKAMMO2);
979                                 self = oldself;
980                         }
981                         if (!f)
982                         {
983                                 if (complain)
984                                 if(clienttype(cl) == CLIENTTYPE_REAL)
985                                 {
986                                         play2(cl, "weapons/unavailable.wav");
987                                         sprint(cl, strcat("You don't have any ammo for the ^2", W_Name(wpn), "\n"));
988                                         Send_WeaponComplain (cl, wpn, W_Name(wpn), 0);
989                                 }
990                                 return FALSE;
991                         }
992                 }
993                 return TRUE;
994         }
995         if (complain)
996         {
997                 // DRESK - 3/16/07
998                 // Report Proper Weapon Status / Modified Weapon Ownership Message
999                 if(weaponsInMap & weaponbit)
1000                 {
1001                         sprint(cl, strcat("You do not have the ^2", W_Name(wpn), "\n") );
1002                         Send_WeaponComplain (cl, wpn, W_Name(wpn), 1);
1003
1004                         if(cvar("g_showweaponspawns"))
1005                         {
1006                                 entity e;
1007                                 string s;
1008
1009                                 e = get_weaponinfo(wpn);
1010                                 s = e.model2;
1011
1012                                 for(e = world; (e = findfloat(e, weapons, weaponbit)); )
1013                                 {
1014                                         if(e.classname == "droppedweapon")
1015                                                 continue;
1016                                         if not(e.flags & FL_ITEM)
1017                                                 continue;
1018                                         WaypointSprite_Spawn(
1019                                                 s,
1020                                                 1, 0,
1021                                                 world, e.origin,
1022                                                 self, 0,
1023                                                 world, enemy,
1024                                                 0
1025                                         );
1026                                 }
1027                         }
1028                 }
1029                 else
1030                 {
1031                         Send_WeaponComplain (cl, wpn, W_Name(wpn), 2);
1032                         sprint(cl, strcat("The ^2", W_Name(wpn), "^7 is ^1NOT AVAILABLE^7 in this map\n") );
1033                 }
1034
1035                 play2(cl, "weapons/unavailable.wav");
1036         }
1037         return FALSE;
1038 };
1039
1040 // Weapon subs
1041 void w_clear()
1042 {
1043         if (self.weapon != -1)
1044                 self.weapon = 0;
1045         if (self.weaponentity)
1046         {
1047                 self.weaponentity.state = WS_CLEAR;
1048                 self.weaponentity.effects = 0;
1049         }
1050 };
1051
1052 void w_ready()
1053 {
1054         if (self.weaponentity)
1055                 self.weaponentity.state = WS_READY;
1056         weapon_thinkf(WFRAME_IDLE, 1000000, w_ready);
1057 };
1058
1059 // Setup weapon for client (after this raise frame will be launched)
1060 void weapon_setup(float windex)
1061 {
1062         entity e;
1063         qcweaponanimation = cvar("sv_qcweaponanimation");
1064         e = get_weaponinfo(windex);
1065         self.items &~= IT_AMMO;
1066         self.items = self.items | e.items;
1067
1068         // the two weapon entities will notice this has changed and update their models
1069         self.weapon = windex;
1070         self.weaponname = e.mdl;
1071         self.bulletcounter = 0;
1072 };
1073
1074 // perform weapon to attack (weaponstate and attack_finished check is here)
1075 void W_SwitchToOtherWeapon(entity pl)
1076 {
1077         // hack to ensure it switches to an OTHER weapon (in case the other fire mode still has ammo, we want that anyway)
1078         float w, ww;
1079         w = W_WeaponBit(pl.weapon);
1080         pl.weapons &~= w;
1081         ww = w_getbestweapon(pl);
1082         pl.weapons |= w;
1083         if(ww)
1084                 W_SwitchWeapon_Force(pl, ww);
1085 }
1086 float weapon_prepareattack_checkammo(float secondary)
1087 {
1088         if not(self.items & IT_UNLIMITED_WEAPON_AMMO)
1089         if (!weapon_action(self.weapon, WR_CHECKAMMO1 + secondary))
1090         {
1091                 W_SwitchToOtherWeapon(self);
1092                 return FALSE;
1093         }
1094         return TRUE;
1095 }
1096 .float race_penalty;
1097 float weapon_prepareattack_check(float secondary, float attacktime)
1098 {
1099         if(!weapon_prepareattack_checkammo(secondary))
1100                 return FALSE;
1101
1102         //if sv_ready_restart_after_countdown is set, don't allow the player to shoot
1103         //if all players readied up and the countdown is running
1104         if(time < game_starttime || time < self.race_penalty) {
1105                 return FALSE;
1106         }
1107
1108         if (timeoutStatus == 2) //don't allow the player to shoot while game is paused
1109                 return FALSE;
1110
1111         // do not even think about shooting if switching
1112         if(self.switchweapon != self.weapon)
1113                 return FALSE;
1114
1115         if(attacktime >= 0)
1116         {
1117                 // don't fire if previous attack is not finished
1118                 if (ATTACK_FINISHED(self) > time + self.weapon_frametime * 0.5)
1119                         return FALSE;
1120                 // don't fire while changing weapon
1121                 if (self.weaponentity.state != WS_READY)
1122                         return FALSE;
1123         }
1124
1125         return TRUE;
1126 }
1127 float weapon_prepareattack_do(float secondary, float attacktime)
1128 {
1129         self.weaponentity.state = WS_INUSE;
1130
1131         self.spawnshieldtime = min(self.spawnshieldtime, time); // kill spawn shield when you fire
1132
1133         // if the weapon hasn't been firing continuously, reset the timer
1134         if(attacktime >= 0)
1135         {
1136                 if (ATTACK_FINISHED(self) < time - self.weapon_frametime * 1.5)
1137                 {
1138                         ATTACK_FINISHED(self) = time;
1139                         //dprint("resetting attack finished to ", ftos(time), "\n");
1140                 }
1141                 ATTACK_FINISHED(self) = ATTACK_FINISHED(self) + attacktime * W_WeaponRateFactor();
1142         }
1143         self.bulletcounter += 1;
1144         //dprint("attack finished ", ftos(ATTACK_FINISHED(self)), "\n");
1145         return TRUE;
1146 }
1147 float weapon_prepareattack(float secondary, float attacktime)
1148 {
1149         if(weapon_prepareattack_check(secondary, attacktime))
1150         {
1151                 weapon_prepareattack_do(secondary, attacktime);
1152                 return TRUE;
1153         }
1154         else
1155                 return FALSE;
1156 }
1157
1158 void weapon_thinkf(float fr, float t, void() func)
1159 {
1160         vector a;
1161         vector of, or, ou;
1162         float restartanim;
1163
1164         if(fr == WFRAME_DONTCHANGE)
1165         {
1166                 fr = self.weaponentity.wframe;
1167                 restartanim = FALSE;
1168         }
1169         else if (fr == WFRAME_IDLE)
1170                 restartanim = FALSE;
1171         else
1172                 restartanim = TRUE;
1173
1174         of = v_forward;
1175         or = v_right;
1176         ou = v_up;
1177
1178         if (self.weaponentity)
1179         {
1180                 self.weaponentity.wframe = fr;
1181                 if (qcweaponanimation)
1182                 {
1183                         if (fr != WFRAME_IDLE)
1184                         {
1185                                 self.weapon_morph0time = time;
1186                                 self.weapon_morph0angles = self.weaponentity.angles;
1187                                 self.weapon_morph0origin = self.weaponentity.origin;
1188
1189                                 self.weapon_morph1angles = '0 0 0';
1190                                 self.weapon_morph1time = time + t;
1191                                 makevectors(self.weapon_morph1angles_x * '-1 0 0' + self.weapon_morph1angles_y * '0 1 0' + self.weapon_morph1angles_z * '0 0 1');
1192                                 self.weapon_morph1origin = QCWEAPONANIMATION_ORIGIN(self.weaponentity);
1193
1194                                 self.weapon_morph2angles = '0 0 0';
1195                                 self.weapon_morph2time = time + t;
1196                                 makevectors(self.weapon_morph2angles_x * '-1 0 0' + self.weapon_morph2angles_y * '0 1 0' + self.weapon_morph2angles_z * '0 0 1');
1197                                 self.weapon_morph2origin = QCWEAPONANIMATION_ORIGIN(self.weaponentity);
1198
1199                                 self.weapon_morph3angles = '0 0 0';
1200                                 self.weapon_morph3time = time + t;
1201                                 makevectors(self.weapon_morph3angles_x * '-1 0 0' + self.weapon_morph3angles_y * '0 1 0' + self.weapon_morph3angles_z * '0 0 1');
1202                                 self.weapon_morph3origin = QCWEAPONANIMATION_ORIGIN(self.weaponentity);
1203
1204                                 self.weapon_morph4angles = '0 0 0';
1205                                 self.weapon_morph4time = time + t;
1206                                 makevectors(self.weapon_morph4angles_x * '-1 0 0' + self.weapon_morph4angles_y * '0 1 0' + self.weapon_morph4angles_z * '0 0 1');
1207                                 self.weapon_morph4origin = QCWEAPONANIMATION_ORIGIN(self.weaponentity);
1208
1209                                 if (fr == WFRAME_FIRE1)
1210                                 {
1211                                         self.weapon_morph1angles = '5 0 0';
1212                                         self.weapon_morph1time = time + t * 0.1;
1213                                         makevectors(self.weapon_morph1angles_x * '-1 0 0' + self.weapon_morph1angles_y * '0 1 0' + self.weapon_morph1angles_z * '0 0 1');
1214                                         self.weapon_morph1origin = QCWEAPONANIMATION_ORIGIN(self.weaponentity);
1215                                         self.weapon_morph4time = time + t + 1; // delay idle effect
1216                                 }
1217                                 else if (fr == WFRAME_FIRE2)
1218                                 {
1219                                         self.weapon_morph1angles = '10 0 0';
1220                                         self.weapon_morph1time = time + t * 0.1;
1221                                         makevectors(self.weapon_morph1angles_x * '-1 0 0' + self.weapon_morph1angles_y * '0 1 0' + self.weapon_morph1angles_z * '0 0 1');
1222                                         self.weapon_morph1origin = QCWEAPONANIMATION_ORIGIN(self.weaponentity);
1223                                         self.weapon_morph4time = time + t + 1; // delay idle effect
1224                                 }
1225                                 else if (fr == WFRAME_RELOAD)
1226                                 {
1227                                         self.weapon_morph1time = time + t * 0.05;
1228                                         self.weapon_morph1angles = '-10 40 0';
1229                                         makevectors(self.weapon_morph1angles_x * '-1 0 0' + self.weapon_morph1angles_y * '0 1 0' + self.weapon_morph1angles_z * '0 0 1');
1230                                         self.weapon_morph1origin = QCWEAPONANIMATION_ORIGIN(self.weaponentity);
1231
1232                                         self.weapon_morph2time = time + t * 0.15;
1233                                         self.weapon_morph2angles = '-10 40 5';
1234                                         makevectors(self.weapon_morph2angles_x * '-1 0 0' + self.weapon_morph2angles_y * '0 1 0' + self.weapon_morph2angles_z * '0 0 1');
1235                                         self.weapon_morph2origin = QCWEAPONANIMATION_ORIGIN(self.weaponentity);
1236
1237                                         self.weapon_morph3time = time + t * 0.25;
1238                                         self.weapon_morph3angles = '-10 40 0';
1239                                         makevectors(self.weapon_morph3angles_x * '-1 0 0' + self.weapon_morph3angles_y * '0 1 0' + self.weapon_morph3angles_z * '0 0 1');
1240                                         self.weapon_morph3origin = QCWEAPONANIMATION_ORIGIN(self.weaponentity);
1241                                 }
1242                         }
1243                 }
1244                 else
1245                 {
1246                         if (fr == WFRAME_IDLE)
1247                                 a = self.weaponentity.anim_idle;
1248                         else if (fr == WFRAME_FIRE1)
1249                                 a = self.weaponentity.anim_fire1;
1250                         else if (fr == WFRAME_FIRE2)
1251                                 a = self.weaponentity.anim_fire2;
1252                         else if (fr == WFRAME_RELOAD)
1253                                 a = self.weaponentity.anim_reload;
1254                         a_z *= g_weaponratefactor;
1255                         setanim(self.weaponentity, a, restartanim == FALSE, restartanim, restartanim);
1256                 }
1257         }
1258
1259         v_forward = of;
1260         v_right = or;
1261         v_up = ou;
1262
1263         if(self.weapon_think == w_ready && func != w_ready && self.weaponentity.state == WS_RAISE)
1264         {
1265                 backtrace("Tried to override initial weapon think function - should this really happen?");
1266         }
1267
1268         t *= W_WeaponRateFactor();
1269
1270         // VorteX: haste can be added here
1271         if (self.weapon_think == w_ready)
1272         {
1273                 self.weapon_nextthink = time;
1274                 //dprint("started firing at ", ftos(time), "\n");
1275         }
1276         if (self.weapon_nextthink < time - self.weapon_frametime * 1.5 || self.weapon_nextthink > time + self.weapon_frametime * 1.5)
1277         {
1278                 self.weapon_nextthink = time;
1279                 //dprint("reset weapon animation timer at ", ftos(time), "\n");
1280         }
1281         self.weapon_nextthink = self.weapon_nextthink + t;
1282         self.weapon_think = func;
1283         //dprint("next ", ftos(self.weapon_nextthink), "\n");
1284
1285         if (restartanim)
1286         if (t)
1287         if (!self.crouch) // shoot anim stands up, this looks bad
1288         {
1289                 local vector anim;
1290                 anim = self.anim_shoot;
1291                 anim_z = anim_y / (t + sys_frametime);
1292                 setanim(self, anim, FALSE, TRUE, TRUE);
1293         }
1294 };
1295
1296 void weapon_boblayer1(float spd, vector org)
1297 {
1298         // VorteX: haste can be added here
1299 };
1300
1301 vector W_CalculateProjectileVelocity(vector pvelocity, vector mvelocity)
1302 {
1303         vector mdirection;
1304         float mspeed;
1305         float outspeed;
1306         float nstyle;
1307         vector outvelocity;
1308
1309         mvelocity = mvelocity * g_weaponspeedfactor;
1310
1311         mdirection = normalize(mvelocity);
1312         mspeed = vlen(mvelocity);
1313
1314         nstyle = cvar("g_projectiles_newton_style");
1315         if(nstyle == 0)
1316         {
1317                 // absolute velocity
1318                 outvelocity = mvelocity;
1319         }
1320         else if(nstyle == 1)
1321         {
1322                 // true Newtonian projectiles
1323                 outvelocity = pvelocity + mvelocity;
1324         }
1325         else if(nstyle == 2)
1326         {
1327                 // true Newtonian projectiles with automatic aim adjustment
1328                 //
1329                 // solve: |outspeed * mdirection - pvelocity| = mspeed
1330                 // outspeed^2 - 2 * outspeed * (mdirection * pvelocity) + pvelocity^2 - mspeed^2 = 0
1331                 // outspeed = (mdirection * pvelocity) +- sqrt((mdirection * pvelocity)^2 - pvelocity^2 + mspeed^2)
1332                 // PLUS SIGN!
1333                 // not defined?
1334                 // then...
1335                 // pvelocity^2 - (mdirection * pvelocity)^2 > mspeed^2
1336                 // velocity without mdirection component > mspeed
1337                 // fire at smallest possible mspeed that works?
1338                 // |(mdirection * pvelocity) * pvelocity - pvelocity| = mspeed
1339
1340                 vector solution;
1341                 solution = solve_quadratic(1, -2 * (mdirection * pvelocity), pvelocity * pvelocity - mspeed * mspeed);
1342                 if(solution_z)
1343                         outspeed = solution_y; // the larger one
1344                 else
1345                 {
1346                         //outspeed = 0; // slowest possible shot
1347                         outspeed = solution_x; // the real part (that is, the average!)
1348                         //dprint("impossible shot, adjusting\n");
1349                 }
1350
1351                 outspeed = bound(mspeed * cvar("g_projectiles_newton_style_2_minfactor"), outspeed, mspeed * cvar("g_projectiles_newton_style_2_maxfactor"));
1352                 outvelocity = mdirection * outspeed;
1353         }
1354         else if(nstyle == 3)
1355         {
1356                 // pseudo-Newtonian:
1357                 outspeed = mspeed + mdirection * pvelocity;
1358                 outspeed = bound(mspeed * 0.7, outspeed, mspeed * 5.0);
1359                 outvelocity = mdirection * outspeed;
1360         }
1361         else if(nstyle == 4)
1362         {
1363                 // tZorkian:
1364                 outspeed = mspeed + vlen(pvelocity);
1365                 outvelocity = mdirection * outspeed;
1366         }
1367         else
1368                 error("g_projectiles_newton_style must be 0 (absolute), 1 (Newtonian), 2 (Newtonian + aimfix), 3 (pseudo Newtonian) or 4 (tZorkian)!");
1369
1370         return outvelocity;
1371 }
1372
1373 void W_AttachToShotorg(entity flash, vector offset)
1374 {
1375         entity xflash;
1376         flash.owner = self;
1377         flash.angles_z = random() * 360;
1378         if(qcweaponanimation)
1379         {
1380                 setorigin(flash, w_shotorg + w_shotdir * 50);
1381                 flash.angles = vectoangles(w_shotdir);
1382                 flash.angles_z = random() * 360;
1383         }
1384         else
1385         {
1386                 if(gettagindex(self.weaponentity, "shot"))
1387                         setattachment(flash, self.weaponentity, "shot");
1388                 else
1389                         setattachment(flash, self.weaponentity, "tag_shot");
1390                 setorigin(flash, offset);
1391
1392                 xflash = spawn();
1393                 copyentity(flash, xflash);
1394
1395                 flash.viewmodelforclient = self;
1396
1397                 if(self.weaponentity.oldorigin_x > 0)
1398                 {
1399                         setattachment(xflash, self.exteriorweaponentity, "");
1400                         setorigin(xflash, self.weaponentity.oldorigin + offset);
1401                 }
1402                 else
1403                 {
1404                         if(gettagindex(self.exteriorweaponentity, "shot"))
1405                                 setattachment(xflash, self.exteriorweaponentity, "shot");
1406                         else
1407                                 setattachment(xflash, self.exteriorweaponentity, "tag_shot");
1408                         setorigin(xflash, offset);
1409                 }
1410         }
1411 }
1412
1413 vector cliptoplane(vector v, vector p)
1414 {
1415         return v - (v * p) * p;
1416 }
1417
1418 vector solve_cubic_pq(float p, float q)
1419 {
1420         float D, u, v, a;
1421         D = q*q/4.0 + p*p*p/27.0;
1422         if(D < 0)
1423         {
1424                 // irreducibilis
1425                 a = 1.0/3.0 * acos(-q/2.0 * sqrt(-27.0/(p*p*p)));
1426                 u = sqrt(-4.0/3.0 * p);
1427                 // a in range 0..pi/3
1428                 // cos(a)
1429                 // cos(a + 2pi/3)
1430                 // cos(a + 4pi/3)
1431                 return
1432                         u *
1433                         (
1434                                 '1 0 0' * cos(a + 2.0/3.0*M_PI)
1435                                 +
1436                                 '0 1 0' * cos(a + 4.0/3.0*M_PI)
1437                                 +
1438                                 '0 0 1' * cos(a)
1439                         );
1440         }
1441         else if(D == 0)
1442         {
1443                 // simple
1444                 if(p == 0)
1445                         return '0 0 0';
1446                 u = 3*q/p;
1447                 v = -u/2;
1448                 if(u >= v)
1449                         return '1 1 0' * v + '0 0 1' * u;
1450                 else
1451                         return '0 1 1' * v + '1 0 0' * u;
1452         }
1453         else
1454         {
1455                 // cardano
1456                 u = cbrt(-q/2.0 + sqrt(D));
1457                 v = cbrt(-q/2.0 - sqrt(D));
1458                 return '1 1 1' * (u + v);
1459         }
1460 }
1461 vector solve_cubic_abcd(float a, float b, float c, float d)
1462 {
1463         // y = 3*a*x + b
1464         // x = (y - b) / 3a
1465         float p, q;
1466         vector v;
1467         p = (9*a*c - 3*b*b);
1468         q = (27*a*a*d - 9*a*b*c + 2*b*b*b);
1469         v = solve_cubic_pq(p, q);
1470         v = (v -  b * '1 1 1') * (1.0 / (3.0 * a));
1471         if(a < 0)
1472                 v += '1 0 -1' * (v_z - v_x); // swap x, z
1473         return v;
1474 }
1475
1476 vector findperpendicular(vector v)
1477 {
1478         vector p;
1479         p_x = v_z;
1480         p_y = -v_x;
1481         p_z = v_y;
1482         return normalize(cliptoplane(p, v));
1483 }
1484
1485 vector W_CalculateProjectileSpread(vector forward, float spread)
1486 {
1487         float sigma;
1488         vector v1, v2;
1489         float dx, dy, r;
1490         float sstyle;
1491         spread *= g_weaponspreadfactor;
1492         if(spread <= 0)
1493                 return forward;
1494         sstyle = cvar("g_projectiles_spread_style");
1495         
1496         if(sstyle == 0)
1497         {
1498                 // this is the baseline for the spread value!
1499                 // standard deviation: sqrt(2/5)
1500                 // density function: sqrt(1-r^2)
1501                 return forward + randomvec() * spread;
1502         }
1503         else if(sstyle == 1)
1504         {
1505                 // same thing, basically
1506                 return normalize(forward + cliptoplane(randomvec() * spread, forward));
1507         }
1508         else if(sstyle == 2)
1509         {
1510                 // circle spread... has at sigma=1 a standard deviation of sqrt(1/2)
1511                 sigma = spread * 0.89442719099991587855; // match baseline stddev
1512                 v1 = findperpendicular(forward);
1513                 v2 = cross(forward, v1);
1514                 // random point on unit circle
1515                 dx = random() * 2 * M_PI;
1516                 dy = sin(dx);
1517                 dx = cos(dx);
1518                 // radius in our dist function
1519                 r = random();
1520                 r = sqrt(r);
1521                 return normalize(forward + (v1 * dx + v2 * dy) * r * sigma);
1522         }
1523         else if(sstyle == 3) // gauss 3d
1524         {
1525                 sigma = spread * 0.44721359549996; // match baseline stddev
1526                 // note: 2D gaussian has sqrt(2) times the stddev of 1D, so this factor is right
1527                 v1 = forward;
1528                 v1_x += gsl_ran_gaussian(sigma);
1529                 v1_y += gsl_ran_gaussian(sigma);
1530                 v1_z += gsl_ran_gaussian(sigma);
1531                 return v1;
1532         }
1533         else if(sstyle == 4) // gauss 2d
1534         {
1535                 sigma = spread * 0.44721359549996; // match baseline stddev
1536                 // note: 2D gaussian has sqrt(2) times the stddev of 1D, so this factor is right
1537                 v1_x = gsl_ran_gaussian(sigma);
1538                 v1_y = gsl_ran_gaussian(sigma);
1539                 v1_z = gsl_ran_gaussian(sigma);
1540                 return normalize(forward + cliptoplane(v1, forward));
1541         }
1542         else if(sstyle == 5) // 1-r
1543         {
1544                 sigma = spread * 1.154700538379252; // match baseline stddev
1545                 v1 = findperpendicular(forward);
1546                 v2 = cross(forward, v1);
1547                 // random point on unit circle
1548                 dx = random() * 2 * M_PI;
1549                 dy = sin(dx);
1550                 dx = cos(dx);
1551                 // radius in our dist function
1552                 r = random();
1553                 r = solve_cubic_abcd(-2, 3, 0, -r) * '0 1 0';
1554                 return normalize(forward + (v1 * dx + v2 * dy) * r * sigma);
1555         }
1556         else if(sstyle == 6) // 1-r^2
1557         {
1558                 sigma = spread * 1.095445115010332; // match baseline stddev
1559                 v1 = findperpendicular(forward);
1560                 v2 = cross(forward, v1);
1561                 // random point on unit circle
1562                 dx = random() * 2 * M_PI;
1563                 dy = sin(dx);
1564                 dx = cos(dx);
1565                 // radius in our dist function
1566                 r = random();
1567                 r = sqrt(1 - r);
1568                 r = sqrt(1 - r);
1569                 return normalize(forward + (v1 * dx + v2 * dy) * r * sigma);
1570         }
1571         else if(sstyle == 7) // (1-r) (2-r)
1572         {
1573                 sigma = spread * 1.224744871391589; // match baseline stddev
1574                 v1 = findperpendicular(forward);
1575                 v2 = cross(forward, v1);
1576                 // random point on unit circle
1577                 dx = random() * 2 * M_PI;
1578                 dy = sin(dx);
1579                 dx = cos(dx);
1580                 // radius in our dist function
1581                 r = random();
1582                 r = 1 - sqrt(r);
1583                 r = 1 - sqrt(r);
1584                 return normalize(forward + (v1 * dx + v2 * dy) * r * sigma);
1585         }
1586         else
1587                 error("g_projectiles_spread_style must be 0 (sphere), 1 (flattened sphere), 2 (circle), 3 (gauss 3D), 4 (gauss plane), 5 (linear falloff), 6 (quadratic falloff), 7 (stronger falloff)!");
1588         return '0 0 0';
1589         /*
1590          * how to derive falloff functions:
1591          * rho(r) := (2-r) * (1-r);
1592          * a : 0;
1593          * b : 1;
1594          * rhor(r) := r * rho(r);
1595          * cr(t) := integrate(rhor(r), r, a, t);
1596          * scr(t) := integrate(rhor(r) * r^2, r, a, t);
1597          * variance : scr(b) / cr(b);
1598          * solve(cr(r) = rand * cr(b), r), programmmode:false;
1599          * sqrt(0.4 / variance), numer;
1600          */
1601 }
1602
1603 #if 0
1604 float mspercallsum;
1605 float mspercallsstyle;
1606 float mspercallcount;
1607 #endif
1608 void W_SetupProjectileVelocityEx(entity missile, vector dir, vector upDir, float pSpeed, float pUpSpeed, float pZSpeed, float spread)
1609 {
1610         if(missile.owner == world)
1611                 error("Unowned missile");
1612
1613         dir = dir + upDir * (pUpSpeed / pSpeed);
1614         dir_z += pZSpeed / pSpeed;
1615         pSpeed *= vlen(dir);
1616         dir = normalize(dir);
1617
1618 #if 0
1619         if(cvar("g_projectiles_spread_style") != mspercallsstyle)
1620         {
1621                 mspercallsum = mspercallcount = 0;
1622                 mspercallsstyle = cvar("g_projectiles_spread_style");
1623         }
1624         mspercallsum -= gettime(GETTIME_HIRES);
1625 #endif
1626         dir = W_CalculateProjectileSpread(dir, spread);
1627 #if 0
1628         mspercallsum += gettime(GETTIME_HIRES);
1629         mspercallcount += 1;
1630         print("avg: ", ftos(mspercallcount / mspercallsum), " per sec\n");
1631 #endif
1632
1633         missile.velocity = W_CalculateProjectileVelocity(missile.owner.velocity, pSpeed * dir);
1634 }
1635
1636 void W_SetupProjectileVelocity(entity missile, float pSpeed, float spread)
1637 {
1638         W_SetupProjectileVelocityEx(missile, w_shotdir, v_up, pSpeed, 0, 0, spread);
1639 }
1640
1641 #define W_SETUPPROJECTILEVELOCITY_UP(m,s) W_SetupProjectileVelocityEx(m, w_shotdir, v_up, cvar(#s "_speed"), cvar(#s "_speed_up"), cvar(#s "_speed_z"), cvar(#s "_spread"))
1642 #define W_SETUPPROJECTILEVELOCITY(m,s) W_SetupProjectileVelocityEx(m, w_shotdir, v_up, cvar(#s "_speed"), 0, 0, cvar(#s "_spread"))