]> git.xonotic.org Git - xonotic/darkplaces.git/blob - vid_sdl.c
vid: misc cleanups
[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_usingvsync = false;
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 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         VID_BuildJoyState(&joystate);
1017         VID_ApplyJoyState(&joystate);
1018 }
1019
1020 /////////////////////
1021 // Message Handling
1022 ////
1023
1024 #ifdef SDL_R_RESTART
1025 static qbool sdl_needs_restart;
1026 static void sdl_start(void)
1027 {
1028 }
1029 static void sdl_shutdown(void)
1030 {
1031         sdl_needs_restart = false;
1032 }
1033 static void sdl_newmap(void)
1034 {
1035 }
1036 #endif
1037
1038 static keynum_t buttonremap[] =
1039 {
1040         K_MOUSE1,
1041         K_MOUSE3,
1042         K_MOUSE2,
1043         K_MOUSE4,
1044         K_MOUSE5,
1045         K_MOUSE6,
1046         K_MOUSE7,
1047         K_MOUSE8,
1048         K_MOUSE9,
1049         K_MOUSE10,
1050         K_MOUSE11,
1051         K_MOUSE12,
1052         K_MOUSE13,
1053         K_MOUSE14,
1054         K_MOUSE15,
1055         K_MOUSE16,
1056 };
1057
1058 //#define DEBUGSDLEVENTS
1059 void Sys_SDL_HandleEvents(void)
1060 {
1061         static qbool sound_active = true;
1062         int keycode;
1063         int i;
1064         const char *chp;
1065         qbool isdown;
1066         Uchar unicode;
1067         SDL_Event event;
1068
1069         VID_EnableJoystick(true);
1070
1071         while( SDL_PollEvent( &event ) )
1072                 loop_start:
1073                 switch( event.type ) {
1074                         case SDL_QUIT:
1075 #ifdef DEBUGSDLEVENTS
1076                                 Con_DPrintf("SDL_Event: SDL_QUIT\n");
1077 #endif
1078                                 host.state = host_shutdown;
1079                                 break;
1080                         case SDL_KEYDOWN:
1081                         case SDL_KEYUP:
1082 #ifdef DEBUGSDLEVENTS
1083                                 if (event.type == SDL_KEYDOWN)
1084                                         Con_DPrintf("SDL_Event: SDL_KEYDOWN %i\n", event.key.keysym.sym);
1085                                 else
1086                                         Con_DPrintf("SDL_Event: SDL_KEYUP %i\n", event.key.keysym.sym);
1087 #endif
1088                                 keycode = MapKey(event.key.keysym.sym);
1089                                 isdown = (event.key.state == SDL_PRESSED);
1090                                 unicode = 0;
1091                                 if(isdown)
1092                                 {
1093                                         if(SDL_PollEvent(&event))
1094                                         {
1095                                                 if(event.type == SDL_TEXTINPUT)
1096                                                 {
1097                                                         // combine key code from SDL_KEYDOWN event and character
1098                                                         // from SDL_TEXTINPUT event in a single Key_Event call
1099 #ifdef DEBUGSDLEVENTS
1100                                                         Con_DPrintf("SDL_Event: SDL_TEXTINPUT - text: %s\n", event.text.text);
1101 #endif
1102                                                         unicode = u8_getchar_utf8_enabled(event.text.text + (int)u8_bytelen(event.text.text, 0), NULL);
1103                                                 }
1104                                                 else
1105                                                 {
1106                                                         if (!VID_JoyBlockEmulatedKeys(keycode))
1107                                                                 Key_Event(keycode, 0, isdown);
1108                                                         goto loop_start;
1109                                                 }
1110                                         }
1111                                 }
1112                                 if (!VID_JoyBlockEmulatedKeys(keycode))
1113                                         Key_Event(keycode, unicode, isdown);
1114                                 break;
1115                         case SDL_MOUSEBUTTONDOWN:
1116                         case SDL_MOUSEBUTTONUP:
1117 #ifdef DEBUGSDLEVENTS
1118                                 if (event.type == SDL_MOUSEBUTTONDOWN)
1119                                         Con_DPrintf("SDL_Event: SDL_MOUSEBUTTONDOWN\n");
1120                                 else
1121                                         Con_DPrintf("SDL_Event: SDL_MOUSEBUTTONUP\n");
1122 #endif
1123                                 if (!vid_touchscreen.integer)
1124                                 if (event.button.button > 0 && event.button.button <= ARRAY_SIZE(buttonremap))
1125                                         Key_Event( buttonremap[event.button.button - 1], 0, event.button.state == SDL_PRESSED );
1126                                 break;
1127                         case SDL_MOUSEWHEEL:
1128                                 // TODO support wheel x direction.
1129                                 i = event.wheel.y;
1130                                 while (i > 0) {
1131                                         --i;
1132                                         Key_Event( K_MWHEELUP, 0, true );
1133                                         Key_Event( K_MWHEELUP, 0, false );
1134                                 }
1135                                 while (i < 0) {
1136                                         ++i;
1137                                         Key_Event( K_MWHEELDOWN, 0, true );
1138                                         Key_Event( K_MWHEELDOWN, 0, false );
1139                                 }
1140                                 break;
1141                         case SDL_JOYBUTTONDOWN:
1142                         case SDL_JOYBUTTONUP:
1143                         case SDL_JOYAXISMOTION:
1144                         case SDL_JOYBALLMOTION:
1145                         case SDL_JOYHATMOTION:
1146 #ifdef DEBUGSDLEVENTS
1147                                 Con_DPrintf("SDL_Event: SDL_JOY*\n");
1148 #endif
1149                                 break;
1150                         case SDL_WINDOWEVENT:
1151 #ifdef DEBUGSDLEVENTS
1152                                 Con_DPrintf("SDL_Event: SDL_WINDOWEVENT %i\n", (int)event.window.event);
1153 #endif
1154                                 //if (event.window.windowID == window) // how to compare?
1155                                 {
1156                                         switch(event.window.event)
1157                                         {
1158                                         case SDL_WINDOWEVENT_SHOWN:
1159                                                 vid_hidden = false;
1160                                                 break;
1161                                         case  SDL_WINDOWEVENT_HIDDEN:
1162                                                 vid_hidden = true;
1163                                                 break;
1164                                         case SDL_WINDOWEVENT_EXPOSED:
1165 #ifdef DEBUGSDLEVENTS
1166                                                 Con_DPrintf("SDL_Event: SDL_WINDOWEVENT_EXPOSED\n");
1167 #endif
1168                                                 break;
1169                                         case SDL_WINDOWEVENT_MOVED:
1170                                                 break;
1171                                         case SDL_WINDOWEVENT_RESIZED:
1172                                                 if(vid_resizable.integer < 2)
1173                                                 {
1174                                                         vid.width = event.window.data1;
1175                                                         vid.height = event.window.data2;
1176 #ifdef SDL_R_RESTART
1177                                                         // better not call R_Modules_Restart_f from here directly, as this may wreak havoc...
1178                                                         // so, let's better queue it for next frame
1179                                                         if(!sdl_needs_restart)
1180                                                         {
1181                                                                 Cbuf_AddText(cmd_local, "\nr_restart\n");
1182                                                                 sdl_needs_restart = true;
1183                                                         }
1184 #endif
1185                                                 }
1186                                                 break;
1187                                         case SDL_WINDOWEVENT_MINIMIZED:
1188                                                 break;
1189                                         case SDL_WINDOWEVENT_MAXIMIZED:
1190                                                 break;
1191                                         case SDL_WINDOWEVENT_RESTORED:
1192                                                 break;
1193                                         case SDL_WINDOWEVENT_ENTER:
1194                                                 break;
1195                                         case SDL_WINDOWEVENT_LEAVE:
1196                                                 break;
1197                                         case SDL_WINDOWEVENT_FOCUS_GAINED:
1198                                                 vid_hasfocus = true;
1199                                                 break;
1200                                         case SDL_WINDOWEVENT_FOCUS_LOST:
1201                                                 vid_hasfocus = false;
1202                                                 break;
1203                                         case SDL_WINDOWEVENT_CLOSE:
1204                                                 host.state = host_shutdown;
1205                                                 break;
1206                                         }
1207                                 }
1208                                 break;
1209                         case SDL_TEXTEDITING:
1210 #ifdef DEBUGSDLEVENTS
1211                                 Con_DPrintf("SDL_Event: SDL_TEXTEDITING - composition = %s, cursor = %d, selection lenght = %d\n", event.edit.text, event.edit.start, event.edit.length);
1212 #endif
1213                                 // FIXME!  this is where composition gets supported
1214                                 break;
1215                         case SDL_TEXTINPUT:
1216 #ifdef DEBUGSDLEVENTS
1217                                 Con_DPrintf("SDL_Event: SDL_TEXTINPUT - text: %s\n", event.text.text);
1218 #endif
1219                                 // convert utf8 string to char
1220                                 // NOTE: this code is supposed to run even if utf8enable is 0
1221                                 chp = event.text.text;
1222                                 while (*chp != 0)
1223                                 {
1224                                         // input the chars one by one (there can be multiple chars when e.g. using an "input method")
1225                                         unicode = u8_getchar_utf8_enabled(chp, &chp);
1226                                         Key_Event(K_TEXT, unicode, true);
1227                                         Key_Event(K_TEXT, unicode, false);
1228                                 }
1229                                 break;
1230                         case SDL_MOUSEMOTION:
1231                                 break;
1232                         case SDL_FINGERDOWN:
1233 #ifdef DEBUGSDLEVENTS
1234                                 Con_DPrintf("SDL_FINGERDOWN for finger %i\n", (int)event.tfinger.fingerId);
1235 #endif
1236                                 for (i = 0;i < MAXFINGERS-1;i++)
1237                                 {
1238                                         if (!multitouch[i][0])
1239                                         {
1240                                                 multitouch[i][0] = event.tfinger.fingerId + 1;
1241                                                 multitouch[i][1] = event.tfinger.x;
1242                                                 multitouch[i][2] = event.tfinger.y;
1243                                                 // TODO: use event.tfinger.pressure?
1244                                                 break;
1245                                         }
1246                                 }
1247                                 if (i == MAXFINGERS-1)
1248                                         Con_DPrintf("Too many fingers at once!\n");
1249                                 break;
1250                         case SDL_FINGERUP:
1251 #ifdef DEBUGSDLEVENTS
1252                                 Con_DPrintf("SDL_FINGERUP for finger %i\n", (int)event.tfinger.fingerId);
1253 #endif
1254                                 for (i = 0;i < MAXFINGERS-1;i++)
1255                                 {
1256                                         if (multitouch[i][0] == event.tfinger.fingerId + 1)
1257                                         {
1258                                                 multitouch[i][0] = 0;
1259                                                 break;
1260                                         }
1261                                 }
1262                                 if (i == MAXFINGERS-1)
1263                                         Con_DPrintf("No SDL_FINGERDOWN event matches this SDL_FINGERMOTION event\n");
1264                                 break;
1265                         case SDL_FINGERMOTION:
1266 #ifdef DEBUGSDLEVENTS
1267                                 Con_DPrintf("SDL_FINGERMOTION for finger %i\n", (int)event.tfinger.fingerId);
1268 #endif
1269                                 for (i = 0;i < MAXFINGERS-1;i++)
1270                                 {
1271                                         if (multitouch[i][0] == event.tfinger.fingerId + 1)
1272                                         {
1273                                                 multitouch[i][1] = event.tfinger.x;
1274                                                 multitouch[i][2] = event.tfinger.y;
1275                                                 break;
1276                                         }
1277                                 }
1278                                 if (i == MAXFINGERS-1)
1279                                         Con_DPrintf("No SDL_FINGERDOWN event matches this SDL_FINGERMOTION event\n");
1280                                 break;
1281                         default:
1282 #ifdef DEBUGSDLEVENTS
1283                                 Con_DPrintf("Received unrecognized SDL_Event type 0x%x\n", event.type);
1284 #endif
1285                                 break;
1286                 }
1287
1288         // enable/disable sound on focus gain/loss
1289         if ((!vid_hidden && vid_activewindow) || !snd_mutewhenidle.integer)
1290         {
1291                 if (!sound_active)
1292                 {
1293                         S_UnblockSound ();
1294                         sound_active = true;
1295                 }
1296         }
1297         else
1298         {
1299                 if (sound_active)
1300                 {
1301                         S_BlockSound ();
1302                         sound_active = false;
1303                 }
1304         }
1305 }
1306
1307 /////////////////
1308 // Video system
1309 ////
1310
1311 void *GL_GetProcAddress(const char *name)
1312 {
1313         void *p = NULL;
1314         p = SDL_GL_GetProcAddress(name);
1315         return p;
1316 }
1317
1318 qbool GL_ExtensionSupported(const char *name)
1319 {
1320         return SDL_GL_ExtensionSupported(name);
1321 }
1322
1323 void VID_Init (void)
1324 {
1325 #ifndef __IPHONEOS__
1326 #ifdef MACOSX
1327         Cvar_RegisterVariable(&apple_mouse_noaccel);
1328 #endif
1329 #endif
1330 #ifdef DP_MOBILETOUCH
1331         Cvar_SetValueQuick(&vid_touchscreen, 1);
1332 #endif
1333         Cvar_RegisterVariable(&joy_sdl2_trigger_deadzone);
1334
1335 #ifdef SDL_R_RESTART
1336         R_RegisterModule("SDL", sdl_start, sdl_shutdown, sdl_newmap, NULL, NULL);
1337 #endif
1338
1339         if (SDL_Init(SDL_INIT_VIDEO) < 0)
1340                 Sys_Error ("Failed to init SDL video subsystem: %s", SDL_GetError());
1341         if (SDL_InitSubSystem(SDL_INIT_JOYSTICK) < 0)
1342                 Con_Printf(CON_ERROR "Failed to init SDL joystick subsystem: %s\n", SDL_GetError());
1343 }
1344
1345 static int vid_sdljoystickindex = -1;
1346 void VID_EnableJoystick(qbool enable)
1347 {
1348         int index = joy_enable.integer > 0 ? joy_index.integer : -1;
1349         int numsdljoysticks;
1350         qbool success = false;
1351         int sharedcount = 0;
1352         int sdlindex = -1;
1353         sharedcount = VID_Shared_SetJoystick(index);
1354         if (index >= 0 && index < sharedcount)
1355                 success = true;
1356         sdlindex = index - sharedcount;
1357
1358         numsdljoysticks = SDL_NumJoysticks();
1359         if (sdlindex < 0 || sdlindex >= numsdljoysticks)
1360                 sdlindex = -1;
1361
1362         // update cvar containing count of XInput joysticks + SDL joysticks
1363         if (joy_detected.integer != sharedcount + numsdljoysticks)
1364                 Cvar_SetValueQuick(&joy_detected, sharedcount + numsdljoysticks);
1365
1366         if (vid_sdljoystickindex != sdlindex)
1367         {
1368                 vid_sdljoystickindex = sdlindex;
1369                 // close SDL joystick if active
1370                 if (vid_sdljoystick)
1371                 {
1372                         SDL_JoystickClose(vid_sdljoystick);
1373                         vid_sdljoystick = NULL;
1374                 }
1375                 if (vid_sdlgamecontroller)
1376                 {
1377                         SDL_GameControllerClose(vid_sdlgamecontroller);
1378                         vid_sdlgamecontroller = NULL;
1379                 }
1380                 if (sdlindex >= 0)
1381                 {
1382                         vid_sdljoystick = SDL_JoystickOpen(sdlindex);
1383                         if (vid_sdljoystick)
1384                         {
1385                                 const char *joystickname = SDL_JoystickName(vid_sdljoystick);
1386                                 if (SDL_IsGameController(vid_sdljoystickindex))
1387                                 {
1388                                         vid_sdlgamecontroller = SDL_GameControllerOpen(vid_sdljoystickindex);
1389                                         Con_DPrintf("Using SDL GameController mappings for Joystick %i\n", index);
1390                                 }
1391                                 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));
1392                         }
1393                         else
1394                         {
1395                                 Con_Printf(CON_ERROR "Joystick %i failed (SDL_JoystickOpen(%i) returned: %s)\n", index, sdlindex, SDL_GetError());
1396                                 sdlindex = -1;
1397                         }
1398                 }
1399         }
1400
1401         if (sdlindex >= 0)
1402                 success = true;
1403
1404         if (joy_active.integer != (success ? 1 : 0))
1405                 Cvar_SetValueQuick(&joy_active, success ? 1 : 0);
1406 }
1407
1408 static void VID_OutputVersion(void)
1409 {
1410         SDL_version version;
1411         SDL_GetVersion(&version);
1412         Con_Printf(     "Linked against SDL version %d.%d.%d\n"
1413                                         "Using SDL library version %d.%d.%d\n",
1414                                         SDL_MAJOR_VERSION, SDL_MINOR_VERSION, SDL_PATCHLEVEL,
1415                                         version.major, version.minor, version.patch );
1416 }
1417
1418 #ifdef WIN32
1419 static void AdjustWindowBounds(viddef_mode_t *mode, RECT *rect)
1420 {
1421         int workWidth;
1422         int workHeight;
1423         int titleBarPixels = 2;
1424         int screenHeight;
1425         RECT workArea;
1426         LONG width = mode->width; // vid_width
1427         LONG height = mode->height; // vid_height
1428
1429         // adjust width and height for the space occupied by window decorators (title bar, borders)
1430         rect->top = 0;
1431         rect->left = 0;
1432         rect->right = width;
1433         rect->bottom = height;
1434         AdjustWindowRectEx(rect, WS_CAPTION|WS_THICKFRAME, false, 0);
1435
1436         SystemParametersInfo(SPI_GETWORKAREA, 0, &workArea, 0);
1437         workWidth = workArea.right - workArea.left;
1438         workHeight = workArea.bottom - workArea.top;
1439
1440         // SDL forces the window height to be <= screen height - 27px (on Win8.1 - probably intended for the title bar) 
1441         // If the task bar is docked to the the left screen border and we move the window to negative y,
1442         // there would be some part of the regular desktop visible on the bottom of the screen.
1443         screenHeight = GetSystemMetrics(SM_CYSCREEN);
1444         if (screenHeight == workHeight)
1445                 titleBarPixels = -rect->top;
1446
1447         //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);
1448
1449         // if height and width matches the physical or previously adjusted screen height and width, adjust it to available desktop area
1450         if ((width == GetSystemMetrics(SM_CXSCREEN) || width == workWidth) && (height == screenHeight || height == workHeight - titleBarPixels))
1451         {
1452                 rect->left = workArea.left;
1453                 mode->width = workWidth;
1454                 rect->top = workArea.top + titleBarPixels;
1455                 mode->height = workHeight - titleBarPixels;
1456         }
1457         else 
1458         {
1459                 rect->left = workArea.left + max(0, (workWidth - width) / 2);
1460                 rect->top = workArea.top + max(0, (workHeight - height) / 2);
1461         }
1462 }
1463 #endif
1464
1465 static qbool VID_InitModeGL(viddef_mode_t *mode)
1466 {
1467         int windowflags = SDL_WINDOW_SHOWN | SDL_WINDOW_OPENGL;
1468         // currently SDL_WINDOWPOS_UNDEFINED behaves exactly like SDL_WINDOWPOS_CENTERED, this might change some day
1469         // https://trello.com/c/j56vUcwZ/81-centered-vs-undefined-window-position
1470         int xPos = SDL_WINDOWPOS_UNDEFINED;
1471         int yPos = SDL_WINDOWPOS_UNDEFINED;
1472         int i;
1473 #ifndef USE_GLES2
1474         // SDL usually knows best
1475         const char *drivername = NULL;
1476 #endif
1477
1478         win_half_width = mode->width>>1;
1479         win_half_height = mode->height>>1;
1480
1481         if(vid_resizable.integer)
1482                 windowflags |= SDL_WINDOW_RESIZABLE;
1483
1484         VID_OutputVersion();
1485
1486 #ifndef USE_GLES2
1487 // 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
1488         i = Sys_CheckParm("-gl_driver");
1489         if (i && i < sys.argc - 1)
1490                 drivername = sys.argv[i + 1];
1491         if (SDL_GL_LoadLibrary(drivername) < 0)
1492         {
1493                 Con_Printf(CON_ERROR "Unable to load GL driver \"%s\": %s\n", drivername, SDL_GetError());
1494                 return false;
1495         }
1496 #endif
1497
1498 #ifdef DP_MOBILETOUCH
1499         // mobile platforms are always fullscreen, we'll get the resolution after opening the window
1500         mode->fullscreen = true;
1501         // hide the menu with SDL_WINDOW_BORDERLESS
1502         windowflags |= SDL_WINDOW_FULLSCREEN | SDL_WINDOW_BORDERLESS;
1503 #endif
1504
1505
1506         if (mode->fullscreen)
1507         {
1508                 if (vid_desktopfullscreen.integer)
1509                 {
1510                         vid_mode_t m = VID_GetDesktopMode();
1511                         mode->width = m.width;
1512                         mode->height = m.height;
1513                         windowflags |= SDL_WINDOW_FULLSCREEN_DESKTOP;
1514                 }
1515                 else
1516                         windowflags |= SDL_WINDOW_FULLSCREEN;
1517         }
1518         else
1519         {
1520                 if (vid_borderless.integer)
1521                         windowflags |= SDL_WINDOW_BORDERLESS;
1522 #ifdef WIN32
1523                 if (vid_ignore_taskbar.integer)
1524                 {
1525                         xPos = SDL_WINDOWPOS_CENTERED;
1526                         yPos = SDL_WINDOWPOS_CENTERED;
1527                 }
1528                 else
1529                 {
1530                         RECT rect;
1531                         AdjustWindowBounds(mode, &rect);
1532                         xPos = rect.left;
1533                         yPos = rect.top;
1534                 }
1535 #endif
1536         }
1537
1538
1539         if (vid_mouse_clickthrough.integer)
1540                 SDL_SetHint(SDL_HINT_MOUSE_FOCUS_CLICKTHROUGH, "1");
1541
1542         SDL_GL_SetAttribute (SDL_GL_DOUBLEBUFFER, 1);
1543         SDL_GL_SetAttribute (SDL_GL_RED_SIZE, 8);
1544         SDL_GL_SetAttribute (SDL_GL_GREEN_SIZE, 8);
1545         SDL_GL_SetAttribute (SDL_GL_BLUE_SIZE, 8);
1546         SDL_GL_SetAttribute (SDL_GL_ALPHA_SIZE, 8);
1547         SDL_GL_SetAttribute (SDL_GL_DEPTH_SIZE, 24);
1548         SDL_GL_SetAttribute (SDL_GL_STENCIL_SIZE, 8);
1549         if (mode->stereobuffer)
1550                 SDL_GL_SetAttribute (SDL_GL_STEREO, 1);
1551         if (mode->samples > 1)
1552         {
1553                 SDL_GL_SetAttribute (SDL_GL_MULTISAMPLEBUFFERS, 1);
1554                 SDL_GL_SetAttribute (SDL_GL_MULTISAMPLESAMPLES, mode->samples);
1555         }
1556
1557 #ifdef USE_GLES2
1558         SDL_GL_SetAttribute (SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_ES);
1559         SDL_GL_SetAttribute (SDL_GL_CONTEXT_MAJOR_VERSION, 2);
1560         SDL_GL_SetAttribute (SDL_GL_CONTEXT_MINOR_VERSION, 0);
1561 #else
1562         SDL_GL_SetAttribute (SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
1563         SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
1564         SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 2);
1565         /* Requesting a Core profile and 3.2 minimum is mandatory on macOS and older Mesa drivers.
1566          * It works fine on other drivers too except NVIDIA, see HACK below.
1567          */
1568 #endif
1569
1570         SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, (gl_debug.integer > 0 ? SDL_GL_CONTEXT_DEBUG_FLAG : 0));
1571
1572         window = SDL_CreateWindow(gamename, xPos, yPos, mode->width, mode->height, windowflags);
1573         if (window == NULL)
1574         {
1575                 Con_Printf(CON_ERROR "Failed to set video mode to %ix%i: %s\n", mode->width, mode->height, SDL_GetError());
1576                 VID_Shutdown();
1577                 return false;
1578         }
1579         SDL_GetWindowSize(window, &mode->width, &mode->height);
1580         context = SDL_GL_CreateContext(window);
1581         if (context == NULL)
1582         {
1583                 Con_Printf(CON_ERROR "Failed to initialize OpenGL context: %s\n", SDL_GetError());
1584                 VID_Shutdown();
1585                 return false;
1586         }
1587
1588         GL_InitFunctions();
1589
1590 #if !defined(USE_GLES2) && !defined(MACOSX)
1591         // NVIDIA hates the Core profile and limits the version to the minimum we specified.
1592         // HACK: to detect NVIDIA we first need a context, fortunately replacing it takes a few milliseconds
1593         gl_vendor = (const char *)qglGetString(GL_VENDOR);
1594         if (strncmp(gl_vendor, "NVIDIA", 6) == 0)
1595         {
1596                 Con_DPrint("The Way It's Meant To Be Played: replacing OpenGL Core profile with Compatibility profile...\n");
1597                 SDL_GL_DeleteContext(context);
1598                 SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_COMPATIBILITY);
1599                 context = SDL_GL_CreateContext(window);
1600                 if (context == NULL)
1601                 {
1602                         Con_Printf(CON_ERROR "Failed to initialize OpenGL context: %s\n", SDL_GetError());
1603                         VID_Shutdown();
1604                         return false;
1605                 }
1606         }
1607 #endif
1608
1609         SDL_GL_SetSwapInterval(bound(-1, vid_vsync.integer, 1));
1610         vid_usingvsync = (vid_vsync.integer != 0);
1611
1612         vid_hidden = false;
1613         vid_activewindow = true;
1614         vid_hasfocus = true;
1615         vid_usingmouse = false;
1616         vid_usinghidecursor = false;
1617
1618         // clear to black (loading plaque will be seen over this)
1619         GL_Clear(GL_COLOR_BUFFER_BIT, NULL, 1.0f, 0);
1620         VID_Finish(); // checks vid_hidden
1621
1622         GL_Setup();
1623
1624         // VorteX: set other info
1625         Cvar_SetQuick(&gl_info_vendor, gl_vendor);
1626         Cvar_SetQuick(&gl_info_renderer, gl_renderer);
1627         Cvar_SetQuick(&gl_info_version, gl_version);
1628         Cvar_SetQuick(&gl_info_platform, "SDL");
1629         Cvar_SetQuick(&gl_info_driver, drivername ? drivername : "");
1630
1631         return true;
1632 }
1633
1634 qbool VID_InitMode(viddef_mode_t *mode)
1635 {
1636         // GAME_STEELSTORM specific
1637         steelstorm_showing_map = Cvar_FindVar(&cvars_all, "steelstorm_showing_map", ~0);
1638         steelstorm_showing_mousecursor = Cvar_FindVar(&cvars_all, "steelstorm_showing_mousecursor", ~0);
1639
1640         if (!SDL_WasInit(SDL_INIT_VIDEO) && SDL_InitSubSystem(SDL_INIT_VIDEO) < 0)
1641                 Sys_Error ("Failed to init SDL video subsystem: %s", SDL_GetError());
1642
1643         Cvar_SetValueQuick(&vid_touchscreen_supportshowkeyboard, SDL_HasScreenKeyboardSupport() ? 1 : 0);
1644         return VID_InitModeGL(mode);
1645 }
1646
1647 void VID_Shutdown (void)
1648 {
1649         VID_EnableJoystick(false);
1650         VID_SetMouse(false, false);
1651
1652         SDL_GL_DeleteContext(context);
1653         context = NULL;
1654         SDL_DestroyWindow(window);
1655         window = NULL;
1656
1657         SDL_QuitSubSystem(SDL_INIT_VIDEO);
1658 }
1659
1660 void VID_Finish (void)
1661 {
1662         qbool vid_usevsync;
1663         vid_activewindow = !vid_hidden && vid_hasfocus;
1664
1665         VID_UpdateGamma();
1666
1667         if (!vid_hidden)
1668         {
1669                 switch(vid.renderpath)
1670                 {
1671                 case RENDERPATH_GL32:
1672                 case RENDERPATH_GLES2:
1673                         CHECKGLERROR
1674                         if (r_speeds.integer == 2 || gl_finish.integer)
1675                                 GL_Finish();
1676
1677                         vid_usevsync = (vid_vsync.integer && !cls.timedemo);
1678                         if (vid_usingvsync != vid_usevsync)
1679                         {
1680                                 vid_usingvsync = vid_usevsync;
1681                                 if (SDL_GL_SetSwapInterval(vid_usevsync != 0) >= 0)
1682                                         Con_DPrintf("Vsync %s\n", vid_usevsync ? "activated" : "deactivated");
1683                                 else
1684                                         Con_DPrintf("ERROR: can't %s vsync\n", vid_usevsync ? "activate" : "deactivate");
1685                         }
1686                         SDL_GL_SwapWindow(window);
1687                         break;
1688                 }
1689         }
1690 }
1691
1692 vid_mode_t VID_GetDesktopMode(void)
1693 {
1694         SDL_DisplayMode mode;
1695         int bpp;
1696         Uint32 rmask, gmask, bmask, amask;
1697         vid_mode_t desktop_mode;
1698
1699         SDL_GetDesktopDisplayMode(0, &mode);
1700         SDL_PixelFormatEnumToMasks(mode.format, &bpp, &rmask, &gmask, &bmask, &amask);
1701         desktop_mode.width = mode.w;
1702         desktop_mode.height = mode.h;
1703         desktop_mode.bpp = bpp;
1704         desktop_mode.refreshrate = mode.refresh_rate;
1705         desktop_mode.pixelheight_num = 1;
1706         desktop_mode.pixelheight_denom = 1; // SDL does not provide this
1707         // TODO check whether this actually works, or whether we do still need
1708         // a read-window-size-after-entering-desktop-fullscreen hack for
1709         // multiscreen setups.
1710         return desktop_mode;
1711 }
1712
1713 size_t VID_ListModes(vid_mode_t *modes, size_t maxcount)
1714 {
1715         size_t k = 0;
1716         int modenum;
1717         int nummodes = SDL_GetNumDisplayModes(0);
1718         SDL_DisplayMode mode;
1719         for (modenum = 0;modenum < nummodes;modenum++)
1720         {
1721                 if (k >= maxcount)
1722                         break;
1723                 if (SDL_GetDisplayMode(0, modenum, &mode))
1724                         continue;
1725                 modes[k].width = mode.w;
1726                 modes[k].height = mode.h;
1727                 // FIXME bpp?
1728                 modes[k].refreshrate = mode.refresh_rate;
1729                 modes[k].pixelheight_num = 1;
1730                 modes[k].pixelheight_denom = 1; // SDL does not provide this
1731                 k++;
1732         }
1733         return k;
1734 }