# sdl_v.cpp

Go to the documentation of this file.

    00001 /* $Id: sdl_v.cpp 25528 2013-06-30 08:58:35Z rubidium $ */
    00002
    00003 /*
    00004  * This file is part of OpenTTD.
    00005  * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
    00006  * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
    00007  * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
    00008  */
    00009
    00012 #ifdef WITH_SDL
    00013
    00014 #include "../stdafx.h"
    00015 #include "../openttd.h"
    00016 #include "../gfx_func.h"
    00017 #include "../sdl.h"
    00018 #include "../rev.h"
    00019 #include "../blitter/factory.hpp"
    00020 #include "../network/network.h"
    00021 #include "../thread/thread.h"
    00022 #include "../progress.h"
    00023 #include "../core/random_func.hpp"
    00024 #include "../core/math_func.hpp"
    00025 #include "../fileio_func.h"
    00026 #include "sdl_v.h"
    00027 #include <SDL.h>
    00028
    00029 static FVideoDriver_SDL iFVideoDriver_SDL;
    00030
    00031 static SDL_Surface *_sdl_screen;
    00032 static SDL_Surface *_sdl_realscreen;
    00033 static bool _all_modes;
    00034
    00036 static bool _draw_threaded;
    00038 static ThreadObject *_draw_thread = NULL;
    00040 static ThreadMutex *_draw_mutex = NULL;
    00042 static volatile bool _draw_continue;
    00043 static Palette _local_palette;
    00044
    00045 #define MAX_DIRTY_RECTS 100
    00046 static SDL_Rect _dirty_rects[MAX_DIRTY_RECTS];
    00047 static int _num_dirty_rects;
    00048 static int _use_hwpalette;
    00049 static int _requested_hwpalette; /* Did we request a HWPALETTE for the current video mode? */
    00050
    00051 void VideoDriver_SDL::MakeDirty(int left, int top, int width, int height)
    00052 {
    00053   if (_num_dirty_rects < MAX_DIRTY_RECTS) {
    00054     _dirty_rects[_num_dirty_rects].x = left;
    00055     _dirty_rects[_num_dirty_rects].y = top;
    00056     _dirty_rects[_num_dirty_rects].w = width;
    00057     _dirty_rects[_num_dirty_rects].h = height;
    00058   }
    00059   _num_dirty_rects++;
    00060 }
    00061
    00062 static void UpdatePalette(bool init = false)
    00063 {
    00064   SDL_Color pal[256];
    00065
    00066   for (int i = 0; i != _local_palette.count_dirty; i++) {
    00067     pal[i].r = _local_palette.palette[_local_palette.first_dirty + i].r;
    00068     pal[i].g = _local_palette.palette[_local_palette.first_dirty + i].g;
    00069     pal[i].b = _local_palette.palette[_local_palette.first_dirty + i].b;
    00070     pal[i].unused = 0;
    00071   }
    00072
    00073   SDL_CALL SDL_SetColors(_sdl_screen, pal, _local_palette.first_dirty, _local_palette.count_dirty);
    00074
    00075   if (_sdl_screen != _sdl_realscreen && init) {
    00076     /* When using a shadow surface, also set our palette on the real screen. This lets SDL
    00077      * allocate as much colors (or approximations) as
    00078      * possible, instead of using only the default SDL
    00079      * palette. This allows us to get more colors exactly
    00080      * right and might allow using better approximations for
    00081      * other colors.
    00082      *
    00083      * Note that colors allocations are tried in-order, so
    00084      * this favors colors further up into the palette. Also
    00085      * note that if two colors from the same animation
    00086      * sequence are approximated using the same color, that
    00087      * animation will stop working.
    00088      *
    00089      * Since changing the system palette causes the colours
    00090      * to change right away, and allocations might
    00091      * drastically change, we can't use this for animation,
    00092      * since that could cause weird coloring between the
    00093      * palette change and the blitting below, so we only set
    00094      * the real palette during initialisation.
    00095      */
    00096     SDL_CALL SDL_SetColors(_sdl_realscreen, pal, _local_palette.first_dirty, _local_palette.count_dirty);
    00097   }
    00098
    00099   if (_sdl_screen != _sdl_realscreen && !init) {
    00100     /* We're not using real hardware palette, but are letting SDL
    00101      * approximate the palette during shadow -> screen copy. To
    00102      * change the palette, we need to recopy the entire screen.
    00103      *
    00104      * Note that this operation can slow down the rendering
    00105      * considerably, especially since changing the shadow
    00106      * palette will need the next blit to re-detect the
    00107      * best mapping of shadow palette colors to real palette
    00108      * colors from scratch.
    00109      */
    00110     SDL_CALL SDL_BlitSurface(_sdl_screen, NULL, _sdl_realscreen, NULL);
    00111     SDL_CALL SDL_UpdateRect(_sdl_realscreen, 0, 0, 0, 0);
    00112   }
    00113 }
    00114
    00115 static void InitPalette()
    00116 {
    00117   _local_palette = _cur_palette;
    00118   _local_palette.first_dirty = 0;
    00119   _local_palette.count_dirty = 256;
    00120   UpdatePalette(true);
    00121 }
    00122
    00123 static void CheckPaletteAnim()
    00124 {
    00125   if (_cur_palette.count_dirty != 0) {
    00126     Blitter *blitter = BlitterFactoryBase::GetCurrentBlitter();
    00127
    00128     switch (blitter->UsePaletteAnimation()) {
    00129       case Blitter::PALETTE_ANIMATION_VIDEO_BACKEND:
    00130         UpdatePalette();
    00131         break;
    00132
    00133       case Blitter::PALETTE_ANIMATION_BLITTER:
    00134         blitter->PaletteAnimate(_local_palette);
    00135         break;
    00136
    00137       case Blitter::PALETTE_ANIMATION_NONE:
    00138         break;
    00139
    00140       default:
    00141         NOT_REACHED();
    00142     }
    00143     _cur_palette.count_dirty = 0;
    00144   }
    00145 }
    00146
    00147 static void DrawSurfaceToScreen()
    00148 {
    00149   int n = _num_dirty_rects;
    00150   if (n == 0) return;
    00151
    00152   _num_dirty_rects = 0;
    00153   if (n > MAX_DIRTY_RECTS) {
    00154     if (_sdl_screen != _sdl_realscreen) {
    00155       SDL_CALL SDL_BlitSurface(_sdl_screen, NULL, _sdl_realscreen, NULL);
    00156     }
    00157     SDL_CALL SDL_UpdateRect(_sdl_realscreen, 0, 0, 0, 0);
    00158   } else {
    00159     if (_sdl_screen != _sdl_realscreen) {
    00160       for (int i = 0; i < n; i++) {
    00161         SDL_CALL SDL_BlitSurface(_sdl_screen, &_dirty_rects[i], _sdl_realscreen, &_dirty_rects[i]);
    00162       }
    00163     }
    00164     SDL_CALL SDL_UpdateRects(_sdl_realscreen, n, _dirty_rects);
    00165   }
    00166 }
    00167
    00168 static void DrawSurfaceToScreenThread(void *)
    00169 {
    00170   /* First tell the main thread we're started */
    00171   _draw_mutex->BeginCritical();
    00172   _draw_mutex->SendSignal();
    00173
    00174   /* Now wait for the first thing to draw! */
    00175   _draw_mutex->WaitForSignal();
    00176
    00177   while (_draw_continue) {
    00178     CheckPaletteAnim();
    00179     /* Then just draw and wait till we stop */
    00180     DrawSurfaceToScreen();
    00181     _draw_mutex->WaitForSignal();
    00182   }
    00183
    00184   _draw_mutex->EndCritical();
    00185   _draw_thread->Exit();
    00186 }
    00187
    00188 static const Dimension _default_resolutions[] = {
    00189   { 640,  480},
    00190   { 800,  600},
    00191   {1024,  768},
    00192   {1152,  864},
    00193   {1280,  800},
    00194   {1280,  960},
    00195   {1280, 1024},
    00196   {1400, 1050},
    00197   {1600, 1200},
    00198   {1680, 1050},
    00199   {1920, 1200}
    00200 };
    00201
    00202 static void GetVideoModes()
    00203 {
    00204   SDL_Rect **modes = SDL_CALL SDL_ListModes(NULL, SDL_SWSURFACE | SDL_FULLSCREEN);
    00205   if (modes == NULL) usererror("sdl: no modes available");
    00206
    00207   _all_modes = (SDL_CALL SDL_ListModes(NULL, SDL_SWSURFACE | (_fullscreen ? SDL_FULLSCREEN : 0)) == (void*)-1);
    00208   if (modes == (void*)-1) {
    00209     int n = 0;
    00210     for (uint i = 0; i < lengthof(_default_resolutions); i++) {
    00211       if (SDL_CALL SDL_VideoModeOK(_default_resolutions[i].width, _default_resolutions[i].height, 8, SDL_FULLSCREEN) != 0) {
    00212         _resolutions[n] = _default_resolutions[i];
    00213         if (++n == lengthof(_resolutions)) break;
    00214       }
    00215     }
    00216     _num_resolutions = n;
    00217   } else {
    00218     int n = 0;
    00219     for (int i = 0; modes[i]; i++) {
    00220       uint w = modes[i]->w;
    00221       uint h = modes[i]->h;
    00222       int j;
    00223       for (j = 0; j < n; j++) {
    00224         if (_resolutions[j].width == w && _resolutions[j].height == h) break;
    00225       }
    00226
    00227       if (j == n) {
    00228         _resolutions[j].width  = w;
    00229         _resolutions[j].height = h;
    00230         if (++n == lengthof(_resolutions)) break;
    00231       }
    00232     }
    00233     _num_resolutions = n;
    00234     SortResolutions(_num_resolutions);
    00235   }
    00236 }
    00237
    00238 static void GetAvailableVideoMode(uint *w, uint *h)
    00239 {
    00240   /* All modes available? */
    00241   if (_all_modes || _num_resolutions == 0) return;
    00242
    00243   /* Is the wanted mode among the available modes? */
    00244   for (int i = 0; i != _num_resolutions; i++) {
    00245     if (*w == _resolutions[i].width && *h == _resolutions[i].height) return;
    00246   }
    00247
    00248   /* Use the closest possible resolution */
    00249   int best = 0;
    00250   uint delta = Delta(_resolutions[0].width, *w) * Delta(_resolutions[0].height, *h);
    00251   for (int i = 1; i != _num_resolutions; ++i) {
    00252     uint newdelta = Delta(_resolutions[i].width, *w) * Delta(_resolutions[i].height, *h);
    00253     if (newdelta < delta) {
    00254       best = i;
    00255       delta = newdelta;
    00256     }
    00257   }
    00258   *w = _resolutions[best].width;
    00259   *h = _resolutions[best].height;
    00260 }
    00261
    00262 #ifdef WIN32
    00263 /* Let's redefine the LoadBMP macro with because we are dynamically
    00264  * loading SDL and need to 'SDL_CALL' all functions */
    00265 #undef SDL_LoadBMP
    00266 #define SDL_LoadBMP(file) SDL_LoadBMP_RW(SDL_CALL SDL_RWFromFile(file, "rb"), 1)
    00267 #endif
    00268
    00269 bool VideoDriver_SDL::CreateMainSurface(uint w, uint h)
    00270 {
    00271   SDL_Surface *newscreen, *icon;
    00272   char caption[50];
    00273   int bpp = BlitterFactoryBase::GetCurrentBlitter()->GetScreenDepth();
    00274   bool want_hwpalette;
    00275
    00276   GetAvailableVideoMode(&w, &h);
    00277
    00278   DEBUG(driver, 1, "SDL: using mode %ux%ux%d", w, h, bpp);
    00279
    00280   if (bpp == 0) usererror("Can't use a blitter that blits 0 bpp for normal visuals");
    00281
    00282   char icon_path[MAX_PATH];
    00283   if (FioFindFullPath(icon_path, lengthof(icon_path), BASESET_DIR, "openttd.32.bmp") != NULL) {
    00284     /* Give the application an icon */
    00285     icon = SDL_CALL SDL_LoadBMP(icon_path);
    00286     if (icon != NULL) {
    00287       /* Get the colourkey, which will be magenta */
    00288       uint32 rgbmap = SDL_CALL SDL_MapRGB(icon->format, 255, 0, 255);
    00289
    00290       SDL_CALL SDL_SetColorKey(icon, SDL_SRCCOLORKEY, rgbmap);
    00291       SDL_CALL SDL_WM_SetIcon(icon, NULL);
    00292       SDL_CALL SDL_FreeSurface(icon);
    00293     }
    00294   }
    00295
    00296   if (_use_hwpalette == 2) {
    00297     /* Default is to autodetect when to use SDL_HWPALETTE.
    00298      * In this case, SDL_HWPALETTE is only used for 8bpp
    00299      * blitters in fullscreen.
    00300      *
    00301      * When using an 8bpp blitter on a 8bpp system in
    00302      * windowed mode with SDL_HWPALETTE, OpenTTD will claim
    00303      * the system palette, making all other applications
    00304      * get the wrong colours. In this case, we're better of
    00305      * trying to approximate the colors we need using system
    00306      * colors, using a shadow surface (see below).
    00307      *
    00308      * On a 32bpp system, SDL_HWPALETTE is ignored, so it
    00309      * doesn't matter what we do.
    00310      *
    00311      * When using a 32bpp blitter on a 8bpp system, setting
    00312      * SDL_HWPALETTE messes up rendering (at least on X11),
    00313      * so we don't do that. In this case, SDL takes care of
    00314      * color approximation using its own shadow surface
    00315      * (which we can't force in 8bpp on 8bpp mode,
    00316      * unfortunately).
    00317      */
    00318     want_hwpalette = (bpp == 8 && _fullscreen);
    00319   } else {
    00320     /* User specified a value manually */
    00321     want_hwpalette = _use_hwpalette;
    00322   }
    00323
    00324   if (want_hwpalette) DEBUG(driver, 1, "SDL: requesting hardware palete");
    00325
    00326   /* Free any previously allocated shadow surface */
    00327   if (_sdl_screen != NULL && _sdl_screen != _sdl_realscreen) SDL_CALL SDL_FreeSurface(_sdl_screen);
    00328
    00329   if (_sdl_realscreen != NULL) {
    00330     if (_requested_hwpalette != want_hwpalette) {
    00331       /* SDL (at least the X11 driver), reuses the
    00332        * same window and palette settings when the bpp
    00333        * (and a few flags) are the same. Since we need
    00334        * to hwpalette value to change (in particular
    00335        * when switching between fullscreen and
    00336        * windowed), we restart the entire video
    00337        * subsystem to force creating a new window.
    00338        */
    00339       DEBUG(driver, 0, "SDL: Restarting SDL video subsystem, to force hwpalette change");
    00340       SDL_CALL SDL_QuitSubSystem(SDL_INIT_VIDEO);
    00341       SDL_CALL SDL_InitSubSystem(SDL_INIT_VIDEO);
    00342       ClaimMousePointer();
    00343       SetupKeyboard();
    00344     }
    00345   }
    00346   /* Remember if we wanted a hwpalette. We can't reliably query
    00347    * SDL for the SDL_HWPALETTE flag, since it might get set even
    00348    * though we didn't ask for it (when SDL creates a shadow
    00349    * surface, for example). */
    00350   _requested_hwpalette = want_hwpalette;
    00351
    00352   /* DO NOT CHANGE TO HWSURFACE, IT DOES NOT WORK */
    00353   newscreen = SDL_CALL SDL_SetVideoMode(w, h, bpp, SDL_SWSURFACE | (want_hwpalette ? SDL_HWPALETTE : 0) | (_fullscreen ? SDL_FULLSCREEN : SDL_RESIZABLE));
    00354   if (newscreen == NULL) {
    00355     DEBUG(driver, 0, "SDL: Couldn't allocate a window to draw on");
    00356     return false;
    00357   }
    00358   _sdl_realscreen = newscreen;
    00359
    00360   if (bpp == 8 && (_sdl_realscreen->flags & SDL_HWPALETTE) != SDL_HWPALETTE) {
    00361     /* Using an 8bpp blitter, if we didn't get a hardware
    00362      * palette (most likely because we didn't request one,
    00363      * see above), we'll have to set up a shadow surface to
    00364      * render on.
    00365      *
    00366      * Our palette will be applied to this shadow surface,
    00367      * while the real screen surface will use the shared
    00368      * system palette (which will partly contain our colors,
    00369      * but most likely will not have enough free color cells
    00370      * for all of our colors). SDL can use these two
    00371      * palettes at blit time to approximate colors used in
    00372      * the shadow surface using system colors automatically.
    00373      *
    00374      * Note that when using an 8bpp blitter on a 32bpp
    00375      * system, SDL will create an internal shadow surface.
    00376      * This shadow surface will have SDL_HWPALLETE set, so
    00377      * we won't create a second shadow surface in this case.
    00378      */
    00379     DEBUG(driver, 1, "SDL: using shadow surface");
    00380     newscreen = SDL_CALL SDL_CreateRGBSurface(SDL_SWSURFACE, w, h, bpp, 0, 0, 0, 0);
    00381     if (newscreen == NULL) {
    00382       DEBUG(driver, 0, "SDL: Couldn't allocate a shadow surface to draw on");
    00383       return false;
    00384     }
    00385   }
    00386
    00387   /* Delay drawing for this cycle; the next cycle will redraw the whole screen */
    00388   _num_dirty_rects = 0;
    00389
    00390   _screen.width = newscreen->w;
    00391   _screen.height = newscreen->h;
    00392   _screen.pitch = newscreen->pitch / (bpp / 8);
    00393   _screen.dst_ptr = newscreen->pixels;
    00394   _sdl_screen = newscreen;
    00395
    00396   /* When in full screen, we will always have the mouse cursor
    00397    * within the window, even though SDL does not give us the
    00398    * appropriate event to know this. */
    00399   if (_fullscreen) _cursor.in_window = true;
    00400
    00401   Blitter *blitter = BlitterFactoryBase::GetCurrentBlitter();
    00402   blitter->PostResize();
    00403
    00404   InitPalette();
    00405   switch (blitter->UsePaletteAnimation()) {
    00406     case Blitter::PALETTE_ANIMATION_NONE:
    00407     case Blitter::PALETTE_ANIMATION_VIDEO_BACKEND:
    00408       UpdatePalette();
    00409       break;
    00410
    00411     case Blitter::PALETTE_ANIMATION_BLITTER:
    00412       if (_video_driver != NULL) blitter->PaletteAnimate(_local_palette);
    00413       break;
    00414
    00415     default:
    00416       NOT_REACHED();
    00417   }
    00418
    00419   snprintf(caption, sizeof(caption), "OpenTTD %s", _openttd_revision);
    00420   SDL_CALL SDL_WM_SetCaption(caption, caption);
    00421
    00422   GameSizeChanged();
    00423
    00424   return true;
    00425 }
    00426
    00427 bool VideoDriver_SDL::ClaimMousePointer()
    00428 {
    00429   SDL_CALL SDL_ShowCursor(0);
    00430   return true;
    00431 }
    00432
    00433 struct VkMapping {
    00434 #if SDL_VERSION_ATLEAST(1, 3, 0)
    00435   SDL_Keycode vk_from;
    00436 #else
    00437   uint16 vk_from;
    00438 #endif
    00439   byte vk_count;
    00440   byte map_to;
    00441 };
    00442
    00443 #define AS(x, z) {x, 0, z}
    00444 #define AM(x, y, z, w) {x, (byte)(y - x), z}
    00445
    00446 static const VkMapping _vk_mapping[] = {
    00447   /* Pageup stuff + up/down */
    00448   AM(SDLK_PAGEUP, SDLK_PAGEDOWN, WKC_PAGEUP, WKC_PAGEDOWN),
    00449   AS(SDLK_UP,     WKC_UP),
    00450   AS(SDLK_DOWN,   WKC_DOWN),
    00451   AS(SDLK_LEFT,   WKC_LEFT),
    00452   AS(SDLK_RIGHT,  WKC_RIGHT),
    00453
    00454   AS(SDLK_HOME,   WKC_HOME),
    00455   AS(SDLK_END,    WKC_END),
    00456
    00457   AS(SDLK_INSERT, WKC_INSERT),
    00458   AS(SDLK_DELETE, WKC_DELETE),
    00459
    00460   /* Map letters & digits */
    00461   AM(SDLK_a, SDLK_z, 'A', 'Z'),
    00462   AM(SDLK_0, SDLK_9, '0', '9'),
    00463
    00464   AS(SDLK_ESCAPE,    WKC_ESC),
    00465   AS(SDLK_PAUSE,     WKC_PAUSE),
    00466   AS(SDLK_BACKSPACE, WKC_BACKSPACE),
    00467
    00468   AS(SDLK_SPACE,     WKC_SPACE),
    00469   AS(SDLK_RETURN,    WKC_RETURN),
    00470   AS(SDLK_TAB,       WKC_TAB),
    00471
    00472   /* Function keys */
    00473   AM(SDLK_F1, SDLK_F12, WKC_F1, WKC_F12),
    00474
    00475   /* Numeric part. */
    00476   AM(SDLK_KP0, SDLK_KP9, '0', '9'),
    00477   AS(SDLK_KP_DIVIDE,   WKC_NUM_DIV),
    00478   AS(SDLK_KP_MULTIPLY, WKC_NUM_MUL),
    00479   AS(SDLK_KP_MINUS,    WKC_NUM_MINUS),
    00480   AS(SDLK_KP_PLUS,     WKC_NUM_PLUS),
    00481   AS(SDLK_KP_ENTER,    WKC_NUM_ENTER),
    00482   AS(SDLK_KP_PERIOD,   WKC_NUM_DECIMAL),
    00483
    00484   /* Other non-letter keys */
    00485   AS(SDLK_SLASH,        WKC_SLASH),
    00486   AS(SDLK_SEMICOLON,    WKC_SEMICOLON),
    00487   AS(SDLK_EQUALS,       WKC_EQUALS),
    00488   AS(SDLK_LEFTBRACKET,  WKC_L_BRACKET),
    00489   AS(SDLK_BACKSLASH,    WKC_BACKSLASH),
    00490   AS(SDLK_RIGHTBRACKET, WKC_R_BRACKET),
    00491
    00492   AS(SDLK_QUOTE,   WKC_SINGLEQUOTE),
    00493   AS(SDLK_COMMA,   WKC_COMMA),
    00494   AS(SDLK_MINUS,   WKC_MINUS),
    00495   AS(SDLK_PERIOD,  WKC_PERIOD)
    00496 };
    00497
    00498 static uint32 ConvertSdlKeyIntoMy(SDL_keysym *sym)
    00499 {
    00500   const VkMapping *map;
    00501   uint key = 0;
    00502
    00503   for (map = _vk_mapping; map != endof(_vk_mapping); ++map) {
    00504     if ((uint)(sym->sym - map->vk_from) <= map->vk_count) {
    00505       key = sym->sym - map->vk_from + map->map_to;
    00506       break;
    00507     }
    00508   }
    00509
    00510   /* check scancode for BACKQUOTE key, because we want the key left of "1", not anything else (on non-US keyboards) */
    00511 #if defined(WIN32) || defined(__OS2__)
    00512   if (sym->scancode == 41) key = WKC_BACKQUOTE;
    00513 #elif defined(__APPLE__)
    00514   if (sym->scancode == 10) key = WKC_BACKQUOTE;
    00515 #elif defined(__MORPHOS__)
    00516   if (sym->scancode == 0)  key = WKC_BACKQUOTE;  // yes, that key is code '0' under MorphOS :)
    00517 #elif defined(__BEOS__)
    00518   if (sym->scancode == 17) key = WKC_BACKQUOTE;
    00519 #elif defined(__SVR4) && defined(__sun)
    00520   if (sym->scancode == 60) key = WKC_BACKQUOTE;
    00521   if (sym->scancode == 49) key = WKC_BACKSPACE;
    00522 #elif defined(__sgi__)
    00523   if (sym->scancode == 22) key = WKC_BACKQUOTE;
    00524 #else
    00525   if (sym->scancode == 49) key = WKC_BACKQUOTE;
    00526 #endif
    00527
    00528   /* META are the command keys on mac */
    00529   if (sym->mod & KMOD_META)  key |= WKC_META;
    00530   if (sym->mod & KMOD_SHIFT) key |= WKC_SHIFT;
    00531   if (sym->mod & KMOD_CTRL)  key |= WKC_CTRL;
    00532   if (sym->mod & KMOD_ALT)   key |= WKC_ALT;
    00533
    00534   return (key << 16) + sym->unicode;
    00535 }
    00536
    00537 int VideoDriver_SDL::PollEvent()
    00538 {
    00539   SDL_Event ev;
    00540
    00541   if (!SDL_CALL SDL_PollEvent(&ev)) return -2;
    00542
    00543   switch (ev.type) {
    00544     case SDL_MOUSEMOTION:
    00545       if (_cursor.fix_at) {
    00546         int dx = ev.motion.x - _cursor.pos.x;
    00547         int dy = ev.motion.y - _cursor.pos.y;
    00548         if (dx != 0 || dy != 0) {
    00549           _cursor.delta.x = dx;
    00550           _cursor.delta.y = dy;
    00551           SDL_CALL SDL_WarpMouse(_cursor.pos.x, _cursor.pos.y);
    00552         }
    00553       } else {
    00554         _cursor.delta.x = ev.motion.x - _cursor.pos.x;
    00555         _cursor.delta.y = ev.motion.y - _cursor.pos.y;
    00556         _cursor.pos.x = ev.motion.x;
    00557         _cursor.pos.y = ev.motion.y;
    00558         _cursor.dirty = true;
    00559       }
    00560       HandleMouseEvents();
    00561       break;
    00562
    00563     case SDL_MOUSEBUTTONDOWN:
    00564       if (_rightclick_emulate && SDL_CALL SDL_GetModState() & KMOD_CTRL) {
    00565         ev.button.button = SDL_BUTTON_RIGHT;
    00566       }
    00567
    00568       switch (ev.button.button) {
    00569         case SDL_BUTTON_LEFT:
    00570           _left_button_down = true;
    00571           break;
    00572
    00573         case SDL_BUTTON_RIGHT:
    00574           _right_button_down = true;
    00575           _right_button_clicked = true;
    00576           break;
    00577
    00578         case SDL_BUTTON_WHEELUP:   _cursor.wheel--; break;
    00579         case SDL_BUTTON_WHEELDOWN: _cursor.wheel++; break;
    00580
    00581         default: break;
    00582       }
    00583       HandleMouseEvents();
    00584       break;
    00585
    00586     case SDL_MOUSEBUTTONUP:
    00587       if (_rightclick_emulate) {
    00588         _right_button_down = false;
    00589         _left_button_down = false;
    00590         _left_button_clicked = false;
    00591       } else if (ev.button.button == SDL_BUTTON_LEFT) {
    00592         _left_button_down = false;
    00593         _left_button_clicked = false;
    00594       } else if (ev.button.button == SDL_BUTTON_RIGHT) {
    00595         _right_button_down = false;
    00596       }
    00597       HandleMouseEvents();
    00598       break;
    00599
    00600     case SDL_ACTIVEEVENT:
    00601       if (!(ev.active.state & SDL_APPMOUSEFOCUS)) break;
    00602
    00603       if (ev.active.gain) { // mouse entered the window, enable cursor
    00604         _cursor.in_window = true;
    00605       } else {
    00606         UndrawMouseCursor(); // mouse left the window, undraw cursor
    00607         _cursor.in_window = false;
    00608       }
    00609       break;
    00610
    00611     case SDL_QUIT:
    00612       HandleExitGameRequest();
    00613       break;
    00614
    00615     case SDL_KEYDOWN: // Toggle full-screen on ALT + ENTER/F
    00616       if ((ev.key.keysym.mod & (KMOD_ALT | KMOD_META)) &&
    00617           (ev.key.keysym.sym == SDLK_RETURN || ev.key.keysym.sym == SDLK_f)) {
    00618         ToggleFullScreen(!_fullscreen);
    00619       } else {
    00620         HandleKeypress(ConvertSdlKeyIntoMy(&ev.key.keysym));
    00621       }
    00622       break;
    00623
    00624     case SDL_VIDEORESIZE: {
    00625       int w = max(ev.resize.w, 64);
    00626       int h = max(ev.resize.h, 64);
    00627       CreateMainSurface(w, h);
    00628       break;
    00629     }
    00630     case SDL_VIDEOEXPOSE: {
    00631       /* Force a redraw of the entire screen. Note
    00632        * that SDL 1.2 seems to do this automatically
    00633        * in most cases, but 1.3 / 2.0 does not. */
    00634             _num_dirty_rects = MAX_DIRTY_RECTS + 1;
    00635       break;
    00636     }
    00637   }
    00638   return -1;
    00639 }
    00640
    00641 const char *VideoDriver_SDL::Start(const char * const *parm)
    00642 {
    00643   char buf[30];
    00644   _use_hwpalette = GetDriverParamInt(parm, "hw_palette", 2);
    00645
    00646   const char *s = SdlOpen(SDL_INIT_VIDEO);
    00647   if (s != NULL) return s;
    00648
    00649   GetVideoModes();
    00650   if (!CreateMainSurface(_cur_resolution.width, _cur_resolution.height)) {
    00651     return SDL_CALL SDL_GetError();
    00652   }
    00653
    00654   SDL_CALL SDL_VideoDriverName(buf, sizeof buf);
    00655   DEBUG(driver, 1, "SDL: using driver '%s'", buf);
    00656
    00657   MarkWholeScreenDirty();
    00658   SetupKeyboard();
    00659
    00660   _draw_threaded = GetDriverParam(parm, "no_threads") == NULL && GetDriverParam(parm, "no_thread") == NULL;
    00661
    00662   return NULL;
    00663 }
    00664
    00665 void VideoDriver_SDL::SetupKeyboard()
    00666 {
    00667   SDL_CALL SDL_EnableKeyRepeat(SDL_DEFAULT_REPEAT_DELAY, SDL_DEFAULT_REPEAT_INTERVAL);
    00668   SDL_CALL SDL_EnableUNICODE(1);
    00669 }
    00670
    00671 void VideoDriver_SDL::Stop()
    00672 {
    00673   SdlClose(SDL_INIT_VIDEO);
    00674 }
    00675
    00676 void VideoDriver_SDL::MainLoop()
    00677 {
    00678   uint32 cur_ticks = SDL_CALL SDL_GetTicks();
    00679   uint32 last_cur_ticks = cur_ticks;
    00680   uint32 next_tick = cur_ticks + MILLISECONDS_PER_TICK;
    00681   uint32 mod;
    00682   int numkeys;
    00683   Uint8 *keys;
    00684
    00685   CheckPaletteAnim();
    00686
    00687   if (_draw_threaded) {
    00688     /* Initialise the mutex first, because that's the thing we *need*
    00689      * directly in the newly created thread. */
    00690     _draw_mutex = ThreadMutex::New();
    00691     if (_draw_mutex == NULL) {
    00692       _draw_threaded = false;
    00693     } else {
    00694       _draw_mutex->BeginCritical();
    00695       _draw_continue = true;
    00696
    00697       _draw_threaded = ThreadObject::New(&DrawSurfaceToScreenThread, NULL, &_draw_thread);
    00698
    00699       /* Free the mutex if we won't be able to use it. */
    00700       if (!_draw_threaded) {
    00701         _draw_mutex->EndCritical();
    00702         delete _draw_mutex;
    00703         _draw_mutex = NULL;
    00704       } else {
    00705         /* Wait till the draw mutex has started itself. */
    00706         _draw_mutex->WaitForSignal();
    00707       }
    00708     }
    00709   }
    00710
    00711   DEBUG(driver, 1, "SDL: using %sthreads", _draw_threaded ? "" : "no ");
    00712
    00713   for (;;) {
    00714     uint32 prev_cur_ticks = cur_ticks; // to check for wrapping
    00715     InteractiveRandom(); // randomness
    00716
    00717     while (PollEvent() == -1) {}
    00718     if (_exit_game) break;
    00719
    00720     mod = SDL_CALL SDL_GetModState();
    00721 #if SDL_VERSION_ATLEAST(1, 3, 0)
    00722     keys = SDL_CALL SDL_GetKeyboardState(&numkeys);
    00723 #else
    00724     keys = SDL_CALL SDL_GetKeyState(&numkeys);
    00725 #endif
    00726 #if defined(_DEBUG)
    00727     if (_shift_pressed)
    00728 #else
    00729     /* Speedup when pressing tab, except when using ALT+TAB
    00730      * to switch to another application */
    00731 #if SDL_VERSION_ATLEAST(1, 3, 0)
    00732     if (keys[SDL_SCANCODE_TAB] && (mod & KMOD_ALT) == 0)
    00733 #else
    00734     if (keys[SDLK_TAB] && (mod & KMOD_ALT) == 0)
    00735 #endif /* SDL_VERSION_ATLEAST(1, 3, 0) */
    00736 #endif /* defined(_DEBUG) */
    00737     {
    00738       if (!_networking && _game_mode != GM_MENU) _fast_forward |= 2;
    00739     } else if (_fast_forward & 2) {
    00740       _fast_forward = 0;
    00741     }
    00742
    00743     cur_ticks = SDL_CALL SDL_GetTicks();
    00744     if (cur_ticks >= next_tick || (_fast_forward && !_pause_mode) || cur_ticks < prev_cur_ticks) {
    00745       _realtime_tick += cur_ticks - last_cur_ticks;
    00746       last_cur_ticks = cur_ticks;
    00747       next_tick = cur_ticks + MILLISECONDS_PER_TICK;
    00748
    00749       bool old_ctrl_pressed = _ctrl_pressed;
    00750
    00751       _ctrl_pressed  = !!(mod & KMOD_CTRL);
    00752       _shift_pressed = !!(mod & KMOD_SHIFT);
    00753
    00754       /* determine which directional keys are down */
    00755       _dirkeys =
    00756 #if SDL_VERSION_ATLEAST(1, 3, 0)
    00757         (keys[SDL_SCANCODE_LEFT]  ? 1 : 0) |
    00758         (keys[SDL_SCANCODE_UP]    ? 2 : 0) |
    00759         (keys[SDL_SCANCODE_RIGHT] ? 4 : 0) |
    00760         (keys[SDL_SCANCODE_DOWN]  ? 8 : 0);
    00761 #else
    00762         (keys[SDLK_LEFT]  ? 1 : 0) |
    00763         (keys[SDLK_UP]    ? 2 : 0) |
    00764         (keys[SDLK_RIGHT] ? 4 : 0) |
    00765         (keys[SDLK_DOWN]  ? 8 : 0);
    00766 #endif
    00767       if (old_ctrl_pressed != _ctrl_pressed) HandleCtrlChanged();
    00768
    00769       /* The gameloop is the part that can run asynchronously. The rest
    00770        * except sleeping can't. */
    00771       if (_draw_mutex != NULL) _draw_mutex->EndCritical();
    00772
    00773       GameLoop();
    00774
    00775       if (_draw_mutex != NULL) _draw_mutex->BeginCritical();
    00776
    00777       UpdateWindows();
    00778       _local_palette = _cur_palette;
    00779     } else {
    00780       /* Release the thread while sleeping */
    00781       if (_draw_mutex != NULL) _draw_mutex->EndCritical();
    00782       CSleep(1);
    00783       if (_draw_mutex != NULL) _draw_mutex->BeginCritical();
    00784
    00785       NetworkDrawChatMessage();
    00786       DrawMouseCursor();
    00787     }
    00788
    00789     /* End of the critical part. */
    00790     if (_draw_mutex != NULL && !HasModalProgress()) {
    00791       _draw_mutex->SendSignal();
    00792     } else {
    00793       /* Oh, we didn't have threads, then just draw unthreaded */
    00794       CheckPaletteAnim();
    00795       DrawSurfaceToScreen();
    00796     }
    00797   }
    00798
    00799   if (_draw_mutex != NULL) {
    00800     _draw_continue = false;
    00801     /* Sending signal if there is no thread blocked
    00802      * is very valid and results in noop */
    00803     _draw_mutex->SendSignal();
    00804     _draw_mutex->EndCritical();
    00805     _draw_thread->Join();
    00806
    00807     delete _draw_mutex;
    00808     delete _draw_thread;
    00809
    00810     _draw_mutex = NULL;
    00811     _draw_thread = NULL;
    00812   }
    00813 }
    00814
    00815 bool VideoDriver_SDL::ChangeResolution(int w, int h)
    00816 {
    00817   if (_draw_mutex != NULL) _draw_mutex->BeginCritical();
    00818   bool ret = CreateMainSurface(w, h);
    00819   if (_draw_mutex != NULL) _draw_mutex->EndCritical();
    00820   return ret;
    00821 }
    00822
    00823 bool VideoDriver_SDL::ToggleFullscreen(bool fullscreen)
    00824 {
    00825   _fullscreen = fullscreen;
    00826   GetVideoModes(); // get the list of available video modes
    00827   if (_num_resolutions == 0 || !CreateMainSurface(_cur_resolution.width, _cur_resolution.height)) {
    00828     /* switching resolution failed, put back full_screen to original status */
    00829     _fullscreen ^= true;
    00830     return false;
    00831   }
    00832   return true;
    00833 }
    00834
    00835 bool VideoDriver_SDL::AfterBlitterChange()
    00836 {
    00837   return this->ChangeResolution(_screen.width, _screen.height);
    00838 }
    00839
    00840 #endif /* WITH_SDL */