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