]> git.xonotic.org Git - xonotic/darkplaces.git/blob - vid_sdl.c
Windows: opt out of DPI scaling
[xonotic/darkplaces.git] / vid_sdl.c
1 /*
2 Copyright (C) 2003  T. Joseph Carter
3
4 This program is free software; you can redistribute it and/or
5 modify it under the terms of the GNU General Public License
6 as published by the Free Software Foundation; either version 2
7 of the License, or (at your option) any later version.
8
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
12
13 See the GNU General Public License for more details.
14
15 You should have received a copy of the GNU General Public License
16 along with this program; if not, write to the Free Software
17 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
18 */
19 #undef WIN32_LEAN_AND_MEAN  //hush a warning, SDL.h redefines this
20 #include <SDL.h>
21 #include <stdio.h>
22
23 #include "quakedef.h"
24 #include "image.h"
25 #include "utf8lib.h"
26
27 #ifndef __IPHONEOS__
28 #ifdef MACOSX
29 #include <Carbon/Carbon.h>
30 #include <IOKit/hidsystem/IOHIDLib.h>
31 #include <IOKit/hidsystem/IOHIDParameter.h>
32 #include <IOKit/hidsystem/event_status_driver.h>
33 #if (MAC_OS_X_VERSION_MIN_REQUIRED < 120000)
34         #define IOMainPort IOMasterPort
35 #endif
36 static cvar_t apple_mouse_noaccel = {CF_CLIENT | CF_ARCHIVE, "apple_mouse_noaccel", "1", "disables mouse acceleration while DarkPlaces is active"};
37 static qbool vid_usingnoaccel;
38 static double originalMouseSpeed = -1.0;
39 static io_connect_t IN_GetIOHandle(void)
40 {
41         io_connect_t iohandle = MACH_PORT_NULL;
42         kern_return_t status;
43         io_service_t iohidsystem = MACH_PORT_NULL;
44         mach_port_t masterport;
45
46         status = IOMainPort(MACH_PORT_NULL, &masterport);
47         if(status != KERN_SUCCESS)
48                 return 0;
49
50         iohidsystem = IORegistryEntryFromPath(masterport, kIOServicePlane ":/IOResources/IOHIDSystem");
51         if(!iohidsystem)
52                 return 0;
53
54         status = IOServiceOpen(iohidsystem, mach_task_self(), kIOHIDParamConnectType, &iohandle);
55         IOObjectRelease(iohidsystem);
56
57         return iohandle;
58 }
59 #endif
60 #endif
61
62 #ifdef WIN32
63 #define SDL_R_RESTART
64 #endif
65
66 // Tell startup code that we have a client
67 int cl_available = true;
68
69 qbool vid_supportrefreshrate = false;
70
71 static qbool vid_usingmouse = false;
72 static qbool vid_usingmouse_relativeworks = false; // SDL2 workaround for unimplemented RelativeMouse mode
73 static qbool vid_usinghidecursor = false;
74 static qbool vid_hasfocus = false;
75 static qbool vid_wmborder_waiting, vid_wmborderless;
76 static SDL_Joystick *vid_sdljoystick = NULL;
77 static SDL_GameController *vid_sdlgamecontroller = NULL;
78 static cvar_t joy_sdl2_trigger_deadzone = {CF_ARCHIVE | CF_CLIENT, "joy_sdl2_trigger_deadzone", "0.5", "deadzone for triggers to be registered as key presses"};
79 // GAME_STEELSTORM specific
80 static cvar_t *steelstorm_showing_map = NULL; // detect but do not create the cvar
81 static cvar_t *steelstorm_showing_mousecursor = NULL; // detect but do not create the cvar
82
83 static int win_half_width = 50;
84 static int win_half_height = 50;
85
86 static SDL_GLContext context;
87 static SDL_Window *window;
88
89 // Input handling
90
91 #ifndef SDLK_PERCENT
92 #define SDLK_PERCENT '%'
93 #endif
94
95 static int MapKey( unsigned int sdlkey )
96 {
97         switch(sdlkey)
98         {
99         // sdlkey can be Unicode codepoint for non-ascii keys, which are valid
100         default:                      return sdlkey & SDLK_SCANCODE_MASK ? 0 : sdlkey;
101 //      case SDLK_UNKNOWN:            return K_UNKNOWN;
102         case SDLK_RETURN:             return K_ENTER;
103         case SDLK_ESCAPE:             return K_ESCAPE;
104         case SDLK_BACKSPACE:          return K_BACKSPACE;
105         case SDLK_TAB:                return K_TAB;
106         case SDLK_SPACE:              return K_SPACE;
107         case SDLK_EXCLAIM:            return '!';
108         case SDLK_QUOTEDBL:           return '"';
109         case SDLK_HASH:               return '#';
110         case SDLK_PERCENT:            return '%';
111         case SDLK_DOLLAR:             return '$';
112         case SDLK_AMPERSAND:          return '&';
113         case SDLK_QUOTE:              return '\'';
114         case SDLK_LEFTPAREN:          return '(';
115         case SDLK_RIGHTPAREN:         return ')';
116         case SDLK_ASTERISK:           return '*';
117         case SDLK_PLUS:               return '+';
118         case SDLK_COMMA:              return ',';
119         case SDLK_MINUS:              return '-';
120         case SDLK_PERIOD:             return '.';
121         case SDLK_SLASH:              return '/';
122         case SDLK_0:                  return '0';
123         case SDLK_1:                  return '1';
124         case SDLK_2:                  return '2';
125         case SDLK_3:                  return '3';
126         case SDLK_4:                  return '4';
127         case SDLK_5:                  return '5';
128         case SDLK_6:                  return '6';
129         case SDLK_7:                  return '7';
130         case SDLK_8:                  return '8';
131         case SDLK_9:                  return '9';
132         case SDLK_COLON:              return ':';
133         case SDLK_SEMICOLON:          return ';';
134         case SDLK_LESS:               return '<';
135         case SDLK_EQUALS:             return '=';
136         case SDLK_GREATER:            return '>';
137         case SDLK_QUESTION:           return '?';
138         case SDLK_AT:                 return '@';
139         case SDLK_LEFTBRACKET:        return '[';
140         case SDLK_BACKSLASH:          return '\\';
141         case SDLK_RIGHTBRACKET:       return ']';
142         case SDLK_CARET:              return '^';
143         case SDLK_UNDERSCORE:         return '_';
144         case SDLK_BACKQUOTE:          return '`';
145         case SDLK_a:                  return 'a';
146         case SDLK_b:                  return 'b';
147         case SDLK_c:                  return 'c';
148         case SDLK_d:                  return 'd';
149         case SDLK_e:                  return 'e';
150         case SDLK_f:                  return 'f';
151         case SDLK_g:                  return 'g';
152         case SDLK_h:                  return 'h';
153         case SDLK_i:                  return 'i';
154         case SDLK_j:                  return 'j';
155         case SDLK_k:                  return 'k';
156         case SDLK_l:                  return 'l';
157         case SDLK_m:                  return 'm';
158         case SDLK_n:                  return 'n';
159         case SDLK_o:                  return 'o';
160         case SDLK_p:                  return 'p';
161         case SDLK_q:                  return 'q';
162         case SDLK_r:                  return 'r';
163         case SDLK_s:                  return 's';
164         case SDLK_t:                  return 't';
165         case SDLK_u:                  return 'u';
166         case SDLK_v:                  return 'v';
167         case SDLK_w:                  return 'w';
168         case SDLK_x:                  return 'x';
169         case SDLK_y:                  return 'y';
170         case SDLK_z:                  return 'z';
171         case SDLK_CAPSLOCK:           return K_CAPSLOCK;
172         case SDLK_F1:                 return K_F1;
173         case SDLK_F2:                 return K_F2;
174         case SDLK_F3:                 return K_F3;
175         case SDLK_F4:                 return K_F4;
176         case SDLK_F5:                 return K_F5;
177         case SDLK_F6:                 return K_F6;
178         case SDLK_F7:                 return K_F7;
179         case SDLK_F8:                 return K_F8;
180         case SDLK_F9:                 return K_F9;
181         case SDLK_F10:                return K_F10;
182         case SDLK_F11:                return K_F11;
183         case SDLK_F12:                return K_F12;
184         case SDLK_PRINTSCREEN:        return K_PRINTSCREEN;
185         case SDLK_SCROLLLOCK:         return K_SCROLLOCK;
186         case SDLK_PAUSE:              return K_PAUSE;
187         case SDLK_INSERT:             return K_INS;
188         case SDLK_HOME:               return K_HOME;
189         case SDLK_PAGEUP:             return K_PGUP;
190 #ifdef __IPHONEOS__
191         case SDLK_DELETE:             return K_BACKSPACE;
192 #else
193         case SDLK_DELETE:             return K_DEL;
194 #endif
195         case SDLK_END:                return K_END;
196         case SDLK_PAGEDOWN:           return K_PGDN;
197         case SDLK_RIGHT:              return K_RIGHTARROW;
198         case SDLK_LEFT:               return K_LEFTARROW;
199         case SDLK_DOWN:               return K_DOWNARROW;
200         case SDLK_UP:                 return K_UPARROW;
201         case SDLK_NUMLOCKCLEAR:       return K_NUMLOCK;
202         case SDLK_KP_DIVIDE:          return K_KP_DIVIDE;
203         case SDLK_KP_MULTIPLY:        return K_KP_MULTIPLY;
204         case SDLK_KP_MINUS:           return K_KP_MINUS;
205         case SDLK_KP_PLUS:            return K_KP_PLUS;
206         case SDLK_KP_ENTER:           return K_KP_ENTER;
207         case SDLK_KP_1:               return ((SDL_GetModState() & KMOD_NUM) ? K_KP_1 : K_END);
208         case SDLK_KP_2:               return ((SDL_GetModState() & KMOD_NUM) ? K_KP_2 : K_DOWNARROW);
209         case SDLK_KP_3:               return ((SDL_GetModState() & KMOD_NUM) ? K_KP_3 : K_PGDN);
210         case SDLK_KP_4:               return ((SDL_GetModState() & KMOD_NUM) ? K_KP_4 : K_LEFTARROW);
211         case SDLK_KP_5:               return K_KP_5;
212         case SDLK_KP_6:               return ((SDL_GetModState() & KMOD_NUM) ? K_KP_6 : K_RIGHTARROW);
213         case SDLK_KP_7:               return ((SDL_GetModState() & KMOD_NUM) ? K_KP_7 : K_HOME);
214         case SDLK_KP_8:               return ((SDL_GetModState() & KMOD_NUM) ? K_KP_8 : K_UPARROW);
215         case SDLK_KP_9:               return ((SDL_GetModState() & KMOD_NUM) ? K_KP_9 : K_PGUP);
216         case SDLK_KP_0:               return ((SDL_GetModState() & KMOD_NUM) ? K_KP_0 : K_INS);
217         case SDLK_KP_PERIOD:          return ((SDL_GetModState() & KMOD_NUM) ? K_KP_PERIOD : K_DEL);
218 //      case SDLK_APPLICATION:        return K_APPLICATION;
219 //      case SDLK_POWER:              return K_POWER;
220         case SDLK_KP_EQUALS:          return K_KP_EQUALS;
221 //      case SDLK_F13:                return K_F13;
222 //      case SDLK_F14:                return K_F14;
223 //      case SDLK_F15:                return K_F15;
224 //      case SDLK_F16:                return K_F16;
225 //      case SDLK_F17:                return K_F17;
226 //      case SDLK_F18:                return K_F18;
227 //      case SDLK_F19:                return K_F19;
228 //      case SDLK_F20:                return K_F20;
229 //      case SDLK_F21:                return K_F21;
230 //      case SDLK_F22:                return K_F22;
231 //      case SDLK_F23:                return K_F23;
232 //      case SDLK_F24:                return K_F24;
233 //      case SDLK_EXECUTE:            return K_EXECUTE;
234 //      case SDLK_HELP:               return K_HELP;
235 //      case SDLK_MENU:               return K_MENU;
236 //      case SDLK_SELECT:             return K_SELECT;
237 //      case SDLK_STOP:               return K_STOP;
238 //      case SDLK_AGAIN:              return K_AGAIN;
239 //      case SDLK_UNDO:               return K_UNDO;
240 //      case SDLK_CUT:                return K_CUT;
241 //      case SDLK_COPY:               return K_COPY;
242 //      case SDLK_PASTE:              return K_PASTE;
243 //      case SDLK_FIND:               return K_FIND;
244 //      case SDLK_MUTE:               return K_MUTE;
245 //      case SDLK_VOLUMEUP:           return K_VOLUMEUP;
246 //      case SDLK_VOLUMEDOWN:         return K_VOLUMEDOWN;
247 //      case SDLK_KP_COMMA:           return K_KP_COMMA;
248 //      case SDLK_KP_EQUALSAS400:     return K_KP_EQUALSAS400;
249 //      case SDLK_ALTERASE:           return K_ALTERASE;
250 //      case SDLK_SYSREQ:             return K_SYSREQ;
251 //      case SDLK_CANCEL:             return K_CANCEL;
252 //      case SDLK_CLEAR:              return K_CLEAR;
253 //      case SDLK_PRIOR:              return K_PRIOR;
254 //      case SDLK_RETURN2:            return K_RETURN2;
255 //      case SDLK_SEPARATOR:          return K_SEPARATOR;
256 //      case SDLK_OUT:                return K_OUT;
257 //      case SDLK_OPER:               return K_OPER;
258 //      case SDLK_CLEARAGAIN:         return K_CLEARAGAIN;
259 //      case SDLK_CRSEL:              return K_CRSEL;
260 //      case SDLK_EXSEL:              return K_EXSEL;
261 //      case SDLK_KP_00:              return K_KP_00;
262 //      case SDLK_KP_000:             return K_KP_000;
263 //      case SDLK_THOUSANDSSEPARATOR: return K_THOUSANDSSEPARATOR;
264 //      case SDLK_DECIMALSEPARATOR:   return K_DECIMALSEPARATOR;
265 //      case SDLK_CURRENCYUNIT:       return K_CURRENCYUNIT;
266 //      case SDLK_CURRENCYSUBUNIT:    return K_CURRENCYSUBUNIT;
267 //      case SDLK_KP_LEFTPAREN:       return K_KP_LEFTPAREN;
268 //      case SDLK_KP_RIGHTPAREN:      return K_KP_RIGHTPAREN;
269 //      case SDLK_KP_LEFTBRACE:       return K_KP_LEFTBRACE;
270 //      case SDLK_KP_RIGHTBRACE:      return K_KP_RIGHTBRACE;
271 //      case SDLK_KP_TAB:             return K_KP_TAB;
272 //      case SDLK_KP_BACKSPACE:       return K_KP_BACKSPACE;
273 //      case SDLK_KP_A:               return K_KP_A;
274 //      case SDLK_KP_B:               return K_KP_B;
275 //      case SDLK_KP_C:               return K_KP_C;
276 //      case SDLK_KP_D:               return K_KP_D;
277 //      case SDLK_KP_E:               return K_KP_E;
278 //      case SDLK_KP_F:               return K_KP_F;
279 //      case SDLK_KP_XOR:             return K_KP_XOR;
280 //      case SDLK_KP_POWER:           return K_KP_POWER;
281 //      case SDLK_KP_PERCENT:         return K_KP_PERCENT;
282 //      case SDLK_KP_LESS:            return K_KP_LESS;
283 //      case SDLK_KP_GREATER:         return K_KP_GREATER;
284 //      case SDLK_KP_AMPERSAND:       return K_KP_AMPERSAND;
285 //      case SDLK_KP_DBLAMPERSAND:    return K_KP_DBLAMPERSAND;
286 //      case SDLK_KP_VERTICALBAR:     return K_KP_VERTICALBAR;
287 //      case SDLK_KP_DBLVERTICALBAR:  return K_KP_DBLVERTICALBAR;
288 //      case SDLK_KP_COLON:           return K_KP_COLON;
289 //      case SDLK_KP_HASH:            return K_KP_HASH;
290 //      case SDLK_KP_SPACE:           return K_KP_SPACE;
291 //      case SDLK_KP_AT:              return K_KP_AT;
292 //      case SDLK_KP_EXCLAM:          return K_KP_EXCLAM;
293 //      case SDLK_KP_MEMSTORE:        return K_KP_MEMSTORE;
294 //      case SDLK_KP_MEMRECALL:       return K_KP_MEMRECALL;
295 //      case SDLK_KP_MEMCLEAR:        return K_KP_MEMCLEAR;
296 //      case SDLK_KP_MEMADD:          return K_KP_MEMADD;
297 //      case SDLK_KP_MEMSUBTRACT:     return K_KP_MEMSUBTRACT;
298 //      case SDLK_KP_MEMMULTIPLY:     return K_KP_MEMMULTIPLY;
299 //      case SDLK_KP_MEMDIVIDE:       return K_KP_MEMDIVIDE;
300 //      case SDLK_KP_PLUSMINUS:       return K_KP_PLUSMINUS;
301 //      case SDLK_KP_CLEAR:           return K_KP_CLEAR;
302 //      case SDLK_KP_CLEARENTRY:      return K_KP_CLEARENTRY;
303 //      case SDLK_KP_BINARY:          return K_KP_BINARY;
304 //      case SDLK_KP_OCTAL:           return K_KP_OCTAL;
305 //      case SDLK_KP_DECIMAL:         return K_KP_DECIMAL;
306 //      case SDLK_KP_HEXADECIMAL:     return K_KP_HEXADECIMAL;
307         case SDLK_LCTRL:              return K_CTRL;
308         case SDLK_LSHIFT:             return K_SHIFT;
309         case SDLK_LALT:               return K_ALT;
310 //      case SDLK_LGUI:               return K_LGUI;
311         case SDLK_RCTRL:              return K_CTRL;
312         case SDLK_RSHIFT:             return K_SHIFT;
313         case SDLK_RALT:               return K_ALT;
314 //      case SDLK_RGUI:               return K_RGUI;
315 //      case SDLK_MODE:               return K_MODE;
316 //      case SDLK_AUDIONEXT:          return K_AUDIONEXT;
317 //      case SDLK_AUDIOPREV:          return K_AUDIOPREV;
318 //      case SDLK_AUDIOSTOP:          return K_AUDIOSTOP;
319 //      case SDLK_AUDIOPLAY:          return K_AUDIOPLAY;
320 //      case SDLK_AUDIOMUTE:          return K_AUDIOMUTE;
321 //      case SDLK_MEDIASELECT:        return K_MEDIASELECT;
322 //      case SDLK_WWW:                return K_WWW;
323 //      case SDLK_MAIL:               return K_MAIL;
324 //      case SDLK_CALCULATOR:         return K_CALCULATOR;
325 //      case SDLK_COMPUTER:           return K_COMPUTER;
326 //      case SDLK_AC_SEARCH:          return K_AC_SEARCH; // Android button
327 //      case SDLK_AC_HOME:            return K_AC_HOME; // Android button
328         case SDLK_AC_BACK:            return K_ESCAPE; // Android button
329 //      case SDLK_AC_FORWARD:         return K_AC_FORWARD; // Android button
330 //      case SDLK_AC_STOP:            return K_AC_STOP; // Android button
331 //      case SDLK_AC_REFRESH:         return K_AC_REFRESH; // Android button
332 //      case SDLK_AC_BOOKMARKS:       return K_AC_BOOKMARKS; // Android button
333 //      case SDLK_BRIGHTNESSDOWN:     return K_BRIGHTNESSDOWN;
334 //      case SDLK_BRIGHTNESSUP:       return K_BRIGHTNESSUP;
335 //      case SDLK_DISPLAYSWITCH:      return K_DISPLAYSWITCH;
336 //      case SDLK_KBDILLUMTOGGLE:     return K_KBDILLUMTOGGLE;
337 //      case SDLK_KBDILLUMDOWN:       return K_KBDILLUMDOWN;
338 //      case SDLK_KBDILLUMUP:         return K_KBDILLUMUP;
339 //      case SDLK_EJECT:              return K_EJECT;
340 //      case SDLK_SLEEP:              return K_SLEEP;
341         }
342 }
343
344 qbool VID_HasScreenKeyboardSupport(void)
345 {
346         return SDL_HasScreenKeyboardSupport() != SDL_FALSE;
347 }
348
349 void VID_ShowKeyboard(qbool show)
350 {
351         if (!SDL_HasScreenKeyboardSupport())
352                 return;
353
354         if (show)
355         {
356                 if (!SDL_IsTextInputActive())
357                         SDL_StartTextInput();
358         }
359         else
360         {
361                 if (SDL_IsTextInputActive())
362                         SDL_StopTextInput();
363         }
364 }
365
366 qbool VID_ShowingKeyboard(void)
367 {
368         return SDL_IsTextInputActive() != 0;
369 }
370
371 static void VID_SetMouse(qbool relative, qbool hidecursor)
372 {
373 #ifndef DP_MOBILETOUCH
374 #ifdef MACOSX
375         if(relative)
376                 if(vid_usingmouse && (vid_usingnoaccel != !!apple_mouse_noaccel.integer))
377                         VID_SetMouse(false, false); // ungrab first!
378 #endif
379         if (vid_usingmouse != relative)
380         {
381                 vid_usingmouse = relative;
382                 cl_ignoremousemoves = 2;
383                 vid_usingmouse_relativeworks = SDL_SetRelativeMouseMode(relative ? SDL_TRUE : SDL_FALSE) == 0;
384 //              Con_Printf("VID_SetMouse(%i, %i) relativeworks = %i\n", (int)relative, (int)hidecursor, (int)vid_usingmouse_relativeworks);
385 #ifdef MACOSX
386                 if(relative)
387                 {
388                         // Save the status of mouse acceleration
389                         originalMouseSpeed = -1.0; // in case of error
390                         if(apple_mouse_noaccel.integer)
391                         {
392                                 io_connect_t mouseDev = IN_GetIOHandle();
393                                 if(mouseDev != 0)
394                                 {
395                                         if(IOHIDGetAccelerationWithKey(mouseDev, CFSTR(kIOHIDMouseAccelerationType), &originalMouseSpeed) == kIOReturnSuccess)
396                                         {
397                                                 Con_DPrintf("previous mouse acceleration: %f\n", originalMouseSpeed);
398                                                 if(IOHIDSetAccelerationWithKey(mouseDev, CFSTR(kIOHIDMouseAccelerationType), -1.0) != kIOReturnSuccess)
399                                                 {
400                                                         Con_Print("Could not disable mouse acceleration (failed at IOHIDSetAccelerationWithKey).\n");
401                                                         Cvar_SetValueQuick(&apple_mouse_noaccel, 0);
402                                                 }
403                                         }
404                                         else
405                                         {
406                                                 Con_Print("Could not disable mouse acceleration (failed at IOHIDGetAccelerationWithKey).\n");
407                                                 Cvar_SetValueQuick(&apple_mouse_noaccel, 0);
408                                         }
409                                         IOServiceClose(mouseDev);
410                                 }
411                                 else
412                                 {
413                                         Con_Print("Could not disable mouse acceleration (failed at IO_GetIOHandle).\n");
414                                         Cvar_SetValueQuick(&apple_mouse_noaccel, 0);
415                                 }
416                         }
417
418                         vid_usingnoaccel = !!apple_mouse_noaccel.integer;
419                 }
420                 else
421                 {
422                         if(originalMouseSpeed != -1.0)
423                         {
424                                 io_connect_t mouseDev = IN_GetIOHandle();
425                                 if(mouseDev != 0)
426                                 {
427                                         Con_DPrintf("restoring mouse acceleration to: %f\n", originalMouseSpeed);
428                                         if(IOHIDSetAccelerationWithKey(mouseDev, CFSTR(kIOHIDMouseAccelerationType), originalMouseSpeed) != kIOReturnSuccess)
429                                                 Con_Print("Could not re-enable mouse acceleration (failed at IOHIDSetAccelerationWithKey).\n");
430                                         IOServiceClose(mouseDev);
431                                 }
432                                 else
433                                         Con_Print("Could not re-enable mouse acceleration (failed at IO_GetIOHandle).\n");
434                         }
435                 }
436 #endif
437         }
438         if (vid_usinghidecursor != hidecursor)
439         {
440                 vid_usinghidecursor = hidecursor;
441                 SDL_ShowCursor( hidecursor ? SDL_DISABLE : SDL_ENABLE);
442         }
443 #endif
444 }
445
446 // multitouch[10][] represents the mouse pointer
447 // multitouch[][0]: finger active
448 // multitouch[][1]: Y
449 // multitouch[][2]: Y
450 // X and Y coordinates are 0-1.
451 #define MAXFINGERS 11
452 float multitouch[MAXFINGERS][3];
453
454 // this one stores how many areas this finger has touched
455 int multitouchs[MAXFINGERS];
456
457 // modified heavily by ELUAN
458 static qbool VID_TouchscreenArea(int corner, float px, float py, float pwidth, float pheight, const char *icon, float textheight, const char *text, float *resultmove, qbool *resultbutton, keynum_t key, const char *typedtext, float deadzone, float oversizepixels_x, float oversizepixels_y, qbool iamexclusive)
459 {
460         int finger;
461         float fx, fy, fwidth, fheight;
462         float overfx, overfy, overfwidth, overfheight;
463         float rel[3];
464         float sqsum;
465         qbool button = false;
466         VectorClear(rel);
467         if (pwidth > 0 && pheight > 0)
468         {
469                 if (corner & 1) px += vid_conwidth.value;
470                 if (corner & 2) py += vid_conheight.value;
471                 if (corner & 4) px += vid_conwidth.value * 0.5f;
472                 if (corner & 8) py += vid_conheight.value * 0.5f;
473                 if (corner & 16) {px *= vid_conwidth.value * (1.0f / 640.0f);py *= vid_conheight.value * (1.0f / 480.0f);pwidth *= vid_conwidth.value * (1.0f / 640.0f);pheight *= vid_conheight.value * (1.0f / 480.0f);}
474                 fx = px / vid_conwidth.value;
475                 fy = py / vid_conheight.value;
476                 fwidth = pwidth / vid_conwidth.value;
477                 fheight = pheight / vid_conheight.value;
478
479                 // try to prevent oversizepixels_* from interfering with the iamexclusive cvar by not letting we start controlling from too far of the actual touch area (areas without resultbuttons should NEVER have the oversizepixels_* parameters set to anything other than 0)
480                 if (resultbutton)
481                         if (!(*resultbutton))
482                         {
483                                 oversizepixels_x *= 0.2;
484                                 oversizepixels_y *= 0.2;
485                         }
486
487                 oversizepixels_x /= vid_conwidth.value;
488                 oversizepixels_y /= vid_conheight.value;
489
490                 overfx = fx - oversizepixels_x;
491                 overfy = fy - oversizepixels_y;
492                 overfwidth = fwidth + 2*oversizepixels_x;
493                 overfheight = fheight + 2*oversizepixels_y;
494
495                 for (finger = 0;finger < MAXFINGERS;finger++)
496                 {
497                         if (multitouchs[finger] && iamexclusive) // for this to work correctly, you must call touch areas in order of highest to lowest priority
498                                 continue;
499
500                         if (multitouch[finger][0] && multitouch[finger][1] >= overfx && multitouch[finger][2] >= overfy && multitouch[finger][1] < overfx + overfwidth && multitouch[finger][2] < overfy + overfheight)
501                         {
502                                 multitouchs[finger]++;
503
504                                 rel[0] = bound(-1, (multitouch[finger][1] - (fx + 0.5f * fwidth)) * (2.0f / fwidth), 1);
505                                 rel[1] = bound(-1, (multitouch[finger][2] - (fy + 0.5f * fheight)) * (2.0f / fheight), 1);
506                                 rel[2] = 0;
507
508                                 sqsum = rel[0]*rel[0] + rel[1]*rel[1];
509                                 // 2d deadzone
510                                 if (sqsum < deadzone*deadzone)
511                                 {
512                                         rel[0] = 0;
513                                         rel[1] = 0;
514                                 }
515                                 else if (sqsum > 1)
516                                 {
517                                         // ignore the third component
518                                         Vector2Normalize2(rel, rel);
519                                 }
520                                 button = true;
521                                 break;
522                         }
523                 }
524                 if (scr_numtouchscreenareas < 128)
525                 {
526                         scr_touchscreenareas[scr_numtouchscreenareas].pic = icon;
527                         scr_touchscreenareas[scr_numtouchscreenareas].text = text;
528                         scr_touchscreenareas[scr_numtouchscreenareas].textheight = textheight;
529                         scr_touchscreenareas[scr_numtouchscreenareas].rect[0] = px;
530                         scr_touchscreenareas[scr_numtouchscreenareas].rect[1] = py;
531                         scr_touchscreenareas[scr_numtouchscreenareas].rect[2] = pwidth;
532                         scr_touchscreenareas[scr_numtouchscreenareas].rect[3] = pheight;
533                         scr_touchscreenareas[scr_numtouchscreenareas].active = button;
534                         // the pics may have alpha too.
535                         scr_touchscreenareas[scr_numtouchscreenareas].activealpha = 1.f;
536                         scr_touchscreenareas[scr_numtouchscreenareas].inactivealpha = 0.95f;
537                         scr_numtouchscreenareas++;
538                 }
539         }
540         if (resultmove)
541         {
542                 if (button)
543                         VectorCopy(rel, resultmove);
544                 else
545                         VectorClear(resultmove);
546         }
547         if (resultbutton)
548         {
549                 if (*resultbutton != button)
550                 {
551                         if ((int)key > 0)
552                                 Key_Event(key, 0, button);
553                         if (typedtext && typedtext[0] && !*resultbutton)
554                         {
555                                 // FIXME: implement UTF8 support - nothing actually specifies a UTF8 string here yet, but should support it...
556                                 int i;
557                                 for (i = 0;typedtext[i];i++)
558                                 {
559                                         Key_Event(K_TEXT, typedtext[i], true);
560                                         Key_Event(K_TEXT, typedtext[i], false);
561                                 }
562                         }
563                 }
564                 *resultbutton = button;
565         }
566         return button;
567 }
568
569 // ELUAN:
570 // not reentrant, but we only need one mouse cursor anyway...
571 static void VID_TouchscreenCursor(float px, float py, float pwidth, float pheight, qbool *resultbutton, keynum_t key)
572 {
573         int finger;
574         float fx, fy, fwidth, fheight;
575         qbool button = false;
576         static int cursorfinger = -1;
577         static int cursorfreemovement = false;
578         static int canclick = false;
579         static int clickxy[2];
580         static int relclickxy[2];
581         static double clickrealtime = 0;
582
583         if (steelstorm_showing_mousecursor && steelstorm_showing_mousecursor->integer)
584         if (pwidth > 0 && pheight > 0)
585         {
586                 fx = px / vid_conwidth.value;
587                 fy = py / vid_conheight.value;
588                 fwidth = pwidth / vid_conwidth.value;
589                 fheight = pheight / vid_conheight.value;
590                 for (finger = 0;finger < MAXFINGERS;finger++)
591                 {
592                         if (multitouch[finger][0] && multitouch[finger][1] >= fx && multitouch[finger][2] >= fy && multitouch[finger][1] < fx + fwidth && multitouch[finger][2] < fy + fheight)
593                         {
594                                 if (cursorfinger == -1)
595                                 {
596                                         clickxy[0] =  multitouch[finger][1] * vid_width.value - 0.5f * pwidth;
597                                         clickxy[1] =  multitouch[finger][2] * vid_height.value - 0.5f * pheight;
598                                         relclickxy[0] =  (multitouch[finger][1] - fx) * vid_width.value - 0.5f * pwidth;
599                                         relclickxy[1] =  (multitouch[finger][2] - fy) * vid_height.value - 0.5f * pheight;
600                                 }
601                                 cursorfinger = finger;
602                                 button = true;
603                                 canclick = true;
604                                 cursorfreemovement = false;
605                                 break;
606                         }
607                 }
608                 if (scr_numtouchscreenareas < 128)
609                 {
610                         if (clickrealtime + 1 > host.realtime)
611                         {
612                                 scr_touchscreenareas[scr_numtouchscreenareas].pic = "gfx/gui/touch_puck_cur_click.tga";
613                         }
614                         else if (button)
615                         {
616                                 scr_touchscreenareas[scr_numtouchscreenareas].pic = "gfx/gui/touch_puck_cur_touch.tga";
617                         }
618                         else
619                         {
620                                 switch ((int)host.realtime * 10 % 20)
621                                 {
622                                 case 0:
623                                         scr_touchscreenareas[scr_numtouchscreenareas].pic = "gfx/gui/touch_puck_cur_touch.tga";
624                                         break;
625                                 default:
626                                         scr_touchscreenareas[scr_numtouchscreenareas].pic = "gfx/gui/touch_puck_cur_idle.tga";
627                                 }
628                         }
629                         scr_touchscreenareas[scr_numtouchscreenareas].text = "";
630                         scr_touchscreenareas[scr_numtouchscreenareas].textheight = 0;
631                         scr_touchscreenareas[scr_numtouchscreenareas].rect[0] = px;
632                         scr_touchscreenareas[scr_numtouchscreenareas].rect[1] = py;
633                         scr_touchscreenareas[scr_numtouchscreenareas].rect[2] = pwidth;
634                         scr_touchscreenareas[scr_numtouchscreenareas].rect[3] = pheight;
635                         scr_touchscreenareas[scr_numtouchscreenareas].active = button;
636                         scr_touchscreenareas[scr_numtouchscreenareas].activealpha = 1.0f;
637                         scr_touchscreenareas[scr_numtouchscreenareas].inactivealpha = 1.0f;
638                         scr_numtouchscreenareas++;
639                 }
640         }
641
642         if (cursorfinger != -1)
643         {
644                 if (multitouch[cursorfinger][0])
645                 {
646                         if (multitouch[cursorfinger][1] * vid_width.value - 0.5f * pwidth < clickxy[0] - 1 ||
647                                 multitouch[cursorfinger][1] * vid_width.value - 0.5f * pwidth > clickxy[0] + 1 ||
648                                 multitouch[cursorfinger][2] * vid_height.value - 0.5f * pheight< clickxy[1] - 1 ||
649                                 multitouch[cursorfinger][2] * vid_height.value - 0.5f * pheight> clickxy[1] + 1) // finger drifted more than the allowed amount
650                         {
651                                 cursorfreemovement = true;
652                         }
653                         if (cursorfreemovement)
654                         {
655                                 // in_windowmouse_x* is in screen resolution coordinates, not console resolution
656                                 in_windowmouse_x = multitouch[cursorfinger][1] * vid_width.value - 0.5f * pwidth - relclickxy[0];
657                                 in_windowmouse_y = multitouch[cursorfinger][2] * vid_height.value - 0.5f * pheight - relclickxy[1];
658                         }
659                 }
660                 else
661                 {
662                         cursorfinger = -1;
663                 }
664         }
665
666         if (resultbutton)
667         {
668                 if (/**resultbutton != button && */(int)key > 0)
669                 {
670                         if (!button && !cursorfreemovement && canclick)
671                         {
672                                 Key_Event(key, 0, true);
673                                 canclick = false;
674                                 clickrealtime = host.realtime;
675                         }
676
677                         // SS:BR can't qc can't cope with presses and releases on the same frame
678                         if (clickrealtime && clickrealtime + 0.1 < host.realtime)
679                         {
680                                 Key_Event(key, 0, false);
681                                 clickrealtime = 0;
682                         }
683                 }
684
685                 *resultbutton = button;
686         }
687 }
688
689 void VID_BuildJoyState(vid_joystate_t *joystate)
690 {
691         VID_Shared_BuildJoyState_Begin(joystate);
692
693         if (vid_sdljoystick)
694         {
695                 SDL_Joystick *joy = vid_sdljoystick;
696                 int j;
697
698                 if (vid_sdlgamecontroller)
699                 {
700                         for (j = 0; j <= SDL_CONTROLLER_AXIS_MAX; ++j)
701                         {
702                                 joystate->axis[j] = SDL_GameControllerGetAxis(vid_sdlgamecontroller, (SDL_GameControllerAxis)j) * (1.0f / 32767.0f);
703                         }
704                         for (j = 0; j < SDL_CONTROLLER_BUTTON_MAX; ++j)
705                                 joystate->button[j] = SDL_GameControllerGetButton(vid_sdlgamecontroller, (SDL_GameControllerButton)j);
706                         // emulate joy buttons for trigger "axes"
707                         joystate->button[SDL_CONTROLLER_BUTTON_MAX] = VID_JoyState_GetAxis(joystate, SDL_CONTROLLER_AXIS_TRIGGERLEFT, 1, joy_sdl2_trigger_deadzone.value) > 0.0f;
708                         joystate->button[SDL_CONTROLLER_BUTTON_MAX+1] = VID_JoyState_GetAxis(joystate, SDL_CONTROLLER_AXIS_TRIGGERRIGHT, 1, joy_sdl2_trigger_deadzone.value) > 0.0f;
709                 }
710                 else
711
712                 {
713                         int numaxes;
714                         int numbuttons;
715                         numaxes = SDL_JoystickNumAxes(joy);
716                         for (j = 0;j < numaxes;j++)
717                                 joystate->axis[j] = SDL_JoystickGetAxis(joy, j) * (1.0f / 32767.0f);
718                         numbuttons = SDL_JoystickNumButtons(joy);
719                         for (j = 0;j < numbuttons;j++)
720                                 joystate->button[j] = SDL_JoystickGetButton(joy, j);
721                 }
722         }
723
724         VID_Shared_BuildJoyState_Finish(joystate);
725 }
726
727 // clear every touch screen area, except the one with button[skip]
728 #define Vid_ClearAllTouchscreenAreas(skip) \
729         if (skip != 0) \
730                 VID_TouchscreenCursor(0, 0, 0, 0, &buttons[0], K_MOUSE1); \
731         if (skip != 1) \
732                 VID_TouchscreenArea( 0,   0,   0,   0,   0, NULL                         , 0.0f, NULL, move, &buttons[1], K_MOUSE4, NULL, 0, 0, 0, false); \
733         if (skip != 2) \
734                 VID_TouchscreenArea( 0,   0,   0,   0,   0, NULL                         , 0.0f, NULL, aim,  &buttons[2], K_MOUSE5, NULL, 0, 0, 0, false); \
735         if (skip != 3) \
736                 VID_TouchscreenArea( 0,   0,   0,   0,   0, NULL                         , 0.0f, NULL, NULL, &buttons[3], K_SHIFT, NULL, 0, 0, 0, false); \
737         if (skip != 4) \
738                 VID_TouchscreenArea( 0,   0,   0,   0,   0, NULL                         , 0.0f, NULL, NULL, &buttons[4], K_MOUSE2, NULL, 0, 0, 0, false); \
739         if (skip != 9) \
740                 VID_TouchscreenArea( 0,   0,   0,   0,   0, NULL                         , 0.0f, NULL, NULL, &buttons[9], K_MOUSE3, NULL, 0, 0, 0, false); \
741         if (skip != 10) \
742                 VID_TouchscreenArea( 0,   0,   0,   0,   0, NULL                         , 0.0f, NULL, NULL, &buttons[10], (keynum_t)'m', NULL, 0, 0, 0, false); \
743         if (skip != 11) \
744                 VID_TouchscreenArea( 0,   0,   0,   0,   0, NULL                         , 0.0f, NULL, NULL, &buttons[11], (keynum_t)'b', NULL, 0, 0, 0, false); \
745         if (skip != 12) \
746                 VID_TouchscreenArea( 0,   0,   0,   0,   0, NULL                         , 0.0f, NULL, NULL, &buttons[12], (keynum_t)'q', NULL, 0, 0, 0, false); \
747         if (skip != 13) \
748                 VID_TouchscreenArea( 0,   0,   0,   0,   0, NULL                         , 0.0f, NULL, NULL, &buttons[13], (keynum_t)'`', NULL, 0, 0, 0, false); \
749         if (skip != 14) \
750                 VID_TouchscreenArea( 0,   0,   0,   0,   0, NULL                         , 0.0f, NULL, NULL, &buttons[14], K_ESCAPE, NULL, 0, 0, 0, false); \
751         if (skip != 15) \
752                 VID_TouchscreenArea( 0,  0,  0,  0,  0, NULL                         , 0.0f, NULL, NULL, &buttons[15], K_SPACE, NULL, 0, 0, 0, false); \
753
754 /////////////////////
755 // Movement handling
756 ////
757
758 static void IN_Move_TouchScreen_SteelStorm(void)
759 {
760         // ELUAN
761         int i, numfingers;
762         float xscale, yscale;
763         float move[3], aim[3];
764         static qbool oldbuttons[128];
765         static qbool buttons[128];
766         keydest_t keydest = (key_consoleactive & KEY_CONSOLEACTIVE_USER) ? key_console : key_dest;
767         memcpy(oldbuttons, buttons, sizeof(oldbuttons));
768         memset(multitouchs, 0, sizeof(multitouchs));
769
770         for (i = 0, numfingers = 0; i < MAXFINGERS - 1; i++)
771                 if (multitouch[i][0])
772                         numfingers++;
773
774         /*
775         Enable this to use a mouse as a touch device (it may conflict with the iamexclusive parameter if a finger is also reported as a mouse at the same location
776         if (numfingers == 1)
777         {
778                 multitouch[MAXFINGERS-1][0] = SDL_GetMouseState(&x, &y) ? 11 : 0;
779                 multitouch[MAXFINGERS-1][1] = (float)x / vid.width;
780                 multitouch[MAXFINGERS-1][2] = (float)y / vid.height;
781         }
782         else
783         {
784                 // disable it so it doesn't get stuck, because SDL seems to stop updating it if there are more than 1 finger on screen
785                 multitouch[MAXFINGERS-1][0] = 0;
786         }*/
787
788         // TODO: make touchscreen areas controlled by a config file or the VMs. THIS IS A MESS!
789         // TODO: can't just clear buttons[] when entering a new keydest, some keys would remain pressed
790         // SS:BR menuqc has many peculiarities, including that it can't accept more than one command per frame and pressing and releasing on the same frame
791
792         // Tuned for the SGS3, use it's value as a base. CLEAN THIS.
793         xscale = vid_touchscreen_density.value / 2.0f;
794         yscale = vid_touchscreen_density.value / 2.0f;
795         switch(keydest)
796         {
797         case key_console:
798                 Vid_ClearAllTouchscreenAreas(14);
799                 VID_TouchscreenArea( 0,   0, 160,  64,  64, "gfx/gui/touch_menu_button.tga"         , 0.0f, NULL, NULL, &buttons[14], K_ESCAPE, NULL, 0, 0, 0, false);
800                 break;
801         case key_game:
802                 if (steelstorm_showing_map && steelstorm_showing_map->integer) // FIXME: another hack to be removed when touchscreen areas go to QC
803                 {
804                         VID_TouchscreenArea( 0,   0,   0, vid_conwidth.value, vid_conheight.value, NULL                         , 0.0f, NULL, NULL, &buttons[10], (keynum_t)'m', NULL, 0, 0, 0, false);
805                         Vid_ClearAllTouchscreenAreas(10);
806                 }
807                 else if (steelstorm_showing_mousecursor && steelstorm_showing_mousecursor->integer)
808                 {
809                         // in_windowmouse_x* is in screen resolution coordinates, not console resolution
810                         VID_TouchscreenCursor((float)in_windowmouse_x/vid_width.value*vid_conwidth.value, (float)in_windowmouse_y/vid_height.value*vid_conheight.value, 192*xscale, 192*yscale, &buttons[0], K_MOUSE1);
811                         Vid_ClearAllTouchscreenAreas(0);
812                 }
813                 else
814                 {
815                         VID_TouchscreenCursor(0, 0, 0, 0, &buttons[0], K_MOUSE1);
816
817                         VID_TouchscreenArea( 2,16*xscale,-240*yscale, 224*xscale, 224*yscale, "gfx/gui/touch_l_thumb_dpad.tga", 0.0f, NULL, move, &buttons[1], (keynum_t)0, NULL, 0.15, 112*xscale, 112*yscale, false);
818
819                         VID_TouchscreenArea( 3,-240*xscale,-160*yscale, 224*xscale, 128*yscale, "gfx/gui/touch_r_thumb_turn_n_shoot.tga"    , 0.0f, NULL, NULL,  0, (keynum_t)0, NULL, 0, 56*xscale, 0, false);
820                         VID_TouchscreenArea( 3,-240*xscale,-256*yscale, 224*xscale, 224*yscale, NULL    , 0.0f, NULL, aim,  &buttons[2], (keynum_t)0, NULL, 0.2, 56*xscale, 0, false);
821
822                         VID_TouchscreenArea( 2, (vid_conwidth.value / 2) - 128,-80,  256,  80, NULL, 0.0f, NULL, NULL, &buttons[3], K_SHIFT, NULL, 0, 0, 0, true);
823
824                         VID_TouchscreenArea( 3,-240*xscale,-256*yscale, 224*xscale,  64*yscale, "gfx/gui/touch_secondary_slide.tga", 0.0f, NULL, NULL, &buttons[4], K_MOUSE2, NULL, 0, 56*xscale, 0, false);
825                         VID_TouchscreenArea( 3,-240*xscale,-256*yscale, 224*xscale,  160*yscale, NULL , 0.0f, NULL, NULL, &buttons[9], K_MOUSE3, NULL, 0.2, 56*xscale, 0, false);
826
827                         VID_TouchscreenArea( 1,-100,   0, 100, 100, NULL                         , 0.0f, NULL, NULL, &buttons[10], (keynum_t)'m', NULL, 0, 0, 0, true);
828                         VID_TouchscreenArea( 1,-100, 120, 100, 100, NULL                         , 0.0f, NULL, NULL, &buttons[11], (keynum_t)'b', NULL, 0, 0, 0, true);
829                         VID_TouchscreenArea( 0,   0,   0,  64,  64, NULL                         , 0.0f, NULL, NULL, &buttons[12], (keynum_t)'q', NULL, 0, 0, 0, true);
830                         if (developer.integer)
831                                 VID_TouchscreenArea( 0,   0,  96,  64,  64, NULL                         , 0.0f, NULL, NULL, &buttons[13], (keynum_t)'`', NULL, 0, 0, 0, true);
832                         else
833                                 VID_TouchscreenArea( 0,   0,   0,   0,   0, NULL                         , 0.0f, NULL, NULL, &buttons[13], (keynum_t)'`', NULL, 0, 0, 0, false);
834                         VID_TouchscreenArea( 0,   0, 160,  64,  64, "gfx/gui/touch_menu_button.tga"         , 0.0f, NULL, NULL, &buttons[14], K_ESCAPE, NULL, 0, 0, 0, true);
835                         switch(cl.activeweapon)
836                         {
837                         case 14:
838                                 VID_TouchscreenArea( 2,  16*xscale,-320*yscale, 224*xscale, 64*yscale, "gfx/gui/touch_booster.tga" , 0.0f, NULL, NULL, &buttons[15], K_SPACE, NULL, 0, 0, 0, true);
839                                 break;
840                         case 12:
841                                 VID_TouchscreenArea( 2,  16*xscale,-320*yscale, 224*xscale, 64*yscale, "gfx/gui/touch_shockwave.tga" , 0.0f, NULL, NULL, &buttons[15], K_SPACE, NULL, 0, 0, 0, true);
842                                 break;
843                         default:
844                                 VID_TouchscreenArea( 0,  0,  0,  0,  0, NULL , 0.0f, NULL, NULL, &buttons[15], K_SPACE, NULL, 0, 0, 0, false);
845                         }
846                 }
847                 break;
848         default:
849                 if (!steelstorm_showing_mousecursor || !steelstorm_showing_mousecursor->integer)
850                 {
851                         Vid_ClearAllTouchscreenAreas(14);
852                         // this way we can skip cutscenes
853                         VID_TouchscreenArea( 0,   0,   0, vid_conwidth.value, vid_conheight.value, NULL                         , 0.0f, NULL, NULL, &buttons[14], K_ESCAPE, NULL, 0, 0, 0, false);
854                 }
855                 else
856                 {
857                         // in_windowmouse_x* is in screen resolution coordinates, not console resolution
858                         VID_TouchscreenCursor((float)in_windowmouse_x/vid_width.value*vid_conwidth.value, (float)in_windowmouse_y/vid_height.value*vid_conheight.value, 192*xscale, 192*yscale, &buttons[0], K_MOUSE1);
859                         Vid_ClearAllTouchscreenAreas(0);
860                 }
861                 break;
862         }
863
864         if (VID_ShowingKeyboard() && (float)in_windowmouse_y > vid_height.value / 2 - 10)
865                 in_windowmouse_y = 128;
866
867         cl.cmd.forwardmove -= move[1] * cl_forwardspeed.value;
868         cl.cmd.sidemove += move[0] * cl_sidespeed.value;
869         cl.viewangles[0] += aim[1] * cl_pitchspeed.value * cl.realframetime;
870         cl.viewangles[1] -= aim[0] * cl_yawspeed.value * cl.realframetime;
871 }
872
873 static void IN_Move_TouchScreen_Quake(void)
874 {
875         int x, y;
876         float move[3], aim[3], click[3];
877         static qbool oldbuttons[128];
878         static qbool buttons[128];
879         keydest_t keydest = (key_consoleactive & KEY_CONSOLEACTIVE_USER) ? key_console : key_dest;
880         memcpy(oldbuttons, buttons, sizeof(oldbuttons));
881         memset(multitouchs, 0, sizeof(multitouchs));
882
883         // simple quake controls
884         multitouch[MAXFINGERS-1][0] = SDL_GetMouseState(&x, &y);
885         multitouch[MAXFINGERS-1][1] = x * 32768 / vid.width;
886         multitouch[MAXFINGERS-1][2] = y * 32768 / vid.height;
887
888         // top of screen is toggleconsole and K_ESCAPE
889         switch(keydest)
890         {
891         case key_console:
892                 VID_TouchscreenArea( 0,   0,   0,  64,  64, NULL                         , 0.0f, NULL, NULL, &buttons[13], (keynum_t)'`', NULL, 0, 0, 0, true);
893                 VID_TouchscreenArea( 0,  64,   0,  64,  64, "gfx/touch_menu.tga"         , 0.0f, NULL, NULL, &buttons[14], K_ESCAPE, NULL, 0, 0, 0, true);
894                 if (!VID_ShowingKeyboard())
895                 {
896                         // user entered a command, close the console now
897                         Con_ToggleConsole_f(cmd_local);
898                 }
899                 VID_TouchscreenArea( 0,   0,   0,   0,   0, NULL                         , 0.0f, NULL, NULL, &buttons[15], (keynum_t)0, NULL, 0, 0, 0, true);
900                 VID_TouchscreenArea( 0,   0,   0,   0,   0, NULL                         , 0.0f, NULL, move, &buttons[0], K_MOUSE4, NULL, 0, 0, 0, true);
901                 VID_TouchscreenArea( 0,   0,   0,   0,   0, NULL                         , 0.0f, NULL, aim,  &buttons[1], K_MOUSE5, NULL, 0, 0, 0, true);
902                 VID_TouchscreenArea( 0,   0,   0,   0,   0, NULL                         , 0.0f, NULL, click,&buttons[2], K_MOUSE1, NULL, 0, 0, 0, true);
903                 VID_TouchscreenArea( 0,   0,   0,   0,   0, NULL                         , 0.0f, NULL, NULL, &buttons[3], K_SPACE, NULL, 0, 0, 0, true);
904                 VID_TouchscreenArea( 0,   0,   0,   0,   0, NULL                         , 0.0f, NULL, NULL, &buttons[4], K_MOUSE2, NULL, 0, 0, 0, true);
905                 break;
906         case key_game:
907                 VID_TouchscreenArea( 0,   0,   0,  64,  64, NULL                         , 0.0f, NULL, NULL, &buttons[13], (keynum_t)'`', NULL, 0, 0, 0, true);
908                 VID_TouchscreenArea( 0,  64,   0,  64,  64, "gfx/touch_menu.tga"         , 0.0f, NULL, NULL, &buttons[14], K_ESCAPE, NULL, 0, 0, 0, true);
909                 VID_TouchscreenArea( 2,   0,-128, 128, 128, "gfx/touch_movebutton.tga"   , 0.0f, NULL, move, &buttons[0], K_MOUSE4, NULL, 0, 0, 0, true);
910                 VID_TouchscreenArea( 3,-128,-128, 128, 128, "gfx/touch_aimbutton.tga"    , 0.0f, NULL, aim,  &buttons[1], K_MOUSE5, NULL, 0, 0, 0, true);
911                 VID_TouchscreenArea( 2,   0,-160,  64,  32, "gfx/touch_jumpbutton.tga"   , 0.0f, NULL, NULL, &buttons[3], K_SPACE, NULL, 0, 0, 0, true);
912                 VID_TouchscreenArea( 3,-128,-160,  64,  32, "gfx/touch_attackbutton.tga" , 0.0f, NULL, NULL, &buttons[2], K_MOUSE1, NULL, 0, 0, 0, true);
913                 VID_TouchscreenArea( 3, -64,-160,  64,  32, "gfx/touch_attack2button.tga", 0.0f, NULL, NULL, &buttons[4], K_MOUSE2, NULL, 0, 0, 0, true);
914                 buttons[15] = false;
915                 break;
916         default:
917                 VID_TouchscreenArea( 0,   0,   0,  64,  64, NULL                         , 0.0f, NULL, NULL, &buttons[13], (keynum_t)'`', NULL, 0, 0, 0, true);
918                 VID_TouchscreenArea( 0,  64,   0,  64,  64, "gfx/touch_menu.tga"         , 0.0f, NULL, NULL, &buttons[14], K_ESCAPE, NULL, 0, 0, 0, true);
919                 // in menus, an icon in the corner activates keyboard
920                 VID_TouchscreenArea( 2,   0, -32,  32,  32, "gfx/touch_keyboard.tga"     , 0.0f, NULL, NULL, &buttons[15], (keynum_t)0, NULL, 0, 0, 0, true);
921                 if (buttons[15])
922                         VID_ShowKeyboard(true);
923                 VID_TouchscreenArea( 0,   0,   0,   0,   0, NULL                         , 0.0f, NULL, move, &buttons[0], K_MOUSE4, NULL, 0, 0, 0, true);
924                 VID_TouchscreenArea( 0,   0,   0,   0,   0, NULL                         , 0.0f, NULL, aim,  &buttons[1], K_MOUSE5, NULL, 0, 0, 0, true);
925                 VID_TouchscreenArea(16, -320,-480,640, 960, NULL                         , 0.0f, NULL, click,&buttons[2], K_MOUSE1, NULL, 0, 0, 0, true);
926                 VID_TouchscreenArea( 0,   0,   0,   0,   0, NULL                         , 0.0f, NULL, NULL, &buttons[3], K_SPACE, NULL, 0, 0, 0, true);
927                 VID_TouchscreenArea( 0,   0,   0,   0,   0, NULL                         , 0.0f, NULL, NULL, &buttons[4], K_MOUSE2, NULL, 0, 0, 0, true);
928                 if (buttons[2])
929                 {
930                         in_windowmouse_x = x;
931                         in_windowmouse_y = y;
932                 }
933                 break;
934         }
935
936         cl.cmd.forwardmove -= move[1] * cl_forwardspeed.value;
937         cl.cmd.sidemove += move[0] * cl_sidespeed.value;
938         cl.viewangles[0] += aim[1] * cl_pitchspeed.value * cl.realframetime;
939         cl.viewangles[1] -= aim[0] * cl_yawspeed.value * cl.realframetime;
940 }
941
942 void IN_Move( void )
943 {
944         static int old_x = 0, old_y = 0;
945         static int stuck = 0;
946         static keydest_t oldkeydest;
947         static qbool oldshowkeyboard;
948         int x, y;
949         vid_joystate_t joystate;
950         keydest_t keydest = (key_consoleactive & KEY_CONSOLEACTIVE_USER) ? key_console : key_dest;
951
952         scr_numtouchscreenareas = 0;
953
954         // Only apply the new keyboard state if the input changes.
955         if (keydest != oldkeydest || !!vid_touchscreen_showkeyboard.integer != oldshowkeyboard)
956         {
957                 switch(keydest)
958                 {
959                         case key_console: VID_ShowKeyboard(true);break;
960                         case key_message: VID_ShowKeyboard(true);break;
961                         default: VID_ShowKeyboard(!!vid_touchscreen_showkeyboard.integer); break;
962                 }
963         }
964         oldkeydest = keydest;
965         oldshowkeyboard = !!vid_touchscreen_showkeyboard.integer;
966
967         if (vid_touchscreen.integer)
968         {
969                 switch(gamemode)
970                 {
971                 case GAME_STEELSTORM:
972                         IN_Move_TouchScreen_SteelStorm();
973                         break;
974                 default:
975                         IN_Move_TouchScreen_Quake();
976                         break;
977                 }
978         }
979         else
980         {
981                 if (vid_usingmouse)
982                 {
983                         if (vid_stick_mouse.integer || !vid_usingmouse_relativeworks)
984                         {
985                                 // have the mouse stuck in the middle, example use: prevent expose effect of beryl during the game when not using
986                                 // window grabbing. --blub
987         
988                                 // we need 2 frames to initialize the center position
989                                 if(!stuck)
990                                 {
991                                         SDL_WarpMouseInWindow(window, win_half_width, win_half_height);
992                                         SDL_GetMouseState(&x, &y);
993                                         SDL_GetRelativeMouseState(&x, &y);
994                                         ++stuck;
995                                 } else {
996                                         SDL_GetRelativeMouseState(&x, &y);
997                                         in_mouse_x = x + old_x;
998                                         in_mouse_y = y + old_y;
999                                         SDL_GetMouseState(&x, &y);
1000                                         old_x = x - win_half_width;
1001                                         old_y = y - win_half_height;
1002                                         SDL_WarpMouseInWindow(window, win_half_width, win_half_height);
1003                                 }
1004                         } else {
1005                                 SDL_GetRelativeMouseState( &x, &y );
1006                                 in_mouse_x = x;
1007                                 in_mouse_y = y;
1008                         }
1009                 }
1010
1011                 SDL_GetMouseState(&x, &y);
1012                 in_windowmouse_x = x;
1013                 in_windowmouse_y = y;
1014         }
1015
1016         //Con_Printf("Mouse position: in_mouse %f %f in_windowmouse %f %f\n", in_mouse_x, in_mouse_y, in_windowmouse_x, in_windowmouse_y);
1017
1018         VID_BuildJoyState(&joystate);
1019         VID_ApplyJoyState(&joystate);
1020 }
1021
1022 /////////////////////
1023 // Message Handling
1024 ////
1025
1026 #ifdef SDL_R_RESTART
1027 static qbool sdl_needs_restart;
1028 static void sdl_start(void)
1029 {
1030 }
1031 static void sdl_shutdown(void)
1032 {
1033         sdl_needs_restart = false;
1034 }
1035 static void sdl_newmap(void)
1036 {
1037 }
1038 #endif
1039
1040 static keynum_t buttonremap[] =
1041 {
1042         K_MOUSE1,
1043         K_MOUSE3,
1044         K_MOUSE2,
1045         K_MOUSE4,
1046         K_MOUSE5,
1047         K_MOUSE6,
1048         K_MOUSE7,
1049         K_MOUSE8,
1050         K_MOUSE9,
1051         K_MOUSE10,
1052         K_MOUSE11,
1053         K_MOUSE12,
1054         K_MOUSE13,
1055         K_MOUSE14,
1056         K_MOUSE15,
1057         K_MOUSE16,
1058 };
1059
1060 //#define DEBUGSDLEVENTS
1061 static void VID_ChangeDisplay_c(cvar_t *var);
1062 void Sys_SDL_HandleEvents(void)
1063 {
1064         static qbool sound_active = true;
1065         int keycode;
1066         int i;
1067         const char *chp;
1068         qbool isdown;
1069         Uchar unicode;
1070         SDL_Event event;
1071
1072         VID_EnableJoystick(true);
1073
1074         while( SDL_PollEvent( &event ) )
1075                 loop_start:
1076                 switch( event.type ) {
1077                         case SDL_QUIT:
1078 #ifdef DEBUGSDLEVENTS
1079                                 Con_DPrintf("SDL_Event: SDL_QUIT\n");
1080 #endif
1081                                 host.state = host_shutdown;
1082                                 break;
1083                         case SDL_KEYDOWN:
1084                         case SDL_KEYUP:
1085 #ifdef DEBUGSDLEVENTS
1086                                 if (event.type == SDL_KEYDOWN)
1087                                         Con_DPrintf("SDL_Event: SDL_KEYDOWN %i\n", event.key.keysym.sym);
1088                                 else
1089                                         Con_DPrintf("SDL_Event: SDL_KEYUP %i\n", event.key.keysym.sym);
1090 #endif
1091                                 keycode = MapKey(event.key.keysym.sym);
1092                                 isdown = (event.key.state == SDL_PRESSED);
1093                                 unicode = 0;
1094                                 if(isdown)
1095                                 {
1096                                         if(SDL_PollEvent(&event))
1097                                         {
1098                                                 if(event.type == SDL_TEXTINPUT)
1099                                                 {
1100                                                         // combine key code from SDL_KEYDOWN event and character
1101                                                         // from SDL_TEXTINPUT event in a single Key_Event call
1102 #ifdef DEBUGSDLEVENTS
1103                                                         Con_DPrintf("SDL_Event: SDL_TEXTINPUT - text: %s\n", event.text.text);
1104 #endif
1105                                                         unicode = u8_getchar_utf8_enabled(event.text.text + (int)u8_bytelen(event.text.text, 0), NULL);
1106                                                 }
1107                                                 else
1108                                                 {
1109                                                         if (!VID_JoyBlockEmulatedKeys(keycode))
1110                                                                 Key_Event(keycode, 0, isdown);
1111                                                         goto loop_start;
1112                                                 }
1113                                         }
1114                                 }
1115                                 if (!VID_JoyBlockEmulatedKeys(keycode))
1116                                         Key_Event(keycode, unicode, isdown);
1117                                 break;
1118                         case SDL_MOUSEBUTTONDOWN:
1119                         case SDL_MOUSEBUTTONUP:
1120 #ifdef DEBUGSDLEVENTS
1121                                 if (event.type == SDL_MOUSEBUTTONDOWN)
1122                                         Con_DPrintf("SDL_Event: SDL_MOUSEBUTTONDOWN\n");
1123                                 else
1124                                         Con_DPrintf("SDL_Event: SDL_MOUSEBUTTONUP\n");
1125 #endif
1126                                 if (!vid_touchscreen.integer)
1127                                 if (event.button.button > 0 && event.button.button <= ARRAY_SIZE(buttonremap))
1128                                         Key_Event( buttonremap[event.button.button - 1], 0, event.button.state == SDL_PRESSED );
1129                                 break;
1130                         case SDL_MOUSEWHEEL:
1131                                 // TODO support wheel x direction.
1132                                 i = event.wheel.y;
1133                                 while (i > 0) {
1134                                         --i;
1135                                         Key_Event( K_MWHEELUP, 0, true );
1136                                         Key_Event( K_MWHEELUP, 0, false );
1137                                 }
1138                                 while (i < 0) {
1139                                         ++i;
1140                                         Key_Event( K_MWHEELDOWN, 0, true );
1141                                         Key_Event( K_MWHEELDOWN, 0, false );
1142                                 }
1143                                 break;
1144                         case SDL_JOYBUTTONDOWN:
1145                         case SDL_JOYBUTTONUP:
1146                         case SDL_JOYAXISMOTION:
1147                         case SDL_JOYBALLMOTION:
1148                         case SDL_JOYHATMOTION:
1149 #ifdef DEBUGSDLEVENTS
1150                                 Con_DPrintf("SDL_Event: SDL_JOY*\n");
1151 #endif
1152                                 break;
1153                         case SDL_WINDOWEVENT:
1154 #ifdef DEBUGSDLEVENTS
1155                                 Con_DPrintf("SDL_Event: SDL_WINDOWEVENT %i\n", (int)event.window.event);
1156 #endif
1157                                 //if (event.window.windowID == window) // how to compare?
1158                                 {
1159                                         switch(event.window.event)
1160                                         {
1161                                         case SDL_WINDOWEVENT_SHOWN:
1162                                                 vid_hidden = false;
1163                                                 break;
1164                                         case  SDL_WINDOWEVENT_HIDDEN:
1165                                                 vid_hidden = true;
1166                                                 break;
1167                                         case SDL_WINDOWEVENT_EXPOSED:
1168 #ifdef DEBUGSDLEVENTS
1169                                                 Con_DPrintf("SDL_Event: SDL_WINDOWEVENT_EXPOSED\n");
1170 #endif
1171                                                 break;
1172                                         case SDL_WINDOWEVENT_MOVED:
1173                                                 vid.xPos = event.window.data1;
1174                                                 vid.yPos = event.window.data2;
1175                                                 // Update vid.displayindex (current monitor) as it may have changed
1176                                                 // SDL_GetWindowDisplayIndex() doesn't work if the window manager moves the fullscreen window, but this works:
1177                                                 for (i = 0; i < vid_info_displaycount.integer; ++i)
1178                                                 {
1179                                                         SDL_Rect displaybounds;
1180                                                         if (SDL_GetDisplayBounds(i, &displaybounds) < 0)
1181                                                         {
1182                                                                 Con_Printf(CON_ERROR "Error getting bounds of display %i: \"%s\"\n", i, SDL_GetError());
1183                                                                 return;
1184                                                         }
1185                                                         if (vid.xPos >= displaybounds.x && vid.xPos < displaybounds.x + displaybounds.w)
1186                                                         if (vid.yPos >= displaybounds.y && vid.yPos < displaybounds.y + displaybounds.h)
1187                                                         {
1188                                                                 vid.displayindex = i;
1189                                                                 break;
1190                                                         }
1191                                                 }
1192                                                 // when the window manager adds/removes the border it's likely to move the SDL window
1193                                                 // we'll need to correct that to (re)align the xhair with the monitor
1194                                                 if (vid_wmborder_waiting)
1195                                                 {
1196                                                         SDL_GetWindowBordersSize(window, &i, NULL, NULL, NULL);
1197                                                         if (!i != vid_wmborderless) // border state changed
1198                                                         {
1199                                                                 SDL_SetWindowPosition(window, SDL_WINDOWPOS_CENTERED_DISPLAY(vid.displayindex), SDL_WINDOWPOS_CENTERED_DISPLAY(vid.displayindex));
1200                                                                 SDL_GetWindowPosition(window, &vid.xPos, &vid.yPos);
1201                                                                 vid_wmborder_waiting = false;
1202                                                         }
1203                                                 }
1204                                                 break;
1205                                         case SDL_WINDOWEVENT_RESIZED: // external events only
1206                                                 if(vid_resizable.integer < 2)
1207                                                 {
1208                                                         //vid.width = event.window.data1;
1209                                                         //vid.height = event.window.data2;
1210                                                         // get the real framebuffer size in case the platform's screen coordinates are DPI scaled
1211                                                         SDL_GL_GetDrawableSize(window, &vid.width, &vid.height);
1212 #ifdef SDL_R_RESTART
1213                                                         // better not call R_Modules_Restart_f from here directly, as this may wreak havoc...
1214                                                         // so, let's better queue it for next frame
1215                                                         if(!sdl_needs_restart)
1216                                                         {
1217                                                                 Cbuf_AddText(cmd_local, "\nr_restart\n");
1218                                                                 sdl_needs_restart = true;
1219                                                         }
1220 #endif
1221                                                 }
1222                                                 break;
1223                                         case SDL_WINDOWEVENT_SIZE_CHANGED: // internal and external events
1224                                                 break;
1225                                         case SDL_WINDOWEVENT_MINIMIZED:
1226                                                 break;
1227                                         case SDL_WINDOWEVENT_MAXIMIZED:
1228                                                 break;
1229                                         case SDL_WINDOWEVENT_RESTORED:
1230                                                 break;
1231                                         case SDL_WINDOWEVENT_ENTER:
1232                                                 break;
1233                                         case SDL_WINDOWEVENT_LEAVE:
1234                                                 break;
1235                                         case SDL_WINDOWEVENT_FOCUS_GAINED:
1236                                                 vid_hasfocus = true;
1237                                                 break;
1238                                         case SDL_WINDOWEVENT_FOCUS_LOST:
1239                                                 vid_hasfocus = false;
1240                                                 break;
1241                                         case SDL_WINDOWEVENT_CLOSE:
1242                                                 host.state = host_shutdown;
1243                                                 break;
1244                                         case SDL_WINDOWEVENT_TAKE_FOCUS:
1245                                                 break;
1246                                         case SDL_WINDOWEVENT_HIT_TEST:
1247                                                 break;
1248                                         case SDL_WINDOWEVENT_ICCPROF_CHANGED:
1249                                                 break;
1250                                         case SDL_WINDOWEVENT_DISPLAY_CHANGED:
1251                                                 // this event can't be relied on in fullscreen, see SDL_WINDOWEVENT_MOVED above
1252                                                 vid.displayindex = event.window.data1;
1253                                                 break;
1254                                         }
1255                                 }
1256                                 break;
1257                         case SDL_DISPLAYEVENT: // Display hotplugging
1258                                 switch (event.display.event)
1259                                 {
1260                                         case SDL_DISPLAYEVENT_CONNECTED:
1261                                                 Con_Printf("Display %i connected: %s\nA vid_restart may be necessary!\n", event.display.display, SDL_GetDisplayName(event.display.display));
1262                                                 Cvar_SetValueQuick(&vid_info_displaycount, SDL_GetNumVideoDisplays());
1263                                                 // Ideally we'd call VID_ChangeDisplay_c() to try to switch to the preferred display here,
1264                                                 // but we may need a vid_restart first, see comments in VID_ChangeDisplay_c().
1265                                                 break;
1266                                         case SDL_DISPLAYEVENT_DISCONNECTED:
1267                                                 Con_Printf("Display %i disconnected.\nA vid_restart may be necessary!\n", event.display.display);
1268                                                 Cvar_SetValueQuick(&vid_info_displaycount, SDL_GetNumVideoDisplays());
1269                                                 break;
1270                                         case SDL_DISPLAYEVENT_ORIENTATION:
1271                                                 break;
1272                                 }
1273                                 break;
1274                         case SDL_TEXTEDITING:
1275 #ifdef DEBUGSDLEVENTS
1276                                 Con_DPrintf("SDL_Event: SDL_TEXTEDITING - composition = %s, cursor = %d, selection lenght = %d\n", event.edit.text, event.edit.start, event.edit.length);
1277 #endif
1278                                 // FIXME!  this is where composition gets supported
1279                                 break;
1280                         case SDL_TEXTINPUT:
1281 #ifdef DEBUGSDLEVENTS
1282                                 Con_DPrintf("SDL_Event: SDL_TEXTINPUT - text: %s\n", event.text.text);
1283 #endif
1284                                 // convert utf8 string to char
1285                                 // NOTE: this code is supposed to run even if utf8enable is 0
1286                                 chp = event.text.text;
1287                                 while (*chp != 0)
1288                                 {
1289                                         // input the chars one by one (there can be multiple chars when e.g. using an "input method")
1290                                         unicode = u8_getchar_utf8_enabled(chp, &chp);
1291                                         Key_Event(K_TEXT, unicode, true);
1292                                         Key_Event(K_TEXT, unicode, false);
1293                                 }
1294                                 break;
1295                         case SDL_MOUSEMOTION:
1296                                 break;
1297                         case SDL_FINGERDOWN:
1298 #ifdef DEBUGSDLEVENTS
1299                                 Con_DPrintf("SDL_FINGERDOWN for finger %i\n", (int)event.tfinger.fingerId);
1300 #endif
1301                                 for (i = 0;i < MAXFINGERS-1;i++)
1302                                 {
1303                                         if (!multitouch[i][0])
1304                                         {
1305                                                 multitouch[i][0] = event.tfinger.fingerId + 1;
1306                                                 multitouch[i][1] = event.tfinger.x;
1307                                                 multitouch[i][2] = event.tfinger.y;
1308                                                 // TODO: use event.tfinger.pressure?
1309                                                 break;
1310                                         }
1311                                 }
1312                                 if (i == MAXFINGERS-1)
1313                                         Con_DPrintf("Too many fingers at once!\n");
1314                                 break;
1315                         case SDL_FINGERUP:
1316 #ifdef DEBUGSDLEVENTS
1317                                 Con_DPrintf("SDL_FINGERUP for finger %i\n", (int)event.tfinger.fingerId);
1318 #endif
1319                                 for (i = 0;i < MAXFINGERS-1;i++)
1320                                 {
1321                                         if (multitouch[i][0] == event.tfinger.fingerId + 1)
1322                                         {
1323                                                 multitouch[i][0] = 0;
1324                                                 break;
1325                                         }
1326                                 }
1327                                 if (i == MAXFINGERS-1)
1328                                         Con_DPrintf("No SDL_FINGERDOWN event matches this SDL_FINGERMOTION event\n");
1329                                 break;
1330                         case SDL_FINGERMOTION:
1331 #ifdef DEBUGSDLEVENTS
1332                                 Con_DPrintf("SDL_FINGERMOTION for finger %i\n", (int)event.tfinger.fingerId);
1333 #endif
1334                                 for (i = 0;i < MAXFINGERS-1;i++)
1335                                 {
1336                                         if (multitouch[i][0] == event.tfinger.fingerId + 1)
1337                                         {
1338                                                 multitouch[i][1] = event.tfinger.x;
1339                                                 multitouch[i][2] = event.tfinger.y;
1340                                                 break;
1341                                         }
1342                                 }
1343                                 if (i == MAXFINGERS-1)
1344                                         Con_DPrintf("No SDL_FINGERDOWN event matches this SDL_FINGERMOTION event\n");
1345                                 break;
1346                         default:
1347 #ifdef DEBUGSDLEVENTS
1348                                 Con_DPrintf("Received unrecognized SDL_Event type 0x%x\n", event.type);
1349 #endif
1350                                 break;
1351                 }
1352
1353         vid_activewindow = !vid_hidden && vid_hasfocus;
1354
1355         // enable/disable sound on focus gain/loss
1356         if (vid_activewindow || !snd_mutewhenidle.integer)
1357         {
1358                 if (!sound_active)
1359                 {
1360                         S_UnblockSound ();
1361                         sound_active = true;
1362                 }
1363         }
1364         else
1365         {
1366                 if (sound_active)
1367                 {
1368                         S_BlockSound ();
1369                         sound_active = false;
1370                 }
1371         }
1372
1373         if (!vid_activewindow || key_consoleactive || scr_loading)
1374                 VID_SetMouse(false, false);
1375         else if (key_dest == key_menu || key_dest == key_menu_grabbed)
1376                 VID_SetMouse(vid_mouse.integer && !in_client_mouse && !vid_touchscreen.integer, !vid_touchscreen.integer);
1377         else
1378                 VID_SetMouse(vid_mouse.integer && !cl.csqc_wantsmousemove && cl_prydoncursor.integer <= 0 && (!cls.demoplayback || cl_demo_mousegrab.integer) && !vid_touchscreen.integer, !vid_touchscreen.integer);
1379 }
1380
1381 /////////////////
1382 // Video system
1383 ////
1384
1385 void *GL_GetProcAddress(const char *name)
1386 {
1387         void *p = NULL;
1388         p = SDL_GL_GetProcAddress(name);
1389         return p;
1390 }
1391
1392 qbool GL_ExtensionSupported(const char *name)
1393 {
1394         return SDL_GL_ExtensionSupported(name);
1395 }
1396
1397 static void VID_ChangeDisplay_c(cvar_t *var)
1398 {
1399         unsigned int fullscreenwanted, fullscreencurrent;
1400         unsigned int displaywanted = bound(0, vid_display.integer, vid_info_displaycount.integer - 1);
1401
1402         if (!window)
1403                 return;
1404
1405         fullscreencurrent = SDL_GetWindowFlags(window) & (SDL_WINDOW_FULLSCREEN_DESKTOP | SDL_WINDOW_FULLSCREEN);
1406         if (vid_fullscreen.integer)
1407                 fullscreenwanted = vid_desktopfullscreen.integer ? SDL_WINDOW_FULLSCREEN_DESKTOP : SDL_WINDOW_FULLSCREEN;
1408         else
1409                 fullscreenwanted = 0;
1410
1411         // moving to another display, changing the fullscreen mode or switching to windowed
1412         if (vid.displayindex != displaywanted // SDL seems unable to move any fullscreen window to another display
1413         || fullscreencurrent != fullscreenwanted) // even for desktop <-> exclusive: switching to windowed first feels safer
1414         {
1415                 if (SDL_SetWindowFullscreen(window, 0) < 0)
1416                 {
1417                         Con_Printf(CON_ERROR "ERROR: can't deactivate fullscreen on display %i because %s\n", vid.displayindex, SDL_GetError());
1418                         return;
1419                 }
1420                 vid.fullscreen = false;
1421                 Con_DPrintf("Fullscreen deactivated on display %i\n", vid.displayindex);
1422         }
1423
1424         // switching to windowed
1425         if (!fullscreenwanted)
1426         {
1427                 int toppx;
1428                 SDL_SetWindowSize(window, vid.width = vid_width.integer, vid.height = vid_height.integer);
1429                 SDL_SetWindowResizable(window, vid_resizable.integer ? SDL_TRUE : SDL_FALSE);
1430                 SDL_SetWindowBordered(window, (SDL_bool)!vid_borderless.integer);
1431                 SDL_GetWindowBordersSize(window, &toppx, NULL, NULL, NULL);
1432                 vid_wmborderless = !toppx;
1433                 if (vid_borderless.integer != vid_wmborderless) // this is not the state we're looking for
1434                         vid_wmborder_waiting = true;
1435         }
1436
1437         // moving to another display or switching to windowed
1438         if (vid.displayindex != displaywanted || !fullscreenwanted)
1439         {
1440 //              SDL_SetWindowPosition(window, SDL_WINDOWPOS_CENTERED_DISPLAY(displaywanted), SDL_WINDOWPOS_CENTERED_DISPLAY(displaywanted));
1441 //              SDL_GetWindowPosition(window, &vid.xPos, &vid.yPos);
1442
1443                 /* bones_was_here BUG: after SDL_DISPLAYEVENT hotplug events,
1444                  * SDL_WINDOWPOS_CENTERED_DISPLAY(displaywanted) may place the window somewhere completely invisible.
1445                  * WORKAROUND: manual positioning seems safer: although SDL_GetDisplayBounds() may return outdated values,
1446                  * SDL_SetWindowPosition() always placed the window somewhere fully visible, even if it wasn't correct,
1447                  * when tested with SDL 2.26.5.
1448                  */
1449                 SDL_Rect displaybounds;
1450                 if (SDL_GetDisplayBounds(displaywanted, &displaybounds) < 0)
1451                 {
1452                         Con_Printf(CON_ERROR "Error getting bounds of display %i: \"%s\"\n", displaywanted, SDL_GetError());
1453                         return;
1454                 }
1455                 vid.xPos = displaybounds.x + 0.5 * (displaybounds.w - vid.width);
1456                 vid.yPos = displaybounds.y + 0.5 * (displaybounds.h - vid.height);
1457                 SDL_SetWindowPosition(window, vid.xPos, vid.yPos);
1458
1459                 vid.displayindex = displaywanted;
1460         }
1461
1462         // switching to a fullscreen mode
1463         if (fullscreenwanted)
1464         {
1465                 if (SDL_SetWindowFullscreen(window, fullscreenwanted) < 0)
1466                 {
1467                         Con_Printf(CON_ERROR "ERROR: can't activate fullscreen on display %i because %s\n", vid.displayindex, SDL_GetError());
1468                         return;
1469                 }
1470                 // get the real framebuffer size in case the platform's screen coordinates are DPI scaled
1471                 SDL_GL_GetDrawableSize(window, &vid.width, &vid.height);
1472                 vid.fullscreen = true;
1473                 Con_DPrintf("Fullscreen activated on display %i\n", vid.displayindex);
1474         }
1475 }
1476
1477 static void VID_SetVsync_c(cvar_t *var)
1478 {
1479         signed char vsyncwanted = cls.timedemo ? 0 : bound(-1, vid_vsync.integer, 1);
1480
1481         if (!context)
1482                 return;
1483         if (SDL_GL_GetSwapInterval() == vsyncwanted)
1484                 return;
1485
1486         if (SDL_GL_SetSwapInterval(vsyncwanted) >= 0)
1487                 Con_DPrintf("Vsync %s\n", vsyncwanted ? "activated" : "deactivated");
1488         else
1489                 Con_Printf(CON_ERROR "ERROR: can't %s vsync because %s\n", vsyncwanted ? "activate" : "deactivate", SDL_GetError());
1490 }
1491
1492 void VID_Init (void)
1493 {
1494         SDL_version version;
1495
1496 #ifndef __IPHONEOS__
1497 #ifdef MACOSX
1498         Cvar_RegisterVariable(&apple_mouse_noaccel);
1499 #endif
1500 #endif
1501 #ifdef DP_MOBILETOUCH
1502         Cvar_SetValueQuick(&vid_touchscreen, 1);
1503 #endif
1504         Cvar_RegisterVariable(&joy_sdl2_trigger_deadzone);
1505
1506 #ifdef SDL_R_RESTART
1507         R_RegisterModule("SDL", sdl_start, sdl_shutdown, sdl_newmap, NULL, NULL);
1508 #endif
1509
1510 #if defined(__linux__)
1511         // exclusive fullscreen is no longer functional (and when it worked was obnoxious and not faster)
1512         Cvar_SetValueQuick(&vid_desktopfullscreen, 1);
1513         vid_desktopfullscreen.flags |= CF_READONLY;
1514 #endif
1515
1516         Cvar_RegisterCallback(&vid_fullscreen,             VID_ChangeDisplay_c);
1517         Cvar_RegisterCallback(&vid_desktopfullscreen,      VID_ChangeDisplay_c);
1518         Cvar_RegisterCallback(&vid_display,                VID_ChangeDisplay_c);
1519         Cvar_RegisterCallback(&vid_resizable,              VID_ChangeDisplay_c);
1520         Cvar_RegisterCallback(&vid_borderless,             VID_ChangeDisplay_c);
1521         Cvar_RegisterCallback(&vid_vsync,                  VID_SetVsync_c);
1522
1523         if (SDL_Init(SDL_INIT_VIDEO) < 0)
1524                 Sys_Error ("Failed to init SDL video subsystem: %s", SDL_GetError());
1525         if (SDL_InitSubSystem(SDL_INIT_JOYSTICK) < 0)
1526                 Con_Printf(CON_ERROR "Failed to init SDL joystick subsystem: %s\n", SDL_GetError());
1527
1528         SDL_GetVersion(&version);
1529         Con_Printf("Linked against SDL version %d.%d.%d\n"
1530                    "Using SDL library version %d.%d.%d\n",
1531                    SDL_MAJOR_VERSION, SDL_MINOR_VERSION, SDL_PATCHLEVEL,
1532                    version.major, version.minor, version.patch);
1533 }
1534
1535 static int vid_sdljoystickindex = -1;
1536 void VID_EnableJoystick(qbool enable)
1537 {
1538         int index = joy_enable.integer > 0 ? joy_index.integer : -1;
1539         int numsdljoysticks;
1540         qbool success = false;
1541         int sharedcount = 0;
1542         int sdlindex = -1;
1543         sharedcount = VID_Shared_SetJoystick(index);
1544         if (index >= 0 && index < sharedcount)
1545                 success = true;
1546         sdlindex = index - sharedcount;
1547
1548         numsdljoysticks = SDL_NumJoysticks();
1549         if (sdlindex < 0 || sdlindex >= numsdljoysticks)
1550                 sdlindex = -1;
1551
1552         // update cvar containing count of XInput joysticks + SDL joysticks
1553         if (joy_detected.integer != sharedcount + numsdljoysticks)
1554                 Cvar_SetValueQuick(&joy_detected, sharedcount + numsdljoysticks);
1555
1556         if (vid_sdljoystickindex != sdlindex)
1557         {
1558                 vid_sdljoystickindex = sdlindex;
1559                 // close SDL joystick if active
1560                 if (vid_sdljoystick)
1561                 {
1562                         SDL_JoystickClose(vid_sdljoystick);
1563                         vid_sdljoystick = NULL;
1564                 }
1565                 if (vid_sdlgamecontroller)
1566                 {
1567                         SDL_GameControllerClose(vid_sdlgamecontroller);
1568                         vid_sdlgamecontroller = NULL;
1569                 }
1570                 if (sdlindex >= 0)
1571                 {
1572                         vid_sdljoystick = SDL_JoystickOpen(sdlindex);
1573                         if (vid_sdljoystick)
1574                         {
1575                                 const char *joystickname = SDL_JoystickName(vid_sdljoystick);
1576                                 if (SDL_IsGameController(vid_sdljoystickindex))
1577                                 {
1578                                         vid_sdlgamecontroller = SDL_GameControllerOpen(vid_sdljoystickindex);
1579                                         Con_DPrintf("Using SDL GameController mappings for Joystick %i\n", index);
1580                                 }
1581                                 Con_Printf("Joystick %i opened (SDL_Joystick %i is \"%s\" with %i axes, %i buttons, %i balls)\n", index, sdlindex, joystickname, (int)SDL_JoystickNumAxes(vid_sdljoystick), (int)SDL_JoystickNumButtons(vid_sdljoystick), (int)SDL_JoystickNumBalls(vid_sdljoystick));
1582                         }
1583                         else
1584                         {
1585                                 Con_Printf(CON_ERROR "Joystick %i failed (SDL_JoystickOpen(%i) returned: %s)\n", index, sdlindex, SDL_GetError());
1586                                 sdlindex = -1;
1587                         }
1588                 }
1589         }
1590
1591         if (sdlindex >= 0)
1592                 success = true;
1593
1594         if (joy_active.integer != (success ? 1 : 0))
1595                 Cvar_SetValueQuick(&joy_active, success ? 1 : 0);
1596 }
1597
1598 #ifdef WIN32
1599 static void AdjustWindowBounds(viddef_mode_t *mode, RECT *rect)
1600 {
1601         int workWidth;
1602         int workHeight;
1603         int titleBarPixels = 2;
1604         int screenHeight;
1605         RECT workArea;
1606         LONG width = mode->width; // vid_width
1607         LONG height = mode->height; // vid_height
1608
1609         // adjust width and height for the space occupied by window decorators (title bar, borders)
1610         rect->top = 0;
1611         rect->left = 0;
1612         rect->right = width;
1613         rect->bottom = height;
1614         AdjustWindowRectEx(rect, WS_CAPTION|WS_THICKFRAME, false, 0);
1615
1616         SystemParametersInfo(SPI_GETWORKAREA, 0, &workArea, 0);
1617         workWidth = workArea.right - workArea.left;
1618         workHeight = workArea.bottom - workArea.top;
1619
1620         // SDL forces the window height to be <= screen height - 27px (on Win8.1 - probably intended for the title bar) 
1621         // If the task bar is docked to the the left screen border and we move the window to negative y,
1622         // there would be some part of the regular desktop visible on the bottom of the screen.
1623         screenHeight = GetSystemMetrics(SM_CYSCREEN);
1624         if (screenHeight == workHeight)
1625                 titleBarPixels = -rect->top;
1626
1627         //Con_Printf("window mode: %dx%d, workArea: %d/%d-%d/%d (%dx%d), title: %d\n", width, height, workArea.left, workArea.top, workArea.right, workArea.bottom, workArea.right - workArea.left, workArea.bottom - workArea.top, titleBarPixels);
1628
1629         // if height and width matches the physical or previously adjusted screen height and width, adjust it to available desktop area
1630         if ((width == GetSystemMetrics(SM_CXSCREEN) || width == workWidth) && (height == screenHeight || height == workHeight - titleBarPixels))
1631         {
1632                 rect->left = workArea.left;
1633                 mode->width = workWidth;
1634                 rect->top = workArea.top + titleBarPixels;
1635                 mode->height = workHeight - titleBarPixels;
1636         }
1637         else 
1638         {
1639                 rect->left = workArea.left + max(0, (workWidth - width) / 2);
1640                 rect->top = workArea.top + max(0, (workHeight - height) / 2);
1641         }
1642 }
1643 #endif
1644
1645 static qbool VID_InitModeGL(viddef_mode_t *mode)
1646 {
1647         int windowflags = SDL_WINDOW_SHOWN | SDL_WINDOW_OPENGL;
1648         int i;
1649 #ifndef USE_GLES2
1650         // SDL usually knows best
1651         const char *drivername = NULL;
1652 #endif
1653
1654         // video display selection (multi-monitor)
1655         Cvar_SetValueQuick(&vid_info_displaycount, SDL_GetNumVideoDisplays());
1656         vid.displayindex = bound(0, vid_display.integer, vid_info_displaycount.integer - 1);
1657         vid.xPos = SDL_WINDOWPOS_CENTERED_DISPLAY(vid.displayindex);
1658         vid.yPos = SDL_WINDOWPOS_CENTERED_DISPLAY(vid.displayindex);
1659         vid_wmborder_waiting = vid_wmborderless = false;
1660
1661         win_half_width = mode->width>>1;
1662         win_half_height = mode->height>>1;
1663
1664         if(vid_resizable.integer)
1665                 windowflags |= SDL_WINDOW_RESIZABLE;
1666
1667 #ifndef USE_GLES2
1668 // COMMANDLINEOPTION: SDL GL: -gl_driver <drivername> selects a GL driver library, default is whatever SDL recommends, useful only for 3dfxogl.dll/3dfxvgl.dll or fxmesa or similar, if you don't know what this is for, you don't need it
1669         i = Sys_CheckParm("-gl_driver");
1670         if (i && i < sys.argc - 1)
1671                 drivername = sys.argv[i + 1];
1672         if (SDL_GL_LoadLibrary(drivername) < 0)
1673         {
1674                 Con_Printf(CON_ERROR "Unable to load GL driver \"%s\": %s\n", drivername, SDL_GetError());
1675                 return false;
1676         }
1677 #endif
1678
1679 #ifdef DP_MOBILETOUCH
1680         // mobile platforms are always fullscreen, we'll get the resolution after opening the window
1681         mode->fullscreen = true;
1682         // hide the menu with SDL_WINDOW_BORDERLESS
1683         windowflags |= SDL_WINDOW_FULLSCREEN | SDL_WINDOW_BORDERLESS;
1684 #endif
1685
1686
1687         if (mode->fullscreen)
1688         {
1689                 if (vid_desktopfullscreen.integer)
1690                 {
1691                         vid_mode_t m = VID_GetDesktopMode();
1692                         mode->width = m.width;
1693                         mode->height = m.height;
1694                         windowflags |= SDL_WINDOW_FULLSCREEN_DESKTOP;
1695                 }
1696                 else
1697                         windowflags |= SDL_WINDOW_FULLSCREEN;
1698         }
1699         else
1700         {
1701                 if (vid_borderless.integer)
1702                         windowflags |= SDL_WINDOW_BORDERLESS;
1703                 else
1704                         vid_wmborder_waiting = true; // waiting for border to be added
1705 #ifdef WIN32
1706                 if (!vid_ignore_taskbar.integer)
1707                 {
1708                         RECT rect;
1709                         AdjustWindowBounds(mode, &rect);
1710                         vid.xPos = rect.left;
1711                         vid.xPos = rect.top;
1712                         vid_wmborder_waiting = false;
1713                 }
1714 #endif
1715         }
1716
1717         // DPI scaling prevents use of the native resolution, causing blurry rendering
1718         // and/or mouse cursor problems, so we need to opt-out.
1719 #ifdef WIN32
1720         SDL_SetHint(SDL_HINT_WINDOWS_DPI_AWARENESS, "1");
1721 #endif
1722
1723         if (vid_mouse_clickthrough.integer)
1724                 SDL_SetHint(SDL_HINT_MOUSE_FOCUS_CLICKTHROUGH, "1");
1725
1726         SDL_GL_SetAttribute (SDL_GL_DOUBLEBUFFER, 1);
1727         SDL_GL_SetAttribute (SDL_GL_RED_SIZE, 8);
1728         SDL_GL_SetAttribute (SDL_GL_GREEN_SIZE, 8);
1729         SDL_GL_SetAttribute (SDL_GL_BLUE_SIZE, 8);
1730         SDL_GL_SetAttribute (SDL_GL_ALPHA_SIZE, 8);
1731         SDL_GL_SetAttribute (SDL_GL_DEPTH_SIZE, 24);
1732         SDL_GL_SetAttribute (SDL_GL_STENCIL_SIZE, 8);
1733         if (mode->stereobuffer)
1734                 SDL_GL_SetAttribute (SDL_GL_STEREO, 1);
1735         if (mode->samples > 1)
1736         {
1737                 SDL_GL_SetAttribute (SDL_GL_MULTISAMPLEBUFFERS, 1);
1738                 SDL_GL_SetAttribute (SDL_GL_MULTISAMPLESAMPLES, mode->samples);
1739         }
1740
1741 #ifdef USE_GLES2
1742         SDL_GL_SetAttribute (SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_ES);
1743         SDL_GL_SetAttribute (SDL_GL_CONTEXT_MAJOR_VERSION, 2);
1744         SDL_GL_SetAttribute (SDL_GL_CONTEXT_MINOR_VERSION, 0);
1745 #else
1746         SDL_GL_SetAttribute (SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
1747         SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
1748         SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 2);
1749         /* Requesting a Core profile and 3.2 minimum is mandatory on macOS and older Mesa drivers.
1750          * It works fine on other drivers too except NVIDIA, see HACK below.
1751          */
1752 #endif
1753
1754         SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, (gl_debug.integer > 0 ? SDL_GL_CONTEXT_DEBUG_FLAG : 0));
1755
1756         window = SDL_CreateWindow(gamename, vid.xPos, vid.yPos, mode->width, mode->height, windowflags);
1757         if (window == NULL)
1758         {
1759                 Con_Printf(CON_ERROR "Failed to set video mode to %ix%i: %s\n", mode->width, mode->height, SDL_GetError());
1760                 VID_Shutdown();
1761                 return false;
1762         }
1763         // get the real framebuffer size in case the platform's screen coordinates are DPI scaled
1764         SDL_GL_GetDrawableSize(window, &mode->width, &mode->height);
1765         // After using SDL_WINDOWPOS_CENTERED_DISPLAY we don't know the real position
1766         SDL_GetWindowPosition(window, &vid.xPos, &vid.yPos);
1767
1768         context = SDL_GL_CreateContext(window);
1769         if (context == NULL)
1770                 Sys_Error("Failed to initialize OpenGL context: %s\n", SDL_GetError());
1771
1772         GL_InitFunctions();
1773
1774 #if !defined(USE_GLES2) && !defined(MACOSX)
1775         // NVIDIA hates the Core profile and limits the version to the minimum we specified.
1776         // HACK: to detect NVIDIA we first need a context, fortunately replacing it takes a few milliseconds
1777         gl_vendor = (const char *)qglGetString(GL_VENDOR);
1778         if (strncmp(gl_vendor, "NVIDIA", 6) == 0)
1779         {
1780                 Con_DPrint("The Way It's Meant To Be Played: replacing OpenGL Core profile with Compatibility profile...\n");
1781                 SDL_GL_DeleteContext(context);
1782                 SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_COMPATIBILITY);
1783                 context = SDL_GL_CreateContext(window);
1784                 if (context == NULL)
1785                         Sys_Error("Failed to initialize OpenGL context: %s\n", SDL_GetError());
1786         }
1787 #endif
1788
1789         // apply vid_vsync
1790         Cvar_Callback(&vid_vsync);
1791
1792         vid_hidden = false;
1793         vid_activewindow = true;
1794         vid_hasfocus = true;
1795         vid_usingmouse = false;
1796         vid_usinghidecursor = false;
1797
1798         // clear to black (loading plaque will be seen over this)
1799         GL_Clear(GL_COLOR_BUFFER_BIT, NULL, 1.0f, 0);
1800         VID_Finish(); // checks vid_hidden
1801
1802         GL_Setup();
1803
1804         // VorteX: set other info
1805         Cvar_SetQuick(&gl_info_vendor, gl_vendor);
1806         Cvar_SetQuick(&gl_info_renderer, gl_renderer);
1807         Cvar_SetQuick(&gl_info_version, gl_version);
1808         Cvar_SetQuick(&gl_info_driver, drivername ? drivername : "");
1809
1810         for (i = 0; i < vid_info_displaycount.integer; ++i)
1811                 Con_Printf("Display %i: %s\n", i, SDL_GetDisplayName(i));
1812
1813         return true;
1814 }
1815
1816 qbool VID_InitMode(viddef_mode_t *mode)
1817 {
1818         // GAME_STEELSTORM specific
1819         steelstorm_showing_map = Cvar_FindVar(&cvars_all, "steelstorm_showing_map", ~0);
1820         steelstorm_showing_mousecursor = Cvar_FindVar(&cvars_all, "steelstorm_showing_mousecursor", ~0);
1821
1822         if (!SDL_WasInit(SDL_INIT_VIDEO) && SDL_InitSubSystem(SDL_INIT_VIDEO) < 0)
1823                 Sys_Error ("Failed to init SDL video subsystem: %s", SDL_GetError());
1824
1825         Cvar_SetValueQuick(&vid_touchscreen_supportshowkeyboard, SDL_HasScreenKeyboardSupport() ? 1 : 0);
1826         return VID_InitModeGL(mode);
1827 }
1828
1829 void VID_Shutdown (void)
1830 {
1831         VID_EnableJoystick(false);
1832         VID_SetMouse(false, false);
1833
1834         SDL_GL_DeleteContext(context);
1835         context = NULL;
1836         SDL_DestroyWindow(window);
1837         window = NULL;
1838
1839         SDL_QuitSubSystem(SDL_INIT_VIDEO);
1840 }
1841
1842 void VID_Finish (void)
1843 {
1844         VID_UpdateGamma();
1845
1846         if (!vid_hidden)
1847         {
1848                 switch(vid.renderpath)
1849                 {
1850                 case RENDERPATH_GL32:
1851                 case RENDERPATH_GLES2:
1852                         CHECKGLERROR
1853                         if (r_speeds.integer == 2 || gl_finish.integer)
1854                                 GL_Finish();
1855                         SDL_GL_SwapWindow(window);
1856                         break;
1857                 }
1858         }
1859 }
1860
1861 vid_mode_t VID_GetDesktopMode(void)
1862 {
1863         SDL_DisplayMode mode;
1864         int bpp;
1865         Uint32 rmask, gmask, bmask, amask;
1866         vid_mode_t desktop_mode;
1867
1868         SDL_GetDesktopDisplayMode(vid.displayindex, &mode);
1869         SDL_PixelFormatEnumToMasks(mode.format, &bpp, &rmask, &gmask, &bmask, &amask);
1870         desktop_mode.width = mode.w;
1871         desktop_mode.height = mode.h;
1872         desktop_mode.bpp = bpp;
1873         desktop_mode.refreshrate = mode.refresh_rate;
1874         desktop_mode.pixelheight_num = 1;
1875         desktop_mode.pixelheight_denom = 1; // SDL does not provide this
1876         return desktop_mode;
1877 }
1878
1879 size_t VID_ListModes(vid_mode_t *modes, size_t maxcount)
1880 {
1881         size_t k = 0;
1882         int modenum;
1883         int nummodes = SDL_GetNumDisplayModes(vid.displayindex);
1884         SDL_DisplayMode mode;
1885         for (modenum = 0;modenum < nummodes;modenum++)
1886         {
1887                 if (k >= maxcount)
1888                         break;
1889                 if (SDL_GetDisplayMode(vid.displayindex, modenum, &mode))
1890                         continue;
1891                 modes[k].width = mode.w;
1892                 modes[k].height = mode.h;
1893                 // FIXME bpp?
1894                 modes[k].refreshrate = mode.refresh_rate;
1895                 modes[k].pixelheight_num = 1;
1896                 modes[k].pixelheight_denom = 1; // SDL does not provide this
1897                 k++;
1898         }
1899         return k;
1900 }