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