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