]> icculus.org git repositories - divverent/darkplaces.git/blob - vid_sdl.c
SDL: parameters -resizable, -stick_mouse, -no_input_grabbing (Blub)
[divverent/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
25 // Tell startup code that we have a client
26 int cl_available = true;
27
28 qboolean vid_supportrefreshrate = false;
29
30 cvar_t joy_detected = {CVAR_READONLY, "joy_detected", "0", "number of joysticks detected by engine"};
31 cvar_t joy_enable = {0, "joy_enable", "1", "enables joystick support"};
32 cvar_t joy_index = {0, "joy_index", "0", "selects which joystick to use if you have multiple"};
33 cvar_t joy_axisforward = {0, "joy_axisforward", "1", "which joystick axis to query for forward/backward movement"};
34 cvar_t joy_axisside = {0, "joy_axisside", "0", "which joystick axis to query for right/left movement"};
35 cvar_t joy_axisup = {0, "joy_axisup", "-1", "which joystick axis to query for up/down movement"};
36 cvar_t joy_axispitch = {0, "joy_axispitch", "3", "which joystick axis to query for looking up/down"};
37 cvar_t joy_axisyaw = {0, "joy_axisyaw", "2", "which joystick axis to query for looking right/left"};
38 cvar_t joy_axisroll = {0, "joy_axisroll", "-1", "which joystick axis to query for tilting head right/left"};
39 cvar_t joy_deadzoneforward = {0, "joy_deadzoneforward", "0", "deadzone tolerance, suggested values are in the range 0 to 0.01"};
40 cvar_t joy_deadzoneside = {0, "joy_deadzoneside", "0", "deadzone tolerance, suggested values are in the range 0 to 0.01"};
41 cvar_t joy_deadzoneup = {0, "joy_deadzoneup", "0", "deadzone tolerance, suggested values are in the range 0 to 0.01"};
42 cvar_t joy_deadzonepitch = {0, "joy_deadzonepitch", "0", "deadzone tolerance, suggested values are in the range 0 to 0.01"};
43 cvar_t joy_deadzoneyaw = {0, "joy_deadzoneyaw", "0", "deadzone tolerance, suggested values are in the range 0 to 0.01"};
44 cvar_t joy_deadzoneroll = {0, "joy_deadzoneroll", "0", "deadzone tolerance, suggested values are in the range 0 to 0.01"};
45 cvar_t joy_sensitivityforward = {0, "joy_sensitivityforward", "-1", "movement multiplier"};
46 cvar_t joy_sensitivityside = {0, "joy_sensitivityside", "1", "movement multiplier"};
47 cvar_t joy_sensitivityup = {0, "joy_sensitivityup", "1", "movement multiplier"};
48 cvar_t joy_sensitivitypitch = {0, "joy_sensitivitypitch", "1", "movement multiplier"};
49 cvar_t joy_sensitivityyaw = {0, "joy_sensitivityyaw", "-1", "movement multiplier"};
50 cvar_t joy_sensitivityroll = {0, "joy_sensitivityroll", "1", "movement multiplier"};
51
52
53 static qboolean vid_usingmouse;
54 static qboolean vid_isfullscreen;
55 static int vid_numjoysticks = 0;
56 #define MAX_JOYSTICKS 8
57 static SDL_Joystick *vid_joysticks[MAX_JOYSTICKS];
58
59 static int win_half_width = 50;
60 static int win_half_height = 50;
61 static int stick_mouse = 0;
62 static int grab_input = 1;
63
64 static SDL_Surface *screen;
65
66 /////////////////////////
67 // Input handling
68 ////
69 //TODO: Add joystick support
70 //TODO: Add error checking
71
72
73 //keysym to quake keysym mapping
74 #define tenoh   0,0,0,0,0, 0,0,0,0,0
75 #define fiftyoh tenoh, tenoh, tenoh, tenoh, tenoh
76 #define hundredoh fiftyoh, fiftyoh
77 static unsigned int tbl_sdltoquake[] =
78 {
79         0,0,0,0,                //SDLK_UNKNOWN          = 0,
80         0,0,0,0,                //SDLK_FIRST            = 0,
81         K_BACKSPACE,    //SDLK_BACKSPACE        = 8,
82         K_TAB,                  //SDLK_TAB                      = 9,
83         0,0,
84         0,                              //SDLK_CLEAR            = 12,
85         K_ENTER,                //SDLK_RETURN           = 13,
86     0,0,0,0,0,
87         K_PAUSE,                //SDLK_PAUSE            = 19,
88         0,0,0,0,0,0,0,
89         K_ESCAPE,               //SDLK_ESCAPE           = 27,
90         0,0,0,0,
91         K_SPACE,                //SDLK_SPACE            = 32,
92         '!',                    //SDLK_EXCLAIM          = 33,
93         '"',                    //SDLK_QUOTEDBL         = 34,
94         '#',                    //SDLK_HASH                     = 35,
95         '$',                    //SDLK_DOLLAR           = 36,
96         0,
97         '&',                    //SDLK_AMPERSAND        = 38,
98         '\'',                   //SDLK_QUOTE            = 39,
99         '(',                    //SDLK_LEFTPAREN        = 40,
100         ')',                    //SDLK_RIGHTPAREN       = 41,
101         '*',                    //SDLK_ASTERISK         = 42,
102         '+',                    //SDLK_PLUS                     = 43,
103         ',',                    //SDLK_COMMA            = 44,
104         '-',                    //SDLK_MINUS            = 45,
105         '.',                    //SDLK_PERIOD           = 46,
106         '/',                    //SDLK_SLASH            = 47,
107         '0',                    //SDLK_0                        = 48,
108         '1',                    //SDLK_1                        = 49,
109         '2',                    //SDLK_2                        = 50,
110         '3',                    //SDLK_3                        = 51,
111         '4',                    //SDLK_4                        = 52,
112         '5',                    //SDLK_5                        = 53,
113         '6',                    //SDLK_6                        = 54,
114         '7',                    //SDLK_7                        = 55,
115         '8',                    //SDLK_8                        = 56,
116         '9',                    //SDLK_9                        = 57,
117         ':',                    //SDLK_COLON            = 58,
118         ';',                    //SDLK_SEMICOLON        = 59,
119         '<',                    //SDLK_LESS                     = 60,
120         '=',                    //SDLK_EQUALS           = 61,
121         '>',                    //SDLK_GREATER          = 62,
122         '?',                    //SDLK_QUESTION         = 63,
123         '@',                    //SDLK_AT                       = 64,
124         0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
125         '[',            //SDLK_LEFTBRACKET      = 91,
126         '\\',           //SDLK_BACKSLASH        = 92,
127         ']',            //SDLK_RIGHTBRACKET     = 93,
128         '^',            //SDLK_CARET            = 94,
129         '_',            //SDLK_UNDERSCORE       = 95,
130         '`',            //SDLK_BACKQUOTE        = 96,
131         'a',            //SDLK_a                        = 97,
132         'b',            //SDLK_b                        = 98,
133         'c',            //SDLK_c                        = 99,
134         'd',            //SDLK_d                        = 100,
135         'e',            //SDLK_e                        = 101,
136         'f',            //SDLK_f                        = 102,
137         'g',            //SDLK_g                        = 103,
138         'h',            //SDLK_h                        = 104,
139         'i',            //SDLK_i                        = 105,
140         'j',            //SDLK_j                        = 106,
141         'k',            //SDLK_k                        = 107,
142         'l',            //SDLK_l                        = 108,
143         'm',            //SDLK_m                        = 109,
144         'n',            //SDLK_n                        = 110,
145         'o',            //SDLK_o                        = 111,
146         'p',            //SDLK_p                        = 112,
147         'q',            //SDLK_q                        = 113,
148         'r',            //SDLK_r                        = 114,
149         's',            //SDLK_s                        = 115,
150         't',            //SDLK_t                        = 116,
151         'u',            //SDLK_u                        = 117,
152         'v',            //SDLK_v                        = 118,
153         'w',            //SDLK_w                        = 119,
154         'x',            //SDLK_x                        = 120,
155         'y',            //SDLK_y                        = 121,
156         'z',            //SDLK_z                        = 122,
157         0,0,0,0,
158         K_DEL,          //SDLK_DELETE           = 127,
159         hundredoh /*227*/, tenoh, tenoh, 0,0,0,0,0,0,0,0,
160         K_KP_0,         //SDLK_KP0              = 256,
161         K_KP_1,         //SDLK_KP1              = 257,
162         K_KP_2,         //SDLK_KP2              = 258,
163         K_KP_3,         //SDLK_KP3              = 259,
164         K_KP_4,         //SDLK_KP4              = 260,
165         K_KP_5,         //SDLK_KP5              = 261,
166         K_KP_6,         //SDLK_KP6              = 262,
167         K_KP_7,         //SDLK_KP7              = 263,
168         K_KP_8,         //SDLK_KP8              = 264,
169         K_KP_9,         //SDLK_KP9              = 265,
170         K_KP_PERIOD,//SDLK_KP_PERIOD    = 266,
171         K_KP_DIVIDE,//SDLK_KP_DIVIDE    = 267,
172         K_KP_MULTIPLY,//SDLK_KP_MULTIPLY= 268,
173         K_KP_MINUS,     //SDLK_KP_MINUS         = 269,
174         K_KP_PLUS,      //SDLK_KP_PLUS          = 270,
175         K_KP_ENTER,     //SDLK_KP_ENTER         = 271,
176         K_KP_EQUALS,//SDLK_KP_EQUALS    = 272,
177         K_UPARROW,      //SDLK_UP               = 273,
178         K_DOWNARROW,//SDLK_DOWN         = 274,
179         K_RIGHTARROW,//SDLK_RIGHT       = 275,
180         K_LEFTARROW,//SDLK_LEFT         = 276,
181         K_INS,          //SDLK_INSERT   = 277,
182         K_HOME,         //SDLK_HOME             = 278,
183         K_END,          //SDLK_END              = 279,
184         K_PGUP,         //SDLK_PAGEUP   = 280,
185         K_PGDN,         //SDLK_PAGEDOWN = 281,
186         K_F1,           //SDLK_F1               = 282,
187         K_F2,           //SDLK_F2               = 283,
188         K_F3,           //SDLK_F3               = 284,
189         K_F4,           //SDLK_F4               = 285,
190         K_F5,           //SDLK_F5               = 286,
191         K_F6,           //SDLK_F6               = 287,
192         K_F7,           //SDLK_F7               = 288,
193         K_F8,           //SDLK_F8               = 289,
194         K_F9,           //SDLK_F9               = 290,
195         K_F10,          //SDLK_F10              = 291,
196         K_F11,          //SDLK_F11              = 292,
197         K_F12,          //SDLK_F12              = 293,
198         0,                      //SDLK_F13              = 294,
199         0,                      //SDLK_F14              = 295,
200         0,                      //SDLK_F15              = 296,
201         0,0,0,
202         K_NUMLOCK,      //SDLK_NUMLOCK  = 300,
203         K_CAPSLOCK,     //SDLK_CAPSLOCK = 301,
204         K_SCROLLOCK,//SDLK_SCROLLOCK= 302,
205         K_SHIFT,        //SDLK_RSHIFT   = 303,
206         K_SHIFT,        //SDLK_LSHIFT   = 304,
207         K_CTRL,         //SDLK_RCTRL    = 305,
208         K_CTRL,         //SDLK_LCTRL    = 306,
209         K_ALT,          //SDLK_RALT             = 307,
210         K_ALT,          //SDLK_LALT             = 308,
211         0,                      //SDLK_RMETA    = 309,
212         0,                      //SDLK_LMETA    = 310,
213         0,                      //SDLK_LSUPER   = 311,          /* Left "Windows" key */
214         0,                      //SDLK_RSUPER   = 312,          /* Right "Windows" key */
215         K_ALT,                  //SDLK_MODE             = 313,          /* "Alt Gr" key */
216         0,                      //SDLK_COMPOSE  = 314,          /* Multi-key compose key */
217         0,                      //SDLK_HELP             = 315,
218         0,                      //SDLK_PRINT    = 316,
219         0,                      //SDLK_SYSREQ   = 317,
220         K_PAUSE,        //SDLK_BREAK    = 318,
221         0,                      //SDLK_MENU             = 319,
222         0,                      //SDLK_POWER    = 320,          /* Power Macintosh power key */
223         'e',            //SDLK_EURO             = 321,          /* Some european keyboards */
224         0                       //SDLK_UNDO             = 322,          /* Atari keyboard has Undo */
225 };
226 #undef tenoh
227 #undef fiftyoh
228 #undef hundredoh
229
230 static int MapKey( unsigned int sdlkey )
231 {
232         if( sdlkey > sizeof(tbl_sdltoquake)/ sizeof(int) )
233                 return 0;
234     return tbl_sdltoquake[ sdlkey ];
235 }
236
237 static void IN_Activate( qboolean grab )
238 {
239         //SDL_WM_GrabInput( SDL_GRAB_OFF );
240         //Con_Printf("< Turning off input-grabbing. --blub\n");
241         if (grab)
242         {
243                 if (!vid_usingmouse)
244                 {
245                         vid_usingmouse = true;
246                         cl_ignoremousemove = true;
247                         if(grab_input) {
248                                 SDL_WM_GrabInput( SDL_GRAB_ON );
249                         }
250                         SDL_ShowCursor( SDL_DISABLE );
251                 }               
252         }
253         else
254         {
255                 if (vid_usingmouse)
256                 {
257                         vid_usingmouse = false;
258                         cl_ignoremousemove = true;
259                         if(grab_input) {
260                                 SDL_WM_GrabInput( SDL_GRAB_OFF );
261                         }
262                         SDL_ShowCursor( SDL_ENABLE );
263                 }
264         }
265 }
266
267 static double IN_JoystickGetAxis(SDL_Joystick *joy, int axis, double sensitivity, double deadzone)
268 {
269         double value;
270         if (axis < 0 || axis >= SDL_JoystickNumAxes(joy))
271                 return 0; // no such axis on this joystick
272         value = SDL_JoystickGetAxis(joy, axis) * (1.0 / 32767.0);
273         value = bound(-1, value, 1);
274         if (fabs(value) < deadzone)
275                 return 0; // within deadzone around center
276         return value * sensitivity;
277 }
278
279 void IN_Move( void )
280 {
281         int j;
282         static int old_x = 0, old_y = 0;
283         static int stuck = 0;
284         int x, y;
285         if( vid_usingmouse )
286         {
287                 if(stick_mouse)
288                 {
289                         // have the mouse stuck in the middle, example use: prevent expose effect of beryl during the game when not using
290                         // window grabbing. --blub
291                         
292                         // we need 2 frames to initialize the center position
293                         if(!stuck)
294                         {
295                                 SDL_WarpMouse(win_half_width, win_half_height);
296                                 SDL_GetMouseState(&x, &y);
297                                 SDL_GetRelativeMouseState(&x, &y);
298                                 ++stuck;
299                         } else {
300                                 SDL_GetRelativeMouseState(&x, &y);
301                                 in_mouse_x = x + old_x;
302                                 in_mouse_y = y + old_y;
303                                 SDL_GetMouseState(&x, &y);
304                                 old_x = x - win_half_width;
305                                 old_y = y - win_half_height;
306                                 SDL_WarpMouse(win_half_width, win_half_height);
307                         }
308                 } else {
309                         SDL_GetRelativeMouseState( &x, &y );
310                         in_mouse_x = x;
311                         in_mouse_y = y;
312                 }
313         }
314         if (vid_numjoysticks && joy_enable.integer && joy_index.integer >= 0 && joy_index.integer < vid_numjoysticks)
315         {
316                 SDL_Joystick *joy = vid_joysticks[joy_index.integer];
317                 int numballs = SDL_JoystickNumBalls(joy);
318                 for (j = 0;j < numballs;j++)
319                 {
320                         SDL_JoystickGetBall(joy, j, &x, &y);
321                         in_mouse_x += x;
322                         in_mouse_y += y;
323                 }
324                 cl.cmd.forwardmove += IN_JoystickGetAxis(joy, joy_axisforward.integer, joy_sensitivityforward.value, joy_deadzoneforward.value) * cl_forwardspeed.value;
325                 cl.cmd.sidemove    += IN_JoystickGetAxis(joy, joy_axisside.integer, joy_sensitivityside.value, joy_deadzoneside.value) * cl_sidespeed.value;
326                 cl.cmd.upmove      += IN_JoystickGetAxis(joy, joy_axisup.integer, joy_sensitivityup.value, joy_deadzoneup.value) * cl_upspeed.value;
327                 cl.viewangles[0]   += IN_JoystickGetAxis(joy, joy_axispitch.integer, joy_sensitivitypitch.value, joy_deadzonepitch.value) * cl.realframetime * cl_pitchspeed.value;
328                 cl.viewangles[1]   += IN_JoystickGetAxis(joy, joy_axisyaw.integer, joy_sensitivityyaw.value, joy_deadzoneyaw.value) * cl.realframetime * cl_yawspeed.value;
329                 //cl.viewangles[2]   += IN_JoystickGetAxis(joy, joy_axisroll.integer, joy_sensitivityroll.value, joy_deadzoneroll.value) * cl.realframetime * cl_rollspeed.value;
330         }
331 }
332
333 /////////////////////
334 // Message Handling
335 ////
336
337 static int Sys_EventFilter( SDL_Event *event )
338 {
339         //TODO: Add a quit query in linux, too - though linux user are more likely to know what they do
340 #ifdef WIN32
341         if( event->type == SDL_QUIT && MessageBox( NULL, "Are you sure you want to quit?", "Confirm Exit", MB_YESNO | MB_SETFOREGROUND | MB_ICONQUESTION ) == IDNO )
342                 return 0;
343         else
344                 return 1;
345 #else
346         return 1;
347 #endif
348 }
349
350 static keynum_t buttonremap[18] =
351 {
352         K_MOUSE1,
353         K_MOUSE3,
354         K_MOUSE2,
355         K_MWHEELUP,
356         K_MWHEELDOWN,
357         K_MOUSE4,
358         K_MOUSE5,
359         K_MOUSE6,
360         K_MOUSE7,
361         K_MOUSE8,
362         K_MOUSE9,
363         K_MOUSE10,
364         K_MOUSE11,
365         K_MOUSE12,
366         K_MOUSE13,
367         K_MOUSE14,
368         K_MOUSE15,
369         K_MOUSE16,
370 };
371
372 void Sys_SendKeyEvents( void )
373 {
374         static qboolean sound_active = true;
375         SDL_Event event;
376
377         while( SDL_PollEvent( &event ) )
378                 switch( event.type ) {
379                         case SDL_QUIT:
380                                 Sys_Quit(0);
381                                 break;
382                         case SDL_KEYDOWN:
383                         case SDL_KEYUP:
384                                 Key_Event( MapKey( event.key.keysym.sym ), (char)event.key.keysym.unicode, (event.key.state == SDL_PRESSED) );
385                                 break;
386                         case SDL_ACTIVEEVENT:
387                                 if( event.active.state == SDL_APPACTIVE )
388                                 {
389                                         if( event.active.gain )
390                                                 vid_hidden = false;
391                                         else
392                                                 vid_hidden = true;
393                                 }
394                                 break;
395                         case SDL_MOUSEBUTTONDOWN:
396                         case SDL_MOUSEBUTTONUP:
397                                 if (event.button.button <= 18)
398                                         Key_Event( buttonremap[event.button.button - 1], 0, event.button.state == SDL_PRESSED );
399                                 break;
400                         case SDL_JOYBUTTONDOWN:
401                                 if (!joy_enable.integer)
402                                         break; // ignore down events if joystick has been disabled
403                         case SDL_JOYBUTTONUP:
404                                 if (event.jbutton.button < 48)
405                                         Key_Event( event.jbutton.button + (event.jbutton.button < 16 ? K_JOY1 : K_AUX1 - 16), 0, (event.jbutton.state == SDL_PRESSED) );
406                                 break;
407                 }
408
409         // enable/disable sound on focus gain/loss
410         if (!vid_hidden && (vid_activewindow || !snd_mutewhenidle.integer))
411         {
412                 if (!sound_active)
413                 {
414                         S_UnblockSound ();
415                         sound_active = true;
416                 }
417         }
418         else
419         {
420                 if (sound_active)
421                 {
422                         S_BlockSound ();
423                         sound_active = false;
424                 }
425         }
426 }
427
428 /////////////////
429 // Video system
430 ////
431
432 void *GL_GetProcAddress(const char *name)
433 {
434         void *p = NULL;
435         p = SDL_GL_GetProcAddress(name);
436         return p;
437 }
438
439 static int Sys_EventFilter( SDL_Event *event );
440 static qboolean vid_sdl_initjoysticksystem = false;
441 void VID_Init (void)
442 {
443         Cvar_RegisterVariable(&joy_detected);
444         Cvar_RegisterVariable(&joy_enable);
445         Cvar_RegisterVariable(&joy_index);
446         Cvar_RegisterVariable(&joy_axisforward);
447         Cvar_RegisterVariable(&joy_axisside);
448         Cvar_RegisterVariable(&joy_axisup);
449         Cvar_RegisterVariable(&joy_axispitch);
450         Cvar_RegisterVariable(&joy_axisyaw);
451         //Cvar_RegisterVariable(&joy_axisroll);
452         Cvar_RegisterVariable(&joy_deadzoneforward);
453         Cvar_RegisterVariable(&joy_deadzoneside);
454         Cvar_RegisterVariable(&joy_deadzoneup);
455         Cvar_RegisterVariable(&joy_deadzonepitch);
456         Cvar_RegisterVariable(&joy_deadzoneyaw);
457         //Cvar_RegisterVariable(&joy_deadzoneroll);
458         Cvar_RegisterVariable(&joy_sensitivityforward);
459         Cvar_RegisterVariable(&joy_sensitivityside);
460         Cvar_RegisterVariable(&joy_sensitivityup);
461         Cvar_RegisterVariable(&joy_sensitivitypitch);
462         Cvar_RegisterVariable(&joy_sensitivityyaw);
463         //Cvar_RegisterVariable(&joy_sensitivityroll);
464
465         if (SDL_Init(SDL_INIT_VIDEO) < 0)
466                 Sys_Error ("Failed to init SDL video subsystem: %s", SDL_GetError());
467         vid_sdl_initjoysticksystem = SDL_Init(SDL_INIT_JOYSTICK) >= 0;
468         if (vid_sdl_initjoysticksystem)
469                 Con_Printf("Failed to init SDL joystick subsystem: %s\n", SDL_GetError());
470         vid_isfullscreen = false;
471 }
472
473 // set the icon (we dont use SDL here since it would be too much a PITA)
474 #ifdef WIN32
475 #include "resource.h"
476 #include <SDL_syswm.h>
477 static void VID_SetCaption()
478 {
479     SDL_SysWMinfo       info;
480         HICON                   icon;
481
482         // set the caption
483         SDL_WM_SetCaption( gamename, NULL );
484
485         // get the HWND handle
486     SDL_VERSION( &info.version );
487         if( !SDL_GetWMInfo( &info ) )
488                 return;
489
490         icon = LoadIcon( GetModuleHandle( NULL ), MAKEINTRESOURCE( IDI_ICON1 ) );
491 #ifndef _W64 //If Windows 64bit data types don't exist
492 #define SetClassLongPtr SetClassLong
493 #define GCLP_HICON GCL_HICON
494 #define LONG_PTR LONG
495 #endif
496         SetClassLongPtr( info.window, GCLP_HICON, (LONG_PTR)icon );
497 }
498 #else
499 static void VID_SetCaption()
500 {
501         SDL_WM_SetCaption( gamename, NULL );
502 }
503 #endif
504
505 static void VID_OutputVersion()
506 {
507         const SDL_version *version;
508         version = SDL_Linked_Version();
509         Con_Printf(     "Linked against SDL version %d.%d.%d\n"
510                                         "Using SDL library version %d.%d.%d\n",
511                                         SDL_MAJOR_VERSION, SDL_MINOR_VERSION, SDL_PATCHLEVEL,
512                                         version->major, version->minor, version->patch );
513 }
514
515 int VID_InitMode(int fullscreen, int width, int height, int bpp, int refreshrate, int stereobuffer)
516 {
517         int i;
518         static int notfirstvideomode = false;
519         int flags = SDL_OPENGL;
520         const char *drivername;
521
522         win_half_width = width>>1;
523         win_half_height = height>>1;
524
525         VID_OutputVersion();
526
527         /*
528         SDL Hack
529                 We cant switch from one OpenGL video mode to another.
530                 Thus we first switch to some stupid 2D mode and then back to OpenGL.
531         */
532         if (notfirstvideomode)
533                 SDL_SetVideoMode( 0, 0, 0, 0 );
534         notfirstvideomode = true;
535
536         // SDL usually knows best
537         drivername = NULL;
538
539 // 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
540         i = COM_CheckParm("-gl_driver");
541         if (i && i < com_argc - 1)
542                 drivername = com_argv[i + 1];
543         if (SDL_GL_LoadLibrary(drivername) < 0)
544         {
545                 Con_Printf("Unable to load GL driver \"%s\": %s\n", drivername, SDL_GetError());
546                 return false;
547         }
548
549         
550         if(COM_CheckParm("-resizable")) {
551                 flags |= SDL_RESIZABLE;
552         }
553            
554         stick_mouse = COM_CheckParm("-stick_mouse");
555         if(COM_CheckParm("-no_input_grabbing")) {
556                 grab_input = 0;
557         } else {
558                 grab_input = 1;
559         }
560         
561         if ((qglGetString = (const GLubyte* (GLAPIENTRY *)(GLenum name))GL_GetProcAddress("glGetString")) == NULL)
562         {
563                 VID_Shutdown();
564                 Con_Print("Required OpenGL function glGetString not found\n");
565                 return false;
566         }
567
568         // Knghtbrd: should do platform-specific extension string function here
569
570         vid_isfullscreen = false;
571         if (fullscreen) {
572                 flags |= SDL_FULLSCREEN;
573                 vid_isfullscreen = true;
574         }
575         //flags |= SDL_HWSURFACE;
576
577         SDL_GL_SetAttribute (SDL_GL_DOUBLEBUFFER, 1);
578         if (bpp >= 32)
579         {
580                 SDL_GL_SetAttribute (SDL_GL_RED_SIZE, 8);
581                 SDL_GL_SetAttribute (SDL_GL_GREEN_SIZE, 8);
582                 SDL_GL_SetAttribute (SDL_GL_BLUE_SIZE, 8);
583                 SDL_GL_SetAttribute (SDL_GL_ALPHA_SIZE, 8);
584                 SDL_GL_SetAttribute (SDL_GL_DEPTH_SIZE, 24);
585                 SDL_GL_SetAttribute (SDL_GL_STENCIL_SIZE, 8);
586         }
587         else
588         {
589                 SDL_GL_SetAttribute (SDL_GL_RED_SIZE, 1);
590                 SDL_GL_SetAttribute (SDL_GL_GREEN_SIZE, 1);
591                 SDL_GL_SetAttribute (SDL_GL_BLUE_SIZE, 1);
592                 SDL_GL_SetAttribute (SDL_GL_DEPTH_SIZE, 16);
593         }
594         if (stereobuffer)
595                 SDL_GL_SetAttribute (SDL_GL_STEREO, 1);
596
597         screen = SDL_SetVideoMode(width, height, bpp, flags);
598         
599         if (screen == NULL)
600         {
601                 Con_Printf("Failed to set video mode to %ix%i: %s\n", width, height, SDL_GetError());
602                 VID_Shutdown();
603                 return false;
604         }
605
606         // set window title
607         VID_SetCaption();
608         // set up an event filter to ask confirmation on close button in WIN32
609         SDL_SetEventFilter( (SDL_EventFilter) Sys_EventFilter );
610         // init keyboard
611         SDL_EnableUNICODE( SDL_ENABLE );
612         // enable key repeat since everyone expects it
613         SDL_EnableKeyRepeat(SDL_DEFAULT_REPEAT_DELAY, SDL_DEFAULT_REPEAT_INTERVAL);
614
615         gl_renderer = (const char *)qglGetString(GL_RENDERER);
616         gl_vendor = (const char *)qglGetString(GL_VENDOR);
617         gl_version = (const char *)qglGetString(GL_VERSION);
618         gl_extensions = (const char *)qglGetString(GL_EXTENSIONS);
619         gl_platform = "SDL";
620         // Knghtbrd: should assign platform-specific extensions here
621         //TODO: maybe ;)
622         gl_platformextensions = "";
623         gl_videosyncavailable = false;
624
625         GL_Init();
626
627         vid_numjoysticks = SDL_NumJoysticks();
628         vid_numjoysticks = bound(0, vid_numjoysticks, MAX_JOYSTICKS);
629         Cvar_SetValueQuick(&joy_detected, vid_numjoysticks);
630         Con_Printf("%d SDL joystick(s) found:\n", vid_numjoysticks);
631         memset(vid_joysticks, 0, sizeof(vid_joysticks));
632         for (i = 0;i < vid_numjoysticks;i++)
633         {
634                 SDL_Joystick *joy;
635                 joy = vid_joysticks[i] = SDL_JoystickOpen(i);
636                 if (!joy)
637                 {
638                         Con_Printf("joystick #%i: open failed: %s\n", i, SDL_GetError());
639                         continue;
640                 }
641                 Con_Printf("joystick #%i: opened \"%s\" with %i axes, %i buttons, %i balls\n", i, SDL_JoystickName(i), (int)SDL_JoystickNumAxes(joy), (int)SDL_JoystickNumButtons(joy), (int)SDL_JoystickNumBalls(joy));
642         }
643
644         vid_hidden = false;
645         vid_activewindow = false;
646         vid_usingmouse = false;
647
648         if(!grab_input)
649                 SDL_WM_GrabInput(SDL_GRAB_OFF);
650         return true;
651 }
652
653 void VID_Shutdown (void)
654 {
655         // this is needed to retry gamma after a vid_restart
656         VID_RestoreSystemGamma();
657
658         IN_Activate(false);
659         SDL_QuitSubSystem(SDL_INIT_VIDEO);
660 }
661
662 int VID_SetGamma (unsigned short *ramps, int rampsize)
663 {
664         return !SDL_SetGammaRamp (ramps, ramps + rampsize, ramps + rampsize*2);
665 }
666
667 int VID_GetGamma (unsigned short *ramps, int rampsize)
668 {
669         return !SDL_GetGammaRamp (ramps, ramps + rampsize, ramps + rampsize*2);
670 }
671
672 void VID_Finish (qboolean allowmousegrab)
673 {
674         Uint8 appstate;
675         qboolean vid_usemouse;
676
677         //react on appstate changes
678         appstate = SDL_GetAppState();
679
680         vid_hidden = !(appstate & SDL_APPACTIVE);
681
682         if( vid_hidden || !( appstate & SDL_APPMOUSEFOCUS ) || !( appstate & SDL_APPINPUTFOCUS ) )
683                 vid_activewindow = false;
684         else
685                 vid_activewindow = true;
686
687         vid_usemouse = false;
688         if( allowmousegrab && vid_mouse.integer && !key_consoleactive && (key_dest != key_game || !cls.demoplayback) )
689                 vid_usemouse = true;
690         if( vid_isfullscreen )
691                 vid_usemouse = true;
692         if( !vid_activewindow )
693                 vid_usemouse = false;
694
695         IN_Activate(vid_usemouse);
696
697         VID_UpdateGamma(false, 256);
698
699         if (r_render.integer && !vid_hidden)
700         {
701                 CHECKGLERROR
702                 if (r_speeds.integer || gl_finish.integer)
703                 {
704                         qglFinish();CHECKGLERROR
705                 }
706                 SDL_GL_SwapBuffers();
707         }
708 }