]> de.git.xonotic.org Git - xonotic/darkplaces.git/blob - vid_shared.c
Clean up GL extensions a bit to only have the stuff the engine actually uses.
[xonotic/darkplaces.git] / vid_shared.c
1
2 #include "quakedef.h"
3 #ifdef CONFIG_CD
4 #include "cdaudio.h"
5 #endif
6 #include "image.h"
7
8 #ifdef WIN32
9 //#include <XInput.h>
10 #define XINPUT_GAMEPAD_DPAD_UP          0x0001
11 #define XINPUT_GAMEPAD_DPAD_DOWN        0x0002
12 #define XINPUT_GAMEPAD_DPAD_LEFT        0x0004
13 #define XINPUT_GAMEPAD_DPAD_RIGHT       0x0008
14 #define XINPUT_GAMEPAD_START            0x0010
15 #define XINPUT_GAMEPAD_BACK             0x0020
16 #define XINPUT_GAMEPAD_LEFT_THUMB       0x0040
17 #define XINPUT_GAMEPAD_RIGHT_THUMB      0x0080
18 #define XINPUT_GAMEPAD_LEFT_SHOULDER    0x0100
19 #define XINPUT_GAMEPAD_RIGHT_SHOULDER   0x0200
20 #define XINPUT_GAMEPAD_A                0x1000
21 #define XINPUT_GAMEPAD_B                0x2000
22 #define XINPUT_GAMEPAD_X                0x4000
23 #define XINPUT_GAMEPAD_Y                0x8000
24 #define XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE  7849
25 #define XINPUT_GAMEPAD_RIGHT_THUMB_DEADZONE 8689
26 #define XINPUT_GAMEPAD_TRIGGER_THRESHOLD    30
27 #define XUSER_INDEX_ANY                 0x000000FF
28
29 typedef struct xinput_gamepad_s
30 {
31         WORD wButtons;
32         BYTE bLeftTrigger;
33         BYTE bRightTrigger;
34         SHORT sThumbLX;
35         SHORT sThumbLY;
36         SHORT sThumbRX;
37         SHORT sThumbRY;
38 }
39 xinput_gamepad_t;
40
41 typedef struct xinput_state_s
42 {
43         DWORD dwPacketNumber;
44         xinput_gamepad_t Gamepad;
45 }
46 xinput_state_t;
47
48 typedef struct xinput_keystroke_s
49 {
50     WORD    VirtualKey;
51     WCHAR   Unicode;
52     WORD    Flags;
53     BYTE    UserIndex;
54     BYTE    HidCode;
55 }
56 xinput_keystroke_t;
57
58 DWORD (WINAPI *qXInputGetState)(DWORD index, xinput_state_t *state);
59 DWORD (WINAPI *qXInputGetKeystroke)(DWORD index, DWORD reserved, xinput_keystroke_t *keystroke);
60
61 qboolean vid_xinputinitialized = false;
62 int vid_xinputindex = -1;
63 #endif
64
65 // global video state
66 viddef_t vid;
67
68 // AK FIXME -> input_dest
69 qboolean in_client_mouse = true;
70
71 // AK where should it be placed ?
72 float in_mouse_x, in_mouse_y;
73 float in_windowmouse_x, in_windowmouse_y;
74
75 // LordHavoc: if window is hidden, don't update screen
76 qboolean vid_hidden = true;
77 // LordHavoc: if window is not the active window, don't hog as much CPU time,
78 // let go of the mouse, turn off sound, and restore system gamma ramps...
79 qboolean vid_activewindow = true;
80
81 vid_joystate_t vid_joystate;
82
83 #ifdef WIN32
84 cvar_t joy_xinputavailable = {CVAR_READONLY, "joy_xinputavailable", "0", "indicates which devices are being reported by the Windows XInput API (first controller = 1, second = 2, third = 4, fourth = 8, added together)"};
85 #endif
86 cvar_t joy_active = {CVAR_READONLY, "joy_active", "0", "indicates that a joystick is active (detected and enabled)"};
87 cvar_t joy_detected = {CVAR_READONLY, "joy_detected", "0", "number of joysticks detected by engine"};
88 cvar_t joy_enable = {CVAR_SAVE, "joy_enable", "0", "enables joystick support"};
89 cvar_t joy_index = {0, "joy_index", "0", "selects which joystick to use if you have multiple (0 uses the first controller, 1 uses the second, ...)"};
90 cvar_t joy_axisforward = {0, "joy_axisforward", "1", "which joystick axis to query for forward/backward movement"};
91 cvar_t joy_axisside = {0, "joy_axisside", "0", "which joystick axis to query for right/left movement"};
92 cvar_t joy_axisup = {0, "joy_axisup", "-1", "which joystick axis to query for up/down movement"};
93 cvar_t joy_axispitch = {0, "joy_axispitch", "3", "which joystick axis to query for looking up/down"};
94 cvar_t joy_axisyaw = {0, "joy_axisyaw", "2", "which joystick axis to query for looking right/left"};
95 cvar_t joy_axisroll = {0, "joy_axisroll", "-1", "which joystick axis to query for tilting head right/left"};
96 cvar_t joy_deadzoneforward = {0, "joy_deadzoneforward", "0", "deadzone tolerance, suggested values are in the range 0 to 0.01"};
97 cvar_t joy_deadzoneside = {0, "joy_deadzoneside", "0", "deadzone tolerance, suggested values are in the range 0 to 0.01"};
98 cvar_t joy_deadzoneup = {0, "joy_deadzoneup", "0", "deadzone tolerance, suggested values are in the range 0 to 0.01"};
99 cvar_t joy_deadzonepitch = {0, "joy_deadzonepitch", "0", "deadzone tolerance, suggested values are in the range 0 to 0.01"};
100 cvar_t joy_deadzoneyaw = {0, "joy_deadzoneyaw", "0", "deadzone tolerance, suggested values are in the range 0 to 0.01"};
101 cvar_t joy_deadzoneroll = {0, "joy_deadzoneroll", "0", "deadzone tolerance, suggested values are in the range 0 to 0.01"};
102 cvar_t joy_sensitivityforward = {0, "joy_sensitivityforward", "-1", "movement multiplier"};
103 cvar_t joy_sensitivityside = {0, "joy_sensitivityside", "1", "movement multiplier"};
104 cvar_t joy_sensitivityup = {0, "joy_sensitivityup", "1", "movement multiplier"};
105 cvar_t joy_sensitivitypitch = {0, "joy_sensitivitypitch", "1", "movement multiplier"};
106 cvar_t joy_sensitivityyaw = {0, "joy_sensitivityyaw", "-1", "movement multiplier"};
107 cvar_t joy_sensitivityroll = {0, "joy_sensitivityroll", "1", "movement multiplier"};
108 cvar_t joy_axiskeyevents = {CVAR_SAVE, "joy_axiskeyevents", "0", "generate uparrow/leftarrow etc. keyevents for joystick axes, use if your joystick driver is not generating them"};
109 cvar_t joy_axiskeyevents_deadzone = {CVAR_SAVE, "joy_axiskeyevents_deadzone", "0.5", "deadzone value for axes"};
110 cvar_t joy_x360_axisforward = {0, "joy_x360_axisforward", "1", "which joystick axis to query for forward/backward movement"};
111 cvar_t joy_x360_axisside = {0, "joy_x360_axisside", "0", "which joystick axis to query for right/left movement"};
112 cvar_t joy_x360_axisup = {0, "joy_x360_axisup", "-1", "which joystick axis to query for up/down movement"};
113 cvar_t joy_x360_axispitch = {0, "joy_x360_axispitch", "3", "which joystick axis to query for looking up/down"};
114 cvar_t joy_x360_axisyaw = {0, "joy_x360_axisyaw", "2", "which joystick axis to query for looking right/left"};
115 cvar_t joy_x360_axisroll = {0, "joy_x360_axisroll", "-1", "which joystick axis to query for tilting head right/left"};
116 cvar_t joy_x360_deadzoneforward = {0, "joy_x360_deadzoneforward", "0.266", "deadzone tolerance, suggested values are in the range 0 to 0.01"};
117 cvar_t joy_x360_deadzoneside = {0, "joy_x360_deadzoneside", "0.266", "deadzone tolerance, suggested values are in the range 0 to 0.01"};
118 cvar_t joy_x360_deadzoneup = {0, "joy_x360_deadzoneup", "0.266", "deadzone tolerance, suggested values are in the range 0 to 0.01"};
119 cvar_t joy_x360_deadzonepitch = {0, "joy_x360_deadzonepitch", "0.266", "deadzone tolerance, suggested values are in the range 0 to 0.01"};
120 cvar_t joy_x360_deadzoneyaw = {0, "joy_x360_deadzoneyaw", "0.266", "deadzone tolerance, suggested values are in the range 0 to 0.01"};
121 cvar_t joy_x360_deadzoneroll = {0, "joy_x360_deadzoneroll", "0.266", "deadzone tolerance, suggested values are in the range 0 to 0.01"};
122 cvar_t joy_x360_sensitivityforward = {0, "joy_x360_sensitivityforward", "1", "movement multiplier"};
123 cvar_t joy_x360_sensitivityside = {0, "joy_x360_sensitivityside", "1", "movement multiplier"};
124 cvar_t joy_x360_sensitivityup = {0, "joy_x360_sensitivityup", "1", "movement multiplier"};
125 cvar_t joy_x360_sensitivitypitch = {0, "joy_x360_sensitivitypitch", "-1", "movement multiplier"};
126 cvar_t joy_x360_sensitivityyaw = {0, "joy_x360_sensitivityyaw", "-1", "movement multiplier"};
127 cvar_t joy_x360_sensitivityroll = {0, "joy_x360_sensitivityroll", "1", "movement multiplier"};
128
129 // VorteX: more info cvars, mostly set in VID_CheckExtensions
130 cvar_t gl_info_vendor = {CVAR_READONLY, "gl_info_vendor", "", "indicates brand of graphics chip"};
131 cvar_t gl_info_renderer = {CVAR_READONLY, "gl_info_renderer", "", "indicates graphics chip model and other information"};
132 cvar_t gl_info_version = {CVAR_READONLY, "gl_info_version", "", "indicates version of current renderer. begins with 1.0.0, 1.1.0, 1.2.0, 1.3.1 etc."};
133 cvar_t gl_info_extensions = {CVAR_READONLY, "gl_info_extensions", "", "indicates extension list found by engine, space separated."};
134 cvar_t gl_info_platform = {CVAR_READONLY, "gl_info_platform", "", "indicates GL platform: WGL, GLX, or AGL."};
135 cvar_t gl_info_driver = {CVAR_READONLY, "gl_info_driver", "", "name of driver library (opengl32.dll, libGL.so.1, or whatever)."};
136
137 cvar_t vid_fullscreen = {CVAR_SAVE, "vid_fullscreen", "1", "use fullscreen (1) or windowed (0)"};
138 cvar_t vid_width = {CVAR_SAVE, "vid_width", "640", "resolution"};
139 cvar_t vid_height = {CVAR_SAVE, "vid_height", "480", "resolution"};
140 cvar_t vid_bitsperpixel = {CVAR_READONLY, "vid_bitsperpixel", "32", "how many bits per pixel to render at (this is not currently configurable)"};
141 cvar_t vid_samples = {CVAR_SAVE, "vid_samples", "1", "how many anti-aliasing samples per pixel to request from the graphics driver (4 is recommended, 1 is faster)"};
142 cvar_t vid_refreshrate = {CVAR_SAVE, "vid_refreshrate", "60", "refresh rate to use, in hz (higher values flicker less, if supported by your monitor)"};
143 cvar_t vid_userefreshrate = {CVAR_SAVE, "vid_userefreshrate", "0", "set this to 1 to make vid_refreshrate used, or to 0 to let the engine choose a sane default"};
144 cvar_t vid_stereobuffer = {CVAR_SAVE, "vid_stereobuffer", "0", "enables 'quad-buffered' stereo rendering for stereo shutterglasses, HMD (head mounted display) devices, or polarized stereo LCDs, if supported by your drivers"};
145 // the density cvars are completely optional, set and use when something needs to have a density-independent size.
146 // TODO: set them when changing resolution, setting them from the commandline will be independent from the resolution - use only if you have a native fixed resolution.
147 // values for the Samsung Galaxy SIII, Snapdragon version: 2.000000 density, 304.799988 xdpi, 303.850464 ydpi
148 cvar_t vid_touchscreen_density = {0, "vid_touchscreen_density", "2.0", "Standard quantized screen density multiplier (see Android documentation for DisplayMetrics), similar values are given on iPhoneOS"};
149 cvar_t vid_touchscreen_xdpi = {0, "vid_touchscreen_xdpi", "300", "Horizontal DPI of the screen (only valid on Android currently)"};
150 cvar_t vid_touchscreen_ydpi = {0, "vid_touchscreen_ydpi", "300", "Vertical DPI of the screen (only valid on Android currently)"};
151
152 cvar_t vid_vsync = {CVAR_SAVE, "vid_vsync", "0", "sync to vertical blank, prevents 'tearing' (seeing part of one frame and part of another on the screen at the same time), automatically disabled when doing timedemo benchmarks"};
153 cvar_t vid_mouse = {CVAR_SAVE, "vid_mouse", "1", "whether to use the mouse in windowed mode (fullscreen always does)"};
154 cvar_t vid_grabkeyboard = {CVAR_SAVE, "vid_grabkeyboard", "0", "whether to grab the keyboard when mouse is active (prevents use of volume control keys, music player keys, etc on some keyboards)"};
155 cvar_t vid_minwidth = {0, "vid_minwidth", "0", "minimum vid_width that is acceptable (to be set in default.cfg in mods)"};
156 cvar_t vid_minheight = {0, "vid_minheight", "0", "minimum vid_height that is acceptable (to be set in default.cfg in mods)"};
157 cvar_t gl_finish = {0, "gl_finish", "0", "make the cpu wait for the graphics processor at the end of each rendered frame (can help with strange input or video lag problems on some machines)"};
158 cvar_t vid_sRGB = {CVAR_SAVE, "vid_sRGB", "0", "if hardware is capable, modify rendering to be gamma corrected for the sRGB color standard (computer monitors, TVs), recommended"};
159 cvar_t vid_sRGB_fallback = {CVAR_SAVE, "vid_sRGB_fallback", "0", "do an approximate sRGB fallback if not properly supported by hardware (2: also use the fallback if framebuffer is 8bit, 3: always use the fallback even if sRGB is supported)"};
160
161 cvar_t vid_touchscreen = {0, "vid_touchscreen", "0", "Use touchscreen-style input (no mouse grab, track mouse motion only while button is down, screen areas for mimicing joystick axes and buttons"};
162 cvar_t vid_touchscreen_showkeyboard = {0, "vid_touchscreen_showkeyboard", "0", "shows the platform's screen keyboard for text entry, can be set by csqc or menu qc if it wants to receive text input, does nothing if the platform has no screen keyboard"};
163 cvar_t vid_touchscreen_supportshowkeyboard = {CVAR_READONLY, "vid_touchscreen_supportshowkeyboard", "0", "indicates if the platform supports a virtual keyboard"};
164 cvar_t vid_stick_mouse = {CVAR_SAVE, "vid_stick_mouse", "0", "have the mouse stuck in the center of the screen" };
165 cvar_t vid_resizable = {CVAR_SAVE, "vid_resizable", "0", "0: window not resizable, 1: resizable, 2: window can be resized but the framebuffer isn't adjusted" };
166 cvar_t vid_desktopfullscreen = {CVAR_SAVE, "vid_desktopfullscreen", "1", "force desktop resolution for fullscreen; also use some OS dependent tricks for better fullscreen integration"};
167
168 cvar_t v_gamma = {CVAR_SAVE, "v_gamma", "1", "inverse gamma correction value, a brightness effect that does not affect white or black, and tends to make the image grey and dull"};
169 cvar_t v_contrast = {CVAR_SAVE, "v_contrast", "1", "brightness of white (values above 1 give a brighter image with increased color saturation, unlike v_gamma)"};
170 cvar_t v_brightness = {CVAR_SAVE, "v_brightness", "0", "brightness of black, useful for monitors that are too dark"};
171 cvar_t v_contrastboost = {CVAR_SAVE, "v_contrastboost", "1", "by how much to multiply the contrast in dark areas (1 is no change)"};
172 cvar_t v_color_enable = {CVAR_SAVE, "v_color_enable", "0", "enables black-grey-white color correction curve controls"};
173 cvar_t v_color_black_r = {CVAR_SAVE, "v_color_black_r", "0", "desired color of black"};
174 cvar_t v_color_black_g = {CVAR_SAVE, "v_color_black_g", "0", "desired color of black"};
175 cvar_t v_color_black_b = {CVAR_SAVE, "v_color_black_b", "0", "desired color of black"};
176 cvar_t v_color_grey_r = {CVAR_SAVE, "v_color_grey_r", "0.5", "desired color of grey"};
177 cvar_t v_color_grey_g = {CVAR_SAVE, "v_color_grey_g", "0.5", "desired color of grey"};
178 cvar_t v_color_grey_b = {CVAR_SAVE, "v_color_grey_b", "0.5", "desired color of grey"};
179 cvar_t v_color_white_r = {CVAR_SAVE, "v_color_white_r", "1", "desired color of white"};
180 cvar_t v_color_white_g = {CVAR_SAVE, "v_color_white_g", "1", "desired color of white"};
181 cvar_t v_color_white_b = {CVAR_SAVE, "v_color_white_b", "1", "desired color of white"};
182 cvar_t v_glslgamma_2d = {CVAR_SAVE, "v_glslgamma_2d", "1", "applies GLSL gamma to 2d pictures (HUD, fonts)"};
183 cvar_t v_psycho = {0, "v_psycho", "0", "easter egg - R.I.P. zinx http://obits.al.com/obituaries/birmingham/obituary.aspx?n=christopher-robert-lais&pid=186080667"};
184
185 // brand of graphics chip
186 const char *gl_vendor;
187 // graphics chip model and other information
188 const char *gl_renderer;
189 // begins with 1.0.0, 1.1.0, 1.2.0, 1.2.1, 1.3.0, 1.3.1, or 1.4.0
190 const char *gl_version;
191 // extensions list, space separated
192 const char *gl_extensions;
193 // WGL, GLX, or AGL
194 const char *gl_platform;
195 // another extensions list, containing platform-specific extensions that are
196 // not in the main list
197 const char *gl_platformextensions;
198 // name of driver library (opengl32.dll, libGL.so.1, or whatever)
199 char gl_driver[256];
200
201 #ifndef USE_GLES2
202 // GL_ARB_multitexture
203 void (GLAPIENTRY *qglActiveTexture) (GLenum);
204
205 // general GL functions
206
207 void (GLAPIENTRY *qglClearColor)(GLclampf red, GLclampf green, GLclampf blue, GLclampf alpha);
208
209 void (GLAPIENTRY *qglClear)(GLbitfield mask);
210
211 void (GLAPIENTRY *qglBlendFunc)(GLenum sfactor, GLenum dfactor);
212 void (GLAPIENTRY *qglCullFace)(GLenum mode);
213
214 void (GLAPIENTRY *qglDrawBuffer)(GLenum mode);
215 void (GLAPIENTRY *qglReadBuffer)(GLenum mode);
216 void (GLAPIENTRY *qglEnable)(GLenum cap);
217 void (GLAPIENTRY *qglDisable)(GLenum cap);
218 GLboolean (GLAPIENTRY *qglIsEnabled)(GLenum cap);
219
220 void (GLAPIENTRY *qglGetBooleanv)(GLenum pname, GLboolean *params);
221 void (GLAPIENTRY *qglGetDoublev)(GLenum pname, GLdouble *params);
222 void (GLAPIENTRY *qglGetFloatv)(GLenum pname, GLfloat *params);
223 void (GLAPIENTRY *qglGetIntegerv)(GLenum pname, GLint *params);
224
225 GLenum (GLAPIENTRY *qglGetError)(void);
226 const GLubyte* (GLAPIENTRY *qglGetString)(GLenum name);
227 void (GLAPIENTRY *qglFinish)(void);
228 void (GLAPIENTRY *qglFlush)(void);
229
230 void (GLAPIENTRY *qglClearDepth)(GLclampd depth);
231 void (GLAPIENTRY *qglDepthFunc)(GLenum func);
232 void (GLAPIENTRY *qglDepthMask)(GLboolean flag);
233 void (GLAPIENTRY *qglDepthRange)(GLclampd near_val, GLclampd far_val);
234 void (GLAPIENTRY *qglDepthRangef)(GLclampf near_val, GLclampf far_val);
235 void (GLAPIENTRY *qglColorMask)(GLboolean red, GLboolean green, GLboolean blue, GLboolean alpha);
236
237 void (GLAPIENTRY *qglDrawElements)(GLenum mode, GLsizei count, GLenum type, const GLvoid *indices);
238 void (GLAPIENTRY *qglDrawArrays)(GLenum mode, GLint first, GLsizei count);
239
240 void (GLAPIENTRY *qglViewport)(GLint x, GLint y, GLsizei width, GLsizei height);
241
242 void (GLAPIENTRY *qglReadPixels)(GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, GLvoid *pixels);
243
244 void (GLAPIENTRY *qglStencilFunc)(GLenum func, GLint ref, GLuint mask);
245 void (GLAPIENTRY *qglStencilMask)(GLuint mask);
246 void (GLAPIENTRY *qglStencilOp)(GLenum fail, GLenum zfail, GLenum zpass);
247 void (GLAPIENTRY *qglClearStencil)(GLint s);
248
249 void (GLAPIENTRY *qglTexParameterf)(GLenum target, GLenum pname, GLfloat param);
250 void (GLAPIENTRY *qglTexParameterfv)(GLenum target, GLenum pname, GLfloat *params);
251 void (GLAPIENTRY *qglTexParameteri)(GLenum target, GLenum pname, GLint param);
252 void (GLAPIENTRY *qglGetTexParameterfv)(GLenum target, GLenum pname, GLfloat *params);
253 void (GLAPIENTRY *qglGetTexParameteriv)(GLenum target, GLenum pname, GLint *params);
254 void (GLAPIENTRY *qglGetTexLevelParameterfv)(GLenum target, GLint level, GLenum pname, GLfloat *params);
255 void (GLAPIENTRY *qglGetTexLevelParameteriv)(GLenum target, GLint level, GLenum pname, GLint *params);
256 void (GLAPIENTRY *qglGetTexImage)(GLenum target, GLint level, GLenum format, GLenum type, GLvoid *pixels);
257 void (GLAPIENTRY *qglHint)(GLenum target, GLenum mode);
258
259 void (GLAPIENTRY *qglGenTextures)(GLsizei n, GLuint *textures);
260 void (GLAPIENTRY *qglDeleteTextures)(GLsizei n, const GLuint *textures);
261 void (GLAPIENTRY *qglBindTexture)(GLenum target, GLuint texture);
262
263 void (GLAPIENTRY *qglPixelStorei)(GLenum pname, GLint param);
264
265 void (GLAPIENTRY *qglTexImage2D)(GLenum target, GLint level, GLint internalFormat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, const GLvoid *pixels);
266 void (GLAPIENTRY *qglTexSubImage2D)(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, const GLvoid *pixels);
267 void (GLAPIENTRY *qglCopyTexImage2D)(GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLsizei height, GLint border);
268 void (GLAPIENTRY *qglCopyTexSubImage2D)(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height);
269
270 void (GLAPIENTRY *qglTexImage3D)(GLenum target, GLint level, GLenum internalFormat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, const GLvoid *pixels);
271 void (GLAPIENTRY *qglTexSubImage3D)(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const GLvoid *pixels);
272 void (GLAPIENTRY *qglCopyTexSubImage3D)(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLint x, GLint y, GLsizei width, GLsizei height);
273
274 void (GLAPIENTRY *qglScissor)(GLint x, GLint y, GLsizei width, GLsizei height);
275
276 void (GLAPIENTRY *qglPolygonOffset)(GLfloat factor, GLfloat units);
277 void (GLAPIENTRY *qglPolygonMode)(GLenum face, GLenum mode);
278
279 void (GLAPIENTRY *qglPointSize)(GLfloat size);
280
281 void (GLAPIENTRY *qglBlendEquationEXT)(GLenum);
282
283 void (GLAPIENTRY *qglStencilOpSeparate)(GLenum, GLenum, GLenum, GLenum);
284 void (GLAPIENTRY *qglStencilFuncSeparate)(GLenum, GLenum, GLint, GLuint);
285 void (GLAPIENTRY *qglActiveStencilFaceEXT)(GLenum);
286
287 void (GLAPIENTRY *qglDeleteShader)(GLuint obj);
288 void (GLAPIENTRY *qglDeleteProgram)(GLuint obj);
289 void (GLAPIENTRY *qglDetachShader)(GLuint containerObj, GLuint attachedObj);
290 GLuint (GLAPIENTRY *qglCreateShader)(GLenum shaderType);
291 void (GLAPIENTRY *qglShaderSource)(GLuint shaderObj, GLsizei count, const GLchar **string, const GLint *length);
292 void (GLAPIENTRY *qglCompileShader)(GLuint shaderObj);
293 GLuint (GLAPIENTRY *qglCreateProgram)(void);
294 void (GLAPIENTRY *qglAttachShader)(GLuint containerObj, GLuint obj);
295 void (GLAPIENTRY *qglLinkProgram)(GLuint programObj);
296 void (GLAPIENTRY *qglUseProgram)(GLuint programObj);
297 void (GLAPIENTRY *qglValidateProgram)(GLuint programObj);
298 void (GLAPIENTRY *qglUniform1f)(GLint location, GLfloat v0);
299 void (GLAPIENTRY *qglUniform2f)(GLint location, GLfloat v0, GLfloat v1);
300 void (GLAPIENTRY *qglUniform3f)(GLint location, GLfloat v0, GLfloat v1, GLfloat v2);
301 void (GLAPIENTRY *qglUniform4f)(GLint location, GLfloat v0, GLfloat v1, GLfloat v2, GLfloat v3);
302 void (GLAPIENTRY *qglUniform1i)(GLint location, GLint v0);
303 void (GLAPIENTRY *qglUniform2i)(GLint location, GLint v0, GLint v1);
304 void (GLAPIENTRY *qglUniform3i)(GLint location, GLint v0, GLint v1, GLint v2);
305 void (GLAPIENTRY *qglUniform4i)(GLint location, GLint v0, GLint v1, GLint v2, GLint v3);
306 void (GLAPIENTRY *qglUniform1fv)(GLint location, GLsizei count, const GLfloat *value);
307 void (GLAPIENTRY *qglUniform2fv)(GLint location, GLsizei count, const GLfloat *value);
308 void (GLAPIENTRY *qglUniform3fv)(GLint location, GLsizei count, const GLfloat *value);
309 void (GLAPIENTRY *qglUniform4fv)(GLint location, GLsizei count, const GLfloat *value);
310 void (GLAPIENTRY *qglUniform1iv)(GLint location, GLsizei count, const GLint *value);
311 void (GLAPIENTRY *qglUniform2iv)(GLint location, GLsizei count, const GLint *value);
312 void (GLAPIENTRY *qglUniform3iv)(GLint location, GLsizei count, const GLint *value);
313 void (GLAPIENTRY *qglUniform4iv)(GLint location, GLsizei count, const GLint *value);
314 void (GLAPIENTRY *qglUniformMatrix2fv)(GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
315 void (GLAPIENTRY *qglUniformMatrix3fv)(GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
316 void (GLAPIENTRY *qglUniformMatrix4fv)(GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
317 void (GLAPIENTRY *qglGetShaderiv)(GLuint obj, GLenum pname, GLint *params);
318 void (GLAPIENTRY *qglGetProgramiv)(GLuint obj, GLenum pname, GLint *params);
319 void (GLAPIENTRY *qglGetShaderInfoLog)(GLuint obj, GLsizei maxLength, GLsizei *length, GLchar *infoLog);
320 void (GLAPIENTRY *qglGetProgramInfoLog)(GLuint obj, GLsizei maxLength, GLsizei *length, GLchar *infoLog);
321 void (GLAPIENTRY *qglGetAttachedShaders)(GLuint containerObj, GLsizei maxCount, GLsizei *count, GLuint *obj);
322 GLint (GLAPIENTRY *qglGetUniformLocation)(GLuint programObj, const GLchar *name);
323 void (GLAPIENTRY *qglGetActiveUniform)(GLuint programObj, GLuint index, GLsizei maxLength, GLsizei *length, GLint *size, GLenum *type, GLchar *name);
324 void (GLAPIENTRY *qglGetUniformfv)(GLuint programObj, GLint location, GLfloat *params);
325 void (GLAPIENTRY *qglGetUniformiv)(GLuint programObj, GLint location, GLint *params);
326 void (GLAPIENTRY *qglGetShaderSource)(GLuint obj, GLsizei maxLength, GLsizei *length, GLchar *source);
327
328 void (GLAPIENTRY *qglVertexAttrib1f)(GLuint index, GLfloat v0);
329 void (GLAPIENTRY *qglVertexAttrib1s)(GLuint index, GLshort v0);
330 void (GLAPIENTRY *qglVertexAttrib1d)(GLuint index, GLdouble v0);
331 void (GLAPIENTRY *qglVertexAttrib2f)(GLuint index, GLfloat v0, GLfloat v1);
332 void (GLAPIENTRY *qglVertexAttrib2s)(GLuint index, GLshort v0, GLshort v1);
333 void (GLAPIENTRY *qglVertexAttrib2d)(GLuint index, GLdouble v0, GLdouble v1);
334 void (GLAPIENTRY *qglVertexAttrib3f)(GLuint index, GLfloat v0, GLfloat v1, GLfloat v2);
335 void (GLAPIENTRY *qglVertexAttrib3s)(GLuint index, GLshort v0, GLshort v1, GLshort v2);
336 void (GLAPIENTRY *qglVertexAttrib3d)(GLuint index, GLdouble v0, GLdouble v1, GLdouble v2);
337 void (GLAPIENTRY *qglVertexAttrib4f)(GLuint index, GLfloat v0, GLfloat v1, GLfloat v2, GLfloat v3);
338 void (GLAPIENTRY *qglVertexAttrib4s)(GLuint index, GLshort v0, GLshort v1, GLshort v2, GLshort v3);
339 void (GLAPIENTRY *qglVertexAttrib4d)(GLuint index, GLdouble v0, GLdouble v1, GLdouble v2, GLdouble v3);
340 void (GLAPIENTRY *qglVertexAttrib4Nub)(GLuint index, GLubyte x, GLubyte y, GLubyte z, GLubyte w);
341 void (GLAPIENTRY *qglVertexAttrib1fv)(GLuint index, const GLfloat *v);
342 void (GLAPIENTRY *qglVertexAttrib1sv)(GLuint index, const GLshort *v);
343 void (GLAPIENTRY *qglVertexAttrib1dv)(GLuint index, const GLdouble *v);
344 void (GLAPIENTRY *qglVertexAttrib2fv)(GLuint index, const GLfloat *v);
345 void (GLAPIENTRY *qglVertexAttrib2sv)(GLuint index, const GLshort *v);
346 void (GLAPIENTRY *qglVertexAttrib2dv)(GLuint index, const GLdouble *v);
347 void (GLAPIENTRY *qglVertexAttrib3fv)(GLuint index, const GLfloat *v);
348 void (GLAPIENTRY *qglVertexAttrib3sv)(GLuint index, const GLshort *v);
349 void (GLAPIENTRY *qglVertexAttrib3dv)(GLuint index, const GLdouble *v);
350 void (GLAPIENTRY *qglVertexAttrib4fv)(GLuint index, const GLfloat *v);
351 void (GLAPIENTRY *qglVertexAttrib4sv)(GLuint index, const GLshort *v);
352 void (GLAPIENTRY *qglVertexAttrib4dv)(GLuint index, const GLdouble *v);
353 void (GLAPIENTRY *qglVertexAttrib4iv)(GLuint index, const GLint *v);
354 void (GLAPIENTRY *qglVertexAttrib4bv)(GLuint index, const GLbyte *v);
355 void (GLAPIENTRY *qglVertexAttrib4ubv)(GLuint index, const GLubyte *v);
356 void (GLAPIENTRY *qglVertexAttrib4usv)(GLuint index, const GLushort *v);
357 void (GLAPIENTRY *qglVertexAttrib4uiv)(GLuint index, const GLuint *v);
358 void (GLAPIENTRY *qglVertexAttrib4Nbv)(GLuint index, const GLbyte *v);
359 void (GLAPIENTRY *qglVertexAttrib4Nsv)(GLuint index, const GLshort *v);
360 void (GLAPIENTRY *qglVertexAttrib4Niv)(GLuint index, const GLint *v);
361 void (GLAPIENTRY *qglVertexAttrib4Nubv)(GLuint index, const GLubyte *v);
362 void (GLAPIENTRY *qglVertexAttrib4Nusv)(GLuint index, const GLushort *v);
363 void (GLAPIENTRY *qglVertexAttrib4Nuiv)(GLuint index, const GLuint *v);
364 void (GLAPIENTRY *qglVertexAttribPointer)(GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, const GLvoid *pointer);
365 void (GLAPIENTRY *qglEnableVertexAttribArray)(GLuint index);
366 void (GLAPIENTRY *qglDisableVertexAttribArray)(GLuint index);
367 void (GLAPIENTRY *qglBindAttribLocation)(GLuint programObj, GLuint index, const GLchar *name);
368 void (GLAPIENTRY *qglBindFragDataLocation)(GLuint programObj, GLuint index, const GLchar *name);
369 void (GLAPIENTRY *qglGetActiveAttrib)(GLuint programObj, GLuint index, GLsizei maxLength, GLsizei *length, GLint *size, GLenum *type, GLchar *name);
370 GLint (GLAPIENTRY *qglGetAttribLocation)(GLuint programObj, const GLchar *name);
371 void (GLAPIENTRY *qglGetVertexAttribdv)(GLuint index, GLenum pname, GLdouble *params);
372 void (GLAPIENTRY *qglGetVertexAttribfv)(GLuint index, GLenum pname, GLfloat *params);
373 void (GLAPIENTRY *qglGetVertexAttribiv)(GLuint index, GLenum pname, GLint *params);
374 void (GLAPIENTRY *qglGetVertexAttribPointerv)(GLuint index, GLenum pname, GLvoid **pointer);
375
376 //GL_ARB_vertex_buffer_object
377 void (GLAPIENTRY *qglBindBuffer) (GLenum target, GLuint buffer);
378 void (GLAPIENTRY *qglDeleteBuffers) (GLsizei n, const GLuint *buffers);
379 void (GLAPIENTRY *qglGenBuffers) (GLsizei n, GLuint *buffers);
380 GLboolean (GLAPIENTRY *qglIsBuffer) (GLuint buffer);
381 GLvoid* (GLAPIENTRY *qglMapBuffer) (GLenum target, GLenum access);
382 GLboolean (GLAPIENTRY *qglUnmapBuffer) (GLenum target);
383 void (GLAPIENTRY *qglBufferData) (GLenum target, GLsizeiptrARB size, const GLvoid *data, GLenum usage);
384 void (GLAPIENTRY *qglBufferSubData) (GLenum target, GLintptrARB offset, GLsizeiptrARB size, const GLvoid *data);
385
386 //GL_ARB_framebuffer_object
387 GLboolean (GLAPIENTRY *qglIsRenderbuffer)(GLuint renderbuffer);
388 GLvoid (GLAPIENTRY *qglBindRenderbuffer)(GLenum target, GLuint renderbuffer);
389 GLvoid (GLAPIENTRY *qglDeleteRenderbuffers)(GLsizei n, const GLuint *renderbuffers);
390 GLvoid (GLAPIENTRY *qglGenRenderbuffers)(GLsizei n, GLuint *renderbuffers);
391 GLvoid (GLAPIENTRY *qglRenderbufferStorage)(GLenum target, GLenum internalformat, GLsizei width, GLsizei height);
392 GLvoid (GLAPIENTRY *qglRenderbufferStorageMultisample)(GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height);
393 GLvoid (GLAPIENTRY *qglGetRenderbufferParameteriv)(GLenum target, GLenum pname, GLint *params);
394 GLboolean (GLAPIENTRY *qglIsFramebuffer)(GLuint framebuffer);
395 GLvoid (GLAPIENTRY *qglBindFramebuffer)(GLenum target, GLuint framebuffer);
396 GLvoid (GLAPIENTRY *qglDeleteFramebuffers)(GLsizei n, const GLuint *framebuffers);
397 GLvoid (GLAPIENTRY *qglGenFramebuffers)(GLsizei n, GLuint *framebuffers);
398 GLenum (GLAPIENTRY *qglCheckFramebufferStatus)(GLenum target);
399 GLvoid (GLAPIENTRY *qglFramebufferTexture1D)(GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level);
400 GLvoid (GLAPIENTRY *qglFramebufferTexture2D)(GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level);
401 GLvoid (GLAPIENTRY *qglFramebufferTexture3D)(GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level, GLint layer);
402 GLvoid (GLAPIENTRY *qglFramebufferTextureLayer)(GLenum target, GLenum attachment, GLuint texture, GLint level, GLint layer);
403 GLvoid (GLAPIENTRY *qglFramebufferRenderbuffer)(GLenum target, GLenum attachment, GLenum renderbuffertarget, GLuint renderbuffer);
404 GLvoid (GLAPIENTRY *qglGetFramebufferAttachmentParameteriv)(GLenum target, GLenum attachment, GLenum pname, GLint *params);
405 GLvoid (GLAPIENTRY *qglBlitFramebuffer)(GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1, GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1, GLbitfield mask, GLenum filter);
406 GLvoid (GLAPIENTRY *qglGenerateMipmap)(GLenum target);
407
408 void (GLAPIENTRY *qglDrawBuffersARB)(GLsizei n, const GLenum *bufs);
409
410 void (GLAPIENTRY *qglCompressedTexImage3DARB)(GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLsizei imageSize, const void *data);
411 void (GLAPIENTRY *qglCompressedTexImage2DARB)(GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border,  GLsizei imageSize, const void *data);
412 //void (GLAPIENTRY *qglCompressedTexImage1DARB)(GLenum target, GLint level, GLenum internalformat, GLsizei width, GLint border, GLsizei imageSize, const void *data);
413 void (GLAPIENTRY *qglCompressedTexSubImage3DARB)(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLsizei imageSize, const void *data);
414 void (GLAPIENTRY *qglCompressedTexSubImage2DARB)(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLsizei imageSize, const void *data);
415 //void (GLAPIENTRY *qglCompressedTexSubImage1DARB)(GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLsizei imageSize, const void *data);
416 void (GLAPIENTRY *qglGetCompressedTexImageARB)(GLenum target, GLint lod, void *img);
417
418 void (GLAPIENTRY *qglGenQueriesARB)(GLsizei n, GLuint *ids);
419 void (GLAPIENTRY *qglDeleteQueriesARB)(GLsizei n, const GLuint *ids);
420 GLboolean (GLAPIENTRY *qglIsQueryARB)(GLuint qid);
421 void (GLAPIENTRY *qglBeginQueryARB)(GLenum target, GLuint qid);
422 void (GLAPIENTRY *qglEndQueryARB)(GLenum target);
423 void (GLAPIENTRY *qglGetQueryivARB)(GLenum target, GLenum pname, GLint *params);
424 void (GLAPIENTRY *qglGetQueryObjectivARB)(GLuint qid, GLenum pname, GLint *params);
425 void (GLAPIENTRY *qglGetQueryObjectuivARB)(GLuint qid, GLenum pname, GLuint *params);
426
427 void (GLAPIENTRY *qglSampleCoverageARB)(GLclampf value, GLboolean invert);
428
429 void (GLAPIENTRY *qglGetUniformIndices)(GLuint program, GLsizei uniformCount, const GLchar** uniformNames, GLuint* uniformIndices);
430 void (GLAPIENTRY *qglGetActiveUniformsiv)(GLuint program, GLsizei uniformCount, const GLuint* uniformIndices, GLenum pname, GLint* params);
431 void (GLAPIENTRY *qglGetActiveUniformName)(GLuint program, GLuint uniformIndex, GLsizei bufSize, GLsizei* length, GLchar* uniformName);
432 GLuint (GLAPIENTRY *qglGetUniformBlockIndex)(GLuint program, const GLchar* uniformBlockName);
433 void (GLAPIENTRY *qglGetActiveUniformBlockiv)(GLuint program, GLuint uniformBlockIndex, GLenum pname,  GLint* params);
434 void (GLAPIENTRY *qglGetActiveUniformBlockName)(GLuint program, GLuint uniformBlockIndex, GLsizei bufSize, GLsizei* length, GLchar* uniformBlockName);
435 void (GLAPIENTRY *qglBindBufferRange)(GLenum target, GLuint index, GLuint buffer, GLintptrARB offset, GLsizeiptrARB size);
436 void (GLAPIENTRY *qglBindBufferBase)(GLenum target, GLuint index, GLuint buffer);
437 void (GLAPIENTRY *qglGetIntegeri_v)(GLenum target, GLuint index, GLint* data);
438 void (GLAPIENTRY *qglUniformBlockBinding)(GLuint program, GLuint uniformBlockIndex, GLuint uniformBlockBinding);
439
440 void (GLAPIENTRY *qglBlendFuncSeparate)(GLenum sfactorRGB, GLenum dfactorRGB, GLenum sfactorAlpha, GLenum dfactorAlpha);
441 #endif
442
443 #if _MSC_VER >= 1400
444 #define sscanf sscanf_s
445 #endif
446
447 qboolean GL_CheckExtension(const char *minglver_or_ext, const dllfunction_t *funcs, const char *disableparm, int silent)
448 {
449         int failed = false;
450         const dllfunction_t *func;
451         struct { int major, minor; } min_version, curr_version;
452         char extstr[MAX_INPUTLINE];
453         int ext;
454
455         if(sscanf(minglver_or_ext, "%d.%d", &min_version.major, &min_version.minor) == 2)
456                 ext = 0; // opengl version
457         else if(minglver_or_ext[0] != toupper(minglver_or_ext[0]))
458                 ext = -1; // pseudo name
459         else
460                 ext = 1; // extension name
461
462         if (ext)
463                 Con_DPrintf("checking for %s...  ", minglver_or_ext);
464         else
465                 Con_DPrintf("checking for OpenGL %s core features...  ", minglver_or_ext);
466
467         for (func = funcs;func && func->name;func++)
468                 *func->funcvariable = NULL;
469
470         if (disableparm && (COM_CheckParm(disableparm) || COM_CheckParm("-safe")))
471         {
472                 Con_DPrint("disabled by commandline\n");
473                 return false;
474         }
475
476         if (ext == 1) // opengl extension
477         {
478                 if (!strstr(gl_extensions ? gl_extensions : "", minglver_or_ext) && !strstr(gl_platformextensions ? gl_platformextensions : "", minglver_or_ext))
479                 {
480                         Con_DPrint("not detected\n");
481                         return false;
482                 }
483         }
484
485         if(ext == 0) // opengl version
486         {
487                 if (sscanf(gl_version, "%d.%d", &curr_version.major, &curr_version.minor) < 2)
488                         curr_version.major = curr_version.minor = 1;
489
490                 if (curr_version.major < min_version.major || (curr_version.major == min_version.major && curr_version.minor < min_version.minor))
491                 {
492                         Con_DPrintf("not detected (OpenGL %d.%d loaded)\n", curr_version.major, curr_version.minor);
493                         return false;
494                 }
495         }
496
497         for (func = funcs;func && func->name != NULL;func++)
498         {
499                 // Con_DPrintf("\n    %s...  ", func->name);
500
501                 // functions are cleared before all the extensions are evaluated
502                 if (!(*func->funcvariable = (void *) GL_GetProcAddress(func->name)))
503                 {
504                         if (ext && !silent)
505                                 Con_DPrintf("%s is missing function \"%s\" - broken driver!\n", minglver_or_ext, func->name);
506                         if (!ext)
507                                 Con_Printf("OpenGL %s core features are missing function \"%s\" - broken driver!\n", minglver_or_ext, func->name);
508                         failed = true;
509                 }
510         }
511         // delay the return so it prints all missing functions
512         if (failed)
513                 return false;
514         // VorteX: add to found extension list
515         dpsnprintf(extstr, sizeof(extstr), "%s %s ", gl_info_extensions.string, minglver_or_ext);
516         Cvar_SetQuick(&gl_info_extensions, extstr);
517
518         Con_DPrint("enabled\n");
519         return true;
520 }
521
522 #ifndef USE_GLES2
523 // functions we require from the driver - some of these are OpenGL 2.0, some are a bit newer
524 static dllfunction_t openglfuncs[] =
525 {
526         {"glClearColor", (void **) &qglClearColor},
527         {"glClear", (void **) &qglClear},
528         {"glBlendFunc", (void **) &qglBlendFunc},
529         {"glCullFace", (void **) &qglCullFace},
530         {"glDrawBuffer", (void **) &qglDrawBuffer},
531         {"glReadBuffer", (void **) &qglReadBuffer},
532         {"glEnable", (void **) &qglEnable},
533         {"glDisable", (void **) &qglDisable},
534         {"glIsEnabled", (void **) &qglIsEnabled},
535         {"glGetBooleanv", (void **) &qglGetBooleanv},
536         {"glGetDoublev", (void **) &qglGetDoublev},
537         {"glGetFloatv", (void **) &qglGetFloatv},
538         {"glGetIntegerv", (void **) &qglGetIntegerv},
539         {"glGetError", (void **) &qglGetError},
540         {"glGetString", (void **) &qglGetString},
541         {"glFinish", (void **) &qglFinish},
542         {"glFlush", (void **) &qglFlush},
543         {"glClearDepth", (void **) &qglClearDepth},
544         {"glDepthFunc", (void **) &qglDepthFunc},
545         {"glDepthMask", (void **) &qglDepthMask},
546         {"glDepthRange", (void **) &qglDepthRange},
547         {"glDrawElements", (void **) &qglDrawElements},
548         {"glDrawArrays", (void **) &qglDrawArrays},
549         {"glColorMask", (void **) &qglColorMask},
550         {"glPointSize", (void**) &qglPointSize},
551         {"glViewport", (void **) &qglViewport},
552         {"glReadPixels", (void **) &qglReadPixels},
553         {"glStencilFunc", (void **) &qglStencilFunc},
554         {"glStencilMask", (void **) &qglStencilMask},
555         {"glStencilOp", (void **) &qglStencilOp},
556         {"glClearStencil", (void **) &qglClearStencil},
557         {"glTexParameterf", (void **) &qglTexParameterf},
558         {"glTexParameterfv", (void **) &qglTexParameterfv},
559         {"glTexParameteri", (void **) &qglTexParameteri},
560         {"glGetTexImage", (void **) &qglGetTexImage},
561         {"glGetTexParameterfv", (void **) &qglGetTexParameterfv},
562         {"glGetTexParameteriv", (void **) &qglGetTexParameteriv},
563         {"glGetTexLevelParameterfv", (void **) &qglGetTexLevelParameterfv},
564         {"glGetTexLevelParameteriv", (void **) &qglGetTexLevelParameteriv},
565         {"glHint", (void **) &qglHint},
566         {"glPixelStorei", (void **) &qglPixelStorei},
567         {"glGenTextures", (void **) &qglGenTextures},
568         {"glDeleteTextures", (void **) &qglDeleteTextures},
569         {"glBindTexture", (void **) &qglBindTexture},
570         {"glTexImage2D", (void **) &qglTexImage2D},
571         {"glTexSubImage2D", (void **) &qglTexSubImage2D},
572         {"glCopyTexImage2D", (void **) &qglCopyTexImage2D},
573         {"glCopyTexSubImage2D", (void **) &qglCopyTexSubImage2D},
574         {"glScissor", (void **) &qglScissor},
575         {"glPolygonOffset", (void **) &qglPolygonOffset},
576         {"glPolygonMode", (void **) &qglPolygonMode},
577         {"glActiveTexture", (void **) &qglActiveTexture},
578         {"glTexImage3D", (void **) &qglTexImage3D},
579         {"glTexSubImage3D", (void **) &qglTexSubImage3D},
580         {"glCopyTexSubImage3D", (void **) &qglCopyTexSubImage3D},
581         {"glDeleteShader", (void **) &qglDeleteShader},
582         {"glDeleteProgram", (void **) &qglDeleteProgram},
583         {"glDetachShader", (void **) &qglDetachShader},
584         {"glCreateShader", (void **) &qglCreateShader},
585         {"glShaderSource", (void **) &qglShaderSource},
586         {"glCompileShader", (void **) &qglCompileShader},
587         {"glCreateProgram", (void **) &qglCreateProgram},
588         {"glAttachShader", (void **) &qglAttachShader},
589         {"glLinkProgram", (void **) &qglLinkProgram},
590         {"glUseProgram", (void **) &qglUseProgram},
591         {"glValidateProgram", (void **) &qglValidateProgram},
592         {"glUniform1f", (void **) &qglUniform1f},
593         {"glUniform2f", (void **) &qglUniform2f},
594         {"glUniform3f", (void **) &qglUniform3f},
595         {"glUniform4f", (void **) &qglUniform4f},
596         {"glUniform1i", (void **) &qglUniform1i},
597         {"glUniform2i", (void **) &qglUniform2i},
598         {"glUniform3i", (void **) &qglUniform3i},
599         {"glUniform4i", (void **) &qglUniform4i},
600         {"glUniform1fv", (void **) &qglUniform1fv},
601         {"glUniform2fv", (void **) &qglUniform2fv},
602         {"glUniform3fv", (void **) &qglUniform3fv},
603         {"glUniform4fv", (void **) &qglUniform4fv},
604         {"glUniform1iv", (void **) &qglUniform1iv},
605         {"glUniform2iv", (void **) &qglUniform2iv},
606         {"glUniform3iv", (void **) &qglUniform3iv},
607         {"glUniform4iv", (void **) &qglUniform4iv},
608         {"glUniformMatrix2fv", (void **) &qglUniformMatrix2fv},
609         {"glUniformMatrix3fv", (void **) &qglUniformMatrix3fv},
610         {"glUniformMatrix4fv", (void **) &qglUniformMatrix4fv},
611         {"glGetShaderiv", (void **) &qglGetShaderiv},
612         {"glGetProgramiv", (void **) &qglGetProgramiv},
613         {"glGetShaderInfoLog", (void **) &qglGetShaderInfoLog},
614         {"glGetProgramInfoLog", (void **) &qglGetProgramInfoLog},
615         {"glGetAttachedShaders", (void **) &qglGetAttachedShaders},
616         {"glGetUniformLocation", (void **) &qglGetUniformLocation},
617         {"glGetActiveUniform", (void **) &qglGetActiveUniform},
618         {"glGetUniformfv", (void **) &qglGetUniformfv},
619         {"glGetUniformiv", (void **) &qglGetUniformiv},
620         {"glGetShaderSource", (void **) &qglGetShaderSource},
621         {"glVertexAttrib1f", (void **) &qglVertexAttrib1f},
622         {"glVertexAttrib1s", (void **) &qglVertexAttrib1s},
623         {"glVertexAttrib1d", (void **) &qglVertexAttrib1d},
624         {"glVertexAttrib2f", (void **) &qglVertexAttrib2f},
625         {"glVertexAttrib2s", (void **) &qglVertexAttrib2s},
626         {"glVertexAttrib2d", (void **) &qglVertexAttrib2d},
627         {"glVertexAttrib3f", (void **) &qglVertexAttrib3f},
628         {"glVertexAttrib3s", (void **) &qglVertexAttrib3s},
629         {"glVertexAttrib3d", (void **) &qglVertexAttrib3d},
630         {"glVertexAttrib4f", (void **) &qglVertexAttrib4f},
631         {"glVertexAttrib4s", (void **) &qglVertexAttrib4s},
632         {"glVertexAttrib4d", (void **) &qglVertexAttrib4d},
633         {"glVertexAttrib4Nub", (void **) &qglVertexAttrib4Nub},
634         {"glVertexAttrib1fv", (void **) &qglVertexAttrib1fv},
635         {"glVertexAttrib1sv", (void **) &qglVertexAttrib1sv},
636         {"glVertexAttrib1dv", (void **) &qglVertexAttrib1dv},
637         {"glVertexAttrib2fv", (void **) &qglVertexAttrib1fv},
638         {"glVertexAttrib2sv", (void **) &qglVertexAttrib1sv},
639         {"glVertexAttrib2dv", (void **) &qglVertexAttrib1dv},
640         {"glVertexAttrib3fv", (void **) &qglVertexAttrib1fv},
641         {"glVertexAttrib3sv", (void **) &qglVertexAttrib1sv},
642         {"glVertexAttrib3dv", (void **) &qglVertexAttrib1dv},
643         {"glVertexAttrib4fv", (void **) &qglVertexAttrib1fv},
644         {"glVertexAttrib4sv", (void **) &qglVertexAttrib1sv},
645         {"glVertexAttrib4dv", (void **) &qglVertexAttrib1dv},
646 //      {"glVertexAttrib4iv", (void **) &qglVertexAttrib1iv},
647 //      {"glVertexAttrib4bv", (void **) &qglVertexAttrib1bv},
648 //      {"glVertexAttrib4ubv", (void **) &qglVertexAttrib1ubv},
649 //      {"glVertexAttrib4usv", (void **) &qglVertexAttrib1usv},
650 //      {"glVertexAttrib4uiv", (void **) &qglVertexAttrib1uiv},
651 //      {"glVertexAttrib4Nbv", (void **) &qglVertexAttrib1Nbv},
652 //      {"glVertexAttrib4Nsv", (void **) &qglVertexAttrib1Nsv},
653 //      {"glVertexAttrib4Niv", (void **) &qglVertexAttrib1Niv},
654 //      {"glVertexAttrib4Nubv", (void **) &qglVertexAttrib1Nubv},
655 //      {"glVertexAttrib4Nusv", (void **) &qglVertexAttrib1Nusv},
656 //      {"glVertexAttrib4Nuiv", (void **) &qglVertexAttrib1Nuiv},
657         {"glVertexAttribPointer", (void **) &qglVertexAttribPointer},
658         {"glEnableVertexAttribArray", (void **) &qglEnableVertexAttribArray},
659         {"glDisableVertexAttribArray", (void **) &qglDisableVertexAttribArray},
660         {"glBindAttribLocation", (void **) &qglBindAttribLocation},
661         {"glGetActiveAttrib", (void **) &qglGetActiveAttrib},
662         {"glGetAttribLocation", (void **) &qglGetAttribLocation},
663         {"glGetVertexAttribdv", (void **) &qglGetVertexAttribdv},
664         {"glGetVertexAttribfv", (void **) &qglGetVertexAttribfv},
665         {"glGetVertexAttribiv", (void **) &qglGetVertexAttribiv},
666         {"glGetVertexAttribPointerv", (void **) &qglGetVertexAttribPointerv},
667         {"glBindBuffer"    , (void **) &qglBindBuffer},
668         {"glDeleteBuffers" , (void **) &qglDeleteBuffers},
669         {"glGenBuffers"    , (void **) &qglGenBuffers},
670         {"glIsBuffer"      , (void **) &qglIsBuffer},
671         {"glMapBuffer"     , (void **) &qglMapBuffer},
672         {"glUnmapBuffer"   , (void **) &qglUnmapBuffer},
673         {"glBufferData"    , (void **) &qglBufferData},
674         {"glBufferSubData" , (void **) &qglBufferSubData},
675         {"glIsRenderbuffer"                      , (void **) &qglIsRenderbuffer},
676         {"glBindRenderbuffer"                    , (void **) &qglBindRenderbuffer},
677         {"glDeleteRenderbuffers"                 , (void **) &qglDeleteRenderbuffers},
678         {"glGenRenderbuffers"                    , (void **) &qglGenRenderbuffers},
679         {"glRenderbufferStorage"                 , (void **) &qglRenderbufferStorage},
680         {"glRenderbufferStorageMultisample"      , (void **) &qglRenderbufferStorageMultisample},
681         {"glGetRenderbufferParameteriv"          , (void **) &qglGetRenderbufferParameteriv},
682         {"glIsFramebuffer"                       , (void **) &qglIsFramebuffer},
683         {"glBindFramebuffer"                     , (void **) &qglBindFramebuffer},
684         {"glDeleteFramebuffers"                  , (void **) &qglDeleteFramebuffers},
685         {"glGenFramebuffers"                     , (void **) &qglGenFramebuffers},
686         {"glCheckFramebufferStatus"              , (void **) &qglCheckFramebufferStatus},
687         {"glFramebufferTexture1D"                , (void **) &qglFramebufferTexture1D},
688         {"glFramebufferTexture2D"                , (void **) &qglFramebufferTexture2D},
689         {"glFramebufferTexture3D"                , (void **) &qglFramebufferTexture3D},
690         {"glFramebufferTextureLayer"             , (void **) &qglFramebufferTextureLayer},
691         {"glFramebufferRenderbuffer"             , (void **) &qglFramebufferRenderbuffer},
692         {"glGetFramebufferAttachmentParameteriv" , (void **) &qglGetFramebufferAttachmentParameteriv},
693         {"glBlitFramebuffer"                     , (void **) &qglBlitFramebuffer},
694         {"glGenerateMipmap"                      , (void **) &qglGenerateMipmap},
695         {"glGetUniformIndices"        , (void **) &qglGetUniformIndices},
696         {"glGetActiveUniformsiv"      , (void **) &qglGetActiveUniformsiv},
697         {"glGetActiveUniformName"     , (void **) &qglGetActiveUniformName},
698         {"glGetUniformBlockIndex"     , (void **) &qglGetUniformBlockIndex},
699         {"glGetActiveUniformBlockiv"  , (void **) &qglGetActiveUniformBlockiv},
700         {"glGetActiveUniformBlockName", (void **) &qglGetActiveUniformBlockName},
701         {"glBindBufferRange"          , (void **) &qglBindBufferRange},
702         {"glBindBufferBase"           , (void **) &qglBindBufferBase},
703         {"glGetIntegeri_v"            , (void **) &qglGetIntegeri_v},
704         {"glUniformBlockBinding"      , (void **) &qglUniformBlockBinding},
705         {NULL, NULL}
706 };
707
708 static dllfunction_t blendequationfuncs[] =
709 {
710         {"glBlendEquationEXT", (void **) &qglBlendEquationEXT},
711         {NULL, NULL}
712 };
713
714 static dllfunction_t glsl130funcs[] =
715 {
716         {"glBindFragDataLocation", (void **) &qglBindFragDataLocation},
717         {NULL, NULL}
718 };
719
720 static dllfunction_t texturecompressionfuncs[] =
721 {
722         {"glCompressedTexImage3DARB",    (void **) &qglCompressedTexImage3DARB},
723         {"glCompressedTexImage2DARB",    (void **) &qglCompressedTexImage2DARB},
724         {"glCompressedTexSubImage3DARB", (void **) &qglCompressedTexSubImage3DARB},
725         {"glCompressedTexSubImage2DARB", (void **) &qglCompressedTexSubImage2DARB},
726         {"glGetCompressedTexImageARB",   (void **) &qglGetCompressedTexImageARB},
727         {NULL, NULL}
728 };
729
730 static dllfunction_t occlusionqueryfuncs[] =
731 {
732         {"glGenQueriesARB",              (void **) &qglGenQueriesARB},
733         {"glDeleteQueriesARB",           (void **) &qglDeleteQueriesARB},
734         {"glIsQueryARB",                 (void **) &qglIsQueryARB},
735         {"glBeginQueryARB",              (void **) &qglBeginQueryARB},
736         {"glEndQueryARB",                (void **) &qglEndQueryARB},
737         {"glGetQueryivARB",              (void **) &qglGetQueryivARB},
738         {"glGetQueryObjectivARB",        (void **) &qglGetQueryObjectivARB},
739         {"glGetQueryObjectuivARB",       (void **) &qglGetQueryObjectuivARB},
740         {NULL, NULL}
741 };
742
743 static dllfunction_t drawbuffersfuncs[] =
744 {
745         {"glDrawBuffersARB",             (void **) &qglDrawBuffersARB},
746         {NULL, NULL}
747 };
748
749 static dllfunction_t multisamplefuncs[] =
750 {
751         {"glSampleCoverageARB",          (void **) &qglSampleCoverageARB},
752         {NULL, NULL}
753 };
754
755 static dllfunction_t blendfuncseparatefuncs[] =
756 {
757         {"glBlendFuncSeparateEXT", (void **) &qglBlendFuncSeparate},
758         {NULL, NULL}
759 };
760
761 #endif
762
763 void VID_ClearExtensions(void)
764 {
765         // VorteX: reset extensions info cvar, it got filled by GL_CheckExtension
766         Cvar_SetQuick(&gl_info_extensions, "");
767
768         // clear the extension flags
769         memset(&vid.support, 0, sizeof(vid.support));
770         vid.renderpath = RENDERPATH_GL32;
771         vid.sRGBcapable2D = false;
772         vid.sRGBcapable3D = false;
773         vid.maxtexturesize_2d = 0;
774         vid.maxtexturesize_3d = 0;
775         vid.maxtexturesize_cubemap = 0;
776         vid.texunits = 1;
777         vid.teximageunits = 1;
778         vid.texarrayunits = 1;
779         vid.max_anisotropy = 1;
780         vid.maxdrawbuffers = 1;
781
782 #ifndef USE_GLES2
783         // this is a complete list of all functions that are directly checked in the renderer
784         qglDrawBuffer = NULL;
785         qglFlush = NULL;
786         qglGetCompressedTexImageARB = NULL;
787         qglFramebufferTexture2D = NULL;
788         qglDrawBuffersARB = NULL;
789 #endif
790 }
791
792 #ifndef USE_GLES2
793 void VID_CheckExtensions(void)
794 {
795         char *s;
796         if (!GL_CheckExtension("glbase", openglfuncs, NULL, false))
797                 Sys_Error("OpenGL driver/hardware lacks required features");
798
799         CHECKGLERROR
800
801         Con_DPrint("Checking OpenGL extensions...\n");
802
803         // detect what GLSL version is available, to enable features like r_glsl_skeletal and higher quality reliefmapping
804         vid.support.glshaderversion = 100;
805         s = (char *) qglGetString(GL_SHADING_LANGUAGE_VERSION);
806         if (s)
807                 vid.support.glshaderversion = (int)(atof(s) * 100.0f + 0.5f);
808         if (vid.support.glshaderversion < 100)
809                 vid.support.glshaderversion = 100;
810         Con_DPrintf("Detected GLSL #version %i\n", vid.support.glshaderversion);
811         // get the glBindFragDataLocation function
812         if (vid.support.glshaderversion >= 130)
813                 vid.support.gl20shaders130 = GL_CheckExtension("glshaders130", glsl130funcs, "-noglsl130", true);
814
815         // GL drivers generally prefer GL_BGRA
816         vid.forcetextype = GL_BGRA;
817
818         vid.support.amd_texture_texture4 = GL_CheckExtension("GL_AMD_texture_texture4", NULL, "-notexture4", false);
819         vid.support.arb_draw_buffers = GL_CheckExtension("GL_ARB_draw_buffers", drawbuffersfuncs, "-nodrawbuffers", false);
820         vid.support.arb_occlusion_query = GL_CheckExtension("GL_ARB_occlusion_query", occlusionqueryfuncs, "-noocclusionquery", false);
821         vid.support.arb_query_buffer_object = GL_CheckExtension("GL_ARB_query_buffer_object", NULL, "-noquerybuffer", true);
822         vid.support.arb_texture_compression = GL_CheckExtension("GL_ARB_texture_compression", texturecompressionfuncs, "-notexturecompression", false);
823         vid.support.arb_texture_gather = GL_CheckExtension("GL_ARB_texture_gather", NULL, "-notexturegather", false);
824         vid.support.ext_blend_minmax = GL_CheckExtension("GL_EXT_blend_minmax", blendequationfuncs, "-noblendminmax", false);
825         vid.support.ext_blend_subtract = GL_CheckExtension("GL_EXT_blend_subtract", blendequationfuncs, "-noblendsubtract", false);
826         vid.support.ext_blend_func_separate = GL_CheckExtension("GL_EXT_blend_func_separate", blendfuncseparatefuncs, "-noblendfuncseparate", false);
827         vid.support.ext_packed_depth_stencil = GL_CheckExtension("GL_EXT_packed_depth_stencil", NULL, "-nopackeddepthstencil", false);
828         vid.support.ext_texture_compression_s3tc = GL_CheckExtension("GL_EXT_texture_compression_s3tc", NULL, "-nos3tc", false);
829         vid.support.ext_texture_filter_anisotropic = GL_CheckExtension("GL_EXT_texture_filter_anisotropic", NULL, "-noanisotropy", false);
830         vid.support.ext_texture_srgb = GL_CheckExtension("GL_EXT_texture_sRGB", NULL, "-nosrgb", false);
831         vid.support.arb_texture_float = GL_CheckExtension("GL_ARB_texture_float", NULL, "-notexturefloat", false);
832         vid.support.arb_half_float_pixel = GL_CheckExtension("GL_ARB_half_float_pixel", NULL, "-nohalffloatpixel", false);
833         vid.support.arb_half_float_vertex = GL_CheckExtension("GL_ARB_half_float_vertex", NULL, "-nohalffloatvertex", false);
834         vid.support.arb_multisample = GL_CheckExtension("GL_ARB_multisample", multisamplefuncs, "-nomultisample", false);
835         vid.allowalphatocoverage = false;
836
837 // COMMANDLINEOPTION: GL: -noshaders disables use of OpenGL 2.0 shaders (which allow pixel shader effects, can improve per pixel lighting performance and capabilities)
838 // COMMANDLINEOPTION: GL: -noanisotropy disables GL_EXT_texture_filter_anisotropic (allows higher quality texturing)
839 // COMMANDLINEOPTION: GL: -noblendminmax disables GL_EXT_blend_minmax
840 // COMMANDLINEOPTION: GL: -noblendsubtract disables GL_EXT_blend_subtract
841 // COMMANDLINEOPTION: GL: -nocombine disables GL_ARB_texture_env_combine or GL_EXT_texture_env_combine (required for bumpmapping and faster map rendering)
842 // COMMANDLINEOPTION: GL: -nocubemap disables GL_ARB_texture_cube_map (required for bumpmapping)
843 // COMMANDLINEOPTION: GL: -nodepthtexture disables use of GL_ARB_depth_texture (required for shadowmapping)
844 // COMMANDLINEOPTION: GL: -nodrawbuffers disables use of GL_ARB_draw_buffers (required for r_shadow_deferredprepass)
845 // COMMANDLINEOPTION: GL: -nodrawrangeelements disables GL_EXT_draw_range_elements (renders faster)
846 // COMMANDLINEOPTION: GL: -noedgeclamp disables GL_EXT_texture_edge_clamp or GL_SGIS_texture_edge_clamp (recommended, some cards do not support the other texture clamp method)
847 // COMMANDLINEOPTION: GL: -nofbo disables GL_EXT_framebuffer_object (which accelerates rendering), only used if GL_ARB_fragment_shader is also available
848 // COMMANDLINEOPTION: GL: -nomtex disables GL_ARB_multitexture (required for faster map rendering)
849 // COMMANDLINEOPTION: GL: -noocclusionquery disables GL_ARB_occlusion_query (which allows coronas to fade according to visibility, and potentially used for rendering optimizations)
850 // COMMANDLINEOPTION: GL: -noquerybuffer disables GL_ARB_query_buffer_object (which allows corona fading without synchronous rendering)
851 // COMMANDLINEOPTION: GL: -nos3tc disables GL_EXT_texture_compression_s3tc (which allows use of .dds texture caching)
852 // COMMANDLINEOPTION: GL: -noshadow disables use of GL_ARB_shadow (required for hardware shadowmap filtering)
853 // COMMANDLINEOPTION: GL: -notexture3d disables GL_EXT_texture3D (required for spherical lights, otherwise they render as a column)
854 // COMMANDLINEOPTION: GL: -notexture4 disables GL_AMD_texture_texture4 (which provides fetch4 sampling)
855 // COMMANDLINEOPTION: GL: -notexturecompression disables GL_ARB_texture_compression (which saves video memory if it is supported, but can also degrade image quality, see gl_texturecompression cvar documentation for more information)
856 // COMMANDLINEOPTION: GL: -notexturegather disables GL_ARB_texture_gather (which provides fetch4 sampling)
857 // COMMANDLINEOPTION: GL: -notexturenonpoweroftwo disables GL_ARB_texture_non_power_of_two (which saves video memory if it is supported, but crashes on some buggy drivers)
858 // COMMANDLINEOPTION: GL: -novbo disables GL_ARB_vertex_buffer_object (which accelerates rendering)
859 // COMMANDLINEOPTION: GL: -nosrgb disables GL_EXT_texture_sRGB (which is used for higher quality non-linear texture gamma)
860 // COMMANDLINEOPTION: GL: -nomultisample disables GL_ARB_multisample
861
862         if (vid.support.arb_draw_buffers)
863                 qglGetIntegerv(GL_MAX_DRAW_BUFFERS_ARB, (GLint*)&vid.maxdrawbuffers);
864
865         qglGetIntegerv(GL_MAX_TEXTURE_SIZE, (GLint*)&vid.maxtexturesize_2d);
866         qglGetIntegerv(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, (GLint*)&vid.max_anisotropy);
867         qglGetIntegerv(GL_MAX_CUBE_MAP_TEXTURE_SIZE, (GLint*)&vid.maxtexturesize_cubemap);
868         qglGetIntegerv(GL_MAX_3D_TEXTURE_SIZE, (GLint*)&vid.maxtexturesize_3d);
869
870         vid.texunits = 4;
871         vid.teximageunits = 32;
872         vid.texarrayunits = 10;
873         vid.renderpath = RENDERPATH_GL32;
874         vid.sRGBcapable2D = false;
875         vid.sRGBcapable3D = true;
876         vid.allowalphatocoverage = true; // but see below, it may get turned to false again if GL_SAMPLES_ARB is <= 1
877
878         // enable multisample antialiasing if possible
879         if(vid.support.arb_multisample)
880         {
881                 int samples = 0;
882                 qglGetIntegerv(GL_SAMPLES_ARB, &samples);
883                 vid.samples = samples;
884                 if (samples > 1)
885                         qglEnable(GL_MULTISAMPLE_ARB);
886                 else
887                         vid.allowalphatocoverage = false;
888         }
889         else
890         {
891                 vid.allowalphatocoverage = false;
892                 vid.samples = 1;
893         }
894
895         // VorteX: set other info (maybe place them in VID_InitMode?)
896         Cvar_SetQuick(&gl_info_vendor, gl_vendor);
897         Cvar_SetQuick(&gl_info_renderer, gl_renderer);
898         Cvar_SetQuick(&gl_info_version, gl_version);
899         Cvar_SetQuick(&gl_info_platform, gl_platform ? gl_platform : "");
900         Cvar_SetQuick(&gl_info_driver, gl_driver);
901 }
902 #endif
903
904 float VID_JoyState_GetAxis(const vid_joystate_t *joystate, int axis, float fsensitivity, float deadzone)
905 {
906         float value;
907         value = (axis >= 0 && axis < MAXJOYAXIS) ? joystate->axis[axis] : 0.0f;
908         value = value > deadzone ? (value - deadzone) : (value < -deadzone ? (value + deadzone) : 0.0f);
909         value *= deadzone > 0 ? (1.0f / (1.0f - deadzone)) : 1.0f;
910         value = bound(-1, value, 1);
911         return value * fsensitivity;
912 }
913
914 qboolean VID_JoyBlockEmulatedKeys(int keycode)
915 {
916         int j;
917         vid_joystate_t joystate;
918
919         if (!joy_axiskeyevents.integer)
920                 return false;
921         if (vid_joystate.is360)
922                 return false;
923         if (keycode != K_UPARROW && keycode != K_DOWNARROW && keycode != K_RIGHTARROW && keycode != K_LEFTARROW)
924                 return false;
925
926         // block system-generated key events for arrow keys if we're emulating the arrow keys ourselves
927         VID_BuildJoyState(&joystate);
928         for (j = 32;j < 36;j++)
929                 if (vid_joystate.button[j] || joystate.button[j])
930                         return true;
931
932         return false;
933 }
934
935 void VID_Shared_BuildJoyState_Begin(vid_joystate_t *joystate)
936 {
937 #ifdef WIN32
938         xinput_state_t xinputstate;
939 #endif
940         memset(joystate, 0, sizeof(*joystate));
941 #ifdef WIN32
942         if (vid_xinputindex >= 0 && qXInputGetState && qXInputGetState(vid_xinputindex, &xinputstate) == S_OK)
943         {
944                 joystate->is360 = true;
945                 joystate->button[ 0] = (xinputstate.Gamepad.wButtons & XINPUT_GAMEPAD_DPAD_UP) != 0;
946                 joystate->button[ 1] = (xinputstate.Gamepad.wButtons & XINPUT_GAMEPAD_DPAD_DOWN) != 0;
947                 joystate->button[ 2] = (xinputstate.Gamepad.wButtons & XINPUT_GAMEPAD_DPAD_LEFT) != 0;
948                 joystate->button[ 3] = (xinputstate.Gamepad.wButtons & XINPUT_GAMEPAD_DPAD_RIGHT) != 0;
949                 joystate->button[ 4] = (xinputstate.Gamepad.wButtons & XINPUT_GAMEPAD_START) != 0;
950                 joystate->button[ 5] = (xinputstate.Gamepad.wButtons & XINPUT_GAMEPAD_BACK) != 0;
951                 joystate->button[ 6] = (xinputstate.Gamepad.wButtons & XINPUT_GAMEPAD_LEFT_THUMB) != 0;
952                 joystate->button[ 7] = (xinputstate.Gamepad.wButtons & XINPUT_GAMEPAD_RIGHT_THUMB) != 0;
953                 joystate->button[ 8] = (xinputstate.Gamepad.wButtons & XINPUT_GAMEPAD_LEFT_SHOULDER) != 0;
954                 joystate->button[ 9] = (xinputstate.Gamepad.wButtons & XINPUT_GAMEPAD_RIGHT_SHOULDER) != 0;
955                 joystate->button[10] = (xinputstate.Gamepad.wButtons & XINPUT_GAMEPAD_A) != 0;
956                 joystate->button[11] = (xinputstate.Gamepad.wButtons & XINPUT_GAMEPAD_B) != 0;
957                 joystate->button[12] = (xinputstate.Gamepad.wButtons & XINPUT_GAMEPAD_X) != 0;
958                 joystate->button[13] = (xinputstate.Gamepad.wButtons & XINPUT_GAMEPAD_Y) != 0;
959                 joystate->button[14] = xinputstate.Gamepad.bLeftTrigger >= XINPUT_GAMEPAD_TRIGGER_THRESHOLD;
960                 joystate->button[15] = xinputstate.Gamepad.bRightTrigger >= XINPUT_GAMEPAD_TRIGGER_THRESHOLD;
961                 joystate->button[16] = xinputstate.Gamepad.sThumbLY < -16384;
962                 joystate->button[17] = xinputstate.Gamepad.sThumbLY >  16384;
963                 joystate->button[18] = xinputstate.Gamepad.sThumbLX < -16384;
964                 joystate->button[19] = xinputstate.Gamepad.sThumbLX >  16384;
965                 joystate->button[20] = xinputstate.Gamepad.sThumbRY < -16384;
966                 joystate->button[21] = xinputstate.Gamepad.sThumbRY >  16384;
967                 joystate->button[22] = xinputstate.Gamepad.sThumbRX < -16384;
968                 joystate->button[23] = xinputstate.Gamepad.sThumbRX >  16384;
969                 joystate->axis[ 4] = xinputstate.Gamepad.bLeftTrigger * (1.0f / 255.0f);
970                 joystate->axis[ 5] = xinputstate.Gamepad.bRightTrigger * (1.0f / 255.0f);
971                 joystate->axis[ 0] = xinputstate.Gamepad.sThumbLX * (1.0f / 32767.0f);
972                 joystate->axis[ 1] = xinputstate.Gamepad.sThumbLY * (1.0f / 32767.0f);
973                 joystate->axis[ 2] = xinputstate.Gamepad.sThumbRX * (1.0f / 32767.0f);
974                 joystate->axis[ 3] = xinputstate.Gamepad.sThumbRY * (1.0f / 32767.0f);
975         }
976 #endif
977 }
978
979 void VID_Shared_BuildJoyState_Finish(vid_joystate_t *joystate)
980 {
981         float f, r;
982         if (joystate->is360)
983                 return;
984         // emulate key events for thumbstick
985         f = VID_JoyState_GetAxis(joystate, joy_axisforward.integer, 1, joy_axiskeyevents_deadzone.value) * joy_sensitivityforward.value;
986         r = VID_JoyState_GetAxis(joystate, joy_axisside.integer   , 1, joy_axiskeyevents_deadzone.value) * joy_sensitivityside.value;
987 #if MAXJOYBUTTON != 36
988 #error this code must be updated if MAXJOYBUTTON changes!
989 #endif
990         joystate->button[32] = f > 0.0f;
991         joystate->button[33] = f < 0.0f;
992         joystate->button[34] = r > 0.0f;
993         joystate->button[35] = r < 0.0f;
994 }
995
996 static void VID_KeyEventForButton(qboolean oldbutton, qboolean newbutton, int key, double *timer)
997 {
998         if (oldbutton)
999         {
1000                 if (newbutton)
1001                 {
1002                         if (realtime >= *timer)
1003                         {
1004                                 Key_Event(key, 0, true);
1005                                 *timer = realtime + 0.1;
1006                         }
1007                 }
1008                 else
1009                 {
1010                         Key_Event(key, 0, false);
1011                         *timer = 0;
1012                 }
1013         }
1014         else
1015         {
1016                 if (newbutton)
1017                 {
1018                         Key_Event(key, 0, true);
1019                         *timer = realtime + 0.5;
1020                 }
1021         }
1022 }
1023
1024 #if MAXJOYBUTTON != 36
1025 #error this code must be updated if MAXJOYBUTTON changes!
1026 #endif
1027 static int joybuttonkey[MAXJOYBUTTON][2] =
1028 {
1029         {K_JOY1, K_ENTER}, {K_JOY2, K_ESCAPE}, {K_JOY3, 0}, {K_JOY4, 0}, {K_JOY5, 0}, {K_JOY6, 0}, {K_JOY7, 0}, {K_JOY8, 0}, {K_JOY9, 0}, {K_JOY10, 0}, {K_JOY11, 0}, {K_JOY12, 0}, {K_JOY13, 0}, {K_JOY14, 0}, {K_JOY15, 0}, {K_JOY16, 0},
1030         {K_AUX1, 0}, {K_AUX2, 0}, {K_AUX3, 0}, {K_AUX4, 0}, {K_AUX5, 0}, {K_AUX6, 0}, {K_AUX7, 0}, {K_AUX8, 0}, {K_AUX9, 0}, {K_AUX10, 0}, {K_AUX11, 0}, {K_AUX12, 0}, {K_AUX13, 0}, {K_AUX14, 0}, {K_AUX15, 0}, {K_AUX16, 0},
1031         {K_JOY_UP, K_UPARROW}, {K_JOY_DOWN, K_DOWNARROW}, {K_JOY_RIGHT, K_RIGHTARROW}, {K_JOY_LEFT, K_LEFTARROW},
1032 };
1033
1034 static int joybuttonkey360[][2] =
1035 {
1036         {K_X360_DPAD_UP, K_UPARROW},
1037         {K_X360_DPAD_DOWN, K_DOWNARROW},
1038         {K_X360_DPAD_LEFT, K_LEFTARROW},
1039         {K_X360_DPAD_RIGHT, K_RIGHTARROW},
1040         {K_X360_START, K_ESCAPE},
1041         {K_X360_BACK, K_ESCAPE},
1042         {K_X360_LEFT_THUMB, 0},
1043         {K_X360_RIGHT_THUMB, 0},
1044         {K_X360_LEFT_SHOULDER, 0},
1045         {K_X360_RIGHT_SHOULDER, 0},
1046         {K_X360_A, K_ENTER},
1047         {K_X360_B, K_ESCAPE},
1048         {K_X360_X, 0},
1049         {K_X360_Y, 0},
1050         {K_X360_LEFT_TRIGGER, 0},
1051         {K_X360_RIGHT_TRIGGER, 0},
1052         {K_X360_LEFT_THUMB_DOWN, K_DOWNARROW},
1053         {K_X360_LEFT_THUMB_UP, K_UPARROW},
1054         {K_X360_LEFT_THUMB_LEFT, K_LEFTARROW},
1055         {K_X360_LEFT_THUMB_RIGHT, K_RIGHTARROW},
1056         {K_X360_RIGHT_THUMB_DOWN, 0},
1057         {K_X360_RIGHT_THUMB_UP, 0},
1058         {K_X360_RIGHT_THUMB_LEFT, 0},
1059         {K_X360_RIGHT_THUMB_RIGHT, 0},
1060 };
1061
1062 double vid_joybuttontimer[MAXJOYBUTTON];
1063 void VID_ApplyJoyState(vid_joystate_t *joystate)
1064 {
1065         int j;
1066         int c = joy_axiskeyevents.integer != 0;
1067         if (joystate->is360)
1068         {
1069 #if 0
1070                 // keystrokes (chatpad)
1071                 // DOES NOT WORK - no driver support in xinput1_3.dll :(
1072                 xinput_keystroke_t keystroke;
1073                 while (qXInputGetKeystroke && qXInputGetKeystroke(XUSER_INDEX_ANY, 0, &keystroke) == S_OK)
1074                         Con_Printf("XInput KeyStroke: VirtualKey %i, Unicode %i, Flags %x, UserIndex %i, HidCode %i\n", keystroke.VirtualKey, keystroke.Unicode, keystroke.Flags, keystroke.UserIndex, keystroke.HidCode);
1075 #endif
1076
1077                 // emit key events for buttons
1078                 for (j = 0;j < (int)(sizeof(joybuttonkey360)/sizeof(joybuttonkey360[0]));j++)
1079                         VID_KeyEventForButton(vid_joystate.button[j] != 0, joystate->button[j] != 0, joybuttonkey360[j][c], &vid_joybuttontimer[j]);
1080
1081                 // axes
1082                 cl.cmd.forwardmove += VID_JoyState_GetAxis(joystate, joy_x360_axisforward.integer, joy_x360_sensitivityforward.value, joy_x360_deadzoneforward.value) * cl_forwardspeed.value;
1083                 cl.cmd.sidemove    += VID_JoyState_GetAxis(joystate, joy_x360_axisside.integer, joy_x360_sensitivityside.value, joy_x360_deadzoneside.value) * cl_sidespeed.value;
1084                 cl.cmd.upmove      += VID_JoyState_GetAxis(joystate, joy_x360_axisup.integer, joy_x360_sensitivityup.value, joy_x360_deadzoneup.value) * cl_upspeed.value;
1085                 cl.viewangles[0]   += VID_JoyState_GetAxis(joystate, joy_x360_axispitch.integer, joy_x360_sensitivitypitch.value, joy_x360_deadzonepitch.value) * cl.realframetime * cl_pitchspeed.value;
1086                 cl.viewangles[1]   += VID_JoyState_GetAxis(joystate, joy_x360_axisyaw.integer, joy_x360_sensitivityyaw.value, joy_x360_deadzoneyaw.value) * cl.realframetime * cl_yawspeed.value;
1087                 //cl.viewangles[2]   += VID_JoyState_GetAxis(joystate, joy_x360_axisroll.integer, joy_x360_sensitivityroll.value, joy_x360_deadzoneroll.value) * cl.realframetime * cl_rollspeed.value;
1088         }
1089         else
1090         {
1091                 // emit key events for buttons
1092                 for (j = 0;j < MAXJOYBUTTON;j++)
1093                         VID_KeyEventForButton(vid_joystate.button[j] != 0, joystate->button[j] != 0, joybuttonkey[j][c], &vid_joybuttontimer[j]);
1094
1095                 // axes
1096                 cl.cmd.forwardmove += VID_JoyState_GetAxis(joystate, joy_axisforward.integer, joy_sensitivityforward.value, joy_deadzoneforward.value) * cl_forwardspeed.value;
1097                 cl.cmd.sidemove    += VID_JoyState_GetAxis(joystate, joy_axisside.integer, joy_sensitivityside.value, joy_deadzoneside.value) * cl_sidespeed.value;
1098                 cl.cmd.upmove      += VID_JoyState_GetAxis(joystate, joy_axisup.integer, joy_sensitivityup.value, joy_deadzoneup.value) * cl_upspeed.value;
1099                 cl.viewangles[0]   += VID_JoyState_GetAxis(joystate, joy_axispitch.integer, joy_sensitivitypitch.value, joy_deadzonepitch.value) * cl.realframetime * cl_pitchspeed.value;
1100                 cl.viewangles[1]   += VID_JoyState_GetAxis(joystate, joy_axisyaw.integer, joy_sensitivityyaw.value, joy_deadzoneyaw.value) * cl.realframetime * cl_yawspeed.value;
1101                 //cl.viewangles[2]   += VID_JoyState_GetAxis(joystate, joy_axisroll.integer, joy_sensitivityroll.value, joy_deadzoneroll.value) * cl.realframetime * cl_rollspeed.value;
1102         }
1103
1104         vid_joystate = *joystate;
1105 }
1106
1107 int VID_Shared_SetJoystick(int index)
1108 {
1109 #ifdef WIN32
1110         int i;
1111         int xinputcount = 0;
1112         int xinputindex = -1;
1113         int xinputavailable = 0;
1114         xinput_state_t state;
1115         // detect available XInput controllers
1116         for (i = 0;i < 4;i++)
1117         {
1118                 if (qXInputGetState && qXInputGetState(i, &state) == S_OK)
1119                 {
1120                         xinputavailable |= 1<<i;
1121                         if (index == xinputcount)
1122                                 xinputindex = i;
1123                         xinputcount++;
1124                 }
1125         }
1126         if (joy_xinputavailable.integer != xinputavailable)
1127                 Cvar_SetValueQuick(&joy_xinputavailable, xinputavailable);
1128         if (vid_xinputindex != xinputindex)
1129         {
1130                 vid_xinputindex = xinputindex;
1131                 if (xinputindex >= 0)
1132                         Con_Printf("Joystick %i opened (XInput Device %i)\n", index, xinputindex);
1133         }
1134         return xinputcount;
1135 #else
1136         return 0;
1137 #endif
1138 }
1139
1140
1141 static void Force_CenterView_f (void)
1142 {
1143         cl.viewangles[PITCH] = 0;
1144 }
1145
1146 static int gamma_forcenextframe = false;
1147 static float cachegamma, cachebrightness, cachecontrast, cacheblack[3], cachegrey[3], cachewhite[3], cachecontrastboost;
1148 static int cachecolorenable;
1149
1150 void VID_ApplyGammaToColor(const float *rgb, float *out)
1151 {
1152         int i;
1153         if (cachecolorenable)
1154         {
1155                 for (i = 0; i < 3; i++)
1156                         out[i] = pow(cachecontrastboost * rgb[i] / ((cachecontrastboost - 1) * rgb[i] + 1), 1.0 / invpow(0.5, 1 - cachegrey[i])) * cachewhite[i] + cacheblack[i];
1157         }
1158         else
1159         {
1160                 for (i = 0; i < 3; i++)
1161                         out[i] = pow(cachecontrastboost * rgb[i] / ((cachecontrastboost - 1) * rgb[i] + 1), 1.0 / cachegamma) * cachecontrast + cachebrightness;
1162         }
1163 }
1164
1165 unsigned int vid_gammatables_serial = 0; // so other subsystems can poll if gamma parameters have changed
1166 qboolean vid_gammatables_trivial = true;
1167 void VID_BuildGammaTables(unsigned short *ramps, int rampsize)
1168 {
1169         if (cachecolorenable)
1170         {
1171                 BuildGammaTable16(1.0f, invpow(0.5, 1 - cachegrey[0]), cachewhite[0], cacheblack[0], cachecontrastboost, ramps, rampsize);
1172                 BuildGammaTable16(1.0f, invpow(0.5, 1 - cachegrey[1]), cachewhite[1], cacheblack[1], cachecontrastboost, ramps + rampsize, rampsize);
1173                 BuildGammaTable16(1.0f, invpow(0.5, 1 - cachegrey[2]), cachewhite[2], cacheblack[2], cachecontrastboost, ramps + rampsize*2, rampsize);
1174         }
1175         else
1176         {
1177                 BuildGammaTable16(1.0f, cachegamma, cachecontrast, cachebrightness, cachecontrastboost, ramps, rampsize);
1178                 BuildGammaTable16(1.0f, cachegamma, cachecontrast, cachebrightness, cachecontrastboost, ramps + rampsize, rampsize);
1179                 BuildGammaTable16(1.0f, cachegamma, cachecontrast, cachebrightness, cachecontrastboost, ramps + rampsize*2, rampsize);
1180         }
1181
1182         if(vid.sRGB2D || vid.sRGB3D)
1183         {
1184                 int i;
1185                 for(i = 0; i < 3*rampsize; ++i)
1186                         ramps[i] = (int)floor(bound(0.0f, Image_sRGBFloatFromLinearFloat(ramps[i] / 65535.0f), 1.0f) * 65535.0f + 0.5f);
1187         }
1188
1189         // LordHavoc: this code came from Ben Winslow and Zinx Verituse, I have
1190         // immensely butchered it to work with variable framerates and fit in with
1191         // the rest of darkplaces.
1192         //
1193         // R.I.P. zinx http://obits.al.com/obituaries/birmingham/obituary.aspx?n=christopher-robert-lais&pid=186080667
1194         if (v_psycho.integer)
1195         {
1196                 int x, y;
1197                 float t;
1198                 static float n[3], nd[3], nt[3];
1199                 static int init = true;
1200                 unsigned short *ramp;
1201                 gamma_forcenextframe = true;
1202                 if (init)
1203                 {
1204                         init = false;
1205                         for (x = 0;x < 3;x++)
1206                         {
1207                                 n[x] = lhrandom(0, 1);
1208                                 nd[x] = (rand()&1)?-0.25:0.25;
1209                                 nt[x] = lhrandom(1, 8.2);
1210                         }
1211                 }
1212
1213                 for (x = 0;x < 3;x++)
1214                 {
1215                         nt[x] -= cl.realframetime;
1216                         if (nt[x] < 0)
1217                         {
1218                                 nd[x] = -nd[x];
1219                                 nt[x] += lhrandom(1, 8.2);
1220                         }
1221                         n[x] += nd[x] * cl.realframetime;
1222                         n[x] -= floor(n[x]);
1223                 }
1224
1225                 for (x = 0, ramp = ramps;x < 3;x++)
1226                         for (y = 0, t = n[x] - 0.75f;y < rampsize;y++, t += 0.75f * (2.0f / rampsize))
1227                                 *ramp++ = (unsigned short)(cos(t*(M_PI*2.0)) * 32767.0f + 32767.0f);
1228         }
1229 }
1230
1231 void VID_UpdateGamma(void)
1232 {
1233         cvar_t *c;
1234         float f;
1235         qboolean gamma_changed = false;
1236
1237 #define BOUNDCVAR(cvar, m1, m2) c = &(cvar);f = bound(m1, c->value, m2);if (c->value != f) Cvar_SetValueQuick(c, f);
1238         BOUNDCVAR(v_gamma, 0.1, 5);
1239         BOUNDCVAR(v_contrast, 0.2, 5);
1240         BOUNDCVAR(v_brightness, -v_contrast.value * 0.8, 0.8);
1241         //BOUNDCVAR(v_contrastboost, 0.0625, 16);
1242         BOUNDCVAR(v_color_black_r, 0, 0.8);
1243         BOUNDCVAR(v_color_black_g, 0, 0.8);
1244         BOUNDCVAR(v_color_black_b, 0, 0.8);
1245         BOUNDCVAR(v_color_grey_r, 0, 0.95);
1246         BOUNDCVAR(v_color_grey_g, 0, 0.95);
1247         BOUNDCVAR(v_color_grey_b, 0, 0.95);
1248         BOUNDCVAR(v_color_white_r, 1, 5);
1249         BOUNDCVAR(v_color_white_g, 1, 5);
1250         BOUNDCVAR(v_color_white_b, 1, 5);
1251 #undef BOUNDCVAR
1252
1253         // set vid_gammatables_trivial to true if the current settings would generate the identity gamma table
1254         vid_gammatables_trivial = false;
1255         if(v_psycho.integer == 0)
1256         if(v_contrastboost.value == 1)
1257         if(!vid.sRGB2D)
1258         if(!vid.sRGB3D)
1259         {
1260                 if(v_color_enable.integer)
1261                 {
1262                         if(v_color_black_r.value == 0)
1263                         if(v_color_black_g.value == 0)
1264                         if(v_color_black_b.value == 0)
1265                         if(fabs(v_color_grey_r.value - 0.5) < 1e-6)
1266                         if(fabs(v_color_grey_g.value - 0.5) < 1e-6)
1267                         if(fabs(v_color_grey_b.value - 0.5) < 1e-6)
1268                         if(v_color_white_r.value == 1)
1269                         if(v_color_white_g.value == 1)
1270                         if(v_color_white_b.value == 1)
1271                                 vid_gammatables_trivial = true;
1272                 }
1273                 else
1274                 {
1275                         if(v_gamma.value == 1)
1276                         if(v_contrast.value == 1)
1277                         if(v_brightness.value == 0)
1278                                 vid_gammatables_trivial = true;
1279                 }
1280         }
1281
1282         // if any gamma settings were changed, bump vid_gammatables_serial so we regenerate the gamma ramp texture
1283 #define GAMMACHECK(cache, value) if (cache != (value)) gamma_changed = true;cache = (value)
1284         if(v_psycho.integer)
1285                 gamma_changed = true;
1286         GAMMACHECK(cachegamma      , v_gamma.value);
1287         GAMMACHECK(cachecontrast   , v_contrast.value);
1288         GAMMACHECK(cachebrightness , v_brightness.value);
1289         GAMMACHECK(cachecontrastboost, v_contrastboost.value);
1290         GAMMACHECK(cachecolorenable, v_color_enable.integer);
1291         GAMMACHECK(cacheblack[0]   , v_color_black_r.value);
1292         GAMMACHECK(cacheblack[1]   , v_color_black_g.value);
1293         GAMMACHECK(cacheblack[2]   , v_color_black_b.value);
1294         GAMMACHECK(cachegrey[0]    , v_color_grey_r.value);
1295         GAMMACHECK(cachegrey[1]    , v_color_grey_g.value);
1296         GAMMACHECK(cachegrey[2]    , v_color_grey_b.value);
1297         GAMMACHECK(cachewhite[0]   , v_color_white_r.value);
1298         GAMMACHECK(cachewhite[1]   , v_color_white_g.value);
1299         GAMMACHECK(cachewhite[2]   , v_color_white_b.value);
1300
1301         if(gamma_changed)
1302                 ++vid_gammatables_serial;
1303 #undef GAMMACHECK
1304 }
1305
1306 #ifdef WIN32
1307 static dllfunction_t xinputdllfuncs[] =
1308 {
1309         {"XInputGetState", (void **) &qXInputGetState},
1310         {"XInputGetKeystroke", (void **) &qXInputGetKeystroke},
1311         {NULL, NULL}
1312 };
1313 static const char* xinputdllnames [] =
1314 {
1315         "xinput1_3.dll",
1316         "xinput1_2.dll",
1317         "xinput1_1.dll",
1318         NULL
1319 };
1320 static dllhandle_t xinputdll_dll = NULL;
1321 #endif
1322
1323 void VID_Shared_Init(void)
1324 {
1325         Cvar_RegisterVariable(&gl_info_vendor);
1326         Cvar_RegisterVariable(&gl_info_renderer);
1327         Cvar_RegisterVariable(&gl_info_version);
1328         Cvar_RegisterVariable(&gl_info_extensions);
1329         Cvar_RegisterVariable(&gl_info_platform);
1330         Cvar_RegisterVariable(&gl_info_driver);
1331         Cvar_RegisterVariable(&v_gamma);
1332         Cvar_RegisterVariable(&v_brightness);
1333         Cvar_RegisterVariable(&v_contrastboost);
1334         Cvar_RegisterVariable(&v_contrast);
1335
1336         Cvar_RegisterVariable(&v_color_enable);
1337         Cvar_RegisterVariable(&v_color_black_r);
1338         Cvar_RegisterVariable(&v_color_black_g);
1339         Cvar_RegisterVariable(&v_color_black_b);
1340         Cvar_RegisterVariable(&v_color_grey_r);
1341         Cvar_RegisterVariable(&v_color_grey_g);
1342         Cvar_RegisterVariable(&v_color_grey_b);
1343         Cvar_RegisterVariable(&v_color_white_r);
1344         Cvar_RegisterVariable(&v_color_white_g);
1345         Cvar_RegisterVariable(&v_color_white_b);
1346
1347         Cvar_RegisterVariable(&v_glslgamma_2d);
1348
1349         Cvar_RegisterVariable(&v_psycho);
1350
1351         Cvar_RegisterVariable(&vid_fullscreen);
1352         Cvar_RegisterVariable(&vid_width);
1353         Cvar_RegisterVariable(&vid_height);
1354         Cvar_RegisterVariable(&vid_bitsperpixel);
1355         Cvar_RegisterVariable(&vid_samples);
1356         Cvar_RegisterVariable(&vid_refreshrate);
1357         Cvar_RegisterVariable(&vid_userefreshrate);
1358         Cvar_RegisterVariable(&vid_stereobuffer);
1359         Cvar_RegisterVariable(&vid_touchscreen_density);
1360         Cvar_RegisterVariable(&vid_touchscreen_xdpi);
1361         Cvar_RegisterVariable(&vid_touchscreen_ydpi);
1362         Cvar_RegisterVariable(&vid_vsync);
1363         Cvar_RegisterVariable(&vid_mouse);
1364         Cvar_RegisterVariable(&vid_grabkeyboard);
1365         Cvar_RegisterVariable(&vid_touchscreen);
1366         Cvar_RegisterVariable(&vid_touchscreen_showkeyboard);
1367         Cvar_RegisterVariable(&vid_touchscreen_supportshowkeyboard);
1368         Cvar_RegisterVariable(&vid_stick_mouse);
1369         Cvar_RegisterVariable(&vid_resizable);
1370         Cvar_RegisterVariable(&vid_desktopfullscreen);
1371         Cvar_RegisterVariable(&vid_minwidth);
1372         Cvar_RegisterVariable(&vid_minheight);
1373         Cvar_RegisterVariable(&gl_finish);
1374         Cvar_RegisterVariable(&vid_sRGB);
1375         Cvar_RegisterVariable(&vid_sRGB_fallback);
1376
1377         Cvar_RegisterVariable(&joy_active);
1378 #ifdef WIN32
1379         Cvar_RegisterVariable(&joy_xinputavailable);
1380 #endif
1381         Cvar_RegisterVariable(&joy_detected);
1382         Cvar_RegisterVariable(&joy_enable);
1383         Cvar_RegisterVariable(&joy_index);
1384         Cvar_RegisterVariable(&joy_axisforward);
1385         Cvar_RegisterVariable(&joy_axisside);
1386         Cvar_RegisterVariable(&joy_axisup);
1387         Cvar_RegisterVariable(&joy_axispitch);
1388         Cvar_RegisterVariable(&joy_axisyaw);
1389         //Cvar_RegisterVariable(&joy_axisroll);
1390         Cvar_RegisterVariable(&joy_deadzoneforward);
1391         Cvar_RegisterVariable(&joy_deadzoneside);
1392         Cvar_RegisterVariable(&joy_deadzoneup);
1393         Cvar_RegisterVariable(&joy_deadzonepitch);
1394         Cvar_RegisterVariable(&joy_deadzoneyaw);
1395         //Cvar_RegisterVariable(&joy_deadzoneroll);
1396         Cvar_RegisterVariable(&joy_sensitivityforward);
1397         Cvar_RegisterVariable(&joy_sensitivityside);
1398         Cvar_RegisterVariable(&joy_sensitivityup);
1399         Cvar_RegisterVariable(&joy_sensitivitypitch);
1400         Cvar_RegisterVariable(&joy_sensitivityyaw);
1401         //Cvar_RegisterVariable(&joy_sensitivityroll);
1402         Cvar_RegisterVariable(&joy_axiskeyevents);
1403         Cvar_RegisterVariable(&joy_axiskeyevents_deadzone);
1404         Cvar_RegisterVariable(&joy_x360_axisforward);
1405         Cvar_RegisterVariable(&joy_x360_axisside);
1406         Cvar_RegisterVariable(&joy_x360_axisup);
1407         Cvar_RegisterVariable(&joy_x360_axispitch);
1408         Cvar_RegisterVariable(&joy_x360_axisyaw);
1409         //Cvar_RegisterVariable(&joy_x360_axisroll);
1410         Cvar_RegisterVariable(&joy_x360_deadzoneforward);
1411         Cvar_RegisterVariable(&joy_x360_deadzoneside);
1412         Cvar_RegisterVariable(&joy_x360_deadzoneup);
1413         Cvar_RegisterVariable(&joy_x360_deadzonepitch);
1414         Cvar_RegisterVariable(&joy_x360_deadzoneyaw);
1415         //Cvar_RegisterVariable(&joy_x360_deadzoneroll);
1416         Cvar_RegisterVariable(&joy_x360_sensitivityforward);
1417         Cvar_RegisterVariable(&joy_x360_sensitivityside);
1418         Cvar_RegisterVariable(&joy_x360_sensitivityup);
1419         Cvar_RegisterVariable(&joy_x360_sensitivitypitch);
1420         Cvar_RegisterVariable(&joy_x360_sensitivityyaw);
1421         //Cvar_RegisterVariable(&joy_x360_sensitivityroll);
1422
1423 #ifdef WIN32
1424         Sys_LoadLibrary(xinputdllnames, &xinputdll_dll, xinputdllfuncs);
1425 #endif
1426
1427         Cmd_AddCommand("force_centerview", Force_CenterView_f, "recenters view (stops looking up/down)");
1428         Cmd_AddCommand("vid_restart", VID_Restart_f, "restarts video system (closes and reopens the window, restarts renderer)");
1429 }
1430
1431 static int VID_Mode(int fullscreen, int width, int height, int bpp, float refreshrate, int stereobuffer, int samples)
1432 {
1433         viddef_mode_t mode;
1434         char vabuf[1024];
1435
1436         memset(&mode, 0, sizeof(mode));
1437         mode.fullscreen = fullscreen != 0;
1438         mode.width = width;
1439         mode.height = height;
1440         mode.bitsperpixel = bpp;
1441         mode.refreshrate = vid_userefreshrate.integer ? max(1, refreshrate) : 0;
1442         mode.userefreshrate = vid_userefreshrate.integer != 0;
1443         mode.stereobuffer = stereobuffer != 0;
1444         mode.samples = samples;
1445         cl_ignoremousemoves = 2;
1446         VID_ClearExtensions();
1447
1448         vid.samples = vid.mode.samples;
1449         if (VID_InitMode(&mode))
1450         {
1451                 // accept the (possibly modified) mode
1452                 vid.mode = mode;
1453                 vid.fullscreen     = vid.mode.fullscreen;
1454                 vid.width          = vid.mode.width;
1455                 vid.height         = vid.mode.height;
1456                 vid.bitsperpixel   = vid.mode.bitsperpixel;
1457                 vid.refreshrate    = vid.mode.refreshrate;
1458                 vid.userefreshrate = vid.mode.userefreshrate;
1459                 vid.stereobuffer   = vid.mode.stereobuffer;
1460                 vid.stencil        = vid.mode.bitsperpixel > 16;
1461                 vid.sRGB2D         = vid_sRGB.integer >= 1 && vid.sRGBcapable2D;
1462                 vid.sRGB3D         = vid_sRGB.integer >= 1 && vid.sRGBcapable3D;
1463
1464                 switch(vid.renderpath)
1465                 {
1466                 case RENDERPATH_GL32:
1467 #ifdef GL_STEREO
1468                         {
1469                                 GLboolean stereo;
1470                                 qglGetBooleanv(GL_STEREO, &stereo);
1471                                 vid.stereobuffer = stereo != 0;
1472                         }
1473 #endif
1474                         break;
1475                 case RENDERPATH_GLES2:
1476                 default:
1477                         vid.stereobuffer = false;
1478                         break;
1479                 }
1480
1481                 if(
1482                         (vid_sRGB_fallback.integer >= 3) // force fallback
1483                         ||
1484                         (vid_sRGB_fallback.integer >= 2 && // fallback if framebuffer is 8bit
1485                                 r_viewfbo.integer < 2)
1486                 )
1487                         vid.sRGB2D = vid.sRGB3D = false;
1488
1489                 if(vid.samples != vid.mode.samples)
1490                         Con_Printf("NOTE: requested %dx AA, got %dx AA\n", vid.mode.samples, vid.samples);
1491
1492                 Con_Printf("Video Mode: %s %dx%dx%dx%.2fhz%s%s\n", mode.fullscreen ? "fullscreen" : "window", mode.width, mode.height, mode.bitsperpixel, mode.refreshrate, mode.stereobuffer ? " stereo" : "", mode.samples > 1 ? va(vabuf, sizeof(vabuf), " (%ix AA)", mode.samples) : "");
1493
1494                 Cvar_SetValueQuick(&vid_fullscreen, vid.mode.fullscreen);
1495                 Cvar_SetValueQuick(&vid_width, vid.mode.width);
1496                 Cvar_SetValueQuick(&vid_height, vid.mode.height);
1497                 Cvar_SetValueQuick(&vid_bitsperpixel, vid.mode.bitsperpixel);
1498                 Cvar_SetValueQuick(&vid_samples, vid.mode.samples);
1499                 if(vid_userefreshrate.integer)
1500                         Cvar_SetValueQuick(&vid_refreshrate, vid.mode.refreshrate);
1501                 Cvar_SetValueQuick(&vid_stereobuffer, vid.stereobuffer ? 1 : 0);
1502
1503                 if (vid_touchscreen.integer)
1504                 {
1505                         in_windowmouse_x = vid_width.value / 2.f;
1506                         in_windowmouse_y = vid_height.value / 2.f;
1507                 }
1508
1509                 return true;
1510         }
1511         else
1512                 return false;
1513 }
1514
1515 static void VID_OpenSystems(void)
1516 {
1517         Key_ReleaseAll();
1518         R_Modules_Start();
1519         S_Startup();
1520 }
1521
1522 static void VID_CloseSystems(void)
1523 {
1524         S_Shutdown();
1525         R_Modules_Shutdown();
1526         Key_ReleaseAll();
1527 }
1528
1529 qboolean vid_commandlinecheck = true;
1530 extern qboolean vid_opened;
1531
1532 void VID_Restart_f(void)
1533 {
1534         char vabuf[1024];
1535         char vabuf2[1024];
1536         // don't crash if video hasn't started yet
1537         if (vid_commandlinecheck)
1538                 return;
1539
1540         if (!vid_opened)
1541         {
1542                 SCR_BeginLoadingPlaque(false);
1543                 return;
1544         }
1545
1546         Con_Printf("VID_Restart: changing from %s %dx%dx%dbpp%s%s, to %s %dx%dx%dbpp%s%s.\n",
1547                 vid.mode.fullscreen ? "fullscreen" : "window", vid.mode.width, vid.mode.height, vid.mode.bitsperpixel, vid.mode.fullscreen && vid.mode.userefreshrate ? va(vabuf, sizeof(vabuf), "x%.2fhz", vid.mode.refreshrate) : "", vid.mode.samples > 1 ? va(vabuf2, sizeof(vabuf2), " (%ix AA)", vid.mode.samples) : "",
1548                 vid_fullscreen.integer ? "fullscreen" : "window", vid_width.integer, vid_height.integer, vid_bitsperpixel.integer, vid_fullscreen.integer && vid_userefreshrate.integer ? va(vabuf, sizeof(vabuf), "x%.2fhz", vid_refreshrate.value) : "", vid_samples.integer > 1 ? va(vabuf2, sizeof(vabuf2), " (%ix AA)", vid_samples.integer) : "");
1549         VID_CloseSystems();
1550         VID_Shutdown();
1551         if (!VID_Mode(vid_fullscreen.integer, vid_width.integer, vid_height.integer, vid_bitsperpixel.integer, vid_refreshrate.value, vid_stereobuffer.integer, vid_samples.integer))
1552         {
1553                 Con_Print("Video mode change failed\n");
1554                 if (!VID_Mode(vid.mode.fullscreen, vid.mode.width, vid.mode.height, vid.mode.bitsperpixel, vid.mode.refreshrate, vid.mode.stereobuffer, vid.mode.samples))
1555                         Sys_Error("Unable to restore to last working video mode");
1556         }
1557         VID_OpenSystems();
1558 }
1559
1560 const char *vidfallbacks[][2] =
1561 {
1562         {"vid_stereobuffer", "0"},
1563         {"vid_samples", "1"},
1564         {"vid_userefreshrate", "0"},
1565         {"vid_width", "640"},
1566         {"vid_height", "480"},
1567         {"vid_bitsperpixel", "32"},
1568         {NULL, NULL}
1569 };
1570
1571 // this is only called once by Host_StartVideo and again on each FS_GameDir_f
1572 void VID_Start(void)
1573 {
1574         int i, width, height, success;
1575         if (vid_commandlinecheck)
1576         {
1577                 // interpret command-line parameters
1578                 vid_commandlinecheck = false;
1579 // COMMANDLINEOPTION: Video: -window performs +vid_fullscreen 0
1580                 if (COM_CheckParm("-window") || COM_CheckParm("-safe"))
1581                         Cvar_SetValueQuick(&vid_fullscreen, false);
1582 // COMMANDLINEOPTION: Video: -fullscreen performs +vid_fullscreen 1
1583                 if (COM_CheckParm("-fullscreen"))
1584                         Cvar_SetValueQuick(&vid_fullscreen, true);
1585                 width = 0;
1586                 height = 0;
1587 // COMMANDLINEOPTION: Video: -width <pixels> performs +vid_width <pixels> and also +vid_height <pixels*3/4> if only -width is specified (example: -width 1024 sets 1024x768 mode)
1588                 if ((i = COM_CheckParm("-width")) != 0)
1589                         width = atoi(com_argv[i+1]);
1590 // COMMANDLINEOPTION: Video: -height <pixels> performs +vid_height <pixels> and also +vid_width <pixels*4/3> if only -height is specified (example: -height 768 sets 1024x768 mode)
1591                 if ((i = COM_CheckParm("-height")) != 0)
1592                         height = atoi(com_argv[i+1]);
1593                 if (width == 0)
1594                         width = height * 4 / 3;
1595                 if (height == 0)
1596                         height = width * 3 / 4;
1597                 if (width)
1598                         Cvar_SetValueQuick(&vid_width, width);
1599                 if (height)
1600                         Cvar_SetValueQuick(&vid_height, height);
1601 // COMMANDLINEOPTION: Video: -density <multiplier> performs +vid_touchscreen_density <multiplier> (example -density 1 or -density 1.5)
1602                 if ((i = COM_CheckParm("-density")) != 0)
1603                         Cvar_SetQuick(&vid_touchscreen_density, com_argv[i+1]);
1604 // COMMANDLINEOPTION: Video: -xdpi <dpi> performs +vid_touchscreen_xdpi <dpi> (example -xdpi 160 or -xdpi 320)
1605                 if ((i = COM_CheckParm("-touchscreen_xdpi")) != 0)
1606                         Cvar_SetQuick(&vid_touchscreen_xdpi, com_argv[i+1]);
1607 // COMMANDLINEOPTION: Video: -ydpi <dpi> performs +vid_touchscreen_ydpi <dpi> (example -ydpi 160 or -ydpi 320)
1608                 if ((i = COM_CheckParm("-touchscreen_ydpi")) != 0)
1609                         Cvar_SetQuick(&vid_touchscreen_ydpi, com_argv[i+1]);
1610         }
1611
1612         success = VID_Mode(vid_fullscreen.integer, vid_width.integer, vid_height.integer, vid_bitsperpixel.integer, vid_refreshrate.value, vid_stereobuffer.integer, vid_samples.integer);
1613         if (!success)
1614         {
1615                 Con_Print("Desired video mode fail, trying fallbacks...\n");
1616                 for (i = 0;!success && vidfallbacks[i][0] != NULL;i++)
1617                 {
1618                         Cvar_Set(vidfallbacks[i][0], vidfallbacks[i][1]);
1619                         success = VID_Mode(vid_fullscreen.integer, vid_width.integer, vid_height.integer, vid_bitsperpixel.integer, vid_refreshrate.value, vid_stereobuffer.integer, vid_samples.integer);
1620                 }
1621                 if (!success)
1622                         Sys_Error("Video modes failed");
1623         }
1624         VID_OpenSystems();
1625 }
1626
1627 void VID_Stop(void)
1628 {
1629         VID_CloseSystems();
1630         VID_Shutdown();
1631 }
1632
1633 static int VID_SortModes_Compare(const void *a_, const void *b_)
1634 {
1635         vid_mode_t *a = (vid_mode_t *) a_;
1636         vid_mode_t *b = (vid_mode_t *) b_;
1637         if(a->width > b->width)
1638                 return +1;
1639         if(a->width < b->width)
1640                 return -1;
1641         if(a->height > b->height)
1642                 return +1;
1643         if(a->height < b->height)
1644                 return -1;
1645         if(a->refreshrate > b->refreshrate)
1646                 return +1;
1647         if(a->refreshrate < b->refreshrate)
1648                 return -1;
1649         if(a->bpp > b->bpp)
1650                 return +1;
1651         if(a->bpp < b->bpp)
1652                 return -1;
1653         if(a->pixelheight_num * b->pixelheight_denom > a->pixelheight_denom * b->pixelheight_num)
1654                 return +1;
1655         if(a->pixelheight_num * b->pixelheight_denom < a->pixelheight_denom * b->pixelheight_num)
1656                 return -1;
1657         return 0;
1658 }
1659 size_t VID_SortModes(vid_mode_t *modes, size_t count, qboolean usebpp, qboolean userefreshrate, qboolean useaspect)
1660 {
1661         size_t i;
1662         if(count == 0)
1663                 return 0;
1664         // 1. sort them
1665         qsort(modes, count, sizeof(*modes), VID_SortModes_Compare);
1666         // 2. remove duplicates
1667         for(i = 0; i < count; ++i)
1668         {
1669                 if(modes[i].width && modes[i].height)
1670                 {
1671                         if(i == 0)
1672                                 continue;
1673                         if(modes[i].width != modes[i-1].width)
1674                                 continue;
1675                         if(modes[i].height != modes[i-1].height)
1676                                 continue;
1677                         if(userefreshrate)
1678                                 if(modes[i].refreshrate != modes[i-1].refreshrate)
1679                                         continue;
1680                         if(usebpp)
1681                                 if(modes[i].bpp != modes[i-1].bpp)
1682                                         continue;
1683                         if(useaspect)
1684                                 if(modes[i].pixelheight_num * modes[i-1].pixelheight_denom != modes[i].pixelheight_denom * modes[i-1].pixelheight_num)
1685                                         continue;
1686                 }
1687                 // a dupe, or a bogus mode!
1688                 if(i < count-1)
1689                         memmove(&modes[i], &modes[i+1], sizeof(*modes) * (count-1 - i));
1690                 --i; // check this index again, as mode i+1 is now here
1691                 --count;
1692         }
1693         return count;
1694 }