]> git.xonotic.org Git - xonotic/darkplaces.git/blob - vid_sdl.c
SDL: print version earlier, once only
[xonotic/darkplaces.git] / vid_sdl.c
1 /*
2 Copyright (C) 2003  T. Joseph Carter
3
4 This program is free software; you can redistribute it and/or
5 modify it under the terms of the GNU General Public License
6 as published by the Free Software Foundation; either version 2
7 of the License, or (at your option) any later version.
8
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
12
13 See the GNU General Public License for more details.
14
15 You should have received a copy of the GNU General Public License
16 along with this program; if not, write to the Free Software
17 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
18 */
19 #undef WIN32_LEAN_AND_MEAN  //hush a warning, SDL.h redefines this
20 #include <SDL.h>
21 #include <stdio.h>
22
23 #include "quakedef.h"
24 #include "image.h"
25 #include "utf8lib.h"
26
27 #ifndef __IPHONEOS__
28 #ifdef MACOSX
29 #include <Carbon/Carbon.h>
30 #include <IOKit/hidsystem/IOHIDLib.h>
31 #include <IOKit/hidsystem/IOHIDParameter.h>
32 #include <IOKit/hidsystem/event_status_driver.h>
33 #if (MAC_OS_X_VERSION_MIN_REQUIRED < 120000)
34         #define IOMainPort IOMasterPort
35 #endif
36 static cvar_t apple_mouse_noaccel = {CF_CLIENT | CF_ARCHIVE, "apple_mouse_noaccel", "1", "disables mouse acceleration while DarkPlaces is active"};
37 static qbool vid_usingnoaccel;
38 static double originalMouseSpeed = -1.0;
39 static io_connect_t IN_GetIOHandle(void)
40 {
41         io_connect_t iohandle = MACH_PORT_NULL;
42         kern_return_t status;
43         io_service_t iohidsystem = MACH_PORT_NULL;
44         mach_port_t masterport;
45
46         status = IOMainPort(MACH_PORT_NULL, &masterport);
47         if(status != KERN_SUCCESS)
48                 return 0;
49
50         iohidsystem = IORegistryEntryFromPath(masterport, kIOServicePlane ":/IOResources/IOHIDSystem");
51         if(!iohidsystem)
52                 return 0;
53
54         status = IOServiceOpen(iohidsystem, mach_task_self(), kIOHIDParamConnectType, &iohandle);
55         IOObjectRelease(iohidsystem);
56
57         return iohandle;
58 }
59 #endif
60 #endif
61
62 #ifdef WIN32
63 #define SDL_R_RESTART
64 #endif
65
66 // Tell startup code that we have a client
67 int cl_available = true;
68
69 qbool vid_supportrefreshrate = false;
70
71 static qbool vid_usingmouse = false;
72 static qbool vid_usingmouse_relativeworks = false; // SDL2 workaround for unimplemented RelativeMouse mode
73 static qbool vid_usinghidecursor = false;
74 static qbool vid_hasfocus = false;
75 static qbool vid_wmborder_waiting, vid_wmborderless;
76 static SDL_Joystick *vid_sdljoystick = NULL;
77 static SDL_GameController *vid_sdlgamecontroller = NULL;
78 static cvar_t joy_sdl2_trigger_deadzone = {CF_ARCHIVE | CF_CLIENT, "joy_sdl2_trigger_deadzone", "0.5", "deadzone for triggers to be registered as key presses"};
79 // GAME_STEELSTORM specific
80 static cvar_t *steelstorm_showing_map = NULL; // detect but do not create the cvar
81 static cvar_t *steelstorm_showing_mousecursor = NULL; // detect but do not create the cvar
82
83 static int win_half_width = 50;
84 static int win_half_height = 50;
85
86 static SDL_GLContext context;
87 static SDL_Window *window;
88
89 // Input handling
90
91 #ifndef SDLK_PERCENT
92 #define SDLK_PERCENT '%'
93 #endif
94
95 static int MapKey( unsigned int sdlkey )
96 {
97         switch(sdlkey)
98         {
99         // sdlkey can be Unicode codepoint for non-ascii keys, which are valid
100         default:                      return sdlkey & SDLK_SCANCODE_MASK ? 0 : sdlkey;
101 //      case SDLK_UNKNOWN:            return K_UNKNOWN;
102         case SDLK_RETURN:             return K_ENTER;
103         case SDLK_ESCAPE:             return K_ESCAPE;
104         case SDLK_BACKSPACE:          return K_BACKSPACE;
105         case SDLK_TAB:                return K_TAB;
106         case SDLK_SPACE:              return K_SPACE;
107         case SDLK_EXCLAIM:            return '!';
108         case SDLK_QUOTEDBL:           return '"';
109         case SDLK_HASH:               return '#';
110         case SDLK_PERCENT:            return '%';
111         case SDLK_DOLLAR:             return '$';
112         case SDLK_AMPERSAND:          return '&';
113         case SDLK_QUOTE:              return '\'';
114         case SDLK_LEFTPAREN:          return '(';
115         case SDLK_RIGHTPAREN:         return ')';
116         case SDLK_ASTERISK:           return '*';
117         case SDLK_PLUS:               return '+';
118         case SDLK_COMMA:              return ',';
119         case SDLK_MINUS:              return '-';
120         case SDLK_PERIOD:             return '.';
121         case SDLK_SLASH:              return '/';
122         case SDLK_0:                  return '0';
123         case SDLK_1:                  return '1';
124         case SDLK_2:                  return '2';
125         case SDLK_3:                  return '3';
126         case SDLK_4:                  return '4';
127         case SDLK_5:                  return '5';
128         case SDLK_6:                  return '6';
129         case SDLK_7:                  return '7';
130         case SDLK_8:                  return '8';
131         case SDLK_9:                  return '9';
132         case SDLK_COLON:              return ':';
133         case SDLK_SEMICOLON:          return ';';
134         case SDLK_LESS:               return '<';
135         case SDLK_EQUALS:             return '=';
136         case SDLK_GREATER:            return '>';
137         case SDLK_QUESTION:           return '?';
138         case SDLK_AT:                 return '@';
139         case SDLK_LEFTBRACKET:        return '[';
140         case SDLK_BACKSLASH:          return '\\';
141         case SDLK_RIGHTBRACKET:       return ']';
142         case SDLK_CARET:              return '^';
143         case SDLK_UNDERSCORE:         return '_';
144         case SDLK_BACKQUOTE:          return '`';
145         case SDLK_a:                  return 'a';
146         case SDLK_b:                  return 'b';
147         case SDLK_c:                  return 'c';
148         case SDLK_d:                  return 'd';
149         case SDLK_e:                  return 'e';
150         case SDLK_f:                  return 'f';
151         case SDLK_g:                  return 'g';
152         case SDLK_h:                  return 'h';
153         case SDLK_i:                  return 'i';
154         case SDLK_j:                  return 'j';
155         case SDLK_k:                  return 'k';
156         case SDLK_l:                  return 'l';
157         case SDLK_m:                  return 'm';
158         case SDLK_n:                  return 'n';
159         case SDLK_o:                  return 'o';
160         case SDLK_p:                  return 'p';
161         case SDLK_q:                  return 'q';
162         case SDLK_r:                  return 'r';
163         case SDLK_s:                  return 's';
164         case SDLK_t:                  return 't';
165         case SDLK_u:                  return 'u';
166         case SDLK_v:                  return 'v';
167         case SDLK_w:                  return 'w';
168         case SDLK_x:                  return 'x';
169         case SDLK_y:                  return 'y';
170         case SDLK_z:                  return 'z';
171         case SDLK_CAPSLOCK:           return K_CAPSLOCK;
172         case SDLK_F1:                 return K_F1;
173         case SDLK_F2:                 return K_F2;
174         case SDLK_F3:                 return K_F3;
175         case SDLK_F4:                 return K_F4;
176         case SDLK_F5:                 return K_F5;
177         case SDLK_F6:                 return K_F6;
178         case SDLK_F7:                 return K_F7;
179         case SDLK_F8:                 return K_F8;
180         case SDLK_F9:                 return K_F9;
181         case SDLK_F10:                return K_F10;
182         case SDLK_F11:                return K_F11;
183         case SDLK_F12:                return K_F12;
184         case SDLK_PRINTSCREEN:        return K_PRINTSCREEN;
185         case SDLK_SCROLLLOCK:         return K_SCROLLOCK;
186         case SDLK_PAUSE:              return K_PAUSE;
187         case SDLK_INSERT:             return K_INS;
188         case SDLK_HOME:               return K_HOME;
189         case SDLK_PAGEUP:             return K_PGUP;
190 #ifdef __IPHONEOS__
191         case SDLK_DELETE:             return K_BACKSPACE;
192 #else
193         case SDLK_DELETE:             return K_DEL;
194 #endif
195         case SDLK_END:                return K_END;
196         case SDLK_PAGEDOWN:           return K_PGDN;
197         case SDLK_RIGHT:              return K_RIGHTARROW;
198         case SDLK_LEFT:               return K_LEFTARROW;
199         case SDLK_DOWN:               return K_DOWNARROW;
200         case SDLK_UP:                 return K_UPARROW;
201         case SDLK_NUMLOCKCLEAR:       return K_NUMLOCK;
202         case SDLK_KP_DIVIDE:          return K_KP_DIVIDE;
203         case SDLK_KP_MULTIPLY:        return K_KP_MULTIPLY;
204         case SDLK_KP_MINUS:           return K_KP_MINUS;
205         case SDLK_KP_PLUS:            return K_KP_PLUS;
206         case SDLK_KP_ENTER:           return K_KP_ENTER;
207         case SDLK_KP_1:               return ((SDL_GetModState() & KMOD_NUM) ? K_KP_1 : K_END);
208         case SDLK_KP_2:               return ((SDL_GetModState() & KMOD_NUM) ? K_KP_2 : K_DOWNARROW);
209         case SDLK_KP_3:               return ((SDL_GetModState() & KMOD_NUM) ? K_KP_3 : K_PGDN);
210         case SDLK_KP_4:               return ((SDL_GetModState() & KMOD_NUM) ? K_KP_4 : K_LEFTARROW);
211         case SDLK_KP_5:               return K_KP_5;
212         case SDLK_KP_6:               return ((SDL_GetModState() & KMOD_NUM) ? K_KP_6 : K_RIGHTARROW);
213         case SDLK_KP_7:               return ((SDL_GetModState() & KMOD_NUM) ? K_KP_7 : K_HOME);
214         case SDLK_KP_8:               return ((SDL_GetModState() & KMOD_NUM) ? K_KP_8 : K_UPARROW);
215         case SDLK_KP_9:               return ((SDL_GetModState() & KMOD_NUM) ? K_KP_9 : K_PGUP);
216         case SDLK_KP_0:               return ((SDL_GetModState() & KMOD_NUM) ? K_KP_0 : K_INS);
217         case SDLK_KP_PERIOD:          return ((SDL_GetModState() & KMOD_NUM) ? K_KP_PERIOD : K_DEL);
218 //      case SDLK_APPLICATION:        return K_APPLICATION;
219 //      case SDLK_POWER:              return K_POWER;
220         case SDLK_KP_EQUALS:          return K_KP_EQUALS;
221 //      case SDLK_F13:                return K_F13;
222 //      case SDLK_F14:                return K_F14;
223 //      case SDLK_F15:                return K_F15;
224 //      case SDLK_F16:                return K_F16;
225 //      case SDLK_F17:                return K_F17;
226 //      case SDLK_F18:                return K_F18;
227 //      case SDLK_F19:                return K_F19;
228 //      case SDLK_F20:                return K_F20;
229 //      case SDLK_F21:                return K_F21;
230 //      case SDLK_F22:                return K_F22;
231 //      case SDLK_F23:                return K_F23;
232 //      case SDLK_F24:                return K_F24;
233 //      case SDLK_EXECUTE:            return K_EXECUTE;
234 //      case SDLK_HELP:               return K_HELP;
235 //      case SDLK_MENU:               return K_MENU;
236 //      case SDLK_SELECT:             return K_SELECT;
237 //      case SDLK_STOP:               return K_STOP;
238 //      case SDLK_AGAIN:              return K_AGAIN;
239 //      case SDLK_UNDO:               return K_UNDO;
240 //      case SDLK_CUT:                return K_CUT;
241 //      case SDLK_COPY:               return K_COPY;
242 //      case SDLK_PASTE:              return K_PASTE;
243 //      case SDLK_FIND:               return K_FIND;
244 //      case SDLK_MUTE:               return K_MUTE;
245 //      case SDLK_VOLUMEUP:           return K_VOLUMEUP;
246 //      case SDLK_VOLUMEDOWN:         return K_VOLUMEDOWN;
247 //      case SDLK_KP_COMMA:           return K_KP_COMMA;
248 //      case SDLK_KP_EQUALSAS400:     return K_KP_EQUALSAS400;
249 //      case SDLK_ALTERASE:           return K_ALTERASE;
250 //      case SDLK_SYSREQ:             return K_SYSREQ;
251 //      case SDLK_CANCEL:             return K_CANCEL;
252 //      case SDLK_CLEAR:              return K_CLEAR;
253 //      case SDLK_PRIOR:              return K_PRIOR;
254 //      case SDLK_RETURN2:            return K_RETURN2;
255 //      case SDLK_SEPARATOR:          return K_SEPARATOR;
256 //      case SDLK_OUT:                return K_OUT;
257 //      case SDLK_OPER:               return K_OPER;
258 //      case SDLK_CLEARAGAIN:         return K_CLEARAGAIN;
259 //      case SDLK_CRSEL:              return K_CRSEL;
260 //      case SDLK_EXSEL:              return K_EXSEL;
261 //      case SDLK_KP_00:              return K_KP_00;
262 //      case SDLK_KP_000:             return K_KP_000;
263 //      case SDLK_THOUSANDSSEPARATOR: return K_THOUSANDSSEPARATOR;
264 //      case SDLK_DECIMALSEPARATOR:   return K_DECIMALSEPARATOR;
265 //      case SDLK_CURRENCYUNIT:       return K_CURRENCYUNIT;
266 //      case SDLK_CURRENCYSUBUNIT:    return K_CURRENCYSUBUNIT;
267 //      case SDLK_KP_LEFTPAREN:       return K_KP_LEFTPAREN;
268 //      case SDLK_KP_RIGHTPAREN:      return K_KP_RIGHTPAREN;
269 //      case SDLK_KP_LEFTBRACE:       return K_KP_LEFTBRACE;
270 //      case SDLK_KP_RIGHTBRACE:      return K_KP_RIGHTBRACE;
271 //      case SDLK_KP_TAB:             return K_KP_TAB;
272 //      case SDLK_KP_BACKSPACE:       return K_KP_BACKSPACE;
273 //      case SDLK_KP_A:               return K_KP_A;
274 //      case SDLK_KP_B:               return K_KP_B;
275 //      case SDLK_KP_C:               return K_KP_C;
276 //      case SDLK_KP_D:               return K_KP_D;
277 //      case SDLK_KP_E:               return K_KP_E;
278 //      case SDLK_KP_F:               return K_KP_F;
279 //      case SDLK_KP_XOR:             return K_KP_XOR;
280 //      case SDLK_KP_POWER:           return K_KP_POWER;
281 //      case SDLK_KP_PERCENT:         return K_KP_PERCENT;
282 //      case SDLK_KP_LESS:            return K_KP_LESS;
283 //      case SDLK_KP_GREATER:         return K_KP_GREATER;
284 //      case SDLK_KP_AMPERSAND:       return K_KP_AMPERSAND;
285 //      case SDLK_KP_DBLAMPERSAND:    return K_KP_DBLAMPERSAND;
286 //      case SDLK_KP_VERTICALBAR:     return K_KP_VERTICALBAR;
287 //      case SDLK_KP_DBLVERTICALBAR:  return K_KP_DBLVERTICALBAR;
288 //      case SDLK_KP_COLON:           return K_KP_COLON;
289 //      case SDLK_KP_HASH:            return K_KP_HASH;
290 //      case SDLK_KP_SPACE:           return K_KP_SPACE;
291 //      case SDLK_KP_AT:              return K_KP_AT;
292 //      case SDLK_KP_EXCLAM:          return K_KP_EXCLAM;
293 //      case SDLK_KP_MEMSTORE:        return K_KP_MEMSTORE;
294 //      case SDLK_KP_MEMRECALL:       return K_KP_MEMRECALL;
295 //      case SDLK_KP_MEMCLEAR:        return K_KP_MEMCLEAR;
296 //      case SDLK_KP_MEMADD:          return K_KP_MEMADD;
297 //      case SDLK_KP_MEMSUBTRACT:     return K_KP_MEMSUBTRACT;
298 //      case SDLK_KP_MEMMULTIPLY:     return K_KP_MEMMULTIPLY;
299 //      case SDLK_KP_MEMDIVIDE:       return K_KP_MEMDIVIDE;
300 //      case SDLK_KP_PLUSMINUS:       return K_KP_PLUSMINUS;
301 //      case SDLK_KP_CLEAR:           return K_KP_CLEAR;
302 //      case SDLK_KP_CLEARENTRY:      return K_KP_CLEARENTRY;
303 //      case SDLK_KP_BINARY:          return K_KP_BINARY;
304 //      case SDLK_KP_OCTAL:           return K_KP_OCTAL;
305 //      case SDLK_KP_DECIMAL:         return K_KP_DECIMAL;
306 //      case SDLK_KP_HEXADECIMAL:     return K_KP_HEXADECIMAL;
307         case SDLK_LCTRL:              return K_CTRL;
308         case SDLK_LSHIFT:             return K_SHIFT;
309         case SDLK_LALT:               return K_ALT;
310 //      case SDLK_LGUI:               return K_LGUI;
311         case SDLK_RCTRL:              return K_CTRL;
312         case SDLK_RSHIFT:             return K_SHIFT;
313         case SDLK_RALT:               return K_ALT;
314 //      case SDLK_RGUI:               return K_RGUI;
315 //      case SDLK_MODE:               return K_MODE;
316 //      case SDLK_AUDIONEXT:          return K_AUDIONEXT;
317 //      case SDLK_AUDIOPREV:          return K_AUDIOPREV;
318 //      case SDLK_AUDIOSTOP:          return K_AUDIOSTOP;
319 //      case SDLK_AUDIOPLAY:          return K_AUDIOPLAY;
320 //      case SDLK_AUDIOMUTE:          return K_AUDIOMUTE;
321 //      case SDLK_MEDIASELECT:        return K_MEDIASELECT;
322 //      case SDLK_WWW:                return K_WWW;
323 //      case SDLK_MAIL:               return K_MAIL;
324 //      case SDLK_CALCULATOR:         return K_CALCULATOR;
325 //      case SDLK_COMPUTER:           return K_COMPUTER;
326 //      case SDLK_AC_SEARCH:          return K_AC_SEARCH; // Android button
327 //      case SDLK_AC_HOME:            return K_AC_HOME; // Android button
328         case SDLK_AC_BACK:            return K_ESCAPE; // Android button
329 //      case SDLK_AC_FORWARD:         return K_AC_FORWARD; // Android button
330 //      case SDLK_AC_STOP:            return K_AC_STOP; // Android button
331 //      case SDLK_AC_REFRESH:         return K_AC_REFRESH; // Android button
332 //      case SDLK_AC_BOOKMARKS:       return K_AC_BOOKMARKS; // Android button
333 //      case SDLK_BRIGHTNESSDOWN:     return K_BRIGHTNESSDOWN;
334 //      case SDLK_BRIGHTNESSUP:       return K_BRIGHTNESSUP;
335 //      case SDLK_DISPLAYSWITCH:      return K_DISPLAYSWITCH;
336 //      case SDLK_KBDILLUMTOGGLE:     return K_KBDILLUMTOGGLE;
337 //      case SDLK_KBDILLUMDOWN:       return K_KBDILLUMDOWN;
338 //      case SDLK_KBDILLUMUP:         return K_KBDILLUMUP;
339 //      case SDLK_EJECT:              return K_EJECT;
340 //      case SDLK_SLEEP:              return K_SLEEP;
341         }
342 }
343
344 qbool VID_HasScreenKeyboardSupport(void)
345 {
346         return SDL_HasScreenKeyboardSupport() != SDL_FALSE;
347 }
348
349 void VID_ShowKeyboard(qbool show)
350 {
351         if (!SDL_HasScreenKeyboardSupport())
352                 return;
353
354         if (show)
355         {
356                 if (!SDL_IsTextInputActive())
357                         SDL_StartTextInput();
358         }
359         else
360         {
361                 if (SDL_IsTextInputActive())
362                         SDL_StopTextInput();
363         }
364 }
365
366 qbool VID_ShowingKeyboard(void)
367 {
368         return SDL_IsTextInputActive() != 0;
369 }
370
371 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 static void VID_ChangeDisplay_c(cvar_t *var);
1060 void Sys_SDL_HandleEvents(void)
1061 {
1062         static qbool sound_active = true;
1063         int keycode;
1064         int i;
1065         const char *chp;
1066         qbool 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                                 host.state = host_shutdown;
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                                                 vid.xPos = event.window.data1;
1172                                                 vid.yPos = event.window.data2;
1173                                                 // Update vid.displayindex (current monitor) as it may have changed
1174                                                 // SDL_GetWindowDisplayIndex() doesn't work if the window manager moves the fullscreen window, but this works:
1175                                                 for (i = 0; i < vid_info_displaycount.integer; ++i)
1176                                                 {
1177                                                         SDL_Rect displaybounds;
1178                                                         if (SDL_GetDisplayBounds(i, &displaybounds) < 0)
1179                                                         {
1180                                                                 Con_Printf(CON_ERROR "Error getting bounds of display %i: \"%s\"\n", i, SDL_GetError());
1181                                                                 return;
1182                                                         }
1183                                                         if (vid.xPos >= displaybounds.x && vid.xPos < displaybounds.x + displaybounds.w)
1184                                                         if (vid.yPos >= displaybounds.y && vid.yPos < displaybounds.y + displaybounds.h)
1185                                                         {
1186                                                                 vid.displayindex = i;
1187                                                                 break;
1188                                                         }
1189                                                 }
1190                                                 // when the window manager adds/removes the border it's likely to move the SDL window
1191                                                 // we'll need to correct that to (re)align the xhair with the monitor
1192                                                 if (vid_wmborder_waiting)
1193                                                 {
1194                                                         SDL_GetWindowBordersSize(window, &i, NULL, NULL, NULL);
1195                                                         if (!i != vid_wmborderless) // border state changed
1196                                                         {
1197                                                                 SDL_SetWindowPosition(window, SDL_WINDOWPOS_CENTERED_DISPLAY(vid.displayindex), SDL_WINDOWPOS_CENTERED_DISPLAY(vid.displayindex));
1198                                                                 SDL_GetWindowPosition(window, &vid.xPos, &vid.yPos);
1199                                                                 vid_wmborder_waiting = false;
1200                                                         }
1201                                                 }
1202                                                 break;
1203                                         case SDL_WINDOWEVENT_RESIZED: // external events only
1204                                                 if(vid_resizable.integer < 2)
1205                                                 {
1206                                                         //vid.width = event.window.data1;
1207                                                         //vid.height = event.window.data2;
1208                                                         // get the real framebuffer size in case the platform's screen coordinates are DPI scaled
1209                                                         SDL_GL_GetDrawableSize(window, &vid.width, &vid.height);
1210 #ifdef SDL_R_RESTART
1211                                                         // better not call R_Modules_Restart_f from here directly, as this may wreak havoc...
1212                                                         // so, let's better queue it for next frame
1213                                                         if(!sdl_needs_restart)
1214                                                         {
1215                                                                 Cbuf_AddText(cmd_local, "\nr_restart\n");
1216                                                                 sdl_needs_restart = true;
1217                                                         }
1218 #endif
1219                                                 }
1220                                                 break;
1221                                         case SDL_WINDOWEVENT_SIZE_CHANGED: // internal and external events
1222                                                 break;
1223                                         case SDL_WINDOWEVENT_MINIMIZED:
1224                                                 break;
1225                                         case SDL_WINDOWEVENT_MAXIMIZED:
1226                                                 break;
1227                                         case SDL_WINDOWEVENT_RESTORED:
1228                                                 break;
1229                                         case SDL_WINDOWEVENT_ENTER:
1230                                                 break;
1231                                         case SDL_WINDOWEVENT_LEAVE:
1232                                                 break;
1233                                         case SDL_WINDOWEVENT_FOCUS_GAINED:
1234                                                 vid_hasfocus = true;
1235                                                 break;
1236                                         case SDL_WINDOWEVENT_FOCUS_LOST:
1237                                                 vid_hasfocus = false;
1238                                                 break;
1239                                         case SDL_WINDOWEVENT_CLOSE:
1240                                                 host.state = host_shutdown;
1241                                                 break;
1242                                         case SDL_WINDOWEVENT_TAKE_FOCUS:
1243                                                 break;
1244                                         case SDL_WINDOWEVENT_HIT_TEST:
1245                                                 break;
1246                                         case SDL_WINDOWEVENT_ICCPROF_CHANGED:
1247                                                 break;
1248                                         case SDL_WINDOWEVENT_DISPLAY_CHANGED:
1249                                                 // this event can't be relied on in fullscreen, see SDL_WINDOWEVENT_MOVED above
1250                                                 vid.displayindex = event.window.data1;
1251                                                 break;
1252                                         }
1253                                 }
1254                                 break;
1255                         case SDL_DISPLAYEVENT: // Display hotplugging
1256                                 switch (event.display.event)
1257                                 {
1258                                         case SDL_DISPLAYEVENT_CONNECTED:
1259                                                 Con_Printf("Display %i connected: %s\nA vid_restart may be necessary!\n", event.display.display, SDL_GetDisplayName(event.display.display));
1260                                                 Cvar_SetValueQuick(&vid_info_displaycount, SDL_GetNumVideoDisplays());
1261                                                 // Ideally we'd call VID_ChangeDisplay_c() to try to switch to the preferred display here,
1262                                                 // but we may need a vid_restart first, see comments in VID_ChangeDisplay_c().
1263                                                 break;
1264                                         case SDL_DISPLAYEVENT_DISCONNECTED:
1265                                                 Con_Printf("Display %i disconnected.\nA vid_restart may be necessary!\n", event.display.display);
1266                                                 Cvar_SetValueQuick(&vid_info_displaycount, SDL_GetNumVideoDisplays());
1267                                                 break;
1268                                         case SDL_DISPLAYEVENT_ORIENTATION:
1269                                                 break;
1270                                 }
1271                                 break;
1272                         case SDL_TEXTEDITING:
1273 #ifdef DEBUGSDLEVENTS
1274                                 Con_DPrintf("SDL_Event: SDL_TEXTEDITING - composition = %s, cursor = %d, selection lenght = %d\n", event.edit.text, event.edit.start, event.edit.length);
1275 #endif
1276                                 // FIXME!  this is where composition gets supported
1277                                 break;
1278                         case SDL_TEXTINPUT:
1279 #ifdef DEBUGSDLEVENTS
1280                                 Con_DPrintf("SDL_Event: SDL_TEXTINPUT - text: %s\n", event.text.text);
1281 #endif
1282                                 // convert utf8 string to char
1283                                 // NOTE: this code is supposed to run even if utf8enable is 0
1284                                 chp = event.text.text;
1285                                 while (*chp != 0)
1286                                 {
1287                                         // input the chars one by one (there can be multiple chars when e.g. using an "input method")
1288                                         unicode = u8_getchar_utf8_enabled(chp, &chp);
1289                                         Key_Event(K_TEXT, unicode, true);
1290                                         Key_Event(K_TEXT, unicode, false);
1291                                 }
1292                                 break;
1293                         case SDL_MOUSEMOTION:
1294                                 break;
1295                         case SDL_FINGERDOWN:
1296 #ifdef DEBUGSDLEVENTS
1297                                 Con_DPrintf("SDL_FINGERDOWN for finger %i\n", (int)event.tfinger.fingerId);
1298 #endif
1299                                 for (i = 0;i < MAXFINGERS-1;i++)
1300                                 {
1301                                         if (!multitouch[i][0])
1302                                         {
1303                                                 multitouch[i][0] = event.tfinger.fingerId + 1;
1304                                                 multitouch[i][1] = event.tfinger.x;
1305                                                 multitouch[i][2] = event.tfinger.y;
1306                                                 // TODO: use event.tfinger.pressure?
1307                                                 break;
1308                                         }
1309                                 }
1310                                 if (i == MAXFINGERS-1)
1311                                         Con_DPrintf("Too many fingers at once!\n");
1312                                 break;
1313                         case SDL_FINGERUP:
1314 #ifdef DEBUGSDLEVENTS
1315                                 Con_DPrintf("SDL_FINGERUP for finger %i\n", (int)event.tfinger.fingerId);
1316 #endif
1317                                 for (i = 0;i < MAXFINGERS-1;i++)
1318                                 {
1319                                         if (multitouch[i][0] == event.tfinger.fingerId + 1)
1320                                         {
1321                                                 multitouch[i][0] = 0;
1322                                                 break;
1323                                         }
1324                                 }
1325                                 if (i == MAXFINGERS-1)
1326                                         Con_DPrintf("No SDL_FINGERDOWN event matches this SDL_FINGERMOTION event\n");
1327                                 break;
1328                         case SDL_FINGERMOTION:
1329 #ifdef DEBUGSDLEVENTS
1330                                 Con_DPrintf("SDL_FINGERMOTION for finger %i\n", (int)event.tfinger.fingerId);
1331 #endif
1332                                 for (i = 0;i < MAXFINGERS-1;i++)
1333                                 {
1334                                         if (multitouch[i][0] == event.tfinger.fingerId + 1)
1335                                         {
1336                                                 multitouch[i][1] = event.tfinger.x;
1337                                                 multitouch[i][2] = event.tfinger.y;
1338                                                 break;
1339                                         }
1340                                 }
1341                                 if (i == MAXFINGERS-1)
1342                                         Con_DPrintf("No SDL_FINGERDOWN event matches this SDL_FINGERMOTION event\n");
1343                                 break;
1344                         default:
1345 #ifdef DEBUGSDLEVENTS
1346                                 Con_DPrintf("Received unrecognized SDL_Event type 0x%x\n", event.type);
1347 #endif
1348                                 break;
1349                 }
1350
1351         // enable/disable sound on focus gain/loss
1352         if ((!vid_hidden && vid_activewindow) || !snd_mutewhenidle.integer)
1353         {
1354                 if (!sound_active)
1355                 {
1356                         S_UnblockSound ();
1357                         sound_active = true;
1358                 }
1359         }
1360         else
1361         {
1362                 if (sound_active)
1363                 {
1364                         S_BlockSound ();
1365                         sound_active = false;
1366                 }
1367         }
1368 }
1369
1370 /////////////////
1371 // Video system
1372 ////
1373
1374 void *GL_GetProcAddress(const char *name)
1375 {
1376         void *p = NULL;
1377         p = SDL_GL_GetProcAddress(name);
1378         return p;
1379 }
1380
1381 qbool GL_ExtensionSupported(const char *name)
1382 {
1383         return SDL_GL_ExtensionSupported(name);
1384 }
1385
1386 static void VID_ChangeDisplay_c(cvar_t *var)
1387 {
1388         unsigned int fullscreenwanted, fullscreencurrent;
1389         unsigned int displaywanted = bound(0, vid_display.integer, vid_info_displaycount.integer - 1);
1390
1391         if (!window)
1392                 return;
1393
1394         fullscreencurrent = SDL_GetWindowFlags(window) & (SDL_WINDOW_FULLSCREEN_DESKTOP | SDL_WINDOW_FULLSCREEN);
1395         if (vid_fullscreen.integer)
1396                 fullscreenwanted = vid_desktopfullscreen.integer ? SDL_WINDOW_FULLSCREEN_DESKTOP : SDL_WINDOW_FULLSCREEN;
1397         else
1398                 fullscreenwanted = 0;
1399
1400         // moving to another display, changing the fullscreen mode or switching to windowed
1401         if (vid.displayindex != displaywanted // SDL seems unable to move any fullscreen window to another display
1402         || fullscreencurrent != fullscreenwanted) // even for desktop <-> exclusive: switching to windowed first feels safer
1403         {
1404                 if (SDL_SetWindowFullscreen(window, 0) < 0)
1405                 {
1406                         Con_Printf(CON_ERROR "ERROR: can't deactivate fullscreen on display %i because %s\n", vid.displayindex, SDL_GetError());
1407                         return;
1408                 }
1409                 vid.fullscreen = false;
1410                 Con_DPrintf("Fullscreen deactivated on display %i\n", vid.displayindex);
1411         }
1412
1413         // switching to windowed
1414         if (!fullscreenwanted)
1415         {
1416                 int toppx;
1417                 SDL_SetWindowSize(window, vid.width = vid_width.integer, vid.height = vid_height.integer);
1418                 SDL_SetWindowResizable(window, vid_resizable.integer ? SDL_TRUE : SDL_FALSE);
1419                 SDL_SetWindowBordered(window, (SDL_bool)!vid_borderless.integer);
1420                 SDL_GetWindowBordersSize(window, &toppx, NULL, NULL, NULL);
1421                 vid_wmborderless = !toppx;
1422                 if (vid_borderless.integer != vid_wmborderless) // this is not the state we're looking for
1423                         vid_wmborder_waiting = true;
1424         }
1425
1426         // moving to another display or switching to windowed
1427         if (vid.displayindex != displaywanted || !fullscreenwanted)
1428         {
1429 //              SDL_SetWindowPosition(window, SDL_WINDOWPOS_CENTERED_DISPLAY(displaywanted), SDL_WINDOWPOS_CENTERED_DISPLAY(displaywanted));
1430 //              SDL_GetWindowPosition(window, &vid.xPos, &vid.yPos);
1431
1432                 /* bones_was_here BUG: after SDL_DISPLAYEVENT hotplug events,
1433                  * SDL_WINDOWPOS_CENTERED_DISPLAY(displaywanted) may place the window somewhere completely invisible.
1434                  * WORKAROUND: manual positioning seems safer: although SDL_GetDisplayBounds() may return outdated values,
1435                  * SDL_SetWindowPosition() always placed the window somewhere fully visible, even if it wasn't correct,
1436                  * when tested with SDL 2.26.5.
1437                  */
1438                 SDL_Rect displaybounds;
1439                 if (SDL_GetDisplayBounds(displaywanted, &displaybounds) < 0)
1440                 {
1441                         Con_Printf(CON_ERROR "Error getting bounds of display %i: \"%s\"\n", displaywanted, SDL_GetError());
1442                         return;
1443                 }
1444                 vid.xPos = displaybounds.x + 0.5 * (displaybounds.w - vid.width);
1445                 vid.yPos = displaybounds.y + 0.5 * (displaybounds.h - vid.height);
1446                 SDL_SetWindowPosition(window, vid.xPos, vid.yPos);
1447
1448                 vid.displayindex = displaywanted;
1449         }
1450
1451         // switching to a fullscreen mode
1452         if (fullscreenwanted)
1453         {
1454                 if (SDL_SetWindowFullscreen(window, fullscreenwanted) < 0)
1455                 {
1456                         Con_Printf(CON_ERROR "ERROR: can't activate fullscreen on display %i because %s\n", vid.displayindex, SDL_GetError());
1457                         return;
1458                 }
1459                 // get the real framebuffer size in case the platform's screen coordinates are DPI scaled
1460                 SDL_GL_GetDrawableSize(window, &vid.width, &vid.height);
1461                 vid.fullscreen = true;
1462                 Con_DPrintf("Fullscreen activated on display %i\n", vid.displayindex);
1463         }
1464 }
1465
1466 static void VID_SetVsync_c(cvar_t *var)
1467 {
1468         signed char vsyncwanted = cls.timedemo ? 0 : bound(-1, vid_vsync.integer, 1);
1469
1470         if (!context)
1471                 return;
1472         if (SDL_GL_GetSwapInterval() == vsyncwanted)
1473                 return;
1474
1475         if (SDL_GL_SetSwapInterval(vsyncwanted) >= 0)
1476                 Con_DPrintf("Vsync %s\n", vsyncwanted ? "activated" : "deactivated");
1477         else
1478                 Con_Printf(CON_ERROR "ERROR: can't %s vsync because %s\n", vsyncwanted ? "activate" : "deactivate", SDL_GetError());
1479 }
1480
1481 void VID_Init (void)
1482 {
1483         SDL_version version;
1484
1485 #ifndef __IPHONEOS__
1486 #ifdef MACOSX
1487         Cvar_RegisterVariable(&apple_mouse_noaccel);
1488 #endif
1489 #endif
1490 #ifdef DP_MOBILETOUCH
1491         Cvar_SetValueQuick(&vid_touchscreen, 1);
1492 #endif
1493         Cvar_RegisterVariable(&joy_sdl2_trigger_deadzone);
1494
1495 #ifdef SDL_R_RESTART
1496         R_RegisterModule("SDL", sdl_start, sdl_shutdown, sdl_newmap, NULL, NULL);
1497 #endif
1498
1499 #if defined(__linux__)
1500         // exclusive fullscreen is no longer functional (and when it worked was obnoxious and not faster)
1501         Cvar_SetValueQuick(&vid_desktopfullscreen, 1);
1502         vid_desktopfullscreen.flags |= CF_READONLY;
1503 #endif
1504
1505         Cvar_RegisterCallback(&vid_fullscreen,             VID_ChangeDisplay_c);
1506         Cvar_RegisterCallback(&vid_desktopfullscreen,      VID_ChangeDisplay_c);
1507         Cvar_RegisterCallback(&vid_display,                VID_ChangeDisplay_c);
1508         Cvar_RegisterCallback(&vid_resizable,              VID_ChangeDisplay_c);
1509         Cvar_RegisterCallback(&vid_borderless,             VID_ChangeDisplay_c);
1510         Cvar_RegisterCallback(&vid_vsync,                  VID_SetVsync_c);
1511
1512         if (SDL_Init(SDL_INIT_VIDEO) < 0)
1513                 Sys_Error ("Failed to init SDL video subsystem: %s", SDL_GetError());
1514         if (SDL_InitSubSystem(SDL_INIT_JOYSTICK) < 0)
1515                 Con_Printf(CON_ERROR "Failed to init SDL joystick subsystem: %s\n", SDL_GetError());
1516
1517         SDL_GetVersion(&version);
1518         Con_Printf("Linked against SDL version %d.%d.%d\n"
1519                    "Using SDL library version %d.%d.%d\n",
1520                    SDL_MAJOR_VERSION, SDL_MINOR_VERSION, SDL_PATCHLEVEL,
1521                    version.major, version.minor, version.patch);
1522 }
1523
1524 static int vid_sdljoystickindex = -1;
1525 void VID_EnableJoystick(qbool enable)
1526 {
1527         int index = joy_enable.integer > 0 ? joy_index.integer : -1;
1528         int numsdljoysticks;
1529         qbool success = false;
1530         int sharedcount = 0;
1531         int sdlindex = -1;
1532         sharedcount = VID_Shared_SetJoystick(index);
1533         if (index >= 0 && index < sharedcount)
1534                 success = true;
1535         sdlindex = index - sharedcount;
1536
1537         numsdljoysticks = SDL_NumJoysticks();
1538         if (sdlindex < 0 || sdlindex >= numsdljoysticks)
1539                 sdlindex = -1;
1540
1541         // update cvar containing count of XInput joysticks + SDL joysticks
1542         if (joy_detected.integer != sharedcount + numsdljoysticks)
1543                 Cvar_SetValueQuick(&joy_detected, sharedcount + numsdljoysticks);
1544
1545         if (vid_sdljoystickindex != sdlindex)
1546         {
1547                 vid_sdljoystickindex = sdlindex;
1548                 // close SDL joystick if active
1549                 if (vid_sdljoystick)
1550                 {
1551                         SDL_JoystickClose(vid_sdljoystick);
1552                         vid_sdljoystick = NULL;
1553                 }
1554                 if (vid_sdlgamecontroller)
1555                 {
1556                         SDL_GameControllerClose(vid_sdlgamecontroller);
1557                         vid_sdlgamecontroller = NULL;
1558                 }
1559                 if (sdlindex >= 0)
1560                 {
1561                         vid_sdljoystick = SDL_JoystickOpen(sdlindex);
1562                         if (vid_sdljoystick)
1563                         {
1564                                 const char *joystickname = SDL_JoystickName(vid_sdljoystick);
1565                                 if (SDL_IsGameController(vid_sdljoystickindex))
1566                                 {
1567                                         vid_sdlgamecontroller = SDL_GameControllerOpen(vid_sdljoystickindex);
1568                                         Con_DPrintf("Using SDL GameController mappings for Joystick %i\n", index);
1569                                 }
1570                                 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));
1571                         }
1572                         else
1573                         {
1574                                 Con_Printf(CON_ERROR "Joystick %i failed (SDL_JoystickOpen(%i) returned: %s)\n", index, sdlindex, SDL_GetError());
1575                                 sdlindex = -1;
1576                         }
1577                 }
1578         }
1579
1580         if (sdlindex >= 0)
1581                 success = true;
1582
1583         if (joy_active.integer != (success ? 1 : 0))
1584                 Cvar_SetValueQuick(&joy_active, success ? 1 : 0);
1585 }
1586
1587 #ifdef WIN32
1588 static void AdjustWindowBounds(viddef_mode_t *mode, RECT *rect)
1589 {
1590         int workWidth;
1591         int workHeight;
1592         int titleBarPixels = 2;
1593         int screenHeight;
1594         RECT workArea;
1595         LONG width = mode->width; // vid_width
1596         LONG height = mode->height; // vid_height
1597
1598         // adjust width and height for the space occupied by window decorators (title bar, borders)
1599         rect->top = 0;
1600         rect->left = 0;
1601         rect->right = width;
1602         rect->bottom = height;
1603         AdjustWindowRectEx(rect, WS_CAPTION|WS_THICKFRAME, false, 0);
1604
1605         SystemParametersInfo(SPI_GETWORKAREA, 0, &workArea, 0);
1606         workWidth = workArea.right - workArea.left;
1607         workHeight = workArea.bottom - workArea.top;
1608
1609         // SDL forces the window height to be <= screen height - 27px (on Win8.1 - probably intended for the title bar) 
1610         // If the task bar is docked to the the left screen border and we move the window to negative y,
1611         // there would be some part of the regular desktop visible on the bottom of the screen.
1612         screenHeight = GetSystemMetrics(SM_CYSCREEN);
1613         if (screenHeight == workHeight)
1614                 titleBarPixels = -rect->top;
1615
1616         //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);
1617
1618         // if height and width matches the physical or previously adjusted screen height and width, adjust it to available desktop area
1619         if ((width == GetSystemMetrics(SM_CXSCREEN) || width == workWidth) && (height == screenHeight || height == workHeight - titleBarPixels))
1620         {
1621                 rect->left = workArea.left;
1622                 mode->width = workWidth;
1623                 rect->top = workArea.top + titleBarPixels;
1624                 mode->height = workHeight - titleBarPixels;
1625         }
1626         else 
1627         {
1628                 rect->left = workArea.left + max(0, (workWidth - width) / 2);
1629                 rect->top = workArea.top + max(0, (workHeight - height) / 2);
1630         }
1631 }
1632 #endif
1633
1634 static qbool VID_InitModeGL(viddef_mode_t *mode)
1635 {
1636         int windowflags = SDL_WINDOW_SHOWN | SDL_WINDOW_OPENGL;
1637         int i;
1638 #ifndef USE_GLES2
1639         // SDL usually knows best
1640         const char *drivername = NULL;
1641 #endif
1642
1643         // video display selection (multi-monitor)
1644         Cvar_SetValueQuick(&vid_info_displaycount, SDL_GetNumVideoDisplays());
1645         vid.displayindex = bound(0, vid_display.integer, vid_info_displaycount.integer - 1);
1646         vid.xPos = SDL_WINDOWPOS_CENTERED_DISPLAY(vid.displayindex);
1647         vid.yPos = SDL_WINDOWPOS_CENTERED_DISPLAY(vid.displayindex);
1648         vid_wmborder_waiting = vid_wmborderless = false;
1649
1650         win_half_width = mode->width>>1;
1651         win_half_height = mode->height>>1;
1652
1653         if(vid_resizable.integer)
1654                 windowflags |= SDL_WINDOW_RESIZABLE;
1655
1656 #ifndef USE_GLES2
1657 // 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
1658         i = Sys_CheckParm("-gl_driver");
1659         if (i && i < sys.argc - 1)
1660                 drivername = sys.argv[i + 1];
1661         if (SDL_GL_LoadLibrary(drivername) < 0)
1662         {
1663                 Con_Printf(CON_ERROR "Unable to load GL driver \"%s\": %s\n", drivername, SDL_GetError());
1664                 return false;
1665         }
1666 #endif
1667
1668 #ifdef DP_MOBILETOUCH
1669         // mobile platforms are always fullscreen, we'll get the resolution after opening the window
1670         mode->fullscreen = true;
1671         // hide the menu with SDL_WINDOW_BORDERLESS
1672         windowflags |= SDL_WINDOW_FULLSCREEN | SDL_WINDOW_BORDERLESS;
1673 #endif
1674
1675
1676         if (mode->fullscreen)
1677         {
1678                 if (vid_desktopfullscreen.integer)
1679                 {
1680                         vid_mode_t m = VID_GetDesktopMode();
1681                         mode->width = m.width;
1682                         mode->height = m.height;
1683                         windowflags |= SDL_WINDOW_FULLSCREEN_DESKTOP;
1684                 }
1685                 else
1686                         windowflags |= SDL_WINDOW_FULLSCREEN;
1687         }
1688         else
1689         {
1690                 if (vid_borderless.integer)
1691                         windowflags |= SDL_WINDOW_BORDERLESS;
1692                 else
1693                         vid_wmborder_waiting = true; // waiting for border to be added
1694 #ifdef WIN32
1695                 if (!vid_ignore_taskbar.integer)
1696                 {
1697                         RECT rect;
1698                         AdjustWindowBounds(mode, &rect);
1699                         vid.xPos = rect.left;
1700                         vid.xPos = rect.top;
1701                         vid_wmborder_waiting = false;
1702                 }
1703 #endif
1704         }
1705
1706
1707         if (vid_mouse_clickthrough.integer)
1708                 SDL_SetHint(SDL_HINT_MOUSE_FOCUS_CLICKTHROUGH, "1");
1709
1710         SDL_GL_SetAttribute (SDL_GL_DOUBLEBUFFER, 1);
1711         SDL_GL_SetAttribute (SDL_GL_RED_SIZE, 8);
1712         SDL_GL_SetAttribute (SDL_GL_GREEN_SIZE, 8);
1713         SDL_GL_SetAttribute (SDL_GL_BLUE_SIZE, 8);
1714         SDL_GL_SetAttribute (SDL_GL_ALPHA_SIZE, 8);
1715         SDL_GL_SetAttribute (SDL_GL_DEPTH_SIZE, 24);
1716         SDL_GL_SetAttribute (SDL_GL_STENCIL_SIZE, 8);
1717         if (mode->stereobuffer)
1718                 SDL_GL_SetAttribute (SDL_GL_STEREO, 1);
1719         if (mode->samples > 1)
1720         {
1721                 SDL_GL_SetAttribute (SDL_GL_MULTISAMPLEBUFFERS, 1);
1722                 SDL_GL_SetAttribute (SDL_GL_MULTISAMPLESAMPLES, mode->samples);
1723         }
1724
1725 #ifdef USE_GLES2
1726         SDL_GL_SetAttribute (SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_ES);
1727         SDL_GL_SetAttribute (SDL_GL_CONTEXT_MAJOR_VERSION, 2);
1728         SDL_GL_SetAttribute (SDL_GL_CONTEXT_MINOR_VERSION, 0);
1729 #else
1730         SDL_GL_SetAttribute (SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
1731         SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
1732         SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 2);
1733         /* Requesting a Core profile and 3.2 minimum is mandatory on macOS and older Mesa drivers.
1734          * It works fine on other drivers too except NVIDIA, see HACK below.
1735          */
1736 #endif
1737
1738         SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, (gl_debug.integer > 0 ? SDL_GL_CONTEXT_DEBUG_FLAG : 0));
1739
1740         window = SDL_CreateWindow(gamename, vid.xPos, vid.yPos, mode->width, mode->height, windowflags);
1741         if (window == NULL)
1742         {
1743                 Con_Printf(CON_ERROR "Failed to set video mode to %ix%i: %s\n", mode->width, mode->height, SDL_GetError());
1744                 VID_Shutdown();
1745                 return false;
1746         }
1747         // get the real framebuffer size in case the platform's screen coordinates are DPI scaled
1748         SDL_GL_GetDrawableSize(window, &mode->width, &mode->height);
1749         // After using SDL_WINDOWPOS_CENTERED_DISPLAY we don't know the real position
1750         SDL_GetWindowPosition(window, &vid.xPos, &vid.yPos);
1751
1752         context = SDL_GL_CreateContext(window);
1753         if (context == NULL)
1754         {
1755                 Con_Printf(CON_ERROR "Failed to initialize OpenGL context: %s\n", SDL_GetError());
1756                 VID_Shutdown();
1757                 return false;
1758         }
1759
1760         GL_InitFunctions();
1761
1762 #if !defined(USE_GLES2) && !defined(MACOSX)
1763         // NVIDIA hates the Core profile and limits the version to the minimum we specified.
1764         // HACK: to detect NVIDIA we first need a context, fortunately replacing it takes a few milliseconds
1765         gl_vendor = (const char *)qglGetString(GL_VENDOR);
1766         if (strncmp(gl_vendor, "NVIDIA", 6) == 0)
1767         {
1768                 Con_DPrint("The Way It's Meant To Be Played: replacing OpenGL Core profile with Compatibility profile...\n");
1769                 SDL_GL_DeleteContext(context);
1770                 SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_COMPATIBILITY);
1771                 context = SDL_GL_CreateContext(window);
1772                 if (context == NULL)
1773                 {
1774                         Con_Printf(CON_ERROR "Failed to initialize OpenGL context: %s\n", SDL_GetError());
1775                         VID_Shutdown();
1776                         return false;
1777                 }
1778         }
1779 #endif
1780
1781         // apply vid_vsync
1782         Cvar_Callback(&vid_vsync);
1783
1784         vid_hidden = false;
1785         vid_activewindow = true;
1786         vid_hasfocus = true;
1787         vid_usingmouse = false;
1788         vid_usinghidecursor = false;
1789
1790         // clear to black (loading plaque will be seen over this)
1791         GL_Clear(GL_COLOR_BUFFER_BIT, NULL, 1.0f, 0);
1792         VID_Finish(); // checks vid_hidden
1793
1794         GL_Setup();
1795
1796         // VorteX: set other info
1797         Cvar_SetQuick(&gl_info_vendor, gl_vendor);
1798         Cvar_SetQuick(&gl_info_renderer, gl_renderer);
1799         Cvar_SetQuick(&gl_info_version, gl_version);
1800         Cvar_SetQuick(&gl_info_driver, drivername ? drivername : "");
1801
1802         for (i = 0; i < vid_info_displaycount.integer; ++i)
1803                 Con_Printf("Display %i: %s\n", i, SDL_GetDisplayName(i));
1804
1805         return true;
1806 }
1807
1808 qbool VID_InitMode(viddef_mode_t *mode)
1809 {
1810         // GAME_STEELSTORM specific
1811         steelstorm_showing_map = Cvar_FindVar(&cvars_all, "steelstorm_showing_map", ~0);
1812         steelstorm_showing_mousecursor = Cvar_FindVar(&cvars_all, "steelstorm_showing_mousecursor", ~0);
1813
1814         if (!SDL_WasInit(SDL_INIT_VIDEO) && SDL_InitSubSystem(SDL_INIT_VIDEO) < 0)
1815                 Sys_Error ("Failed to init SDL video subsystem: %s", SDL_GetError());
1816
1817         Cvar_SetValueQuick(&vid_touchscreen_supportshowkeyboard, SDL_HasScreenKeyboardSupport() ? 1 : 0);
1818         return VID_InitModeGL(mode);
1819 }
1820
1821 void VID_Shutdown (void)
1822 {
1823         VID_EnableJoystick(false);
1824         VID_SetMouse(false, false);
1825
1826         SDL_GL_DeleteContext(context);
1827         context = NULL;
1828         SDL_DestroyWindow(window);
1829         window = NULL;
1830
1831         SDL_QuitSubSystem(SDL_INIT_VIDEO);
1832 }
1833
1834 void VID_Finish (void)
1835 {
1836         vid_activewindow = !vid_hidden && vid_hasfocus;
1837
1838         VID_UpdateGamma();
1839
1840         if (!vid_hidden)
1841         {
1842                 switch(vid.renderpath)
1843                 {
1844                 case RENDERPATH_GL32:
1845                 case RENDERPATH_GLES2:
1846                         CHECKGLERROR
1847                         if (r_speeds.integer == 2 || gl_finish.integer)
1848                                 GL_Finish();
1849                         SDL_GL_SwapWindow(window);
1850                         break;
1851                 }
1852         }
1853 }
1854
1855 vid_mode_t VID_GetDesktopMode(void)
1856 {
1857         SDL_DisplayMode mode;
1858         int bpp;
1859         Uint32 rmask, gmask, bmask, amask;
1860         vid_mode_t desktop_mode;
1861
1862         SDL_GetDesktopDisplayMode(vid.displayindex, &mode);
1863         SDL_PixelFormatEnumToMasks(mode.format, &bpp, &rmask, &gmask, &bmask, &amask);
1864         desktop_mode.width = mode.w;
1865         desktop_mode.height = mode.h;
1866         desktop_mode.bpp = bpp;
1867         desktop_mode.refreshrate = mode.refresh_rate;
1868         desktop_mode.pixelheight_num = 1;
1869         desktop_mode.pixelheight_denom = 1; // SDL does not provide this
1870         return desktop_mode;
1871 }
1872
1873 size_t VID_ListModes(vid_mode_t *modes, size_t maxcount)
1874 {
1875         size_t k = 0;
1876         int modenum;
1877         int nummodes = SDL_GetNumDisplayModes(vid.displayindex);
1878         SDL_DisplayMode mode;
1879         for (modenum = 0;modenum < nummodes;modenum++)
1880         {
1881                 if (k >= maxcount)
1882                         break;
1883                 if (SDL_GetDisplayMode(vid.displayindex, modenum, &mode))
1884                         continue;
1885                 modes[k].width = mode.w;
1886                 modes[k].height = mode.h;
1887                 // FIXME bpp?
1888                 modes[k].refreshrate = mode.refresh_rate;
1889                 modes[k].pixelheight_num = 1;
1890                 modes[k].pixelheight_denom = 1; // SDL does not provide this
1891                 k++;
1892         }
1893         return k;
1894 }