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