]> de.git.xonotic.org Git - xonotic/darkplaces.git/blob - vid_sdl.c
12214d2ab5b70cfa962ce8ff797188de247cae28
[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 static cvar_t apple_mouse_noaccel = {CVAR_CLIENT | CVAR_SAVE, "apple_mouse_noaccel", "1", "disables mouse acceleration while DarkPlaces is active"};
34 static qboolean vid_usingnoaccel;
35 static double originalMouseSpeed = -1.0;
36 io_connect_t IN_GetIOHandle(void)
37 {
38         io_connect_t iohandle = MACH_PORT_NULL;
39         kern_return_t status;
40         io_service_t iohidsystem = MACH_PORT_NULL;
41         mach_port_t masterport;
42
43         status = IOMasterPort(MACH_PORT_NULL, &masterport);
44         if(status != KERN_SUCCESS)
45                 return 0;
46
47         iohidsystem = IORegistryEntryFromPath(masterport, kIOServicePlane ":/IOResources/IOHIDSystem");
48         if(!iohidsystem)
49                 return 0;
50
51         status = IOServiceOpen(iohidsystem, mach_task_self(), kIOHIDParamConnectType, &iohandle);
52         IOObjectRelease(iohidsystem);
53
54         return iohandle;
55 }
56 #endif
57 #endif
58
59 #ifdef WIN32
60 #define SDL_R_RESTART
61 #endif
62
63 // Tell startup code that we have a client
64 int cl_available = true;
65
66 qboolean vid_supportrefreshrate = false;
67
68 static qboolean vid_usingmouse = false;
69 static qboolean vid_usingmouse_relativeworks = false; // SDL2 workaround for unimplemented RelativeMouse mode
70 static qboolean vid_usinghidecursor = false;
71 static qboolean vid_hasfocus = false;
72 static qboolean vid_isfullscreen;
73 static qboolean vid_usingvsync = false;
74 static SDL_Joystick *vid_sdljoystick = NULL;
75 static SDL_GameController *vid_sdlgamecontroller = NULL;
76 static cvar_t joy_sdl2_trigger_deadzone = {CVAR_SAVE | CVAR_CLIENT, "joy_sdl2_trigger_deadzone", "0.5", "deadzone for triggers to be registered as key presses"};
77 // GAME_STEELSTORM specific
78 static cvar_t *steelstorm_showing_map = NULL; // detect but do not create the cvar
79 static cvar_t *steelstorm_showing_mousecursor = NULL; // detect but do not create the cvar
80
81 static int win_half_width = 50;
82 static int win_half_height = 50;
83 static int video_bpp;
84
85 static SDL_GLContext context;
86 static SDL_Window *window;
87 static int window_flags;
88 static vid_mode_t desktop_mode;
89
90 // Input handling
91
92 #ifndef SDLK_PERCENT
93 #define SDLK_PERCENT '%'
94 #endif
95
96 static int MapKey( unsigned int sdlkey )
97 {
98         switch(sdlkey)
99         {
100         default: return 0;
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 qboolean VID_HasScreenKeyboardSupport(void)
345 {
346         return SDL_HasScreenKeyboardSupport() != SDL_FALSE;
347 }
348
349 void VID_ShowKeyboard(qboolean 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 qboolean VID_ShowingKeyboard(void)
367 {
368         return SDL_IsTextInputActive() != 0;
369 }
370
371 void VID_SetMouse(qboolean fullscreengrab, qboolean relative, qboolean 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, 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, %i) relativeworks = %i\n", (int)fullscreengrab, (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 qboolean VID_TouchscreenArea(int corner, float px, float py, float pwidth, float pheight, const char *icon, float textheight, const char *text, float *resultmove, qboolean *resultbutton, keynum_t key, const char *typedtext, float deadzone, float oversizepixels_x, float oversizepixels_y, qboolean 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         qboolean 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, qboolean *resultbutton, keynum_t key)
572 {
573         int finger;
574         float fx, fy, fwidth, fheight;
575         qboolean 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 > 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)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 = 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 < 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, j) * (1.0f / 32767.0f);
703                         }
704                         for (j = 0; j < SDL_CONTROLLER_BUTTON_MAX; ++j)
705                                 joystate->button[j] = SDL_GameControllerGetButton(vid_sdlgamecontroller, 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 qboolean oldbuttons[128];
765         static qboolean 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 qboolean oldbuttons[128];
878         static qboolean 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_client);
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 qboolean 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 qboolean 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
1060 // SDL2
1061 void Sys_SendKeyEvents( void )
1062 {
1063         static qboolean sound_active = true;
1064         int keycode;
1065         int i;
1066         qboolean isdown;
1067         Uchar unicode;
1068         SDL_Event event;
1069
1070         VID_EnableJoystick(true);
1071
1072         while( SDL_PollEvent( &event ) )
1073                 loop_start:
1074                 switch( event.type ) {
1075                         case SDL_QUIT:
1076 #ifdef DEBUGSDLEVENTS
1077                                 Con_DPrintf("SDL_Event: SDL_QUIT\n");
1078 #endif
1079                                 Sys_Quit(0);
1080                                 break;
1081                         case SDL_KEYDOWN:
1082                         case SDL_KEYUP:
1083 #ifdef DEBUGSDLEVENTS
1084                                 if (event.type == SDL_KEYDOWN)
1085                                         Con_DPrintf("SDL_Event: SDL_KEYDOWN %i\n", event.key.keysym.sym);
1086                                 else
1087                                         Con_DPrintf("SDL_Event: SDL_KEYUP %i\n", event.key.keysym.sym);
1088 #endif
1089                                 keycode = MapKey(event.key.keysym.sym);
1090                                 isdown = (event.key.state == SDL_PRESSED);
1091                                 unicode = 0;
1092                                 if(isdown)
1093                                 {
1094                                         if(SDL_PollEvent(&event))
1095                                         {
1096                                                 if(event.type == SDL_TEXTINPUT)
1097                                                 {
1098                                                         // combine key code from SDL_KEYDOWN event and character
1099                                                         // from SDL_TEXTINPUT event in a single Key_Event call
1100 #ifdef DEBUGSDLEVENTS
1101                                                         Con_DPrintf("SDL_Event: SDL_TEXTINPUT - text: %s\n", event.text.text);
1102 #endif
1103                                                         unicode = u8_getchar_utf8_enabled(event.text.text + (int)u8_bytelen(event.text.text, 0), NULL);
1104                                                 }
1105                                                 else
1106                                                 {
1107                                                         if (!VID_JoyBlockEmulatedKeys(keycode))
1108                                                                 Key_Event(keycode, 0, isdown);
1109                                                         goto loop_start;
1110                                                 }
1111                                         }
1112                                 }
1113                                 if (!VID_JoyBlockEmulatedKeys(keycode))
1114                                         Key_Event(keycode, unicode, isdown);
1115                                 break;
1116                         case SDL_MOUSEBUTTONDOWN:
1117                         case SDL_MOUSEBUTTONUP:
1118 #ifdef DEBUGSDLEVENTS
1119                                 if (event.type == SDL_MOUSEBUTTONDOWN)
1120                                         Con_DPrintf("SDL_Event: SDL_MOUSEBUTTONDOWN\n");
1121                                 else
1122                                         Con_DPrintf("SDL_Event: SDL_MOUSEBUTTONUP\n");
1123 #endif
1124                                 if (!vid_touchscreen.integer)
1125                                 if (event.button.button > 0 && event.button.button <= ARRAY_SIZE(buttonremap))
1126                                         Key_Event( buttonremap[event.button.button - 1], 0, event.button.state == SDL_PRESSED );
1127                                 break;
1128                         case SDL_MOUSEWHEEL:
1129                                 // TODO support wheel x direction.
1130                                 i = event.wheel.y;
1131                                 while (i > 0) {
1132                                         --i;
1133                                         Key_Event( K_MWHEELUP, 0, true );
1134                                         Key_Event( K_MWHEELUP, 0, false );
1135                                 }
1136                                 while (i < 0) {
1137                                         ++i;
1138                                         Key_Event( K_MWHEELDOWN, 0, true );
1139                                         Key_Event( K_MWHEELDOWN, 0, false );
1140                                 }
1141                                 break;
1142                         case SDL_JOYBUTTONDOWN:
1143                         case SDL_JOYBUTTONUP:
1144                         case SDL_JOYAXISMOTION:
1145                         case SDL_JOYBALLMOTION:
1146                         case SDL_JOYHATMOTION:
1147 #ifdef DEBUGSDLEVENTS
1148                                 Con_DPrintf("SDL_Event: SDL_JOY*\n");
1149 #endif
1150                                 break;
1151                         case SDL_WINDOWEVENT:
1152 #ifdef DEBUGSDLEVENTS
1153                                 Con_DPrintf("SDL_Event: SDL_WINDOWEVENT %i\n", (int)event.window.event);
1154 #endif
1155                                 //if (event.window.windowID == window) // how to compare?
1156                                 {
1157                                         switch(event.window.event)
1158                                         {
1159                                         case SDL_WINDOWEVENT_SHOWN:
1160                                                 vid_hidden = false;
1161                                                 break;
1162                                         case  SDL_WINDOWEVENT_HIDDEN:
1163                                                 vid_hidden = true;
1164                                                 break;
1165                                         case SDL_WINDOWEVENT_EXPOSED:
1166 #ifdef DEBUGSDLEVENTS
1167                                                 Con_DPrintf("SDL_Event: SDL_WINDOWEVENT_EXPOSED\n");
1168 #endif
1169                                                 break;
1170                                         case SDL_WINDOWEVENT_MOVED:
1171                                                 break;
1172                                         case SDL_WINDOWEVENT_RESIZED:
1173                                                 if(vid_resizable.integer < 2)
1174                                                 {
1175                                                         vid.width = event.window.data1;
1176                                                         vid.height = event.window.data2;
1177 #ifdef SDL_R_RESTART
1178                                                         // better not call R_Modules_Restart_f from here directly, as this may wreak havoc...
1179                                                         // so, let's better queue it for next frame
1180                                                         if(!sdl_needs_restart)
1181                                                         {
1182                                                                 Cbuf_AddText(&cmd_client, "\nr_restart\n");
1183                                                                 sdl_needs_restart = true;
1184                                                         }
1185 #endif
1186                                                 }
1187                                                 break;
1188                                         case SDL_WINDOWEVENT_MINIMIZED:
1189                                                 break;
1190                                         case SDL_WINDOWEVENT_MAXIMIZED:
1191                                                 break;
1192                                         case SDL_WINDOWEVENT_RESTORED:
1193                                                 break;
1194                                         case SDL_WINDOWEVENT_ENTER:
1195                                                 break;
1196                                         case SDL_WINDOWEVENT_LEAVE:
1197                                                 break;
1198                                         case SDL_WINDOWEVENT_FOCUS_GAINED:
1199                                                 vid_hasfocus = true;
1200                                                 break;
1201                                         case SDL_WINDOWEVENT_FOCUS_LOST:
1202                                                 vid_hasfocus = false;
1203                                                 break;
1204                                         case SDL_WINDOWEVENT_CLOSE:
1205                                                 Sys_Quit(0);
1206                                                 break;
1207                                         }
1208                                 }
1209                                 break;
1210                         case SDL_TEXTEDITING:
1211 #ifdef DEBUGSDLEVENTS
1212                                 Con_DPrintf("SDL_Event: SDL_TEXTEDITING - composition = %s, cursor = %d, selection lenght = %d\n", event.edit.text, event.edit.start, event.edit.length);
1213 #endif
1214                                 // FIXME!  this is where composition gets supported
1215                                 break;
1216                         case SDL_TEXTINPUT:
1217 #ifdef DEBUGSDLEVENTS
1218                                 Con_DPrintf("SDL_Event: SDL_TEXTINPUT - text: %s\n", event.text.text);
1219 #endif
1220                                 // convert utf8 string to char
1221                                 // NOTE: this code is supposed to run even if utf8enable is 0
1222                                 unicode = u8_getchar_utf8_enabled(event.text.text + (int)u8_bytelen(event.text.text, 0), NULL);
1223                                 Key_Event(K_TEXT, unicode, true);
1224                                 Key_Event(K_TEXT, unicode, false);
1225                                 break;
1226                         case SDL_MOUSEMOTION:
1227                                 break;
1228                         case SDL_FINGERDOWN:
1229 #ifdef DEBUGSDLEVENTS
1230                                 Con_DPrintf("SDL_FINGERDOWN for finger %i\n", (int)event.tfinger.fingerId);
1231 #endif
1232                                 for (i = 0;i < MAXFINGERS-1;i++)
1233                                 {
1234                                         if (!multitouch[i][0])
1235                                         {
1236                                                 multitouch[i][0] = event.tfinger.fingerId + 1;
1237                                                 multitouch[i][1] = event.tfinger.x;
1238                                                 multitouch[i][2] = event.tfinger.y;
1239                                                 // TODO: use event.tfinger.pressure?
1240                                                 break;
1241                                         }
1242                                 }
1243                                 if (i == MAXFINGERS-1)
1244                                         Con_DPrintf("Too many fingers at once!\n");
1245                                 break;
1246                         case SDL_FINGERUP:
1247 #ifdef DEBUGSDLEVENTS
1248                                 Con_DPrintf("SDL_FINGERUP for finger %i\n", (int)event.tfinger.fingerId);
1249 #endif
1250                                 for (i = 0;i < MAXFINGERS-1;i++)
1251                                 {
1252                                         if (multitouch[i][0] == event.tfinger.fingerId + 1)
1253                                         {
1254                                                 multitouch[i][0] = 0;
1255                                                 break;
1256                                         }
1257                                 }
1258                                 if (i == MAXFINGERS-1)
1259                                         Con_DPrintf("No SDL_FINGERDOWN event matches this SDL_FINGERMOTION event\n");
1260                                 break;
1261                         case SDL_FINGERMOTION:
1262 #ifdef DEBUGSDLEVENTS
1263                                 Con_DPrintf("SDL_FINGERMOTION for finger %i\n", (int)event.tfinger.fingerId);
1264 #endif
1265                                 for (i = 0;i < MAXFINGERS-1;i++)
1266                                 {
1267                                         if (multitouch[i][0] == event.tfinger.fingerId + 1)
1268                                         {
1269                                                 multitouch[i][1] = event.tfinger.x;
1270                                                 multitouch[i][2] = event.tfinger.y;
1271                                                 break;
1272                                         }
1273                                 }
1274                                 if (i == MAXFINGERS-1)
1275                                         Con_DPrintf("No SDL_FINGERDOWN event matches this SDL_FINGERMOTION event\n");
1276                                 break;
1277                         default:
1278 #ifdef DEBUGSDLEVENTS
1279                                 Con_DPrintf("Received unrecognized SDL_Event type 0x%x\n", event.type);
1280 #endif
1281                                 break;
1282                 }
1283
1284         // enable/disable sound on focus gain/loss
1285         if ((!vid_hidden && vid_activewindow) || !snd_mutewhenidle.integer)
1286         {
1287                 if (!sound_active)
1288                 {
1289                         S_UnblockSound ();
1290                         sound_active = true;
1291                 }
1292         }
1293         else
1294         {
1295                 if (sound_active)
1296                 {
1297                         S_BlockSound ();
1298                         sound_active = false;
1299                 }
1300         }
1301 }
1302
1303 /////////////////
1304 // Video system
1305 ////
1306
1307 void *GL_GetProcAddress(const char *name)
1308 {
1309         void *p = NULL;
1310         p = SDL_GL_GetProcAddress(name);
1311         return p;
1312 }
1313
1314 qboolean GL_ExtensionSupported(const char *name)
1315 {
1316         return SDL_GL_ExtensionSupported(name);
1317 }
1318
1319 static qboolean vid_sdl_initjoysticksystem = false;
1320
1321 void VID_Init (void)
1322 {
1323 #ifndef __IPHONEOS__
1324 #ifdef MACOSX
1325         Cvar_RegisterVariable(&apple_mouse_noaccel);
1326 #endif
1327 #endif
1328 #ifdef DP_MOBILETOUCH
1329         Cvar_SetValueQuick(&vid_touchscreen, 1);
1330 #endif
1331         Cvar_RegisterVariable(&joy_sdl2_trigger_deadzone);
1332
1333 #ifdef SDL_R_RESTART
1334         R_RegisterModule("SDL", sdl_start, sdl_shutdown, sdl_newmap, NULL, NULL);
1335 #endif
1336
1337         if (SDL_Init(SDL_INIT_VIDEO) < 0)
1338                 Sys_Error ("Failed to init SDL video subsystem: %s", SDL_GetError());
1339         vid_sdl_initjoysticksystem = SDL_InitSubSystem(SDL_INIT_JOYSTICK) >= 0;
1340         if (!vid_sdl_initjoysticksystem)
1341                 Con_Printf("Failed to init SDL joystick subsystem: %s\n", SDL_GetError());
1342         vid_isfullscreen = false;
1343 }
1344
1345 static int vid_sdljoystickindex = -1;
1346 void VID_EnableJoystick(qboolean enable)
1347 {
1348         int index = joy_enable.integer > 0 ? joy_index.integer : -1;
1349         int numsdljoysticks;
1350         qboolean 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("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         LONG width = mode->width; // vid_width
1422         LONG height = mode->height; // vid_height
1423
1424         // adjust width and height for the space occupied by window decorators (title bar, borders)
1425         rect->top = 0;
1426         rect->left = 0;
1427         rect->right = width;
1428         rect->bottom = height;
1429         AdjustWindowRectEx(rect, WS_CAPTION|WS_THICKFRAME, false, 0);
1430
1431         RECT workArea;
1432         SystemParametersInfo(SPI_GETWORKAREA, 0, &workArea, 0);
1433         int workWidth = workArea.right - workArea.left;
1434         int workHeight = workArea.bottom - workArea.top;
1435
1436         // SDL forces the window height to be <= screen height - 27px (on Win8.1 - probably intended for the title bar) 
1437         // If the task bar is docked to the the left screen border and we move the window to negative y,
1438         // there would be some part of the regular desktop visible on the bottom of the screen.
1439         int titleBarPixels = 2;
1440         int screenHeight = GetSystemMetrics(SM_CYSCREEN);
1441         if (screenHeight == workHeight)
1442                 titleBarPixels = -rect->top;
1443
1444         //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);
1445
1446         // if height and width matches the physical or previously adjusted screen height and width, adjust it to available desktop area
1447         if ((width == GetSystemMetrics(SM_CXSCREEN) || width == workWidth) && (height == screenHeight || height == workHeight - titleBarPixels))
1448         {
1449                 rect->left = workArea.left;
1450                 mode->width = workWidth;
1451                 rect->top = workArea.top + titleBarPixels;
1452                 mode->height = workHeight - titleBarPixels;
1453         }
1454         else 
1455         {
1456                 rect->left = workArea.left + max(0, (workWidth - width) / 2);
1457                 rect->top = workArea.top + max(0, (workHeight - height) / 2);
1458         }
1459 }
1460 #endif
1461
1462 static qboolean VID_InitModeGL(viddef_mode_t *mode)
1463 {
1464         int windowflags = SDL_WINDOW_SHOWN | SDL_WINDOW_OPENGL;
1465         int xPos = SDL_WINDOWPOS_UNDEFINED;
1466         int yPos = SDL_WINDOWPOS_UNDEFINED;
1467 #ifndef USE_GLES2
1468         int i;
1469         const char *drivername;
1470 #endif
1471
1472         win_half_width = mode->width>>1;
1473         win_half_height = mode->height>>1;
1474
1475         if(vid_resizable.integer)
1476                 windowflags |= SDL_WINDOW_RESIZABLE;
1477
1478         VID_OutputVersion();
1479
1480 #ifndef USE_GLES2
1481         // SDL usually knows best
1482         drivername = NULL;
1483
1484 // 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
1485         i = COM_CheckParm("-gl_driver");
1486         if (i && i < com_argc - 1)
1487                 drivername = com_argv[i + 1];
1488         if (SDL_GL_LoadLibrary(drivername) < 0)
1489         {
1490                 Con_Printf("Unable to load GL driver \"%s\": %s\n", drivername, SDL_GetError());
1491                 return false;
1492         }
1493 #endif
1494
1495 #ifdef DP_MOBILETOUCH
1496         // mobile platforms are always fullscreen, we'll get the resolution after opening the window
1497         mode->fullscreen = true;
1498         // hide the menu with SDL_WINDOW_BORDERLESS
1499         windowflags |= SDL_WINDOW_FULLSCREEN | SDL_WINDOW_BORDERLESS;
1500 #endif
1501
1502         vid_isfullscreen = false;
1503         {
1504                 if (mode->fullscreen) {
1505                         if (vid_desktopfullscreen.integer)
1506                         {
1507                                 vid_mode_t *m = VID_GetDesktopMode();
1508                                 mode->width = m->width;
1509                                 mode->height = m->height;
1510                                 windowflags |= SDL_WINDOW_FULLSCREEN_DESKTOP;
1511                         }
1512                         else
1513                                 windowflags |= SDL_WINDOW_FULLSCREEN;
1514                         vid_isfullscreen = true;
1515                 }
1516                 else {
1517 #ifdef WIN32
1518                         RECT rect;
1519                         AdjustWindowBounds(mode, &rect);
1520                         xPos = rect.left;
1521                         yPos = rect.top;
1522 #endif
1523                 }
1524         }
1525         //flags |= SDL_HWSURFACE;
1526
1527         SDL_GL_SetAttribute (SDL_GL_DOUBLEBUFFER, 1);
1528         SDL_GL_SetAttribute (SDL_GL_RED_SIZE, 8);
1529         SDL_GL_SetAttribute (SDL_GL_GREEN_SIZE, 8);
1530         SDL_GL_SetAttribute (SDL_GL_BLUE_SIZE, 8);
1531         SDL_GL_SetAttribute (SDL_GL_ALPHA_SIZE, 8);
1532         SDL_GL_SetAttribute (SDL_GL_DEPTH_SIZE, 24);
1533         SDL_GL_SetAttribute (SDL_GL_STENCIL_SIZE, 8);
1534         if (mode->stereobuffer)
1535                 SDL_GL_SetAttribute (SDL_GL_STEREO, 1);
1536         if (mode->samples > 1)
1537         {
1538                 SDL_GL_SetAttribute (SDL_GL_MULTISAMPLEBUFFERS, 1);
1539                 SDL_GL_SetAttribute (SDL_GL_MULTISAMPLESAMPLES, mode->samples);
1540         }
1541
1542 #ifdef USE_GLES2
1543         SDL_GL_SetAttribute (SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_ES);
1544         SDL_GL_SetAttribute (SDL_GL_CONTEXT_MAJOR_VERSION, 2);
1545         SDL_GL_SetAttribute (SDL_GL_CONTEXT_MINOR_VERSION, 0);
1546 #else
1547         SDL_GL_SetAttribute (SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
1548         SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
1549         SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 2);
1550 #endif
1551
1552         SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, (gl_debug.integer > 0 ? SDL_GL_CONTEXT_DEBUG_FLAG : 0));
1553
1554         video_bpp = mode->bitsperpixel;
1555         window_flags = windowflags;
1556         window = SDL_CreateWindow(gamename, xPos, yPos, mode->width, mode->height, windowflags);
1557         if (window == NULL)
1558         {
1559                 Con_Printf("Failed to set video mode to %ix%i: %s\n", mode->width, mode->height, SDL_GetError());
1560                 VID_Shutdown();
1561                 return false;
1562         }
1563         SDL_GetWindowSize(window, &mode->width, &mode->height);
1564         context = SDL_GL_CreateContext(window);
1565         if (context == NULL)
1566         {
1567                 Con_Printf("Failed to initialize OpenGL context: %s\n", SDL_GetError());
1568                 VID_Shutdown();
1569                 return false;
1570         }
1571
1572         SDL_GL_SetSwapInterval(bound(-1, vid_vsync.integer, 1));
1573         vid_usingvsync = (vid_vsync.integer != 0);
1574
1575         gl_platform = "SDL";
1576
1577         GL_Setup();
1578
1579         // VorteX: set other info
1580         extern cvar_t gl_info_vendor;
1581         extern cvar_t gl_info_renderer;
1582         extern cvar_t gl_info_version;
1583         extern cvar_t gl_info_platform;
1584         extern cvar_t gl_info_driver;
1585         Cvar_SetQuick(&gl_info_vendor, gl_vendor);
1586         Cvar_SetQuick(&gl_info_renderer, gl_renderer);
1587         Cvar_SetQuick(&gl_info_version, gl_version);
1588         Cvar_SetQuick(&gl_info_platform, gl_platform ? gl_platform : "");
1589         Cvar_SetQuick(&gl_info_driver, gl_driver);
1590
1591         // LadyHavoc: report supported extensions
1592 #ifdef CONFIG_MENU
1593         Con_DPrintf("\nQuakeC extensions for server and client: %s\nQuakeC extensions for menu: %s\n", vm_sv_extensions, vm_m_extensions);
1594 #else
1595         Con_DPrintf("\nQuakeC extensions for server and client: %s\n", vm_sv_extensions);
1596 #endif
1597
1598         // clear to black (loading plaque will be seen over this)
1599         GL_Clear(GL_COLOR_BUFFER_BIT, NULL, 1.0f, 0);
1600
1601         vid_hidden = false;
1602         vid_activewindow = false;
1603         vid_hasfocus = true;
1604         vid_usingmouse = false;
1605         vid_usinghidecursor = false;
1606                 
1607         return true;
1608 }
1609
1610 extern cvar_t gl_info_extensions;
1611 extern cvar_t gl_info_vendor;
1612 extern cvar_t gl_info_renderer;
1613 extern cvar_t gl_info_version;
1614 extern cvar_t gl_info_platform;
1615 extern cvar_t gl_info_driver;
1616
1617 qboolean VID_InitMode(viddef_mode_t *mode)
1618 {
1619         // GAME_STEELSTORM specific
1620         steelstorm_showing_map = Cvar_FindVar(&cvars_all, "steelstorm_showing_map", ~0);
1621         steelstorm_showing_mousecursor = Cvar_FindVar(&cvars_all, "steelstorm_showing_mousecursor", ~0);
1622
1623         if (!SDL_WasInit(SDL_INIT_VIDEO) && SDL_InitSubSystem(SDL_INIT_VIDEO) < 0)
1624                 Sys_Error ("Failed to init SDL video subsystem: %s", SDL_GetError());
1625
1626         Cvar_SetValueQuick(&vid_touchscreen_supportshowkeyboard, SDL_HasScreenKeyboardSupport() ? 1 : 0);
1627         return VID_InitModeGL(mode);
1628 }
1629
1630 void VID_Shutdown (void)
1631 {
1632         VID_EnableJoystick(false);
1633         VID_SetMouse(false, false, false);
1634
1635         SDL_DestroyWindow(window);
1636         window = NULL;
1637
1638         SDL_QuitSubSystem(SDL_INIT_VIDEO);
1639
1640         gl_driver[0] = 0;
1641         gl_extensions = "";
1642         gl_platform = "";
1643 }
1644
1645 void VID_Finish (void)
1646 {
1647         qboolean vid_usevsync;
1648         vid_activewindow = !vid_hidden && vid_hasfocus;
1649
1650         VID_UpdateGamma();
1651
1652         if (!vid_hidden)
1653         {
1654                 switch(vid.renderpath)
1655                 {
1656                 case RENDERPATH_GL32:
1657                 case RENDERPATH_GLES2:
1658                         CHECKGLERROR
1659                         if (r_speeds.integer == 2 || gl_finish.integer)
1660                                 GL_Finish();
1661
1662                         vid_usevsync = (vid_vsync.integer && !cls.timedemo);
1663                         if (vid_usingvsync != vid_usevsync)
1664                         {
1665                                 vid_usingvsync = vid_usevsync;
1666                                 if (SDL_GL_SetSwapInterval(vid_usevsync != 0) >= 0)
1667                                         Con_DPrintf("Vsync %s\n", vid_usevsync ? "activated" : "deactivated");
1668                                 else
1669                                         Con_DPrintf("ERROR: can't %s vsync\n", vid_usevsync ? "activate" : "deactivate");
1670                         }
1671                         SDL_GL_SwapWindow(window);
1672                         break;
1673                 }
1674         }
1675 }
1676
1677 vid_mode_t *VID_GetDesktopMode(void)
1678 {
1679         SDL_DisplayMode mode;
1680         int bpp;
1681         Uint32 rmask, gmask, bmask, amask;
1682         SDL_GetDesktopDisplayMode(0, &mode);
1683         SDL_PixelFormatEnumToMasks(mode.format, &bpp, &rmask, &gmask, &bmask, &amask);
1684         desktop_mode.width = mode.w;
1685         desktop_mode.height = mode.h;
1686         desktop_mode.bpp = bpp;
1687         desktop_mode.refreshrate = mode.refresh_rate;
1688         desktop_mode.pixelheight_num = 1;
1689         desktop_mode.pixelheight_denom = 1; // SDL does not provide this
1690         // TODO check whether this actually works, or whether we do still need
1691         // a read-window-size-after-entering-desktop-fullscreen hack for
1692         // multiscreen setups.
1693         return &desktop_mode;
1694 }
1695
1696 size_t VID_ListModes(vid_mode_t *modes, size_t maxcount)
1697 {
1698         size_t k = 0;
1699         int modenum;
1700         int nummodes = SDL_GetNumDisplayModes(0);
1701         SDL_DisplayMode mode;
1702         for (modenum = 0;modenum < nummodes;modenum++)
1703         {
1704                 if (k >= maxcount)
1705                         break;
1706                 if (SDL_GetDisplayMode(0, modenum, &mode))
1707                         continue;
1708                 modes[k].width = mode.w;
1709                 modes[k].height = mode.h;
1710                 // FIXME bpp?
1711                 modes[k].refreshrate = mode.refresh_rate;
1712                 modes[k].pixelheight_num = 1;
1713                 modes[k].pixelheight_denom = 1; // SDL does not provide this
1714                 k++;
1715         }
1716         return k;
1717 }