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