c9ad52ef93bf66cdd64ee0a04c2065bd244af937
[xonotic/xonotic-data.pk3dir.git] / qcsrc / client / view.qc
1 #include "view.qh"
2
3 #include "autocvars.qh"
4 #include "miscfunctions.qh"
5 #include "announcer.qh"
6 #include "hud/_mod.qh"
7 #include "mapvoting.qh"
8 #include "shownames.qh"
9 #include "hud/panel/scoreboard.qh"
10 #include "hud/panel/quickmenu.qh"
11
12 #include <client/mutators/_mod.qh>
13
14 #include <common/animdecide.qh>
15 #include <common/deathtypes/all.qh>
16 #include <common/ent_cs.qh>
17 #include <common/anim.qh>
18 #include <common/constants.qh>
19 #include <common/net_linked.qh>
20 #include <common/net_notice.qh>
21 #include <common/debug.qh>
22 #include <common/mapinfo.qh>
23 #include <common/gamemodes/_mod.qh>
24 #include <common/physics/player.qh>
25 #include <common/stats.qh>
26 #include <common/mapobjects/target/music.qh>
27 #include <common/teams.qh>
28 #include <common/wepent.qh>
29
30 #include <common/weapons/weapon/tuba.qh>
31
32 #include <common/vehicles/all.qh>
33 #include <common/weapons/_all.qh>
34 #include <common/mutators/mutator/waypoints/all.qh>
35 #include <common/viewloc.qh>
36 #include <common/mapobjects/trigger/viewloc.qh>
37 #include <common/minigames/cl_minigames.qh>
38 #include <common/minigames/cl_minigames_hud.qh>
39
40 #include <lib/csqcmodel/cl_player.qh>
41 #include <lib/csqcmodel/cl_model.qh>
42 #include "csqcmodel_hooks.qh"
43
44 #include <lib/warpzone/client.qh>
45 #include <lib/warpzone/common.qh>
46
47 #define EFMASK_CHEAP (EF_ADDITIVE | EF_DOUBLESIDED | EF_FULLBRIGHT | EF_NODEPTHTEST | EF_NODRAW | EF_NOSHADOW | EF_SELECTABLE | EF_TELEPORT_BIT)
48
49 float autocvar_cl_viewmodel_scale;
50 float autocvar_cl_viewmodel_alpha = 1;
51
52 bool autocvar_cl_bobmodel;
53 float autocvar_cl_bobmodel_speed;
54 float autocvar_cl_bobmodel_side;
55 float autocvar_cl_bobmodel_up;
56
57 float autocvar_cl_followmodel;
58 float autocvar_cl_followmodel_speed = 0.3;
59 float autocvar_cl_followmodel_limit = 135;
60 float autocvar_cl_followmodel_velocity_lowpass = 0.05;
61 float autocvar_cl_followmodel_highpass = 0.05;
62 float autocvar_cl_followmodel_lowpass = 0.03;
63 bool autocvar_cl_followmodel_velocity_absolute;
64
65 float autocvar_cl_leanmodel;
66 float autocvar_cl_leanmodel_speed = 0.3;
67 float autocvar_cl_leanmodel_limit = 30;
68 float autocvar_cl_leanmodel_highpass1 = 0.2;
69 float autocvar_cl_leanmodel_highpass = 0.2;
70 float autocvar_cl_leanmodel_lowpass = 0.05;
71
72 #define avg_factor(avg_time) (1 - exp(-frametime / max(0.001, avg_time)))
73
74 #define lowpass(value, frac, ref_store, ret) \
75         ret = ref_store = ref_store * (1 - frac) + (value) * frac;
76
77 #define lowpass_limited(value, frac, limit, ref_store, ret) MACRO_BEGIN \
78         float __ignore; lowpass(value, frac, ref_store, __ignore); \
79         ret = ref_store = bound((value) - (limit), ref_store, (value) + (limit)); \
80 MACRO_END
81
82 #define highpass(value, frac, ref_store, ret) MACRO_BEGIN \
83         float __f = 0; lowpass(value, frac, ref_store, __f); \
84         ret = (value) - __f; \
85 MACRO_END
86
87 #define highpass_limited(value, frac, limit, ref_store, ret) MACRO_BEGIN \
88         float __f = 0; lowpass_limited(value, frac, limit, ref_store, __f); \
89         ret = (value) - __f; \
90 MACRO_END
91
92 #define lowpass2(value, frac, ref_store, ref_out) MACRO_BEGIN \
93         lowpass(value.x, frac, ref_store.x, ref_out.x); \
94         lowpass(value.y, frac, ref_store.y, ref_out.y); \
95 MACRO_END
96
97 #define highpass2(value, frac, ref_store, ref_out) MACRO_BEGIN \
98         highpass(value.x, frac, ref_store.x, ref_out.x); \
99         highpass(value.y, frac, ref_store.y, ref_out.y); \
100 MACRO_END
101
102 #define highpass2_limited(value, frac, limit, ref_store, ref_out) MACRO_BEGIN \
103         highpass_limited(value.x, frac, limit, ref_store.x, ref_out.x); \
104         highpass_limited(value.y, frac, limit, ref_store.y, ref_out.y); \
105 MACRO_END
106
107 #define lowpass3(value, frac, ref_store, ref_out) MACRO_BEGIN \
108         lowpass(value.x, frac, ref_store.x, ref_out.x); \
109         lowpass(value.y, frac, ref_store.y, ref_out.y); \
110         lowpass(value.z, frac, ref_store.z, ref_out.z); \
111 MACRO_END
112
113 #define highpass3(value, frac, ref_store, ref_out) MACRO_BEGIN \
114         highpass(value.x, frac, ref_store.x, ref_out.x); \
115         highpass(value.y, frac, ref_store.y, ref_out.y); \
116         highpass(value.z, frac, ref_store.z, ref_out.z); \
117 MACRO_END
118
119 void calc_followmodel_ofs(entity view)
120 {
121         if(cl_followmodel_time == time)
122                 return; // cl_followmodel_ofs already calculated for this frame
123
124         float frac;
125         vector gunorg = '0 0 0';
126         static vector vel_average;
127         static vector gunorg_adjustment_highpass;
128         static vector gunorg_adjustment_lowpass;
129
130         vector vel;
131         if (autocvar_cl_followmodel_velocity_absolute)
132                 vel = view.velocity;
133         else
134         {
135                 vector forward, right, up;
136                 MAKE_VECTORS(view_angles, forward, right, up);
137                 vel.x = view.velocity * forward;
138                 vel.y = view.velocity * right * -1;
139                 vel.z = view.velocity * up;
140         }
141
142         vel.x = bound(vel_average.x - autocvar_cl_followmodel_limit, vel.x, vel_average.x + autocvar_cl_followmodel_limit);
143         vel.y = bound(vel_average.y - autocvar_cl_followmodel_limit, vel.y, vel_average.y + autocvar_cl_followmodel_limit);
144         vel.z = bound(vel_average.z - autocvar_cl_followmodel_limit, vel.z, vel_average.z + autocvar_cl_followmodel_limit);
145
146         frac = avg_factor(autocvar_cl_followmodel_velocity_lowpass);
147         lowpass3(vel, frac, vel_average, gunorg);
148
149         gunorg *= -autocvar_cl_followmodel_speed * 0.042;
150
151         // perform highpass/lowpass on the adjustment vectors (turning velocity into acceleration!)
152         // trick: we must do the lowpass LAST, so the lowpass vector IS the final vector!
153         frac = avg_factor(autocvar_cl_followmodel_highpass);
154         highpass3(gunorg, frac, gunorg_adjustment_highpass, gunorg);
155         frac = avg_factor(autocvar_cl_followmodel_lowpass);
156         lowpass3(gunorg, frac, gunorg_adjustment_lowpass, gunorg);
157
158         if (autocvar_cl_followmodel_velocity_absolute)
159         {
160                 vector fixed_gunorg;
161                 vector forward, right, up;
162                 MAKE_VECTORS(view_angles, forward, right, up);
163                 fixed_gunorg.x = gunorg * forward;
164                 fixed_gunorg.y = gunorg * right * -1;
165                 fixed_gunorg.z = gunorg * up;
166                 gunorg = fixed_gunorg;
167         }
168
169         cl_followmodel_ofs = gunorg;
170         cl_followmodel_time = time;
171 }
172
173 vector leanmodel_ofs(entity view)
174 {
175         float frac;
176         vector gunangles = '0 0 0';
177         static vector gunangles_prev = '0 0 0';
178         static vector gunangles_highpass = '0 0 0';
179         static vector gunangles_adjustment_highpass;
180         static vector gunangles_adjustment_lowpass;
181
182         if (view.csqcmodel_teleported)
183                 gunangles_prev = view_angles;
184
185         // in the highpass, we _store_ the DIFFERENCE to the actual view angles...
186         gunangles_highpass += gunangles_prev;
187         PITCH(gunangles_highpass) += 360 * floor((PITCH(view_angles) - PITCH(gunangles_highpass)) / 360 + 0.5);
188         YAW(gunangles_highpass) += 360 * floor((YAW(view_angles) - YAW(gunangles_highpass)) / 360 + 0.5);
189         ROLL(gunangles_highpass) += 360 * floor((ROLL(view_angles) - ROLL(gunangles_highpass)) / 360 + 0.5);
190         frac = avg_factor(autocvar_cl_leanmodel_highpass1);
191         highpass2_limited(view_angles, frac, autocvar_cl_leanmodel_limit, gunangles_highpass, gunangles);
192         gunangles_prev = view_angles;
193         gunangles_highpass -= gunangles_prev;
194
195         PITCH(gunangles) *= -autocvar_cl_leanmodel_speed;
196         YAW(gunangles) *= -autocvar_cl_leanmodel_speed;
197
198         // we assume here: PITCH = 0, YAW = 1, ROLL = 2
199         frac = avg_factor(autocvar_cl_leanmodel_highpass);
200         highpass2(gunangles, frac, gunangles_adjustment_highpass, gunangles);
201         frac = avg_factor(autocvar_cl_leanmodel_lowpass);
202         lowpass2(gunangles, frac, gunangles_adjustment_lowpass, gunangles);
203
204         gunangles.x = -gunangles.x; // pitch was inverted, now that actually matters
205
206         return gunangles;
207 }
208
209 vector bobmodel_ofs(entity view)
210 {
211         bool clonground = !(view.anim_implicit_state & ANIMIMPLICITSTATE_INAIR);
212         static bool oldonground;
213         static float hitgroundtime;
214         if (clonground)
215         {
216                 float f = time; // cl.movecmd[0].time
217                 if (!oldonground)
218                         hitgroundtime = f;
219         }
220         oldonground = clonground;
221
222         // calculate for swinging gun model
223         // the gun bobs when running on the ground, but doesn't bob when you're in the air.
224         vector gunorg = '0 0 0';
225         static float bobmodel_scale = 0;
226         static float time_ofs = 0; // makes the effect always restart in the same way
227         if (clonground)
228         {
229                 if (time - hitgroundtime > 0.05)
230                         bobmodel_scale = min(1, bobmodel_scale + frametime * 5);
231         }
232         else
233                 bobmodel_scale = max(0, bobmodel_scale - frametime * 5);
234
235         float xyspeed = bound(0, vlen(vec2(view.velocity)), 400);
236         if (bobmodel_scale && xyspeed)
237         {
238                 float bspeed = xyspeed * 0.01 * autocvar_cl_viewmodel_scale * bobmodel_scale;
239                 float s = (time - time_ofs) * autocvar_cl_bobmodel_speed;
240                 gunorg.y = bspeed * autocvar_cl_bobmodel_side * sin(s);
241                 gunorg.z = bspeed * autocvar_cl_bobmodel_up * cos(s * 2);
242         }
243         else
244                 time_ofs = time;
245
246         return gunorg;
247 }
248
249 void viewmodel_animate(entity this)
250 {
251         if (autocvar_chase_active) return;
252         if (STAT(HEALTH) <= 0) return;
253
254         entity view = CSQCModel_server2csqc(player_localentnum - 1);
255
256         if (autocvar_cl_followmodel)
257         {
258                 calc_followmodel_ofs(view);
259                 this.origin += cl_followmodel_ofs;
260         }
261
262         if (autocvar_cl_leanmodel)
263                 this.angles += leanmodel_ofs(view);
264
265         // vertical view bobbing code
266         // TODO: cl_bob
267
268         // horizontal view bobbing code
269         // TODO: cl_bob2
270
271         // fall bobbing code
272         // causes the view to swing down and back up when touching the ground
273         // TODO: cl_bobfall
274
275         // gun model bobbing code
276         if (autocvar_cl_bobmodel)
277                 this.origin += bobmodel_ofs(view);
278 }
279
280 .vector viewmodel_origin, viewmodel_angles;
281 .float weapon_nextthink;
282 .float weapon_eta_last;
283 .float weapon_switchdelay;
284
285 .string name_last;
286
287 void viewmodel_draw(entity this)
288 {
289         if(!this.activeweapon || !autocvar_r_drawviewmodel)
290                 return;
291         int mask = (intermission || (STAT(HEALTH) <= 0) || autocvar_chase_active) ? 0 : MASK_NORMAL;
292         float a = ((autocvar_cl_viewmodel_alpha) ? bound(-1, autocvar_cl_viewmodel_alpha, this.m_alpha) : this.m_alpha);
293         int wepskin = this.m_skin;
294         bool invehicle = player_localentnum > maxclients;
295         if (invehicle) a = -1;
296         Weapon wep = this.activeweapon;
297         int c = entcs_GetClientColors(current_player);
298         vector g = weaponentity_glowmod(wep, NULL, c, this);
299         entity me = CSQCModel_server2csqc(player_localentnum - 1);
300         int fx = ((me.csqcmodel_effects & EFMASK_CHEAP)
301                 | EF_NODEPTHTEST)
302                 &~ (EF_FULLBRIGHT); // can mask team color, so get rid of it
303         for (entity e = this; e; e = e.weaponchild)
304         {
305                 e.drawmask = mask;
306                 e.alpha = a;
307                 e.skin = wepskin;
308                 e.colormap = 256 + c;  // colormap == 0 is black, c == 0 is white
309                 e.glowmod = g;
310                 e.csqcmodel_effects = fx;
311                 CSQCModel_Effects_Apply(e);
312         }
313         if(a >= 0)
314         {
315                 string name = wep.mdl;
316                 string newname = wep.wr_viewmodel(wep, this);
317                 if(newname)
318                         name = newname;
319                 bool swap = name != this.name_last;
320                 // if (swap)
321                 {
322                         this.name_last = name;
323                         CL_WeaponEntity_SetModel(this, name, swap);
324                         this.viewmodel_origin = this.origin;
325                         this.viewmodel_angles = this.angles;
326                 }
327                 anim_update(this);
328                 if ((!this.animstate_override && !this.animstate_looping) || time > this.animstate_endtime)
329                         anim_set(this, this.anim_idle, true, false, false);
330         }
331         float f = 0; // 0..1; 0: fully active
332         float rate = STAT(WEAPONRATEFACTOR);
333         float eta = rate ? ((this.weapon_nextthink - time) / rate) : 0;
334         if (eta <= 0) f = this.weapon_eta_last;
335         else switch (this.state)
336         {
337                 case WS_RAISE:
338                 {
339                         f = eta / max(eta, this.weapon_switchdelay);
340                         break;
341                 }
342                 case WS_DROP:
343                 {
344                         f = 1 - eta / max(eta, this.weapon_switchdelay);
345                         break;
346                 }
347                 case WS_CLEAR:
348                 {
349                         f = 1;
350                         break;
351                 }
352         }
353         this.weapon_eta_last = f;
354         this.origin = this.viewmodel_origin;
355         this.angles = this.viewmodel_angles;
356         this.angles_x = (-90 * f * f);
357         viewmodel_animate(this);
358         MUTATOR_CALLHOOK(DrawViewModel, this);
359         setorigin(this, this.origin);
360 }
361
362 STATIC_INIT(viewmodel) {
363     for(int slot = 0; slot < MAX_WEAPONSLOTS; ++slot)
364         viewmodels[slot] = new(viewmodel);
365 }
366
367 float showfps_prevfps;
368 float showfps_prevfps_time;
369 int showfps_framecounter;
370
371 void fpscounter_update()
372 {
373         if(!STAT(SHOWFPS))
374                 return;
375
376         float currentTime = gettime(GETTIME_REALTIME);
377         showfps_framecounter += 1;
378         if(currentTime - showfps_prevfps_time > STAT(SHOWFPS))
379         {
380                 showfps_prevfps = showfps_framecounter/(currentTime - showfps_prevfps_time);
381                 showfps_framecounter = 0;
382                 showfps_prevfps_time = currentTime;
383
384                 int channel = MSG_C2S;
385                 WriteHeader(channel, fpsreport);
386                 WriteShort(channel, bound(0, rint(showfps_prevfps), 65535)); // prevent insane fps values
387         }
388 }
389
390 STATIC_INIT(fpscounter_init)
391 {
392         float currentTime = gettime(GETTIME_REALTIME);
393         showfps_prevfps_time = currentTime; // we must initialize it to avoid an instant low frame sending
394 }
395
396 float avgspeed;
397 vector GetCurrentFov(float fov)
398 {
399         float zoomsensitivity, zoomspeed, zoomfactor, zoomdir;
400         float velocityzoom, curspeed;
401         vector v;
402
403         zoomsensitivity = autocvar_cl_zoomsensitivity;
404         zoomfactor = autocvar_cl_zoomfactor;
405         if(zoomfactor < 1 || zoomfactor > 30)
406                 zoomfactor = 2.5;
407         zoomspeed = autocvar_cl_zoomspeed;
408         if (zoomspeed >= 0 && (zoomspeed < 0.5 || zoomspeed > 16))
409                 zoomspeed = 3.5;
410
411         zoomdir = button_zoom;
412
413         if(hud == HUD_NORMAL && !spectatee_status)
414         {
415                 for(int slot = 0; slot < MAX_WEAPONSLOTS; ++slot)
416                 {
417                         entity wepent = viewmodels[slot];
418                         if(wepent.switchweapon != wepent.activeweapon)
419                                 continue;
420                         Weapon wep = wepent.activeweapon;
421                         if(wep != WEP_Null && wep.wr_zoomdir)
422                         {
423                                 bool do_zoom = wep.wr_zoomdir(wep); // TODO: merge this with wr_zoom?
424                                 zoomdir += do_zoom;
425                         }
426                 }
427         }
428         if(spectatee_status > 0 || isdemo())
429         {
430                 if(spectatorbutton_zoom)
431                 {
432                         if(zoomdir)
433                                 zoomdir = 0;
434                         else
435                                 zoomdir = 1;
436                 }
437                 // fteqcc failed twice here already, don't optimize this
438         }
439
440         if(zoomdir) { zoomin_effect = 0; }
441
442         if (spectatee_status > 0 && STAT(CAMERA_SPECTATOR) == 2)
443         {
444                 current_viewzoom = 1;
445         }
446         else if (camera_active)
447         {
448                 current_viewzoom = min(1, current_viewzoom + drawframetime);
449         }
450         else if(autocvar_cl_spawnzoom && zoomin_effect)
451         {
452                 float spawnzoomfactor = bound(1, autocvar_cl_spawnzoom_factor, 30);
453
454                 current_viewzoom += (autocvar_cl_spawnzoom_speed * (spawnzoomfactor - current_viewzoom) * drawframetime);
455                 current_viewzoom = bound(1 / spawnzoomfactor, current_viewzoom, 1);
456                 if(current_viewzoom == 1) { zoomin_effect = 0; }
457         }
458         else
459         {
460                 if(zoomspeed < 0) // instant zoom
461                 {
462                         if(zoomdir)
463                                 current_viewzoom = 1 / zoomfactor;
464                         else
465                                 current_viewzoom = 1;
466                 }
467                 else
468                 {
469                         if(zoomdir)
470                                 current_viewzoom = 1 / bound(1, 1 / current_viewzoom + drawframetime * zoomspeed * (zoomfactor - 1), zoomfactor);
471                         else
472                                 current_viewzoom = bound(1 / zoomfactor, current_viewzoom + drawframetime * zoomspeed * (1 - 1 / zoomfactor), 1);
473                 }
474         }
475
476         if(almost_equals(current_viewzoom, 1))
477                 current_zoomfraction = 0;
478         else if(almost_equals(current_viewzoom, 1/zoomfactor))
479                 current_zoomfraction = 1;
480         else
481                 current_zoomfraction = (current_viewzoom - 1) / (1/zoomfactor - 1);
482
483         if(zoomsensitivity < 1)
484                 setsensitivityscale(current_viewzoom ** (1 - zoomsensitivity));
485         else
486                 setsensitivityscale(1);
487
488         if(autocvar_cl_velocityzoom_enabled && autocvar_cl_velocityzoom_type && !autocvar_cl_lockview) // _type = 0 disables velocity zoom too
489         {
490                 if (intermission || (spectatee_status > 0 && STAT(CAMERA_SPECTATOR) == 2))
491                         curspeed = 0;
492                 else
493                 {
494                         vector forward, right, up;
495                         MAKE_VECTORS(view_angles, forward, right, up);
496                         v = pmove_vel;
497                         if(csqcplayer)
498                                 v = csqcplayer.velocity;
499
500                         switch(autocvar_cl_velocityzoom_type)
501                         {
502                                 case 3: curspeed = max(0, forward * v); break;
503                                 case 2: curspeed = (forward * v); break;
504                                 case 1: default: curspeed = vlen(v); break;
505                         }
506                 }
507
508                 velocityzoom = bound(0, drawframetime / max(0.000000001, autocvar_cl_velocityzoom_time), 1); // speed at which the zoom adapts to player velocity
509                 avgspeed = avgspeed * (1 - velocityzoom) + (curspeed / autocvar_cl_velocityzoom_speed) * velocityzoom;
510                 velocityzoom = exp(float2range11(avgspeed * -autocvar_cl_velocityzoom_factor / 1) * 1);
511
512                 //print(ftos(avgspeed), " avgspeed, ", ftos(curspeed), " curspeed, ", ftos(velocityzoom), " return\n"); // for debugging
513         }
514         else
515                 velocityzoom = 1;
516
517         float frustumx, frustumy, fovx, fovy;
518         frustumy = tan(fov * M_PI / 360.0) * 0.75 * current_viewzoom * velocityzoom;
519         frustumx = frustumy * vid_width / vid_height / vid_pixelheight;
520         fovx = atan2(frustumx, 1) / M_PI * 360.0;
521         fovy = atan2(frustumy, 1) / M_PI * 360.0;
522
523         return '1 0 0' * fovx + '0 1 0' * fovy;
524 }
525
526 vector GetViewLocationFOV(float fov)
527 {
528         float frustumy = tan(fov * M_PI / 360.0) * 0.75;
529         float frustumx = frustumy * vid_width / vid_height / vid_pixelheight;
530         float fovx = atan2(frustumx, 1) / M_PI * 360.0;
531         float fovy = atan2(frustumy, 1) / M_PI * 360.0;
532         return '1 0 0' * fovx + '0 1 0' * fovy;
533 }
534
535 vector GetOrthoviewFOV(vector ov_worldmin, vector ov_worldmax, vector ov_mid, vector ov_org)
536 {
537         float fovx, fovy;
538         float width = (ov_worldmax.x - ov_worldmin.x);
539         float height = (ov_worldmax.y - ov_worldmin.y);
540         float distance_to_middle_of_world = vlen(ov_mid - ov_org);
541         fovx = atan2(width/2, distance_to_middle_of_world) / M_PI * 360.0;
542         fovy = atan2(height/2, distance_to_middle_of_world) / M_PI * 360.0;
543         return '1 0 0' * fovx + '0 1 0' * fovy;
544 }
545
546 // this function must match W_SetupShot!
547
548 bool minigame_wasactive;
549
550 float camera_mode;
551 const float CAMERA_FREE = 1;
552 const float CAMERA_CHASE = 2;
553 string NextFrameCommand;
554
555 vector freeze_org, freeze_ang;
556 entity nightvision_noise, nightvision_noise2;
557
558 float myhealth, myhealth_prev;
559 float myhealth_flash;
560
561 float old_blurradius, old_bluralpha;
562 float old_sharpen_intensity;
563
564 vector myhealth_gentlergb;
565
566 float contentavgalpha, liquidalpha_prev;
567 vector liquidcolor_prev;
568
569 float eventchase_current_distance;
570 float eventchase_running;
571 int WantEventchase(entity this, bool want_vehiclechase)
572 {
573         if(autocvar_cl_orthoview)
574                 return 0;
575         if(STAT(GAME_STOPPED) || intermission)
576                 return 1;
577         if(this.viewloc)
578                 return 1;
579         if(spectatee_status >= 0)
580         {
581                 if(want_vehiclechase)
582                         return 1;
583                 if(MUTATOR_CALLHOOK(WantEventchase, this))
584                         return 1;
585                 if(autocvar_cl_eventchase_frozen && STAT(FROZEN))
586                         return 1;
587                 if(autocvar_cl_eventchase_death && (STAT(HEALTH) <= 0))
588                 {
589                         if(autocvar_cl_eventchase_death == 2)
590                         {
591                                 // don't stop eventchase once it's started (even if velocity changes afterwards)
592                                 if(this.velocity == '0 0 0' || eventchase_running)
593                                         return 1;
594                         }
595                         else return 1;
596                 }
597                 if (spectatee_status > 0 && autocvar_cl_eventchase_spectated_change)
598                 {
599                         if (time <= spectatee_status_changed_time + min(3, autocvar_cl_eventchase_spectated_change_time))
600                                 return 1;
601                         else if (eventchase_running)
602                                 return -1; // disable chase_active while eventchase is still enabled so to avoid a glicth
603                 }
604         }
605         return 0;
606 }
607
608 void View_EventChase(entity this)
609 {
610         // event chase camera
611         if(autocvar_chase_active <= 0) // greater than 0 means it's enabled manually, and this code is skipped
612         {
613                 if(STAT(CAMERA_SPECTATOR))
614                 {
615                         if(spectatee_status > 0)
616                         {
617                                 if(!autocvar_chase_active)
618                                 {
619                                         cvar_set("chase_active", "-2");
620                                         return;
621                                 }
622                         }
623                         else if(autocvar_chase_active == -2)
624                                 cvar_set("chase_active", "0");
625
626                         if(autocvar_chase_active == -2)
627                                 return;
628                 }
629                 else if(autocvar_chase_active == -2)
630                         cvar_set("chase_active", "0");
631
632                 bool vehicle_chase = (hud != HUD_NORMAL && (autocvar_cl_eventchase_vehicle || spectatee_status > 0));
633
634                 float vehicle_viewdist = 0;
635                 vector vehicle_viewofs = '0 0 0';
636
637                 if(vehicle_chase)
638                 {
639                         if(hud != HUD_BUMBLEBEE_GUN)
640                         {
641                                 Vehicle info = REGISTRY_GET(Vehicles, hud);
642                                 vehicle_viewdist = info.height;
643                                 vehicle_viewofs = info.view_ofs;
644                                 if(vehicle_viewdist < 0) // when set below 0, this vehicle doesn't use third person view (gunner slots)
645                                         vehicle_chase = false;
646                         }
647                         else
648                                 vehicle_chase = false;
649                 }
650
651                 int eventchase = WantEventchase(this, vehicle_chase);
652                 if (eventchase)
653                 {
654                         vector current_view_origin_override = '0 0 0';
655                         vector view_offset_override = '0 0 0';
656                         float chase_distance_override = 0;
657                         bool custom_eventchase = MUTATOR_CALLHOOK(CustomizeEventchase, this);
658                         if(custom_eventchase)
659                         {
660                                 current_view_origin_override = M_ARGV(0, vector);
661                                 view_offset_override = M_ARGV(1, vector);
662                                 chase_distance_override = M_ARGV(0, float);
663                         }
664                         eventchase_running = true;
665
666                         // make special vector since we can't use view_origin (It is one frame old as of this code, it gets set later with the results this code makes.)
667                         vector current_view_origin = (csqcplayer ? csqcplayer.origin : pmove_org);
668                         if (custom_eventchase)
669                                 current_view_origin = current_view_origin_override;
670
671                         // detect maximum viewoffset and use it
672                         vector view_offset = autocvar_cl_eventchase_viewoffset;
673                         if(vehicle_chase)
674                         {
675                                 if(vehicle_viewofs)
676                                         view_offset = vehicle_viewofs;
677                                 else
678                                         view_offset = autocvar_cl_eventchase_vehicle_viewoffset;
679                         }
680                         if (custom_eventchase)
681                                 view_offset = view_offset_override;
682
683                         if(view_offset)
684                         {
685                                 WarpZone_TraceLine(current_view_origin, current_view_origin + view_offset + ('0 0 1' * autocvar_cl_eventchase_maxs.z), MOVE_WORLDONLY, this);
686                                 if(trace_fraction == 1) { current_view_origin += view_offset; }
687                                 else { current_view_origin.z += max(0, (trace_endpos.z - current_view_origin.z) - autocvar_cl_eventchase_maxs.z); }
688                         }
689
690                         // We must enable chase_active to get a third person view (weapon viewmodel hidden and own player model showing).
691                         // Ideally, there should be another way to enable third person cameras, such as through setproperty()
692                         // -1 enables chase_active while marking it as set by this code, and not by the user (which would be 1)
693                         if(!autocvar_chase_active) { cvar_set("chase_active", "-1"); }
694
695                         // make the camera smooth back
696                         float chase_distance = autocvar_cl_eventchase_distance;
697                         if(vehicle_chase)
698                         {
699                                 if(vehicle_viewofs)
700                                         chase_distance = vehicle_viewdist;
701                                 else
702                                         chase_distance = autocvar_cl_eventchase_vehicle_distance;
703                         }
704                         if (custom_eventchase)
705                                 chase_distance = chase_distance_override;
706
707                         if(autocvar_cl_eventchase_speed && eventchase_current_distance < chase_distance)
708                                 eventchase_current_distance += autocvar_cl_eventchase_speed * (chase_distance - eventchase_current_distance) * frametime; // slow down the further we get
709                         else if(eventchase_current_distance != chase_distance)
710                                 eventchase_current_distance = chase_distance;
711
712                         vector forward, right, up;
713                         MAKE_VECTORS(view_angles, forward, right, up);
714
715                         vector eventchase_target_origin = (current_view_origin - (forward * eventchase_current_distance));
716                         WarpZone_TraceBox(current_view_origin, autocvar_cl_eventchase_mins, autocvar_cl_eventchase_maxs, eventchase_target_origin, MOVE_WORLDONLY, this);
717
718                         // If the boxtrace fails, revert back to line tracing.
719                         if(!this.viewloc)
720                         if(trace_startsolid)
721                         {
722                                 eventchase_target_origin = (current_view_origin - (forward * eventchase_current_distance));
723                                 WarpZone_TraceLine(current_view_origin, eventchase_target_origin, MOVE_WORLDONLY, this);
724                                 setproperty(VF_ORIGIN, (trace_endpos - (forward * autocvar_cl_eventchase_mins.z)));
725                         }
726                         else { setproperty(VF_ORIGIN, trace_endpos); }
727
728                         if(!this.viewloc)
729                                 setproperty(VF_ANGLES, WarpZone_TransformVAngles(WarpZone_trace_transform, view_angles));
730                 }
731
732                 if (eventchase <= 0 && autocvar_chase_active < 0) // time to disable chase_active if it was set by this code
733                 {
734                         eventchase_running = false;
735                         cvar_set("chase_active", "0");
736                         eventchase_current_distance = 0; // start from 0 next time
737                 }
738         }
739         // workaround for camera stuck between player's legs when using chase_active 1
740         // because the engine stops updating the chase_active camera when the game ends
741         else if(intermission)
742         {
743                 cvar_settemp("chase_active", "-1");
744                 eventchase_current_distance = 0;
745         }
746 }
747
748 vector damage_blurpostprocess, content_blurpostprocess;
749
750 void UpdateDamage()
751 {
752         // accumulate damage with each stat update
753         static float damage_total_prev = 0;
754         float damage_total = STAT(DAMAGE_DEALT_TOTAL);
755         float unaccounted_damage_new = COMPARE_INCREASING(damage_total, damage_total_prev);
756         damage_total_prev = damage_total;
757
758         static float damage_dealt_time_prev = 0;
759         float damage_dealt_time = STAT(HIT_TIME);
760         if (damage_dealt_time != damage_dealt_time_prev)
761         {
762                 unaccounted_damage += unaccounted_damage_new;
763                 //LOG_TRACE("dmg total: ", ftos(unaccounted_damage), " (+", ftos(unaccounted_damage_new), ")");
764         }
765         damage_dealt_time_prev = damage_dealt_time;
766
767         // prevent hitsound when switching spectatee
768         static float spectatee_status_prev = 0;
769         if (spectatee_status != spectatee_status_prev)
770                 unaccounted_damage = 0;
771         spectatee_status_prev = spectatee_status;
772 }
773
774 void HitSound()
775 {
776         // varying sound pitch
777
778         bool have_arc = false;
779         for(int slot = 0; slot < MAX_WEAPONSLOTS; ++slot)
780         {
781                 entity wepent = viewmodels[slot];
782
783                 if(wepent.activeweapon == WEP_ARC)
784                         have_arc = true;
785         }
786
787         static float hitsound_time_prev = 0;
788         // HACK: the only way to get the arc to sound consistent with pitch shift is to ignore cl_hitsound_antispam_time
789         bool arc_hack = have_arc && autocvar_cl_hitsound >= 2;
790         if (arc_hack || COMPARE_INCREASING(time, hitsound_time_prev) > autocvar_cl_hitsound_antispam_time)
791         {
792                 if (autocvar_cl_hitsound && unaccounted_damage)
793                 {
794                         // customizable gradient function that crosses (0,a), (c,1) and asymptotically approaches b
795                         float a = autocvar_cl_hitsound_max_pitch;
796                         float b = autocvar_cl_hitsound_min_pitch;
797                         float c = autocvar_cl_hitsound_nom_damage;
798                         float d = unaccounted_damage;
799                         float pitch_shift = (b*d*(a-1) + a*c*(1-b)) / (d*(a-1) + c*(1-b));
800
801                         // if sound variation is disabled, set pitch_shift to 1
802                         if (autocvar_cl_hitsound == 1)
803                                 pitch_shift = 1;
804
805                         // if pitch shift is reversed, mirror in (max-min)/2 + min
806                         if (autocvar_cl_hitsound == 3)
807                         {
808                                 float mirror_value = (a-b)/2 + b;
809                                 pitch_shift = mirror_value + (mirror_value - pitch_shift);
810                         }
811
812                         //LOG_TRACE("dmg total (dmg): ", ftos(unaccounted_damage), " , pitch shift: ", ftos(pitch_shift));
813
814                         // todo: avoid very long and very short sounds from wave stretching using different sound files? seems unnecessary
815                         // todo: normalize sound pressure levels? seems unnecessary
816
817                         sound7(NULL, CH_INFO, SND(HIT), VOL_BASE, ATTN_NONE, pitch_shift * 100, 0);
818                 }
819                 unaccounted_damage = 0;
820                 hitsound_time_prev = time;
821         }
822
823         static float typehit_time_prev = 0;
824         float typehit_time = STAT(TYPEHIT_TIME);
825         if (COMPARE_INCREASING(typehit_time, typehit_time_prev) > autocvar_cl_hitsound_antispam_time)
826         {
827                 sound(NULL, CH_INFO, SND_TYPEHIT, VOL_BASE, ATTN_NONE);
828                 typehit_time_prev = typehit_time;
829         }
830
831         static float kill_time_prev = 0;
832         float kill_time = STAT(KILL_TIME);
833         if (COMPARE_INCREASING(kill_time, kill_time_prev) > autocvar_cl_hitsound_antispam_time)
834         {
835                 sound(NULL, CH_INFO, SND_KILL, VOL_BASE, ATTN_NONE);
836                 kill_time_prev = kill_time;
837         }
838 }
839
840 const int MAX_SPECIALCOMMAND = 15;
841 vector specialcommand_slots[MAX_SPECIALCOMMAND];
842 vector specialcommand_colors[MAX_SPECIALCOMMAND];
843 const float SPECIALCOMMAND_SPEED = 150;
844 const float SPECIALCOMMAND_TURNSPEED = 2;
845 const float SPECIALCOMMAND_SIZE = 0.025;
846 const float SPECIALCOMMAND_CHANCE = 0.35;
847 float sc_spawntime, sc_changetime;
848 vector sc_color = '1 1 1';
849 void SpecialCommand()
850 {
851         if(!STAT(MOVEVARS_SPECIALCOMMAND))
852                 return;
853
854         if(time >= sc_changetime)
855         {
856                 sc_changetime = time + 1;
857                 sc_color = randomvec() * 1.5;
858                 sc_color.x = bound(0.2, sc_color.x, 0.75);
859                 sc_color.y = bound(0.2, sc_color.y, 0.75);
860                 sc_color.z = bound(0.2, sc_color.z, 0.75);
861         }
862         drawfill('0 0 0', vec2(vid_conwidth, vid_conheight), sc_color, autocvar_hud_colorflash_alpha * bound(0.1, sc_changetime - time, 0.3), DRAWFLAG_ADDITIVE);
863
864         if(!precache_pic("gfx/smile"))
865                 return; // damn party poopers
866
867         for(int j = MAX_SPECIALCOMMAND - 1; j >= 0; --j)
868         {
869                 vector slot = specialcommand_slots[j];
870                 if(slot.y)
871                         slot.y += SPECIALCOMMAND_SPEED * frametime;
872                 //if(slot.z)
873                         //slot.z = sin(SPECIALCOMMAND_TURNSPEED * M_PI * time);
874                 if(slot.y >= vid_conheight)
875                         slot = '0 0 0';
876
877                 if(slot == '0 0 0')
878                 {
879                         if(random() <= SPECIALCOMMAND_CHANCE && time > sc_spawntime) // low chance to spawn!
880                         {
881                                 slot.x = bound(0, (random() * vid_conwidth + 1), vid_conwidth);
882                                 slot.y = 1; // start it off 0 so we can use it
883                                 slot.z = floor(random() * REGISTRY_MAX(Weapons));
884                                 sc_spawntime = time + bound(0.4, random(), 0.75); // prevent spawning another one for this amount of time!
885                                 vector newcolor = randomvec() * 2;
886                                 newcolor.x = bound(0.4, newcolor.x, 1);
887                                 newcolor.y = bound(0.4, newcolor.y, 1);
888                                 newcolor.z = bound(0.4, newcolor.z, 1);
889                                 specialcommand_colors[j] = newcolor;
890                         }
891                 }
892                 else
893                 {
894                         vector splash_size = '0 0 0';
895                         splash_size.x = max(vid_conwidth, vid_conheight) * SPECIALCOMMAND_SIZE;
896                         splash_size.y = max(vid_conwidth, vid_conheight) * SPECIALCOMMAND_SIZE;
897                         entity wep = REGISTRY_GET(Weapons, slot.z);
898                         if(wep == WEP_Null)
899                                 drawpic(vec2(slot), "gfx/smile", vec2(splash_size), specialcommand_colors[j], 0.95, DRAWFLAG_NORMAL);
900                         else
901                                 drawpic_skin(vec2(slot), wep.model2, vec2(splash_size), specialcommand_colors[j], 0.95, DRAWFLAG_NORMAL);
902                         //drawrotpic(vec2(slot), slot.z, "gfx/smile", vec2(splash_size), vec2(splash_size) / 2, specialcommand_colors[j], 0.95, DRAWFLAG_NORMAL);
903                 }
904
905                 specialcommand_slots[j] = slot;
906         }
907 }
908
909 void HUD_Draw(entity this)
910 {
911         // if we don't know gametype and scores yet avoid drawing the scoreboard
912         // also in the very first frames, player state may be inconsistent so avoid drawing the hud at all
913         // e.g. since initial player's health is 0 hud would display the hud_damage effect,
914         // cl_deathscoreboard would show the scoreboard and so on
915         if(!gametype)
916                 return;
917
918         Hud_Dynamic_Frame();
919
920         if(!intermission)
921         if (MUTATOR_CALLHOOK(HUD_Draw_overlay))
922         {
923                 drawfill('0 0 0', vec2(vid_conwidth, vid_conheight), M_ARGV(0, vector), autocvar_hud_colorflash_alpha * M_ARGV(1, float), DRAWFLAG_ADDITIVE);
924         }
925         else if(STAT(FROZEN))
926         {
927                 vector col = '0.25 0.90 1';
928                 if(STAT(REVIVE_PROGRESS))
929                         col += vec3(STAT(REVIVE_PROGRESS), -STAT(REVIVE_PROGRESS), -STAT(REVIVE_PROGRESS));
930                 drawfill('0 0 0', vec2(vid_conwidth, vid_conheight), col, autocvar_hud_colorflash_alpha, DRAWFLAG_ADDITIVE);
931         }
932
933         HUD_Scale_Enable();
934         if(!intermission)
935         if(STAT(NADE_TIMER) && autocvar_cl_nade_timer) // give nade top priority, as it's a matter of life and death
936         {
937                 vector col = '0.25 0.90 1' + vec3(STAT(NADE_TIMER), -STAT(NADE_TIMER), -STAT(NADE_TIMER));
938                 DrawCircleClippedPic(vec2(0.5 * vid_conwidth, 0.6 * vid_conheight), 0.1 * vid_conheight, "gfx/crosshair_ring.tga", STAT(NADE_TIMER), col, autocvar_hud_colorflash_alpha, DRAWFLAG_ADDITIVE);
939                 drawstring_aspect(eY * 0.64 * vid_conheight, ((autocvar_cl_nade_timer == 2) ? _("Nade timer") : ""), vec2(vid_conwidth, 0.025 * vid_conheight), '1 1 1', 1, DRAWFLAG_NORMAL);
940         }
941         else if(STAT(CAPTURE_PROGRESS))
942         {
943                 DrawCircleClippedPic(vec2(0.5 * vid_conwidth, 0.6 * vid_conheight), 0.1 * vid_conheight, "gfx/crosshair_ring.tga", STAT(CAPTURE_PROGRESS), '0.25 0.90 1', autocvar_hud_colorflash_alpha, DRAWFLAG_ADDITIVE);
944                 drawstring_aspect(eY * 0.64 * vid_conheight, _("Capture progress"), vec2(vid_conwidth, 0.025 * vid_conheight), '1 1 1', 1, DRAWFLAG_NORMAL);
945         }
946         else if(STAT(REVIVE_PROGRESS))
947         {
948                 DrawCircleClippedPic(vec2(0.5 * vid_conwidth, 0.6 * vid_conheight), 0.1 * vid_conheight, "gfx/crosshair_ring.tga", STAT(REVIVE_PROGRESS), '0.25 0.90 1', autocvar_hud_colorflash_alpha, DRAWFLAG_ADDITIVE);
949                 drawstring_aspect(eY * 0.64 * vid_conheight, _("Revival progress"), vec2(vid_conwidth, 0.025 * vid_conheight), '1 1 1', 1, DRAWFLAG_NORMAL);
950         }
951         HUD_Scale_Disable();
952
953         if(autocvar_r_letterbox == 0)
954                 if(autocvar_viewsize < 120)
955                 {
956                         if(!MUTATOR_CALLHOOK(DrawScoreboardAccuracy))
957                                 Accuracy_LoadLevels();
958
959                         HUD_Main();
960                         HUD_Scale_Disable();
961                 }
962
963         // crosshair goes VERY LAST
964         SpecialCommand();
965         UpdateDamage();
966         HUD_Crosshair(this);
967         HitSound();
968 }
969
970 void ViewLocation_Mouse()
971 {
972         if(spectatee_status)
973                 return; // don't draw it as spectator!
974
975         viewloc_mousepos += getmousepos() * autocvar_menu_mouse_speed;
976         viewloc_mousepos.x = bound(0, viewloc_mousepos.x, vid_conwidth);
977         viewloc_mousepos.y = bound(0, viewloc_mousepos.y, vid_conheight);
978
979         //float cursor_alpha = 1 - autocvar__menu_alpha;
980         //cursor_type = CURSOR_NORMAL;
981         //draw_cursor(viewloc_mousepos, '0.5 0.5 0', "/cursor_move", '1 1 1', cursor_alpha);
982 }
983
984 void HUD_Cursor_Show()
985 {
986         float cursor_alpha = 1 - autocvar__menu_alpha;
987         if(cursor_type == CURSOR_NORMAL)
988                 draw_cursor_normal(mousepos, '1 1 1', cursor_alpha);
989         else if(cursor_type == CURSOR_MOVE)
990                 draw_cursor(mousepos, '0.5 0.5 0', "/cursor_move", '1 1 1', cursor_alpha);
991         else if(cursor_type == CURSOR_RESIZE)
992                 draw_cursor(mousepos, '0.5 0.5 0', "/cursor_resize", '1 1 1', cursor_alpha);
993         else if(cursor_type == CURSOR_RESIZE2)
994                 draw_cursor(mousepos, '0.5 0.5 0', "/cursor_resize2", '1 1 1', cursor_alpha);
995 }
996
997 void HUD_Mouse(entity player)
998 {
999         if(autocvar__menu_alpha == 1)
1000                 return;
1001
1002         if(!cursor_active)
1003         {
1004                 if(player.viewloc && (player.viewloc.spawnflags & VIEWLOC_FREEAIM))
1005                         ViewLocation_Mouse(); // NOTE: doesn't use cursormode
1006                 return;
1007         }
1008
1009         if (cursor_active == -1) // starting to display the cursor
1010         {
1011                 // since HUD_Mouse is called by CSQC_UpdateView before CSQC_InputEvent,
1012                 // in the first frame mousepos is the mouse position of the last time
1013                 // the cursor was displayed, thus we ignore it to avoid a glictch
1014                 cursor_active = 1;
1015                 return;
1016         }
1017
1018         if(!autocvar_hud_cursormode)
1019                 update_mousepos();
1020
1021         cursor_type = CURSOR_NORMAL;
1022         if(autocvar__hud_configure)
1023                 HUD_Panel_Mouse();
1024         else
1025         {
1026                 if (HUD_MinigameMenu_IsOpened())
1027                         HUD_Minigame_Mouse();
1028                 if (QuickMenu_IsOpened())
1029                         QuickMenu_Mouse();
1030                 if (HUD_Radar_Clickable())
1031                         HUD_Radar_Mouse();
1032         }
1033
1034         prevMouseClicked = mouseClicked;
1035
1036         HUD_Cursor_Show();
1037 }
1038
1039 void View_NightVision()
1040 {
1041         if(!(autocvar_r_fakelight >= 2 || autocvar_r_fullbright) || (serverflags & SERVERFLAG_ALLOW_FULLBRIGHT))
1042                 return;
1043
1044         // apply night vision effect
1045         vector tc_00, tc_01, tc_10, tc_11;
1046         vector rgb = '0 0 0';
1047         float a;
1048
1049         if(!nightvision_noise)
1050         {
1051                 nightvision_noise = new(nightvision_noise);
1052         }
1053         if(!nightvision_noise2)
1054         {
1055                 nightvision_noise2 = new(nightvision_noise2);
1056         }
1057
1058         // color tint in yellow
1059         drawfill('0 0 0', autocvar_vid_conwidth * '1 0 0' + autocvar_vid_conheight * '0 1 0', '0.5 1 0.3', 1, DRAWFLAG_MODULATE);
1060
1061         // draw BG
1062         a = Noise_Pink(nightvision_noise, frametime * 1.5) * 0.05 + 0.15;
1063         rgb = '1 1 1';
1064         tc_00 = '0 0 0' + '0.2 0 0' * sin(time * 0.3) + '0 0.3 0' * cos(time * 0.7);
1065         tc_01 = '0 2.25 0' + '0.6 0 0' * cos(time * 1.2) - '0 0.3 0' * sin(time * 2.2);
1066         tc_10 = '1.5 0 0' - '0.2 0 0' * sin(time * 0.5) + '0 0.5 0' * cos(time * 1.7);
1067         //tc_11 = '1 1 0' + '0.6 0 0' * sin(time * 0.6) + '0 0.3 0' * cos(time * 0.1);
1068         tc_11 = tc_01 + tc_10 - tc_00;
1069         R_BeginPolygon("gfx/nightvision-bg.tga", DRAWFLAG_ADDITIVE, true);
1070         R_PolygonVertex('0 0 0', tc_00, rgb, a);
1071         R_PolygonVertex(autocvar_vid_conwidth * '1 0 0', tc_10, rgb, a);
1072         R_PolygonVertex(autocvar_vid_conwidth * '1 0 0' + autocvar_vid_conheight * '0 1 0', tc_11, rgb, a);
1073         R_PolygonVertex(autocvar_vid_conheight * '0 1 0', tc_01, rgb, a);
1074         R_EndPolygon();
1075
1076         // draw FG
1077         a = Noise_Pink(nightvision_noise2, frametime * 0.1) * 0.05 + 0.12;
1078         rgb = '0.3 0.6 0.4' + '0.1 0.4 0.2' * Noise_White(nightvision_noise2, frametime);
1079         tc_00 = '0 0 0' + '1 0 0' * Noise_White(nightvision_noise2, frametime) + '0 1 0' * Noise_White(nightvision_noise2, frametime);
1080         tc_01 = tc_00 + '0 3 0' * (1 + Noise_White(nightvision_noise2, frametime) * 0.2);
1081         tc_10 = tc_00 + '2 0 0' * (1 + Noise_White(nightvision_noise2, frametime) * 0.3);
1082         tc_11 = tc_01 + tc_10 - tc_00;
1083         R_BeginPolygon("gfx/nightvision-fg.tga", DRAWFLAG_ADDITIVE, true);
1084         R_PolygonVertex('0 0 0', tc_00, rgb, a);
1085         R_PolygonVertex(autocvar_vid_conwidth * '1 0 0', tc_10, rgb, a);
1086         R_PolygonVertex(autocvar_vid_conwidth * '1 0 0' + autocvar_vid_conheight * '0 1 0', tc_11, rgb, a);
1087         R_PolygonVertex(autocvar_vid_conheight * '0 1 0', tc_01, rgb, a);
1088         R_EndPolygon();
1089 }
1090
1091 // visual overlay while in liquids
1092 // provides some effects to the postprocessing function
1093 void HUD_Contents()
1094 {
1095         if(!autocvar_hud_contents || MUTATOR_CALLHOOK(HUD_Contents))
1096                 return;
1097
1098         // improved polyblend
1099         float contentalpha_temp, incontent, liquidalpha, contentfadetime;
1100         vector liquidcolor;
1101
1102         switch(pointcontents(view_origin))
1103         {
1104                 case CONTENT_WATER:
1105                         liquidalpha = autocvar_hud_contents_water_alpha;
1106                         liquidcolor = stov(autocvar_hud_contents_water_color);
1107                         incontent = 1;
1108                         break;
1109
1110                 case CONTENT_LAVA:
1111                         liquidalpha = autocvar_hud_contents_lava_alpha;
1112                         liquidcolor = stov(autocvar_hud_contents_lava_color);
1113                         incontent = 1;
1114                         break;
1115
1116                 case CONTENT_SLIME:
1117                         liquidalpha = autocvar_hud_contents_slime_alpha;
1118                         liquidcolor = stov(autocvar_hud_contents_slime_color);
1119                         incontent = 1;
1120                         break;
1121
1122                 default:
1123                         liquidalpha = 0;
1124                         liquidcolor = '0 0 0';
1125                         incontent = 0;
1126                         break;
1127         }
1128
1129         if(incontent) // fade in/out at different speeds so you can do e.g. instant fade when entering water and slow when leaving it.
1130         { // also lets delcare previous values for blending properties, this way it isn't reset until after you have entered a different content
1131                 contentfadetime = autocvar_hud_contents_fadeintime;
1132                 liquidalpha_prev = liquidalpha;
1133                 liquidcolor_prev = liquidcolor;
1134         }
1135         else
1136                 contentfadetime = autocvar_hud_contents_fadeouttime;
1137
1138         contentalpha_temp = bound(0, drawframetime / max(0.0001, contentfadetime), 1);
1139         contentavgalpha = contentavgalpha * (1 - contentalpha_temp) + incontent * contentalpha_temp;
1140
1141         if(contentavgalpha)
1142                 drawfill('0 0 0', vec2(vid_conwidth, vid_conheight), liquidcolor_prev, contentavgalpha * liquidalpha_prev, DRAWFLAG_NORMAL);
1143
1144         if(autocvar_hud_postprocessing)
1145         {
1146                 if(autocvar_hud_contents_blur && contentavgalpha)
1147                 {
1148                         content_blurpostprocess.x = 1;
1149                         content_blurpostprocess.y = contentavgalpha * autocvar_hud_contents_blur;
1150                         content_blurpostprocess.z = contentavgalpha * autocvar_hud_contents_blur_alpha;
1151                 }
1152                 else
1153                 {
1154                         content_blurpostprocess.x = 0;
1155                         content_blurpostprocess.y = 0;
1156                         content_blurpostprocess.z = 0;
1157                 }
1158         }
1159 }
1160
1161 // visual pain effects on the screen
1162 // provides some effects to the postprocessing function
1163 void HUD_Damage()
1164 {
1165         if(!autocvar_hud_damage || STAT(FROZEN))
1166                 return;
1167
1168         vector splash_pos = '0 0 0', splash_size = '0 0 0';
1169         splash_size.x = max(vid_conwidth, vid_conheight);
1170         splash_size.y = max(vid_conwidth, vid_conheight);
1171         splash_pos.x = (vid_conwidth - splash_size.x) / 2;
1172         splash_pos.y = (vid_conheight - splash_size.y) / 2;
1173
1174         float myhealth_flash_temp;
1175         myhealth = STAT(HEALTH);
1176
1177         // fade out
1178         myhealth_flash = max(0, myhealth_flash - autocvar_hud_damage_fade_rate * frametime);
1179         // add new damage
1180         myhealth_flash = bound(0, myhealth_flash + dmg_take * autocvar_hud_damage_factor, autocvar_hud_damage_maxalpha);
1181
1182         float pain_threshold, pain_threshold_lower, pain_threshold_lower_health;
1183         pain_threshold = autocvar_hud_damage_pain_threshold;
1184         pain_threshold_lower = autocvar_hud_damage_pain_threshold_lower;
1185         pain_threshold_lower_health = autocvar_hud_damage_pain_threshold_lower_health;
1186
1187         if(pain_threshold_lower && myhealth < pain_threshold_lower_health)
1188         {
1189                 pain_threshold = pain_threshold - max(autocvar_hud_damage_pain_threshold_pulsating_min, fabs(sin(M_PI * time / autocvar_hud_damage_pain_threshold_pulsating_period))) * pain_threshold_lower * (1 - max(0, myhealth)/pain_threshold_lower_health);
1190         }
1191
1192         myhealth_flash_temp = bound(0, myhealth_flash - pain_threshold, 1);
1193
1194         if(myhealth_prev < 1)
1195         {
1196                 if(myhealth >= 1)
1197                 {
1198                         myhealth_flash = 0; // just spawned, clear the flash immediately
1199                         myhealth_flash_temp = 0;
1200                 }
1201                 else
1202                 {
1203                         myhealth_flash += autocvar_hud_damage_fade_rate * frametime; // dead
1204                 }
1205         }
1206
1207         if(spectatee_status == -1 || intermission)
1208         {
1209                 myhealth_flash = 0; // observing, or match ended
1210                 myhealth_flash_temp = 0;
1211         }
1212
1213         myhealth_prev = myhealth;
1214
1215         // IDEA: change damage color/picture based on player model for robot/alien species?
1216         // pro: matches model better
1217         // contra: it's not red because blood is red, but because red is an alarming color, so red should stay
1218         // maybe different reddish pics?
1219         if(autocvar_cl_gentle_damage || autocvar_cl_gentle)
1220         {
1221                 if(autocvar_cl_gentle_damage == 2)
1222                 {
1223                         if(myhealth_flash < pain_threshold) // only randomize when the flash is gone
1224                                 myhealth_gentlergb = randomvec();
1225                 }
1226                 else
1227                         myhealth_gentlergb = stov(autocvar_hud_damage_gentle_color);
1228
1229                 if(myhealth_flash_temp > 0)
1230                         drawfill('0 0 0', vec2(vid_conwidth, vid_conheight), myhealth_gentlergb, autocvar_hud_damage_gentle_alpha_multiplier * bound(0, myhealth_flash_temp, 1) * autocvar_hud_damage, DRAWFLAG_NORMAL);
1231         }
1232         else if(myhealth_flash_temp > 0)
1233                 drawpic(splash_pos, "gfx/blood", splash_size, stov(autocvar_hud_damage_color), bound(0, myhealth_flash_temp, 1) * autocvar_hud_damage, DRAWFLAG_NORMAL);
1234
1235         if(autocvar_hud_postprocessing) // we still need to set this anyway even when chase_active is set, this way it doesn't get stuck on.
1236         {
1237                 if(autocvar_hud_damage_blur && myhealth_flash_temp)
1238                 {
1239                         damage_blurpostprocess.x = 1;
1240                         damage_blurpostprocess.y = bound(0, myhealth_flash_temp, 1) * autocvar_hud_damage_blur;
1241                         damage_blurpostprocess.z = bound(0, myhealth_flash_temp, 1) * autocvar_hud_damage_blur_alpha;
1242                 }
1243                 else
1244                 {
1245                         damage_blurpostprocess.x = 0;
1246                         damage_blurpostprocess.y = 0;
1247                         damage_blurpostprocess.z = 0;
1248                 }
1249         }
1250 }
1251
1252 void View_PostProcessing()
1253 {
1254         float e1 = (autocvar_hud_postprocessing_maxbluralpha != 0);
1255         float e2 = (autocvar_hud_powerup != 0);
1256         if(autocvar_hud_postprocessing && (e1 || e2)) // TODO: Remove this code and re-do the postprocess handling in the engine, where it properly belongs.
1257         {
1258                 // enable or disable rendering types if they are used or not
1259                 if(cvar("r_glsl_postprocess_uservec1_enable") != e1) { cvar_set("r_glsl_postprocess_uservec1_enable", ftos(e1)); }
1260                 if(cvar("r_glsl_postprocess_uservec2_enable") != e2) { cvar_set("r_glsl_postprocess_uservec2_enable", ftos(e2)); }
1261
1262                 // blur postprocess handling done first (used by hud_damage and hud_contents)
1263                 if((damage_blurpostprocess.x || content_blurpostprocess.x))
1264                 {
1265                         float blurradius = bound(0, damage_blurpostprocess.y + content_blurpostprocess.y, autocvar_hud_postprocessing_maxblurradius);
1266                         float bluralpha = bound(0, damage_blurpostprocess.z + content_blurpostprocess.z, autocvar_hud_postprocessing_maxbluralpha);
1267                         if(blurradius != old_blurradius || bluralpha != old_bluralpha) // reduce cvar_set spam as much as possible
1268                         {
1269                                 cvar_set("r_glsl_postprocess_uservec1", strcat(ftos(blurradius), " ", ftos(bluralpha), " 0 0"));
1270                                 old_blurradius = blurradius;
1271                                 old_bluralpha = bluralpha;
1272                         }
1273                 }
1274                 else if(cvar_string("r_glsl_postprocess_uservec1") != "0 0 0 0") // reduce cvar_set spam as much as possible
1275                 {
1276                         cvar_set("r_glsl_postprocess_uservec1", "0 0 0 0");
1277                         old_blurradius = 0;
1278                         old_bluralpha = 0;
1279                 }
1280
1281                 // edge detection postprocess handling done second (used by hud_powerup)
1282                 float sharpen_intensity = 0, strength_finished = STAT(STRENGTH_FINISHED), invincible_finished = STAT(INVINCIBLE_FINISHED);
1283                 if (strength_finished - time > 0) { sharpen_intensity += (strength_finished - time); }
1284                 if (invincible_finished - time > 0) { sharpen_intensity += (invincible_finished - time); }
1285
1286                 sharpen_intensity = bound(0, ((STAT(HEALTH) > 0) ? sharpen_intensity : 0), 5); // Check to see if player is alive (if not, set 0) - also bound to fade out starting at 5 seconds.
1287
1288                 if(autocvar_hud_powerup && sharpen_intensity > 0)
1289                 {
1290                         if(sharpen_intensity != old_sharpen_intensity) // reduce cvar_set spam as much as possible
1291                         {
1292                                 cvar_set("r_glsl_postprocess_uservec2", strcat(ftos((sharpen_intensity / 5) * autocvar_hud_powerup), " ", ftos(-sharpen_intensity * autocvar_hud_powerup), " 0 0"));
1293                                 old_sharpen_intensity = sharpen_intensity;
1294                         }
1295                 }
1296                 else if(cvar_string("r_glsl_postprocess_uservec2") != "0 0 0 0") // reduce cvar_set spam as much as possible
1297                 {
1298                         cvar_set("r_glsl_postprocess_uservec2", "0 0 0 0");
1299                         old_sharpen_intensity = 0;
1300                 }
1301
1302                 if(cvar("r_glsl_postprocess") == 0)
1303                         cvar_set("r_glsl_postprocess", "2");
1304         }
1305         else if(cvar("r_glsl_postprocess") == 2)
1306                 cvar_set("r_glsl_postprocess", "0");
1307 }
1308
1309 void View_Lock()
1310 {
1311         int lock_type = (!autocvar_hud_cursormode && ((autocvar__hud_configure && spectatee_status <= 0) || intermission > 1 || QuickMenu_IsOpened()));
1312         if (lock_type == 0)
1313                 lock_type = autocvar_cl_lockview;
1314
1315         // lock_type 1: lock origin and angles
1316         // lock_type 2: lock only origin
1317         if(lock_type >= 1)
1318                 setproperty(VF_ORIGIN, freeze_org);
1319         else
1320                 freeze_org = getpropertyvec(VF_ORIGIN);
1321         if(lock_type == 1)
1322                 setproperty(VF_ANGLES, freeze_ang);
1323         else
1324                 freeze_ang = getpropertyvec(VF_ANGLES);
1325 }
1326
1327 void View_DemoCamera()
1328 {
1329         if(camera_active) // Camera for demo playback
1330         {
1331                 if(autocvar_camera_enable)
1332                         CSQC_Demo_Camera();
1333                 else
1334                 {
1335                         cvar_set("chase_active", ftos(chase_active_backup));
1336                         cvar_set("cl_demo_mousegrab", "0");
1337                         camera_active = false;
1338                 }
1339         }
1340         else
1341         {
1342 #ifdef CAMERATEST
1343                 if(autocvar_camera_enable)
1344 #else
1345                 if(autocvar_camera_enable && isdemo())
1346 #endif
1347                 {
1348                         // Enable required Darkplaces cvars
1349                         chase_active_backup = autocvar_chase_active;
1350                         cvar_set("chase_active", "2");
1351                         cvar_set("cl_demo_mousegrab", "1");
1352                         camera_active = true;
1353                         camera_mode = false;
1354                 }
1355         }
1356 }
1357
1358 #ifdef BLURTEST
1359 void View_BlurTest()
1360 {
1361         if(time > blurtest_time0 && time < blurtest_time1)
1362         {
1363                 float t = (time - blurtest_time0) / (blurtest_time1 - blurtest_time0);
1364                 float r = t * blurtest_radius;
1365                 float f = 1 / (t ** blurtest_power) - 1;
1366
1367                 cvar_set("r_glsl_postprocess", "1");
1368                 cvar_set("r_glsl_postprocess_uservec1", strcat(ftos(r), " ", ftos(f), " 0 0"));
1369         }
1370         else
1371         {
1372                 cvar_set("r_glsl_postprocess", "0");
1373                 cvar_set("r_glsl_postprocess_uservec1", "0 0 0 0");
1374         }
1375 }
1376 #endif
1377
1378 void View_CheckButtonStatus()
1379 {
1380         float is_dead = (STAT(HEALTH) <= 0);
1381
1382         // FIXME do we need this hack?
1383         if(isdemo())
1384         {
1385                 // in demos, input_buttons do not work
1386                 button_zoom = (autocvar__togglezoom == "-");
1387         }
1388         else if(button_zoom
1389                 && autocvar_cl_unpress_zoom_on_death
1390                 && (spectatee_status >= 0)
1391                 && (is_dead || intermission))
1392         {
1393                 // no zoom while dead or in intermission please
1394                 localcmd("-zoom\n");
1395                 button_zoom = false;
1396         }
1397
1398         if(autocvar_fov <= 59.5)
1399         {
1400                 if(!zoomscript_caught)
1401                 {
1402                         localcmd("+button9\n");
1403                         zoomscript_caught = 1;
1404                 }
1405         }
1406         else
1407         {
1408                 if(zoomscript_caught)
1409                 {
1410                         localcmd("-button9\n");
1411                         zoomscript_caught = 0;
1412                 }
1413         }
1414
1415         if(active_minigame && HUD_MinigameMenu_IsOpened())
1416         {
1417                 if(!minigame_wasactive)
1418                 {
1419                         localcmd("+button12\n");
1420                         minigame_wasactive = true;
1421                 }
1422         }
1423         else if(minigame_wasactive)
1424         {
1425                 localcmd("-button12\n");
1426                 minigame_wasactive = false;
1427         }
1428
1429         for(int slot = 0; slot < MAX_WEAPONSLOTS; ++slot)
1430         {
1431                 entity wepent = viewmodels[slot];
1432
1433                 if(wepent.last_switchweapon != wepent.switchweapon)
1434                 {
1435                         weapontime = time;
1436                         wepent.last_switchweapon = wepent.switchweapon;
1437                         if(slot == 0 && button_zoom && autocvar_cl_unpress_zoom_on_weapon_switch)
1438                         {
1439                                 localcmd("-zoom\n");
1440                                 button_zoom = false;
1441                         }
1442                         if(slot == 0 && autocvar_cl_unpress_attack_on_weapon_switch)
1443                         {
1444                                 localcmd("-fire\n");
1445                                 localcmd("-fire2\n");
1446                                 button_attack2 = false;
1447                         }
1448                 }
1449                 if(wepent.last_activeweapon != wepent.activeweapon)
1450                 {
1451                         wepent.last_activeweapon = wepent.activeweapon;
1452
1453                         entity e = wepent.activeweapon;
1454                         if(e.netname != "")
1455                                 localcmd(strcat("\ncl_hook_activeweapon ", e.netname), "\n");
1456                         else if(slot == 0)
1457                                 localcmd("\ncl_hook_activeweapon none\n");
1458                 }
1459         }
1460 }
1461
1462 bool ov_enabled;
1463 float oldr_nearclip;
1464 float oldr_farclip_base;
1465 float oldr_farclip_world;
1466 float oldr_novis;
1467 float oldr_useportalculling;
1468 float oldr_useinfinitefarclip;
1469 vector ov_org = '0 0 0';
1470 vector ov_mid = '0 0 0';
1471 vector ov_worldmin = '0 0 0';
1472 vector ov_worldmax = '0 0 0';
1473
1474 void View_Ortho()
1475 {
1476         ov_org = '0 0 0';
1477         ov_mid = '0 0 0';
1478         ov_worldmin = '0 0 0';
1479         ov_worldmax = '0 0 0';
1480         if(autocvar_cl_orthoview)
1481         {
1482                 ov_worldmin = mi_picmin;
1483                 ov_worldmax = mi_picmax;
1484
1485                 float ov_width = (ov_worldmax.x - ov_worldmin.x);
1486                 float ov_height = (ov_worldmax.y - ov_worldmin.y);
1487                 float ov_distance = (max(vid_width, vid_height) * max(ov_width, ov_height));
1488
1489                 ov_mid = ((ov_worldmax + ov_worldmin) * 0.5);
1490                 ov_org = vec3(ov_mid.x, ov_mid.y, (ov_mid.z + ov_distance));
1491
1492                 float ov_nearest = vlen(ov_org - vec3(
1493                         bound(ov_worldmin.x, ov_org.x, ov_worldmax.x),
1494                         bound(ov_worldmin.y, ov_org.y, ov_worldmax.y),
1495                         bound(ov_worldmin.z, ov_org.z, ov_worldmax.z)
1496                 ));
1497
1498                 float ov_furthest = 0;
1499                 float dist = 0;
1500
1501                 if((dist = vdist((vec3(ov_worldmin.x, ov_worldmin.y, ov_worldmin.z) - ov_org), >, ov_furthest))) { ov_furthest = dist; }
1502                 if((dist = vdist((vec3(ov_worldmax.x, ov_worldmin.y, ov_worldmin.z) - ov_org), >, ov_furthest))) { ov_furthest = dist; }
1503                 if((dist = vdist((vec3(ov_worldmin.x, ov_worldmax.y, ov_worldmin.z) - ov_org), >, ov_furthest))) { ov_furthest = dist; }
1504                 if((dist = vdist((vec3(ov_worldmin.x, ov_worldmin.y, ov_worldmax.z) - ov_org), >, ov_furthest))) { ov_furthest = dist; }
1505                 if((dist = vdist((vec3(ov_worldmax.x, ov_worldmax.y, ov_worldmin.z) - ov_org), >, ov_furthest))) { ov_furthest = dist; }
1506                 if((dist = vdist((vec3(ov_worldmin.x, ov_worldmax.y, ov_worldmax.z) - ov_org), >, ov_furthest))) { ov_furthest = dist; }
1507                 if((dist = vdist((vec3(ov_worldmax.x, ov_worldmin.y, ov_worldmax.z) - ov_org), >, ov_furthest))) { ov_furthest = dist; }
1508                 if((dist = vdist((vec3(ov_worldmax.x, ov_worldmax.y, ov_worldmax.z) - ov_org), >, ov_furthest))) { ov_furthest = dist; }
1509
1510                 if(!ov_enabled)
1511                 {
1512                         oldr_nearclip = cvar("r_nearclip");
1513                         oldr_farclip_base = cvar("r_farclip_base");
1514                         oldr_farclip_world = cvar("r_farclip_world");
1515                         oldr_novis = cvar("r_novis");
1516                         oldr_useportalculling = cvar("r_useportalculling");
1517                         oldr_useinfinitefarclip = cvar("r_useinfinitefarclip");
1518                 }
1519
1520                 cvar_settemp("r_nearclip", ftos(ov_nearest));
1521                 cvar_settemp("r_farclip_base", ftos(ov_furthest));
1522                 cvar_settemp("r_farclip_world", "0");
1523                 cvar_settemp("r_novis", "1");
1524                 cvar_settemp("r_useportalculling", "0");
1525                 cvar_settemp("r_useinfinitefarclip", "0");
1526
1527                 setproperty(VF_ORIGIN, ov_org);
1528                 setproperty(VF_ANGLES, '90 0 0');
1529
1530                 ov_enabled = true;
1531
1532                 #if 0
1533                 LOG_INFOF("OrthoView: org = %s, angles = %s, distance = %f, nearest = %f, furthest = %f",
1534                         vtos(ov_org),
1535                         vtos(getpropertyvec(VF_ANGLES)),
1536                         ov_distance,
1537                         ov_nearest,
1538                         ov_furthest);
1539                 #endif
1540         }
1541         else
1542         {
1543                 if(ov_enabled)
1544                 {
1545                         cvar_set("r_nearclip", ftos(oldr_nearclip));
1546                         cvar_set("r_farclip_base", ftos(oldr_farclip_base));
1547                         cvar_set("r_farclip_world", ftos(oldr_farclip_world));
1548                         cvar_set("r_novis", ftos(oldr_novis));
1549                         cvar_set("r_useportalculling", ftos(oldr_useportalculling));
1550                         cvar_set("r_useinfinitefarclip", ftos(oldr_useinfinitefarclip));
1551                 }
1552                 ov_enabled = false;
1553         }
1554 }
1555
1556 void View_UpdateFov()
1557 {
1558         vector fov;
1559         if(autocvar_cl_orthoview)
1560                 fov = GetOrthoviewFOV(ov_worldmin, ov_worldmax, ov_mid, ov_org);
1561         else if(csqcplayer.viewloc)
1562                 fov = GetViewLocationFOV(110); // enforce 110 fov, so things don't look odd
1563         else
1564                 fov = GetCurrentFov(autocvar_fov);
1565
1566         setproperty(VF_FOV, fov);
1567 }
1568
1569 void CSQC_UpdateView(entity this, float w, float h)
1570 {
1571         TC(int, w); TC(int, h);
1572
1573         execute_next_frame();
1574
1575         ++framecount;
1576
1577         stats_get();
1578         hud = STAT(HUD);
1579
1580         ReplicateVars(false);
1581         if (ReplicateVars_NOT_SENDING())
1582                 ReplicateVars_DELAY(0.8 + random() * 0.4); // no need to check cvars every frame
1583
1584         HUD_Scale_Disable();
1585
1586         if(autocvar__hud_showbinds_reload) // menu can set this one
1587         {
1588                 db_close(binddb);
1589                 binddb = db_create();
1590                 cvar_set("_hud_showbinds_reload", "0");
1591         }
1592
1593         if(checkextension("DP_CSQC_MINFPS_QUALITY"))
1594                 view_quality = getproperty(VF_MINFPS_QUALITY);
1595         else
1596                 view_quality = 1;
1597
1598         button_attack2 = PHYS_INPUT_BUTTON_ATCK2(this);
1599         button_zoom = PHYS_INPUT_BUTTON_ZOOM(this);
1600
1601         vector vf_size = getpropertyvec(VF_SIZE);
1602         vector vf_min = getpropertyvec(VF_MIN);
1603         vid_width = vf_size.x;
1604         vid_height = vf_size.y;
1605
1606         ticrate = STAT(MOVEVARS_TICRATE) * STAT(MOVEVARS_TIMESCALE);
1607
1608         WaypointSprite_Load();
1609
1610         CSQCPlayer_SetCamera();
1611
1612         if(player_localentnum <= maxclients) // is it a client?
1613                 current_player = player_localentnum - 1;
1614         else // then player_localentnum is the vehicle I'm driving
1615                 current_player = player_localnum;
1616         myteam = entcs_GetTeam(current_player);
1617
1618         // abused multiple places below
1619         entity local_player = ((csqcplayer) ? csqcplayer : CSQCModel_server2csqc(player_localentnum - 1));
1620         if(!local_player)
1621                 local_player = this; // fall back!
1622
1623         View_EventChase(local_player);
1624
1625         // do lockview after event chase camera so that it still applies whenever necessary.
1626         View_Lock();
1627
1628         WarpZone_FixView();
1629         //WarpZone_FixPMove();
1630
1631         View_Ortho();
1632
1633         // run viewmodel_draw before updating view_angles to the angles calculated by WarpZone_FixView
1634         // viewmodel_draw needs to use the view_angles set by the engine on every CSQC_UpdateView call
1635         for(int slot = 0; slot < MAX_WEAPONSLOTS; ++slot)
1636                 viewmodel_draw(viewmodels[slot]);
1637
1638         // Render the Scene
1639         view_origin = getpropertyvec(VF_ORIGIN);
1640         view_angles = getpropertyvec(VF_ANGLES);
1641         MAKE_VECTORS(view_angles, view_forward, view_right, view_up);
1642
1643 #ifdef BLURTEST
1644         View_BlurTest();
1645 #endif
1646
1647         TargetMusic_Advance();
1648         Fog_Force();
1649         fpscounter_update();
1650
1651         if(drawtime == 0)
1652                 drawframetime = 0.01666667; // when we don't know fps yet, we assume 60fps
1653         else
1654                 drawframetime = bound(0.000001, time - drawtime, 1);
1655         drawtime = time;
1656
1657         // watch for gametype changes here...
1658         // in ParseStuffCMD the cmd isn't executed yet :/
1659         // might even be better to add the gametype to TE_CSQC_INIT...?
1660         if(!postinit)
1661                 PostInit();
1662
1663         if(intermission && !intermission_time)
1664                 intermission_time = time;
1665
1666         if(intermission && !isdemo() && !(calledhooks & HOOK_END))
1667         {
1668                 if(calledhooks & HOOK_START)
1669                 {
1670                         localcmd("\ncl_hook_gameend\n");
1671                         calledhooks |= HOOK_END;
1672                 }
1673         }
1674
1675         Announcer();
1676
1677         View_CheckButtonStatus();
1678
1679         ColorTranslateMode = autocvar_cl_stripcolorcodes;
1680
1681         // ALWAYS Clear Current Scene First
1682         clearscene();
1683
1684         setproperty(VF_ORIGIN, view_origin);
1685         setproperty(VF_ANGLES, view_angles);
1686
1687         // FIXME engine bug? VF_SIZE and VF_MIN are not restored to sensible values by this
1688         setproperty(VF_SIZE, vf_size);
1689         setproperty(VF_MIN, vf_min);
1690
1691         // Assign Standard Viewflags
1692         // Draw the World (and sky)
1693         setproperty(VF_DRAWWORLD, 1);
1694
1695         // Set the console size vars
1696         vid_conwidth = autocvar_vid_conwidth;
1697         vid_conheight = autocvar_vid_conheight;
1698         vid_pixelheight = autocvar_vid_pixelheight;
1699
1700         View_UpdateFov();
1701
1702         View_DemoCamera();
1703
1704         // Draw the Crosshair
1705         setproperty(VF_DRAWCROSSHAIR, 0); //Make sure engine crosshairs are always hidden
1706
1707         // Draw the Engine Status Bar (the default Quake HUD)
1708         setproperty(VF_DRAWENGINESBAR, 0);
1709
1710         // Update the mouse position
1711         /*
1712            mousepos_x = vid_conwidth;
1713            mousepos_y = vid_conheight;
1714            mousepos = mousepos*0.5 + getmousepos();
1715          */
1716
1717         IL_EACH(g_drawables, it.draw, it.draw(it));
1718
1719         addentities(MASK_NORMAL | MASK_ENGINE | MASK_ENGINEVIEWMODELS); // TODO: .health is used in cl_deathfade (a feature we have turned off currently)
1720         renderscene();
1721
1722         // Now the the scene has been rendered, begin with the 2D drawing functions
1723
1724         View_NightVision();
1725         DrawReticle(local_player);
1726         HUD_Contents();
1727         HUD_Damage();
1728         View_PostProcessing();
1729
1730         // draw 2D entities
1731         IL_EACH(g_drawables_2d, it.draw2d, it.draw2d(it));
1732         Draw_ShowNames_All();
1733 #if ENABLE_DEBUGDRAW
1734         Debug_Draw();
1735 #endif
1736
1737         scoreboard_active = Scoreboard_WouldDraw();
1738
1739         HUD_Draw(this); // this parameter for deep vehicle function
1740
1741         if(NextFrameCommand)
1742         {
1743                 localcmd("\n", NextFrameCommand, "\n");
1744                 NextFrameCommand = string_null;
1745         }
1746
1747         // we must do this check AFTER a frame was rendered, or it won't work
1748         if(cs_project_is_b0rked == 0)
1749         {
1750                 string w0, h0;
1751                 w0 = ftos(autocvar_vid_conwidth);
1752                 h0 = ftos(autocvar_vid_conheight);
1753                 //setproperty(VF_VIEWPORT, '0 0 0', '640 480 0');
1754                 //setproperty(VF_FOV, '90 90 0');
1755                 setproperty(VF_ORIGIN, '0 0 0');
1756                 setproperty(VF_ANGLES, '0 0 0');
1757                 setproperty(VF_PERSPECTIVE, 1);
1758                 vector forward, right, up;
1759                 MAKE_VECTORS('0 0 0', forward, right, up);
1760                 vector v1, v2;
1761                 cvar_set("vid_conwidth", "800");
1762                 cvar_set("vid_conheight", "600");
1763                 v1 = cs_project(forward);
1764                 cvar_set("vid_conwidth", "640");
1765                 cvar_set("vid_conheight", "480");
1766                 v2 = cs_project(forward);
1767                 if(v1 == v2)
1768                         cs_project_is_b0rked = 1;
1769                 else
1770                         cs_project_is_b0rked = -1;
1771                 cvar_set("vid_conwidth", w0);
1772                 cvar_set("vid_conheight", h0);
1773         }
1774
1775         HUD_Mouse(local_player);
1776
1777         cl_notice_run();
1778         unpause_update();
1779         Net_Flush();
1780
1781         // let's reset the view back to normal for the end
1782         setproperty(VF_MIN, '0 0 0');
1783         setproperty(VF_SIZE, '1 0 0' * w + '0 1 0' * h);
1784
1785         IL_ENDFRAME();
1786 }
1787
1788
1789 // following vectors must be global to allow seamless switching between camera modes
1790 vector camera_offset, current_camera_offset, mouse_angles, current_angles, current_origin, current_position;
1791 void CSQC_Demo_Camera()
1792 {
1793         float speed, attenuation, dimensions;
1794         vector tmp, delta;
1795
1796         if( autocvar_camera_reset || !camera_mode )
1797         {
1798                 camera_offset = '0 0 0';
1799                 current_angles = '0 0 0';
1800                 camera_direction = '0 0 0';
1801                 camera_offset.z += 30;
1802                 camera_offset.x += 30 * -cos(current_angles.y * DEG2RAD);
1803                 camera_offset.y += 30 * -sin(current_angles.y * DEG2RAD);
1804                 current_origin = view_origin;
1805                 current_camera_offset  = camera_offset;
1806                 cvar_set("camera_reset", "0");
1807                 camera_mode = CAMERA_CHASE;
1808         }
1809
1810         // Camera angles
1811         if( camera_roll )
1812                 mouse_angles.z += camera_roll * autocvar_camera_speed_roll;
1813
1814         if(autocvar_camera_look_player)
1815         {
1816                 vector dir;
1817                 float n;
1818
1819                 dir = normalize(view_origin - current_position);
1820                 n = mouse_angles.z;
1821                 mouse_angles = vectoangles(dir);
1822                 mouse_angles.x = mouse_angles.x * -1;
1823                 mouse_angles.z = n;
1824         }
1825         else
1826         {
1827                 tmp = getmousepos() * 0.1;
1828                 if(vdist(tmp, >, autocvar_camera_mouse_threshold))
1829                 {
1830                         mouse_angles.x += tmp.y * cos(mouse_angles.z * DEG2RAD) + (tmp.x * sin(mouse_angles.z * DEG2RAD));
1831                         mouse_angles.y -= tmp.x * cos(mouse_angles.z * DEG2RAD) + (tmp.y * -sin(mouse_angles.z * DEG2RAD));
1832                 }
1833         }
1834
1835         while (mouse_angles.x < -180) mouse_angles.x = mouse_angles.x + 360;
1836         while (mouse_angles.x > 180) mouse_angles.x = mouse_angles.x - 360;
1837         while (mouse_angles.y < -180) mouse_angles.y = mouse_angles.y + 360;
1838         while (mouse_angles.y > 180) mouse_angles.y = mouse_angles.y - 360;
1839
1840         // Fix difference when angles don't have the same sign
1841         delta = '0 0 0';
1842         if(mouse_angles.y < -60 && current_angles.y > 60)
1843                 delta = '0 360 0';
1844         if(mouse_angles.y > 60 && current_angles.y < -60)
1845                 delta = '0 -360 0';
1846
1847         if(autocvar_camera_look_player)
1848                 attenuation = autocvar_camera_look_attenuation;
1849         else
1850                 attenuation = autocvar_camera_speed_attenuation;
1851
1852         attenuation = 1 / max(1, attenuation);
1853         current_angles += (mouse_angles - current_angles + delta) * attenuation;
1854
1855         while (current_angles.x < -180) current_angles.x = current_angles.x + 360;
1856         while (current_angles.x > 180) current_angles.x = current_angles.x - 360;
1857         while (current_angles.y < -180) current_angles.y = current_angles.y + 360;
1858         while (current_angles.y > 180) current_angles.y = current_angles.y - 360;
1859
1860         // Camera position
1861         tmp = '0 0 0';
1862         dimensions = 0;
1863
1864         if( camera_direction.x )
1865         {
1866                 tmp.x = camera_direction.x * cos(current_angles.y * DEG2RAD);
1867                 tmp.y = camera_direction.x * sin(current_angles.y * DEG2RAD);
1868                 if( autocvar_camera_forward_follows && !autocvar_camera_look_player )
1869                         tmp.z = camera_direction.x * -sin(current_angles.x * DEG2RAD);
1870                 ++dimensions;
1871         }
1872
1873         if( camera_direction.y )
1874         {
1875                 tmp.x += camera_direction.y * -sin(current_angles.y * DEG2RAD);
1876                 tmp.y += camera_direction.y * cos(current_angles.y * DEG2RAD) * cos(current_angles.z * DEG2RAD);
1877                 tmp.z += camera_direction.y * sin(current_angles.z * DEG2RAD);
1878                 ++dimensions;
1879         }
1880
1881         if( camera_direction.z )
1882         {
1883                 tmp.z += camera_direction.z * cos(current_angles.z * DEG2RAD);
1884                 ++dimensions;
1885         }
1886
1887         if(autocvar_camera_free)
1888                 speed = autocvar_camera_speed_free;
1889         else
1890                 speed = autocvar_camera_speed_chase;
1891
1892         if(dimensions)
1893         {
1894                 speed = speed * sqrt(1 / dimensions);
1895                 camera_offset += tmp * speed;
1896         }
1897
1898         current_camera_offset += (camera_offset - current_camera_offset) * attenuation;
1899
1900         // Camera modes
1901         if( autocvar_camera_free )
1902         {
1903                 if ( camera_mode == CAMERA_CHASE )
1904                 {
1905                         current_camera_offset = current_origin + current_camera_offset;
1906                         camera_offset = current_origin + camera_offset;
1907                 }
1908
1909                 camera_mode = CAMERA_FREE;
1910                 current_position = current_camera_offset;
1911         }
1912         else
1913         {
1914                 if ( camera_mode == CAMERA_FREE )
1915                 {
1916                         current_origin = view_origin;
1917                         camera_offset = camera_offset - current_origin;
1918                         current_camera_offset = current_camera_offset - current_origin;
1919                 }
1920
1921                 camera_mode = CAMERA_CHASE;
1922
1923                 if(autocvar_camera_chase_smoothly)
1924                         current_origin += (view_origin - current_origin) * attenuation;
1925                 else
1926                         current_origin = view_origin;
1927
1928                 current_position = current_origin + current_camera_offset;
1929         }
1930
1931         setproperty(VF_ANGLES, current_angles);
1932         setproperty(VF_ORIGIN, current_position);
1933 }