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