sdl_v.cpp

Go to the documentation of this file.
00001 /* $Id$ */
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     }
00344   }
00345   /* Remember if we wanted a hwpalette. We can't reliably query
00346    * SDL for the SDL_HWPALETTE flag, since it might get set even
00347    * though we didn't ask for it (when SDL creates a shadow
00348    * surface, for example). */
00349   _requested_hwpalette = want_hwpalette;
00350 
00351   /* DO NOT CHANGE TO HWSURFACE, IT DOES NOT WORK */
00352   newscreen = SDL_CALL SDL_SetVideoMode(w, h, bpp, SDL_SWSURFACE | (want_hwpalette ? SDL_HWPALETTE : 0) | (_fullscreen ? SDL_FULLSCREEN : SDL_RESIZABLE));
00353   if (newscreen == NULL) {
00354     DEBUG(driver, 0, "SDL: Couldn't allocate a window to draw on");
00355     return false;
00356   }
00357   _sdl_realscreen = newscreen;
00358 
00359   if (bpp == 8 && (_sdl_realscreen->flags & SDL_HWPALETTE) != SDL_HWPALETTE) {
00360     /* Using an 8bpp blitter, if we didn't get a hardware
00361      * palette (most likely because we didn't request one,
00362      * see above), we'll have to set up a shadow surface to
00363      * render on.
00364      *
00365      * Our palette will be applied to this shadow surface,
00366      * while the real screen surface will use the shared
00367      * system palette (which will partly contain our colors,
00368      * but most likely will not have enough free color cells
00369      * for all of our colors). SDL can use these two
00370      * palettes at blit time to approximate colors used in
00371      * the shadow surface using system colors automatically.
00372      *
00373      * Note that when using an 8bpp blitter on a 32bpp
00374      * system, SDL will create an internal shadow surface.
00375      * This shadow surface will have SDL_HWPALLETE set, so
00376      * we won't create a second shadow surface in this case.
00377      */
00378     DEBUG(driver, 1, "SDL: using shadow surface");
00379     newscreen = SDL_CALL SDL_CreateRGBSurface(SDL_SWSURFACE, w, h, bpp, 0, 0, 0, 0);
00380     if (newscreen == NULL) {
00381       DEBUG(driver, 0, "SDL: Couldn't allocate a shadow surface to draw on");
00382       return false;
00383     }
00384   }
00385 
00386   /* Delay drawing for this cycle; the next cycle will redraw the whole screen */
00387   _num_dirty_rects = 0;
00388 
00389   _screen.width = newscreen->w;
00390   _screen.height = newscreen->h;
00391   _screen.pitch = newscreen->pitch / (bpp / 8);
00392   _screen.dst_ptr = newscreen->pixels;
00393   _sdl_screen = newscreen;
00394 
00395   Blitter *blitter = BlitterFactoryBase::GetCurrentBlitter();
00396   blitter->PostResize();
00397 
00398   InitPalette();
00399   switch (blitter->UsePaletteAnimation()) {
00400     case Blitter::PALETTE_ANIMATION_NONE:
00401     case Blitter::PALETTE_ANIMATION_VIDEO_BACKEND:
00402       UpdatePalette();
00403       break;
00404 
00405     case Blitter::PALETTE_ANIMATION_BLITTER:
00406       if (_video_driver != NULL) blitter->PaletteAnimate(_local_palette);
00407       break;
00408 
00409     default:
00410       NOT_REACHED();
00411   }
00412 
00413   snprintf(caption, sizeof(caption), "OpenTTD %s", _openttd_revision);
00414   SDL_CALL SDL_WM_SetCaption(caption, caption);
00415 
00416   GameSizeChanged();
00417 
00418   return true;
00419 }
00420 
00421 bool VideoDriver_SDL::ClaimMousePointer()
00422 {
00423   SDL_CALL SDL_ShowCursor(0);
00424   return true;
00425 }
00426 
00427 struct VkMapping {
00428 #if SDL_VERSION_ATLEAST(1, 3, 0)
00429   SDL_Keycode vk_from;
00430 #else
00431   uint16 vk_from;
00432 #endif
00433   byte vk_count;
00434   byte map_to;
00435 };
00436 
00437 #define AS(x, z) {x, 0, z}
00438 #define AM(x, y, z, w) {x, (byte)(y - x), z}
00439 
00440 static const VkMapping _vk_mapping[] = {
00441   /* Pageup stuff + up/down */
00442   AM(SDLK_PAGEUP, SDLK_PAGEDOWN, WKC_PAGEUP, WKC_PAGEDOWN),
00443   AS(SDLK_UP,     WKC_UP),
00444   AS(SDLK_DOWN,   WKC_DOWN),
00445   AS(SDLK_LEFT,   WKC_LEFT),
00446   AS(SDLK_RIGHT,  WKC_RIGHT),
00447 
00448   AS(SDLK_HOME,   WKC_HOME),
00449   AS(SDLK_END,    WKC_END),
00450 
00451   AS(SDLK_INSERT, WKC_INSERT),
00452   AS(SDLK_DELETE, WKC_DELETE),
00453 
00454   /* Map letters & digits */
00455   AM(SDLK_a, SDLK_z, 'A', 'Z'),
00456   AM(SDLK_0, SDLK_9, '0', '9'),
00457 
00458   AS(SDLK_ESCAPE,    WKC_ESC),
00459   AS(SDLK_PAUSE,     WKC_PAUSE),
00460   AS(SDLK_BACKSPACE, WKC_BACKSPACE),
00461 
00462   AS(SDLK_SPACE,     WKC_SPACE),
00463   AS(SDLK_RETURN,    WKC_RETURN),
00464   AS(SDLK_TAB,       WKC_TAB),
00465 
00466   /* Function keys */
00467   AM(SDLK_F1, SDLK_F12, WKC_F1, WKC_F12),
00468 
00469   /* Numeric part. */
00470   AM(SDLK_KP0, SDLK_KP9, '0', '9'),
00471   AS(SDLK_KP_DIVIDE,   WKC_NUM_DIV),
00472   AS(SDLK_KP_MULTIPLY, WKC_NUM_MUL),
00473   AS(SDLK_KP_MINUS,    WKC_NUM_MINUS),
00474   AS(SDLK_KP_PLUS,     WKC_NUM_PLUS),
00475   AS(SDLK_KP_ENTER,    WKC_NUM_ENTER),
00476   AS(SDLK_KP_PERIOD,   WKC_NUM_DECIMAL),
00477 
00478   /* Other non-letter keys */
00479   AS(SDLK_SLASH,        WKC_SLASH),
00480   AS(SDLK_SEMICOLON,    WKC_SEMICOLON),
00481   AS(SDLK_EQUALS,       WKC_EQUALS),
00482   AS(SDLK_LEFTBRACKET,  WKC_L_BRACKET),
00483   AS(SDLK_BACKSLASH,    WKC_BACKSLASH),
00484   AS(SDLK_RIGHTBRACKET, WKC_R_BRACKET),
00485 
00486   AS(SDLK_QUOTE,   WKC_SINGLEQUOTE),
00487   AS(SDLK_COMMA,   WKC_COMMA),
00488   AS(SDLK_MINUS,   WKC_MINUS),
00489   AS(SDLK_PERIOD,  WKC_PERIOD)
00490 };
00491 
00492 static uint32 ConvertSdlKeyIntoMy(SDL_keysym *sym)
00493 {
00494   const VkMapping *map;
00495   uint key = 0;
00496 
00497   for (map = _vk_mapping; map != endof(_vk_mapping); ++map) {
00498     if ((uint)(sym->sym - map->vk_from) <= map->vk_count) {
00499       key = sym->sym - map->vk_from + map->map_to;
00500       break;
00501     }
00502   }
00503 
00504   /* check scancode for BACKQUOTE key, because we want the key left of "1", not anything else (on non-US keyboards) */
00505 #if defined(WIN32) || defined(__OS2__)
00506   if (sym->scancode == 41) key = WKC_BACKQUOTE;
00507 #elif defined(__APPLE__)
00508   if (sym->scancode == 10) key = WKC_BACKQUOTE;
00509 #elif defined(__MORPHOS__)
00510   if (sym->scancode == 0)  key = WKC_BACKQUOTE;  // yes, that key is code '0' under MorphOS :)
00511 #elif defined(__BEOS__)
00512   if (sym->scancode == 17) key = WKC_BACKQUOTE;
00513 #elif defined(__SVR4) && defined(__sun)
00514   if (sym->scancode == 60) key = WKC_BACKQUOTE;
00515   if (sym->scancode == 49) key = WKC_BACKSPACE;
00516 #elif defined(__sgi__)
00517   if (sym->scancode == 22) key = WKC_BACKQUOTE;
00518 #else
00519   if (sym->scancode == 49) key = WKC_BACKQUOTE;
00520 #endif
00521 
00522   /* META are the command keys on mac */
00523   if (sym->mod & KMOD_META)  key |= WKC_META;
00524   if (sym->mod & KMOD_SHIFT) key |= WKC_SHIFT;
00525   if (sym->mod & KMOD_CTRL)  key |= WKC_CTRL;
00526   if (sym->mod & KMOD_ALT)   key |= WKC_ALT;
00527 
00528   return (key << 16) + sym->unicode;
00529 }
00530 
00531 int VideoDriver_SDL::PollEvent()
00532 {
00533   SDL_Event ev;
00534 
00535   if (!SDL_CALL SDL_PollEvent(&ev)) return -2;
00536 
00537   switch (ev.type) {
00538     case SDL_MOUSEMOTION:
00539       if (_cursor.fix_at) {
00540         int dx = ev.motion.x - _cursor.pos.x;
00541         int dy = ev.motion.y - _cursor.pos.y;
00542         if (dx != 0 || dy != 0) {
00543           _cursor.delta.x = dx;
00544           _cursor.delta.y = dy;
00545           SDL_CALL SDL_WarpMouse(_cursor.pos.x, _cursor.pos.y);
00546         }
00547       } else {
00548         _cursor.delta.x = ev.motion.x - _cursor.pos.x;
00549         _cursor.delta.y = ev.motion.y - _cursor.pos.y;
00550         _cursor.pos.x = ev.motion.x;
00551         _cursor.pos.y = ev.motion.y;
00552         _cursor.dirty = true;
00553       }
00554       HandleMouseEvents();
00555       break;
00556 
00557     case SDL_MOUSEBUTTONDOWN:
00558       if (_rightclick_emulate && SDL_CALL SDL_GetModState() & KMOD_CTRL) {
00559         ev.button.button = SDL_BUTTON_RIGHT;
00560       }
00561 
00562       switch (ev.button.button) {
00563         case SDL_BUTTON_LEFT:
00564           _left_button_down = true;
00565           break;
00566 
00567         case SDL_BUTTON_RIGHT:
00568           _right_button_down = true;
00569           _right_button_clicked = true;
00570           break;
00571 
00572         case SDL_BUTTON_WHEELUP:   _cursor.wheel--; break;
00573         case SDL_BUTTON_WHEELDOWN: _cursor.wheel++; break;
00574 
00575         default: break;
00576       }
00577       HandleMouseEvents();
00578       break;
00579 
00580     case SDL_MOUSEBUTTONUP:
00581       if (_rightclick_emulate) {
00582         _right_button_down = false;
00583         _left_button_down = false;
00584         _left_button_clicked = false;
00585       } else if (ev.button.button == SDL_BUTTON_LEFT) {
00586         _left_button_down = false;
00587         _left_button_clicked = false;
00588       } else if (ev.button.button == SDL_BUTTON_RIGHT) {
00589         _right_button_down = false;
00590       }
00591       HandleMouseEvents();
00592       break;
00593 
00594     case SDL_ACTIVEEVENT:
00595       if (!(ev.active.state & SDL_APPMOUSEFOCUS)) break;
00596 
00597       if (ev.active.gain) { // mouse entered the window, enable cursor
00598         _cursor.in_window = true;
00599       } else {
00600         UndrawMouseCursor(); // mouse left the window, undraw cursor
00601         _cursor.in_window = false;
00602       }
00603       break;
00604 
00605     case SDL_QUIT:
00606       HandleExitGameRequest();
00607       break;
00608 
00609     case SDL_KEYDOWN: // Toggle full-screen on ALT + ENTER/F
00610       if ((ev.key.keysym.mod & (KMOD_ALT | KMOD_META)) &&
00611           (ev.key.keysym.sym == SDLK_RETURN || ev.key.keysym.sym == SDLK_f)) {
00612         ToggleFullScreen(!_fullscreen);
00613       } else {
00614         HandleKeypress(ConvertSdlKeyIntoMy(&ev.key.keysym));
00615       }
00616       break;
00617 
00618     case SDL_VIDEORESIZE: {
00619       int w = max(ev.resize.w, 64);
00620       int h = max(ev.resize.h, 64);
00621       CreateMainSurface(w, h);
00622       break;
00623     }
00624     case SDL_VIDEOEXPOSE: {
00625       /* Force a redraw of the entire screen. Note
00626        * that SDL 1.2 seems to do this automatically
00627        * in most cases, but 1.3 / 2.0 does not. */
00628             _num_dirty_rects = MAX_DIRTY_RECTS + 1;
00629       break;
00630     }
00631   }
00632   return -1;
00633 }
00634 
00635 const char *VideoDriver_SDL::Start(const char * const *parm)
00636 {
00637   char buf[30];
00638   _use_hwpalette = GetDriverParamInt(parm, "hw_palette", 2);
00639 
00640   const char *s = SdlOpen(SDL_INIT_VIDEO);
00641   if (s != NULL) return s;
00642 
00643   GetVideoModes();
00644   if (!CreateMainSurface(_cur_resolution.width, _cur_resolution.height)) {
00645     return SDL_CALL SDL_GetError();
00646   }
00647 
00648   SDL_CALL SDL_VideoDriverName(buf, sizeof buf);
00649   DEBUG(driver, 1, "SDL: using driver '%s'", buf);
00650 
00651   MarkWholeScreenDirty();
00652 
00653   SDL_CALL SDL_EnableKeyRepeat(SDL_DEFAULT_REPEAT_DELAY, SDL_DEFAULT_REPEAT_INTERVAL);
00654   SDL_CALL SDL_EnableUNICODE(1);
00655 
00656   _draw_threaded = GetDriverParam(parm, "no_threads") == NULL && GetDriverParam(parm, "no_thread") == NULL;
00657 
00658   return NULL;
00659 }
00660 
00661 void VideoDriver_SDL::Stop()
00662 {
00663   SdlClose(SDL_INIT_VIDEO);
00664 }
00665 
00666 void VideoDriver_SDL::MainLoop()
00667 {
00668   uint32 cur_ticks = SDL_CALL SDL_GetTicks();
00669   uint32 last_cur_ticks = cur_ticks;
00670   uint32 next_tick = cur_ticks + MILLISECONDS_PER_TICK;
00671   uint32 mod;
00672   int numkeys;
00673   Uint8 *keys;
00674 
00675   CheckPaletteAnim();
00676 
00677   if (_draw_threaded) {
00678     /* Initialise the mutex first, because that's the thing we *need*
00679      * directly in the newly created thread. */
00680     _draw_mutex = ThreadMutex::New();
00681     if (_draw_mutex == NULL) {
00682       _draw_threaded = false;
00683     } else {
00684       _draw_mutex->BeginCritical();
00685       _draw_continue = true;
00686 
00687       _draw_threaded = ThreadObject::New(&DrawSurfaceToScreenThread, NULL, &_draw_thread);
00688 
00689       /* Free the mutex if we won't be able to use it. */
00690       if (!_draw_threaded) {
00691         _draw_mutex->EndCritical();
00692         delete _draw_mutex;
00693       } else {
00694         /* Wait till the draw mutex has started itself. */
00695         _draw_mutex->WaitForSignal();
00696       }
00697     }
00698   }
00699 
00700   DEBUG(driver, 1, "SDL: using %sthreads", _draw_threaded ? "" : "no ");
00701 
00702   for (;;) {
00703     uint32 prev_cur_ticks = cur_ticks; // to check for wrapping
00704     InteractiveRandom(); // randomness
00705 
00706     while (PollEvent() == -1) {}
00707     if (_exit_game) break;
00708 
00709     mod = SDL_CALL SDL_GetModState();
00710 #if SDL_VERSION_ATLEAST(1, 3, 0)
00711     keys = SDL_CALL SDL_GetKeyboardState(&numkeys);
00712 #else
00713     keys = SDL_CALL SDL_GetKeyState(&numkeys);
00714 #endif
00715 #if defined(_DEBUG)
00716     if (_shift_pressed)
00717 #else
00718     /* Speedup when pressing tab, except when using ALT+TAB
00719      * to switch to another application */
00720 #if SDL_VERSION_ATLEAST(1, 3, 0)
00721     if (keys[SDL_SCANCODE_TAB] && (mod & KMOD_ALT) == 0)
00722 #else
00723     if (keys[SDLK_TAB] && (mod & KMOD_ALT) == 0)
00724 #endif /* SDL_VERSION_ATLEAST(1, 3, 0) */
00725 #endif /* defined(_DEBUG) */
00726     {
00727       if (!_networking && _game_mode != GM_MENU) _fast_forward |= 2;
00728     } else if (_fast_forward & 2) {
00729       _fast_forward = 0;
00730     }
00731 
00732     cur_ticks = SDL_CALL SDL_GetTicks();
00733     if (cur_ticks >= next_tick || (_fast_forward && !_pause_mode) || cur_ticks < prev_cur_ticks) {
00734       _realtime_tick += cur_ticks - last_cur_ticks;
00735       last_cur_ticks = cur_ticks;
00736       next_tick = cur_ticks + MILLISECONDS_PER_TICK;
00737 
00738       bool old_ctrl_pressed = _ctrl_pressed;
00739 
00740       _ctrl_pressed  = !!(mod & KMOD_CTRL);
00741       _shift_pressed = !!(mod & KMOD_SHIFT);
00742 
00743       /* determine which directional keys are down */
00744       _dirkeys =
00745 #if SDL_VERSION_ATLEAST(1, 3, 0)
00746         (keys[SDL_SCANCODE_LEFT]  ? 1 : 0) |
00747         (keys[SDL_SCANCODE_UP]    ? 2 : 0) |
00748         (keys[SDL_SCANCODE_RIGHT] ? 4 : 0) |
00749         (keys[SDL_SCANCODE_DOWN]  ? 8 : 0);
00750 #else
00751         (keys[SDLK_LEFT]  ? 1 : 0) |
00752         (keys[SDLK_UP]    ? 2 : 0) |
00753         (keys[SDLK_RIGHT] ? 4 : 0) |
00754         (keys[SDLK_DOWN]  ? 8 : 0);
00755 #endif
00756       if (old_ctrl_pressed != _ctrl_pressed) HandleCtrlChanged();
00757 
00758       /* The gameloop is the part that can run asynchronously. The rest
00759        * except sleeping can't. */
00760       if (_draw_threaded) _draw_mutex->EndCritical();
00761 
00762       GameLoop();
00763 
00764       if (_draw_threaded) _draw_mutex->BeginCritical();
00765 
00766       UpdateWindows();
00767       _local_palette = _cur_palette;
00768     } else {
00769       /* Release the thread while sleeping */
00770       if (_draw_threaded) _draw_mutex->EndCritical();
00771       CSleep(1);
00772       if (_draw_threaded) _draw_mutex->BeginCritical();
00773 
00774       NetworkDrawChatMessage();
00775       DrawMouseCursor();
00776     }
00777 
00778     /* End of the critical part. */
00779     if (_draw_threaded && !HasModalProgress()) {
00780       _draw_mutex->SendSignal();
00781     } else {
00782       /* Oh, we didn't have threads, then just draw unthreaded */
00783       CheckPaletteAnim();
00784       DrawSurfaceToScreen();
00785     }
00786   }
00787 
00788   if (_draw_threaded) {
00789     _draw_continue = false;
00790     /* Sending signal if there is no thread blocked
00791      * is very valid and results in noop */
00792     _draw_mutex->SendSignal();
00793     _draw_mutex->EndCritical();
00794     _draw_thread->Join();
00795 
00796     delete _draw_mutex;
00797     delete _draw_thread;
00798   }
00799 }
00800 
00801 bool VideoDriver_SDL::ChangeResolution(int w, int h)
00802 {
00803   if (_draw_threaded) _draw_mutex->BeginCritical();
00804   bool ret = CreateMainSurface(w, h);
00805   if (_draw_threaded) _draw_mutex->EndCritical();
00806   return ret;
00807 }
00808 
00809 bool VideoDriver_SDL::ToggleFullscreen(bool fullscreen)
00810 {
00811   _fullscreen = fullscreen;
00812   GetVideoModes(); // get the list of available video modes
00813   if (_num_resolutions == 0 || !CreateMainSurface(_cur_resolution.width, _cur_resolution.height)) {
00814     /* switching resolution failed, put back full_screen to original status */
00815     _fullscreen ^= true;
00816     return false;
00817   }
00818   return true;
00819 }
00820 
00821 bool VideoDriver_SDL::AfterBlitterChange()
00822 {
00823   return this->ChangeResolution(_screen.width, _screen.height);
00824 }
00825 
00826 #endif /* WITH_SDL */