view src/video/windx5/SDL_dx5events.c @ 4157:baf615f9f2a0 SDL-1.2

Date: Thu, 16 Oct 2008 20:27:34 +0400 From: "Ilya Kasnacheev" <ilya.kasnacheev@gmail.com> To: sdl@lists.libsdl.org Subject: [SDL] SDL for Windows CE: a few GAPI patches Hi *! I've just ported a POWDER roguelike ( http://www.zincland.com/powder/ ) to Windows CE (PDAs, Windows Mobile/Pocket PC). To do that, I had to get libsdl working. Thanks for the awesome project files, it built without a hitch. Nevertheless, I've found quite a few bugs in Windows CE (GAPI) SDL implementation, which I've solved and now present as a serie of patches. I'll try carefully annotate them. Please annotate them so I can work toward accepting them into the main source tree since without them SDL isn't really working on Windows CE (I wonder why nobody fixed them before, btw: why isn't SDL popular as a way to develop Windows CE games? Where are no ports?) These changes can't be considered flawless, but they can be considered working because I've yet to hear complains about things I fixed and POWDER build for Windows CE is now considered stable. Note: my comments start with !!, delete them before applying. diff -bru SDL-1.2.13/src/video/gapi/SDL_gapivideo.c SDL-1.2.13-new/src/video/gapi/SDL_gapivideo.c --- SDL-1.2.13/src/video/gapi/SDL_gapivideo.c 2007-12-31 07:48:00.000000000 +0300 +++ SDL-1.2.13-new/src/video/gapi/SDL_gapivideo.c 2008-10-16 20:02:11.000000000 +0400 @@ -643,6 +643,7 @@ } gapi->userOrientation = SDL_ORIENTATION_UP; + gapi->systemOrientation = SDL_ORIENTATION_UP; video->flags = SDL_FULLSCREEN; /* Clear flags, GAPI supports fullscreen only */ /* GAPI or VGA? */ @@ -661,18 +662,21 @@ } /* detect user landscape mode */ - if( (width > height) && (GetSystemMetrics(SM_CXSCREEN) < GetSystemMetrics(SM_CYSCREEN))) + if( (width > height) && (gapi->gxProperties.cxWidth < gapi->gxProperties.cyHeight)) gapi->userOrientation = SDL_ORIENTATION_RIGHT; + if(GetSystemMetrics(SM_CYSCREEN) < GetSystemMetrics(SM_CXSCREEN)) + gapi->systemOrientation = SDL_ORIENTATION_RIGHT; + /* shall we apply hires fix? for example when we do not use hires resource */ gapi->hiresFix = 0; - if( gapi->userOrientation == SDL_ORIENTATION_RIGHT ) + if( gapi->systemOrientation == gapi->userOrientation ) { - if( (width > GetSystemMetrics(SM_CYSCREEN)) || (height > GetSystemMetrics(SM_CXSCREEN))) + if( (width > GetSystemMetrics(SM_CXSCREEN)) || (height > GetSystemMetrics(SM_CYSCREEN))) gapi->hiresFix = 1; } else - if( (width > GetSystemMetrics(SM_CXSCREEN)) || (height > GetSystemMetrics(SM_CYSCREEN))) - if( !((width == GetSystemMetrics(SM_CYSCREEN)) && (height == GetSystemMetrics(SM_CXSCREEN)))) // user portrait, device landscape + if( (width > GetSystemMetrics(SM_CYSCREEN)) || (height > GetSystemMetrics(SM_CXSCREEN))) +// if( !((width == gapi->gxProperties.cyHeight) && (height == gapi->gxProperties.cxWidth))) // user portrait, device landscape gapi->hiresFix = 1; switch( gapi->userOrientation ) !! It used to query system metrics which return dimensions according to screen !! orientation, which can really be portrait, left landscape or right landscape. !! This is presumably incorrect because we couldn't care less about user mode !! dimensions - all we want are the GAPI framebuffer dimensions, which only match !! user dimensions in one of possible orientations. !! There's a fair dose of cargo cult programming involved in this fix, but it !! used to work only in one orientation (portrait for PDAs, where frame-buffer !! have same orientation as user screen), and now it works on all orientations. @@ -742,21 +746,30 @@ WIN_FlushMessageQueue(); /* Open GAPI display */ - if( !gapi->useVga && this->hidden->useGXOpenDisplay ) + if( !gapi->useVga && this->hidden->useGXOpenDisplay && !this->hidden->alreadyGXOpened ) + { + this->hidden->alreadyGXOpened = 1; if( !gapi->gxFunc.GXOpenDisplay(SDL_Window, GX_FULLSCREEN) ) { SDL_SetError("Couldn't initialize GAPI"); return(NULL); } + } #if REPORT_VIDEO_INFO printf("Video properties:\n"); printf("display bpp: %d\n", gapi->gxProperties.cBPP); printf("display width: %d\n", gapi->gxProperties.cxWidth); printf("display height: %d\n", gapi->gxProperties.cyHeight); + printf("system display width: %d\n", GetSystemMetrics(SM_CXSCREEN)); + printf("system display height: %d\n", GetSystemMetrics(SM_CYSCREEN)); printf("x pitch: %d\n", gapi->gxProperties.cbxPitch); printf("y pitch: %d\n", gapi->gxProperties.cbyPitch); printf("gapi flags: 0x%x\n", gapi->gxProperties.ffFormat); + printf("user orientation: %d\n", gapi->userOrientation); + printf("system orientation: %d\n", gapi->userOrientation); + printf("gapi orientation: %d\n", gapi->gapiOrientation); + if( !gapi->useVga && this->hidden->useGXOpenDisplay && gapi->needUpdate) { !! Previous version used to call gapi->gxFunc.GXOpenDisplay each time the video !! mode would be changed. You shouldn't, because this call has a meaning "Lock the !! GAPI framebuffer, designate it as busy", so the second call will fail (it is !! already locked/busy). !! Testing might not find that because most programs set up the video mode only !! once, but POWDER does this once in a while, so it crashed when in 320x240 mode !! (640x480 mode doesn't use that code, it worked fine). diff -bru SDL-1.2.13/src/video/gapi/SDL_gapivideo.h SDL-1.2.13-new/src/video/gapi/SDL_gapivideo.h --- SDL-1.2.13/src/video/gapi/SDL_gapivideo.h 2007-12-31 07:48:00.000000000 +0300 +++ SDL-1.2.13-new/src/video/gapi/SDL_gapivideo.h 2008-10-16 20:02:11.000000000 +0400 @@ -132,12 +132,17 @@ #define NUM_MODELISTS 4 /* 8, 16, 24, and 32 bits-per-pixel */ int SDL_nummodes[NUM_MODELISTS]; SDL_Rect **SDL_modelist[NUM_MODELISTS]; + // The orientation of the video mode user wants to get + // Probably restricted to UP and RIGHT enum SDL_ScreenOrientation userOrientation; int invert; char hiresFix; // using hires mode without defining hires resource // -------------- int useGXOpenDisplay; /* use GXOpenDispplay */ + int alreadyGXOpened; int w, h; + // The orientation of GAPI framebuffer. + // Never changes on the same device. enum SDL_ScreenOrientation gapiOrientation; void *buffer; // may be 8, 16, 24, 32 bpp @@ -153,6 +158,10 @@ int startOffset; // in bytes int useVga; int suspended; // do not pu anything into video memory + // The orientation of the system, as defined by SM_CXSCREEN and SM_CYSCREEN + // User can change it by using 'screen layout' in system options + // Restricted to UP or RIGHT + enum SDL_ScreenOrientation systemOrientation; }; !! This is a flag variable, see the previous comment !! And yet another orientation: now we have to keep three of them in mind. diff -bru SDL-1.2.13/src/video/wincommon/SDL_sysevents.c SDL-1.2.13-new/src/video/wincommon/SDL_sysevents.c --- SDL-1.2.13/src/video/wincommon/SDL_sysevents.c 2007-12-31 07:48:02.000000000 +0300 +++ SDL-1.2.13-new/src/video/wincommon/SDL_sysevents.c 2008-10-16 20:02:12.000000000 +0400 @@ -160,10 +160,22 @@ #endif */ } break; + // FIXME: Older version used just SDL_VideoSurface->(w, h) + // w and h are "clipped" while x and y are "raw", which caused + // x in former and y in latter case to be clipped in a wrong direction, + // thus offsetting the coordinate on 2 x clip pixels + // (like, 128 for 640 -> 512 clipping). + // We will now try to extract and use raw values. + // The way to do that RIGHT is do (orientation-dependent) clipping before + // doing this transform, but it's hardly possible. + + // SEE SDL_mouse.c /ClipOffset to understand these calculations. case SDL_ORIENTATION_RIGHT: if (!SDL_VideoSurface) break; - rotatedX = SDL_VideoSurface->w - *y; + rotatedX = (2 * ((SDL_VideoSurface->offset%SDL_VideoSurface->pitch)/ + SDL_VideoSurface->format->BytesPerPixel)) + + SDL_VideoSurface->w - *y; rotatedY = *x; *x = rotatedX; *y = rotatedY; @@ -172,7 +184,8 @@ if (!SDL_VideoSurface) break; rotatedX = *y; - rotatedY = SDL_VideoSurface->h - *x; + rotatedY = (2 * (SDL_VideoSurface->offset/SDL_VideoSurface->pitch)) + + SDL_VideoSurface->h - *x; *x = rotatedX; *y = rotatedY; break; !! That's the trickest part, hence the long comment. !! GAPI would really support only 320x240 or 640x480 mode, if application !! requested the different screen size (as POWDER did, wishing 256x192), then SDL !! is going to grab the first mode that fits the requested, and pad the screen !! with black bars (as they do with wide-screen films). !! It would also get, say, 240x320 mode, and to turn it into 256x192 it would !! need to rotate mouse clicks. !! It worked, but one bug slipped through: it would receive mouse clicks !! unpadded, then rotate them, and then pad the black bars. The problem is: rotate !! is done by GAPI driver while padding is done by SDL core. SDL core doesn't know !! anything about rotating, so it would pad one of dimensions incorrectly. I understand that some of my claims (or code) might seem unbacked, but you can always grab the POWDER binary, compile your own libsdl with one or more of those fixes turned off, and see how weird it would misbehave. I can even supply you with those custom builds of libsdl if you don't want to set up the build environment for windows ce, you'll just need a PDA or a smartphone with it. I plan to take care of SDL on Windows CE as long as I maintain the POWDER port. POWDER is good for that because it: Employs both padded (with centered image, black bars) and unpadded (image occupies full screen) graphics; initializes video more than once; uses both 320x240 and 640x480 video; uses both stylus and buttons. There's still a list of unresolved issues which I'm planning to fix: 1) Arrow buttons on PDA return weird scancodes compared to PC, this caused the game to misbehave before I've fixed that. You can see it on those diagrams: http://wrar.name/upload/powder-htc.png http://wrar.name/upload/powder-pda.png 2) SDL (or underlying windows) doesn't care to rotate arrow presses when we're in a low-res GAPI mode, but it will rotate them in VGA mode (because of different screen orientations, the same arrow buttons can suddently mean different directions). Solution: we should stick to GAPI user orientation (the orientation the program supposedly wants) and rotate the keys on our own. _______________________________________________ SDL mailing list SDL@lists.libsdl.org http://lists.libsdl.org/listinfo.cgi/sdl-libsdl.org
author Sam Lantinga <slouken@libsdl.org>
date Fri, 07 Nov 2008 04:15:36 +0000
parents eb2d5480ae95
children c121d94672cb a1b03ba2fcd0
line wrap: on
line source

/*
    SDL - Simple DirectMedia Layer
    Copyright (C) 1997-2006 Sam Lantinga

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Lesser General Public
    License as published by the Free Software Foundation; either
    version 2.1 of the License, or (at your option) any later version.

    This library 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.  See the GNU
    Lesser General Public License for more details.

    You should have received a copy of the GNU Lesser General Public
    License along with this library; if not, write to the Free Software
    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA

    Sam Lantinga
    slouken@libsdl.org
*/
#include "SDL_config.h"

/* CAUTION!!!!  If you modify this file, check ../windib/SDL_sysevents.c */

#include "directx.h"

#include "SDL_main.h"
#include "SDL_events.h"
#include "SDL_video.h"
#include "SDL_syswm.h"
#include "../../events/SDL_sysevents.h"
#include "../../events/SDL_events_c.h"
#include "../wincommon/SDL_lowvideo.h"
#include "SDL_dx5video.h"

#ifndef WM_APP
#define WM_APP	0x8000
#endif

#ifdef _WIN32_WCE
#define NO_GETKEYBOARDSTATE
#endif

/* The keyboard and mouse device input */
#define MAX_INPUTS	16		/* Maximum of 16-1 input devices */
#define INPUT_QSIZE	512		/* Buffer up to 512 input messages */

static LPDIRECTINPUT dinput = NULL;
static LPDIRECTINPUTDEVICE2 SDL_DIdev[MAX_INPUTS];
static HANDLE               SDL_DIevt[MAX_INPUTS];
static void (*SDL_DIfun[MAX_INPUTS])(const int, DIDEVICEOBJECTDATA *);
static int SDL_DIndev = 0;
static int mouse_lost;
static int mouse_pressed;
static int mouse_buttons_swapped = 0;

/* The translation table from a DirectInput scancode to an SDL keysym */
static SDLKey DIK_keymap[256];
static SDL_keysym *TranslateKey(UINT scancode, SDL_keysym *keysym, int pressed);

/* DJM: If the user setup the window for us, we want to save his window proc,
   and give him a chance to handle some messages. */
#ifdef STRICT
#define WNDPROCTYPE	WNDPROC
#else
#define WNDPROCTYPE	FARPROC
#endif
static WNDPROCTYPE userWindowProc = NULL;

static HWND GetTopLevelParent(HWND hWnd)
{
    HWND hParentWnd;
    while (1)
    {
        hParentWnd = GetParent(hWnd);
        if (hParentWnd == NULL)
            break;
        hWnd = hParentWnd;
    }
    return hWnd;
}

/* Convert a DirectInput return code to a text message */
static void SetDIerror(char *function, int code)
{
	static char *error;
	static char  errbuf[1024];

	errbuf[0] = 0;
	switch (code) {
                case DIERR_GENERIC:
                        error = "Undefined error!";
                        break;
		case DIERR_OLDDIRECTINPUTVERSION:
			error = "Your version of DirectInput needs upgrading";
			break;
		case DIERR_INVALIDPARAM:
                        error = "Invalid parameters";
                        break;
                case DIERR_OUTOFMEMORY:
                        error = "Out of memory";
                        break;
		case DIERR_DEVICENOTREG:
			error = "Device not registered";
			break;
		case DIERR_NOINTERFACE:
			error = "Interface not supported";
			break;
		case DIERR_NOTINITIALIZED:
			error = "Device not initialized";
			break;
		default:
			SDL_snprintf(errbuf, SDL_arraysize(errbuf),
			         "%s: Unknown DirectInput error: 0x%x",
								function, code);
			break;
	}
	if ( ! errbuf[0] ) {
		SDL_snprintf(errbuf, SDL_arraysize(errbuf), "%s: %s", function, error);
	}
	SDL_SetError("%s", errbuf);
	return;
}

/* Initialize DirectInput
   Note:  If NONEXCLUSIVE access is requested for the devices, normal 
          windows input messages will continue to be generated for that
          input device, in addition to DirectInput messages.
 */
static void handle_keyboard(const int numevents, DIDEVICEOBJECTDATA *events);
static void handle_mouse(const int numevents, DIDEVICEOBJECTDATA *events);
struct {
	char *name;
	REFGUID guid;
	LPCDIDATAFORMAT format;
	DWORD win_level;
	DWORD raw_level;
	void (*fun)(const int numevents, DIDEVICEOBJECTDATA *events);
} inputs[] = {
	{ "keyboard",
		&GUID_SysKeyboard, &c_dfDIKeyboard,
		(DISCL_FOREGROUND|DISCL_NONEXCLUSIVE),
		(DISCL_FOREGROUND|DISCL_NONEXCLUSIVE), handle_keyboard },
	{ "mouse",
		&GUID_SysMouse, &c_dfDIMouse,
		(DISCL_FOREGROUND|DISCL_NONEXCLUSIVE),
		(DISCL_FOREGROUND|DISCL_EXCLUSIVE), handle_mouse },
	{ NULL, NULL, NULL, 0, 0, NULL }
};
	
static int DX5_DInputInit(_THIS)
{
	int         i;
	LPDIRECTINPUTDEVICE device;
	HRESULT     result;
	DIPROPDWORD dipdw;
	HWND        topwnd;

	/* Create the DirectInput object */
	result = DInputCreate(SDL_Instance, DIRECTINPUT_VERSION,
							&dinput, NULL);
	if ( result != DI_OK ) {
		SetDIerror("DirectInputCreate", result);
		return(-1);
	}

	/* Create all of our registered input devices */
	SDL_DIndev = 0;
	for ( i=0; inputs[i].name; ++i ) {
		/* Create the DirectInput device */
		result = IDirectInput_CreateDevice(dinput, inputs[i].guid,
								&device, NULL);
		if ( result != DI_OK ) {
			SetDIerror("DirectInput::CreateDevice", result);
			return(-1);
		}
		result = IDirectInputDevice_QueryInterface(device,
			&IID_IDirectInputDevice2, (LPVOID *)&SDL_DIdev[i]);
		IDirectInputDevice_Release(device);
		if ( result != DI_OK ) {
			SetDIerror("DirectInputDevice::QueryInterface", result);
			return(-1);
		}
		topwnd =  GetTopLevelParent(SDL_Window);
		result = IDirectInputDevice2_SetCooperativeLevel(SDL_DIdev[i],
					topwnd, inputs[i].win_level);
		if ( result != DI_OK ) {
			SetDIerror("DirectInputDevice::SetCooperativeLevel",
									result);
			return(-1);
		}
		result = IDirectInputDevice2_SetDataFormat(SDL_DIdev[i],
							inputs[i].format);
		if ( result != DI_OK ) {
			SetDIerror("DirectInputDevice::SetDataFormat", result);
			return(-1);
		}

		/* Set buffered input -- we aren't polling */
		SDL_memset(&dipdw, 0, sizeof(dipdw));
		dipdw.diph.dwSize = sizeof(dipdw);
		dipdw.diph.dwHeaderSize = sizeof(dipdw.diph);
		dipdw.diph.dwObj = 0;
		dipdw.diph.dwHow = DIPH_DEVICE;
		dipdw.dwData = INPUT_QSIZE;
		result = IDirectInputDevice2_SetProperty(SDL_DIdev[i],
						DIPROP_BUFFERSIZE, &dipdw.diph);
		if ( result != DI_OK ) {
			SetDIerror("DirectInputDevice::SetProperty", result);
			return(-1);
		}

		/* Create an event to be signaled when input is ready */
		SDL_DIevt[i] = CreateEvent(NULL, FALSE, FALSE, NULL);
		if ( SDL_DIevt[i] == NULL ) {
			SDL_SetError("Couldn't create DirectInput event");
			return(-1);
		}
		result = IDirectInputDevice2_SetEventNotification(SDL_DIdev[i],
								SDL_DIevt[i]);
		if ( result != DI_OK ) {
			SetDIerror("DirectInputDevice::SetEventNotification",
									result);
			return(-1);
		}
		SDL_DIfun[i] = inputs[i].fun;

		/* Acquire the device for input */
		IDirectInputDevice2_Acquire(SDL_DIdev[i]);

		/* Increment the number of devices we have */
		++SDL_DIndev;
	}
	mouse_pressed = 0;
	mouse_buttons_swapped = GetSystemMetrics(SM_SWAPBUTTON);

	/* DirectInput is ready! */
	return(0);
}

/* Clean up DirectInput */
static void DX5_DInputQuit(_THIS)
{
	int i;

	if ( dinput != NULL ) {
		/* Close and release all DirectInput devices */
		for ( i=0; i<MAX_INPUTS; ++i ) {
			if ( SDL_DIdev[i] != NULL ) {
				IDirectInputDevice2_Unacquire(SDL_DIdev[i]);
				IDirectInputDevice2_SetEventNotification(
							SDL_DIdev[i], NULL);
				if ( SDL_DIevt[i] != NULL ) {
					CloseHandle(SDL_DIevt[i]);
					SDL_DIevt[i] = NULL;
				}
				IDirectInputDevice2_Release(SDL_DIdev[i]);
				SDL_DIdev[i] = NULL;
			}
		}
		/* Release DirectInput */
		IDirectInput_Release(dinput);
		dinput = NULL;
	}
}

/* Flag to tell SDL whether or not we queued an event */
static int posted = 0;

/* Input event handler functions */
static void handle_keyboard(const int numevents, DIDEVICEOBJECTDATA *keybuf)
{
	int i;
	SDL_keysym keysym;

	/* Translate keyboard messages */
	for ( i=0; i<numevents; ++i ) {
		if ( keybuf[i].dwData & 0x80 ) {
			posted = SDL_PrivateKeyboard(SDL_PRESSED,
				    TranslateKey(keybuf[i].dwOfs, &keysym, 1));
		} else {
			posted = SDL_PrivateKeyboard(SDL_RELEASED,
				    TranslateKey(keybuf[i].dwOfs, &keysym, 0));
		}
	}
}
static void handle_mouse(const int numevents, DIDEVICEOBJECTDATA *ptrbuf)
{
	int i;
	Sint16 xrel, yrel;
	Uint8 state;
	Uint8 button;
	DWORD timestamp = 0;

	/* Sanity check. Mailing list reports this being NULL unexpectedly. */
	if (SDL_PublicSurface == NULL) {
		return;
	}

	/* If we are in windowed mode, Windows is taking care of the mouse */
	if (  (SDL_PublicSurface->flags & SDL_OPENGL) ||
	     !(SDL_PublicSurface->flags & SDL_FULLSCREEN) ) {
		return;
	}

	/* If the mouse was lost, regain some sense of mouse state */
	if ( mouse_lost ) {
		POINT mouse_pos;
		Uint8 old_state;
		Uint8 new_state;

		/* Set ourselves up with the current cursor position */
		GetCursorPos(&mouse_pos);
		ScreenToClient(SDL_Window, &mouse_pos);
		posted = SDL_PrivateMouseMotion(0, 0,
				(Sint16)mouse_pos.x, (Sint16)mouse_pos.y);

		/* Check for mouse button changes */
		old_state = SDL_GetMouseState(NULL, NULL);
		new_state = 0;
		{ /* Get the new DirectInput button state for the mouse */
			DIMOUSESTATE distate;
			HRESULT result;

			result=IDirectInputDevice2_GetDeviceState(SDL_DIdev[1],
						sizeof(distate), &distate);
			if ( result != DI_OK ) {
				/* Try again next time */
				SetDIerror(
				"IDirectInputDevice2::GetDeviceState", result);
				return;
			}
			for ( i=3; i>=0; --i ) {
				if ( (distate.rgbButtons[i]&0x80) == 0x80 ) {
					new_state |= 0x01;
				}
				new_state <<= 1;
			}
		}
		for ( i=0; i<8; ++i ) {
			if ( (old_state&0x01) != (new_state&0x01) ) {
				button = (Uint8)(i+1);
				/* Button #2 on two button mice is button 3
				   (the middle button is button 2)
				 */
				if ( button == 2 ) {
					button = 3;
				} else
				if ( button == 3 ) {
					button = 2;
				}
				if ( new_state & 0x01 ) {
					/* Grab mouse so we get mouse-up */
					if ( ++mouse_pressed > 0 ) {
						SetCapture(SDL_Window);
					}
					state = SDL_PRESSED;
				} else {
					/* Release mouse after all mouse-ups */
					if ( --mouse_pressed <= 0 ) {
						ReleaseCapture();
						mouse_pressed = 0;
					}
					state = SDL_RELEASED;
				}
				if ( mouse_buttons_swapped ) {
					if ( button == 1 ) button = 3;
					else
					if ( button == 3 ) button = 1;
				}
				posted = SDL_PrivateMouseButton(state, button,
									0, 0);
			}
			old_state >>= 1;
			new_state >>= 1;
		}
		mouse_lost = 0;
		return;
	}

	/* Translate mouse messages */
	xrel = 0;
	yrel = 0;
	for ( i=0; i<(int)numevents; ++i ) {
		switch (ptrbuf[i].dwOfs) {
			case DIMOFS_X:
				if ( timestamp != ptrbuf[i].dwTimeStamp ) {
					if ( xrel || yrel ) {
						posted = SDL_PrivateMouseMotion(
								0, 1, xrel, yrel);
						xrel = 0;
						yrel = 0;
					}
					timestamp = ptrbuf[i].dwTimeStamp;
				}
				xrel += (Sint16)ptrbuf[i].dwData;
				break;
			case DIMOFS_Y:
				if ( timestamp != ptrbuf[i].dwTimeStamp ) {
					if ( xrel || yrel ) {
						posted = SDL_PrivateMouseMotion(
								0, 1, xrel, yrel);
						xrel = 0;
						yrel = 0;
					}
					timestamp = ptrbuf[i].dwTimeStamp;
				}
				yrel += (Sint16)ptrbuf[i].dwData;
				break;
			case DIMOFS_Z:
				if ( xrel || yrel ) {
					posted = SDL_PrivateMouseMotion(
							0, 1, xrel, yrel);
					xrel = 0;
					yrel = 0;
				}
				timestamp = 0;
				if((int)ptrbuf[i].dwData > 0)
					button = SDL_BUTTON_WHEELUP;
				else
					button = SDL_BUTTON_WHEELDOWN;
				posted = SDL_PrivateMouseButton(
						SDL_PRESSED, button, 0, 0);
				posted |= SDL_PrivateMouseButton(
						SDL_RELEASED, button, 0, 0);
				break;
			case DIMOFS_BUTTON0:
			case DIMOFS_BUTTON1:
			case DIMOFS_BUTTON2:
			case DIMOFS_BUTTON3:
				if ( xrel || yrel ) {
					posted = SDL_PrivateMouseMotion(
							0, 1, xrel, yrel);
					xrel = 0;
					yrel = 0;
				}
				timestamp = 0;
				button = (Uint8)(ptrbuf[i].dwOfs-DIMOFS_BUTTON0)+1;
				/* Button #2 on two button mice is button 3
				   (the middle button is button 2)
				 */
				if ( button == 2 ) {
					button = 3;
				} else
				if ( button == 3 ) {
					button = 2;
				}
				if ( ptrbuf[i].dwData & 0x80 ) {
					/* Grab mouse so we get mouse-up */
					if ( ++mouse_pressed > 0 ) {
						SetCapture(SDL_Window);
					}
					state = SDL_PRESSED;
				} else {
					/* Release mouse after all mouse-ups */
					if ( --mouse_pressed <= 0 ) {
						ReleaseCapture();
						mouse_pressed = 0;
					}
					state = SDL_RELEASED;
				}
				if ( mouse_buttons_swapped ) {
					if ( button == 1 ) button = 3;
					else
					if ( button == 3 ) button = 1;
				}
				posted = SDL_PrivateMouseButton(state, button,
									0, 0);
				break;
		}
	}
	if ( xrel || yrel ) {
		posted = SDL_PrivateMouseMotion( 0, 1, xrel, yrel);
	}
}

/* The main Win32 event handler */
LRESULT DX5_HandleMessage(_THIS, HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
	switch (msg) {
#ifdef WM_ACTIVATEAPP
		case WM_ACTIVATEAPP: {
			int i, active;

			active = (wParam && (GetForegroundWindow() == hwnd));
			if ( active ) {
				for ( i=0; SDL_DIdev[i]; ++i ) {
					IDirectInputDevice2_Acquire(
								SDL_DIdev[i]);
				}
			} else {
				for ( i=0; SDL_DIdev[i]; ++i ) {
					IDirectInputDevice2_Unacquire(
								SDL_DIdev[i]);
				}
				mouse_lost = 1;
			}
		}
		break;
#endif /* WM_ACTIVATEAPP */

#ifdef WM_DISPLAYCHANGE
		case WM_DISPLAYCHANGE: {
			WPARAM BitsPerPixel;
			WORD SizeX, SizeY;

			/* Ack!  The display changed size and/or depth! */
			SizeX = LOWORD(lParam);
			SizeY = HIWORD(lParam);
			BitsPerPixel = wParam;
			/* We cause this message when we go fullscreen */
		}
		break;
#endif /* WM_DISPLAYCHANGE */

		/* The keyboard is handled via DirectInput */
		case WM_SYSKEYUP:
		case WM_SYSKEYDOWN: {
			/* Pass syskey to DefWindwoProc (ALT-F4, etc.) */
		}
		break;
		case WM_KEYUP:
		case WM_KEYDOWN: {
			/* Ignore windows keyboard messages */;
		}
		return(0);

#if defined(SC_SCREENSAVE) || defined(SC_MONITORPOWER)
		/* Don't allow screen savers or monitor power downs.
		   This is because they quietly clear DirectX surfaces.
		   It would be better to allow the application to
		   decide whether or not to blow these off, but the
		   semantics of SDL_PrivateSysWMEvent() don't allow
		   the application that choice.
		 */
		case WM_SYSCOMMAND: {
			if ((wParam&0xFFF0)==SC_SCREENSAVE || 
			    (wParam&0xFFF0)==SC_MONITORPOWER)
				return(0);
		}
		/* Fall through to default processing */

#endif /* SC_SCREENSAVE || SC_MONITORPOWER */

		default: {
			/* Only post the event if we're watching for it */
			if ( SDL_ProcessEvents[SDL_SYSWMEVENT] == SDL_ENABLE ) {
			        SDL_SysWMmsg wmmsg;

				SDL_VERSION(&wmmsg.version);
				wmmsg.hwnd = hwnd;
				wmmsg.msg = msg;
				wmmsg.wParam = wParam;
				wmmsg.lParam = lParam;
				posted = SDL_PrivateSysWMEvent(&wmmsg);

			/* DJM: If the user isn't watching for private
				messages in her SDL event loop, then pass it
				along to any win32 specific window proc.
			 */
			} else if (userWindowProc) {
				return CallWindowProc(userWindowProc, hwnd, msg, wParam, lParam);
			}
		}
		break;
	}
	return(DefWindowProc(hwnd, msg, wParam, lParam));
}

/* This function checks the windows message queue and DirectInput and returns
   1 if there was input, 0 if there was no input, or -1 if the application has
   posted a quit message.
*/
static int DX5_CheckInput(_THIS, int timeout, BOOL processInput)
{
	MSG msg;
	int      i;
	HRESULT  result;
	DWORD    event;

	/* Check the normal windows queue (highest preference) */
	posted = 0;
	while ( ! posted &&
	        PeekMessage(&msg, NULL, 0, 0, PM_NOREMOVE) ) {
		if ( GetMessage(&msg, NULL, 0, 0) > 0 ) {
			DispatchMessage(&msg);
		} else {
			return(-1);
		}
	}
	if ( posted ) {
		return(1);
	}

	/* Pump the DirectInput flow */
	if ( SDL_GetAppState() & SDL_APPINPUTFOCUS ) {
		for ( i=0; i<SDL_DIndev; ++i ) {
			result = IDirectInputDevice2_Poll(SDL_DIdev[i]);
			if ( (result == DIERR_INPUTLOST) ||
					(result == DIERR_NOTACQUIRED) ) {
				if ( SDL_strcmp(inputs[i].name, "mouse") == 0 ) {
					mouse_lost = 1;
				}
				IDirectInputDevice2_Acquire(SDL_DIdev[i]);
				IDirectInputDevice2_Poll(SDL_DIdev[i]);
			}
		}
	}

	/* Wait for messages and input events */
	event = MsgWaitForMultipleObjects(SDL_DIndev, SDL_DIevt, FALSE,
							timeout, QS_ALLEVENTS);
	if ((event >= WAIT_OBJECT_0) && (event < (WAIT_OBJECT_0+SDL_DIndev))) {
		DWORD numevents;
		static DIDEVICEOBJECTDATA evtbuf[INPUT_QSIZE];

		event -= WAIT_OBJECT_0;
		numevents = INPUT_QSIZE;
		result = IDirectInputDevice2_GetDeviceData(
				SDL_DIdev[event], sizeof(DIDEVICEOBJECTDATA),
							evtbuf, &numevents, 0);
		if ( (result == DIERR_INPUTLOST) ||
					(result == DIERR_NOTACQUIRED) ) {
			if ( SDL_strcmp(inputs[event].name, "mouse") == 0 ) {
				mouse_lost = 1;
			}
			IDirectInputDevice2_Acquire(SDL_DIdev[event]);
			result = IDirectInputDevice2_GetDeviceData(
				SDL_DIdev[event], sizeof(DIDEVICEOBJECTDATA),
							evtbuf, &numevents, 0);
		}
		/* Handle the events */
		if ( result == DI_OK && processInput ) {
			/* Note: This can post multiple events to event queue
			 */
			(*SDL_DIfun[event])((int)numevents, evtbuf);
			return(1);
		}
	}
	if ( event != WAIT_TIMEOUT ) {
		/* Maybe there was a windows message? */
		if ( PeekMessage(&msg, NULL, 0, 0, PM_NOREMOVE) ) {
			if ( GetMessage(&msg, NULL, 0, 0) > 0 ) {
				DispatchMessage(&msg);
			} else {
				return(-1);
			}
			return(1);
		}
	}
	return(0);
}

/* Change cooperative level based on whether or not we are fullscreen */
void DX5_DInputReset(_THIS, int fullscreen)
{
	DWORD level;
	int i;
	HRESULT result;
	HWND topwnd;

	for ( i=0; i<MAX_INPUTS; ++i ) {
		if ( SDL_DIdev[i] != NULL ) {
			if ( fullscreen ) {
				level = inputs[i].raw_level;
			} else {
				level = inputs[i].win_level;
			}
			IDirectInputDevice2_Unacquire(SDL_DIdev[i]);
			topwnd = GetTopLevelParent(SDL_Window);
			result = IDirectInputDevice2_SetCooperativeLevel(
					SDL_DIdev[i], topwnd, level);
			IDirectInputDevice2_Acquire(SDL_DIdev[i]);
			if ( result != DI_OK ) {
				SetDIerror(
			"DirectInputDevice::SetCooperativeLevel", result);
			}
		}
	}
	mouse_lost = 1;

	/* Flush pending input */
	DX5_CheckInput(this, 0, FALSE);
}

void DX5_PumpEvents(_THIS)
{
	/* Wait for messages and DirectInput */
	while ( DX5_CheckInput(this, 0, TRUE) > 0 ) {
		/* Loop and check again */;
	}
}

void DX5_InitOSKeymap(_THIS)
{
#ifndef DIK_PAUSE
#define DIK_PAUSE	0xC5
#endif
#ifndef DIK_OEM_102
#define DIK_OEM_102	0x56	/* < > | on UK/Germany keyboards */
#endif
	int i;

	/* Map the DIK scancodes to SDL keysyms */
	for ( i=0; i<SDL_arraysize(DIK_keymap); ++i )
		DIK_keymap[i] = 0;

	/* Defined DIK_* constants */
	DIK_keymap[DIK_ESCAPE] = SDLK_ESCAPE;
	DIK_keymap[DIK_1] = SDLK_1;
	DIK_keymap[DIK_2] = SDLK_2;
	DIK_keymap[DIK_3] = SDLK_3;
	DIK_keymap[DIK_4] = SDLK_4;
	DIK_keymap[DIK_5] = SDLK_5;
	DIK_keymap[DIK_6] = SDLK_6;
	DIK_keymap[DIK_7] = SDLK_7;
	DIK_keymap[DIK_8] = SDLK_8;
	DIK_keymap[DIK_9] = SDLK_9;
	DIK_keymap[DIK_0] = SDLK_0;
	DIK_keymap[DIK_MINUS] = SDLK_MINUS;
	DIK_keymap[DIK_EQUALS] = SDLK_EQUALS;
	DIK_keymap[DIK_BACK] = SDLK_BACKSPACE;
	DIK_keymap[DIK_TAB] = SDLK_TAB;
	DIK_keymap[DIK_Q] = SDLK_q;
	DIK_keymap[DIK_W] = SDLK_w;
	DIK_keymap[DIK_E] = SDLK_e;
	DIK_keymap[DIK_R] = SDLK_r;
	DIK_keymap[DIK_T] = SDLK_t;
	DIK_keymap[DIK_Y] = SDLK_y;
	DIK_keymap[DIK_U] = SDLK_u;
	DIK_keymap[DIK_I] = SDLK_i;
	DIK_keymap[DIK_O] = SDLK_o;
	DIK_keymap[DIK_P] = SDLK_p;
	DIK_keymap[DIK_LBRACKET] = SDLK_LEFTBRACKET;
	DIK_keymap[DIK_RBRACKET] = SDLK_RIGHTBRACKET;
	DIK_keymap[DIK_RETURN] = SDLK_RETURN;
	DIK_keymap[DIK_LCONTROL] = SDLK_LCTRL;
	DIK_keymap[DIK_A] = SDLK_a;
	DIK_keymap[DIK_S] = SDLK_s;
	DIK_keymap[DIK_D] = SDLK_d;
	DIK_keymap[DIK_F] = SDLK_f;
	DIK_keymap[DIK_G] = SDLK_g;
	DIK_keymap[DIK_H] = SDLK_h;
	DIK_keymap[DIK_J] = SDLK_j;
	DIK_keymap[DIK_K] = SDLK_k;
	DIK_keymap[DIK_L] = SDLK_l;
	DIK_keymap[DIK_SEMICOLON] = SDLK_SEMICOLON;
	DIK_keymap[DIK_APOSTROPHE] = SDLK_QUOTE;
	DIK_keymap[DIK_GRAVE] = SDLK_BACKQUOTE;
	DIK_keymap[DIK_LSHIFT] = SDLK_LSHIFT;
	DIK_keymap[DIK_BACKSLASH] = SDLK_BACKSLASH;
	DIK_keymap[DIK_OEM_102] = SDLK_LESS;
	DIK_keymap[DIK_Z] = SDLK_z;
	DIK_keymap[DIK_X] = SDLK_x;
	DIK_keymap[DIK_C] = SDLK_c;
	DIK_keymap[DIK_V] = SDLK_v;
	DIK_keymap[DIK_B] = SDLK_b;
	DIK_keymap[DIK_N] = SDLK_n;
	DIK_keymap[DIK_M] = SDLK_m;
	DIK_keymap[DIK_COMMA] = SDLK_COMMA;
	DIK_keymap[DIK_PERIOD] = SDLK_PERIOD;
	DIK_keymap[DIK_SLASH] = SDLK_SLASH;
	DIK_keymap[DIK_RSHIFT] = SDLK_RSHIFT;
	DIK_keymap[DIK_MULTIPLY] = SDLK_KP_MULTIPLY;
	DIK_keymap[DIK_LMENU] = SDLK_LALT;
	DIK_keymap[DIK_SPACE] = SDLK_SPACE;
	DIK_keymap[DIK_CAPITAL] = SDLK_CAPSLOCK;
	DIK_keymap[DIK_F1] = SDLK_F1;
	DIK_keymap[DIK_F2] = SDLK_F2;
	DIK_keymap[DIK_F3] = SDLK_F3;
	DIK_keymap[DIK_F4] = SDLK_F4;
	DIK_keymap[DIK_F5] = SDLK_F5;
	DIK_keymap[DIK_F6] = SDLK_F6;
	DIK_keymap[DIK_F7] = SDLK_F7;
	DIK_keymap[DIK_F8] = SDLK_F8;
	DIK_keymap[DIK_F9] = SDLK_F9;
	DIK_keymap[DIK_F10] = SDLK_F10;
	DIK_keymap[DIK_NUMLOCK] = SDLK_NUMLOCK;
	DIK_keymap[DIK_SCROLL] = SDLK_SCROLLOCK;
	DIK_keymap[DIK_NUMPAD7] = SDLK_KP7;
	DIK_keymap[DIK_NUMPAD8] = SDLK_KP8;
	DIK_keymap[DIK_NUMPAD9] = SDLK_KP9;
	DIK_keymap[DIK_SUBTRACT] = SDLK_KP_MINUS;
	DIK_keymap[DIK_NUMPAD4] = SDLK_KP4;
	DIK_keymap[DIK_NUMPAD5] = SDLK_KP5;
	DIK_keymap[DIK_NUMPAD6] = SDLK_KP6;
	DIK_keymap[DIK_ADD] = SDLK_KP_PLUS;
	DIK_keymap[DIK_NUMPAD1] = SDLK_KP1;
	DIK_keymap[DIK_NUMPAD2] = SDLK_KP2;
	DIK_keymap[DIK_NUMPAD3] = SDLK_KP3;
	DIK_keymap[DIK_NUMPAD0] = SDLK_KP0;
	DIK_keymap[DIK_DECIMAL] = SDLK_KP_PERIOD;
	DIK_keymap[DIK_F11] = SDLK_F11;
	DIK_keymap[DIK_F12] = SDLK_F12;

	DIK_keymap[DIK_F13] = SDLK_F13;
	DIK_keymap[DIK_F14] = SDLK_F14;
	DIK_keymap[DIK_F15] = SDLK_F15;

	DIK_keymap[DIK_NUMPADEQUALS] = SDLK_KP_EQUALS;
	DIK_keymap[DIK_NUMPADENTER] = SDLK_KP_ENTER;
	DIK_keymap[DIK_RCONTROL] = SDLK_RCTRL;
	DIK_keymap[DIK_DIVIDE] = SDLK_KP_DIVIDE;
	DIK_keymap[DIK_SYSRQ] = SDLK_PRINT;
	DIK_keymap[DIK_RMENU] = SDLK_RALT;
	DIK_keymap[DIK_PAUSE] = SDLK_PAUSE;
	DIK_keymap[DIK_HOME] = SDLK_HOME;
	DIK_keymap[DIK_UP] = SDLK_UP;
	DIK_keymap[DIK_PRIOR] = SDLK_PAGEUP;
	DIK_keymap[DIK_LEFT] = SDLK_LEFT;
	DIK_keymap[DIK_RIGHT] = SDLK_RIGHT;
	DIK_keymap[DIK_END] = SDLK_END;
	DIK_keymap[DIK_DOWN] = SDLK_DOWN;
	DIK_keymap[DIK_NEXT] = SDLK_PAGEDOWN;
	DIK_keymap[DIK_INSERT] = SDLK_INSERT;
	DIK_keymap[DIK_DELETE] = SDLK_DELETE;
	DIK_keymap[DIK_LWIN] = SDLK_LMETA;
	DIK_keymap[DIK_RWIN] = SDLK_RMETA;
	DIK_keymap[DIK_APPS] = SDLK_MENU;
}

static SDL_keysym *TranslateKey(UINT scancode, SDL_keysym *keysym, int pressed)
{
	/* Set the keysym information */
	keysym->scancode = (unsigned char)scancode;
	keysym->sym = DIK_keymap[scancode];
	keysym->mod = KMOD_NONE;
	keysym->unicode = 0;
	if ( pressed && SDL_TranslateUNICODE ) {
		UINT vkey;
#ifndef NO_GETKEYBOARDSTATE
		BYTE	keystate[256];
		Uint16	wchars[2];
#endif

		vkey = MapVirtualKey(scancode, 1);
#ifdef NO_GETKEYBOARDSTATE
		/* Uh oh, better hope the vkey is close enough.. */
		keysym->unicode = vkey;
#else
		GetKeyboardState(keystate);
		if (SDL_ToUnicode(vkey, scancode, keystate, wchars, sizeof(wchars)/sizeof(wchars[0]), 0) == 1)
		{
			keysym->unicode = wchars[0];
		}
#endif /* NO_GETKEYBOARDSTATE */
	}
	return(keysym);
}

int DX5_CreateWindow(_THIS)
{
	char *windowid = SDL_getenv("SDL_WINDOWID");
	int i;

	/* Clear out DirectInput variables in case we fail */
	for ( i=0; i<MAX_INPUTS; ++i ) {
		SDL_DIdev[i] = NULL;
		SDL_DIevt[i] = NULL;
		SDL_DIfun[i] = NULL;
	}

	SDL_RegisterApp(NULL, 0, 0);

	SDL_windowid = (windowid != NULL);
	if ( SDL_windowid ) {
		SDL_Window = (HWND)SDL_strtoull(windowid, NULL, 0);
		if ( SDL_Window == NULL ) {
			SDL_SetError("Couldn't get user specified window");
			return(-1);
		}

		/* DJM: we want all event's for the user specified
			window to be handled by SDL.
		 */
		userWindowProc = (WNDPROCTYPE)GetWindowLongPtr(SDL_Window, GWLP_WNDPROC);
		SetWindowLongPtr(SDL_Window, GWLP_WNDPROC, (LONG_PTR)WinMessage);
	} else {
		SDL_Window = CreateWindow(SDL_Appname, SDL_Appname,
                        (WS_OVERLAPPED|WS_CAPTION|WS_SYSMENU|WS_MINIMIZEBOX),
                        CW_USEDEFAULT, CW_USEDEFAULT, 0, 0, NULL, NULL, SDL_Instance, NULL);
		if ( SDL_Window == NULL ) {
			SDL_SetError("Couldn't create window");
			return(-1);
		}
		ShowWindow(SDL_Window, SW_HIDE);
	}

	/* Initialize DirectInput */
	if ( DX5_DInputInit(this) < 0 ) {
		return(-1);
	}

	/* JC 14 Mar 2006
		Flush the message loop or this can cause big problems later
		Especially if the user decides to use dialog boxes or assert()!
	*/
	WIN_FlushMessageQueue();

	/* Ready to roll */
	return(0);
}

void DX5_DestroyWindow(_THIS)
{
	/* Close down DirectInput */
	DX5_DInputQuit(this);

	/* Destroy our window */
	if ( SDL_windowid ) {
		SetWindowLongPtr(SDL_Window, GWLP_WNDPROC, (LONG_PTR)userWindowProc);
	} else {
		DestroyWindow(SDL_Window);
	}
	SDL_UnregisterApp();

	/* JC 14 Mar 2006
		Flush the message loop or this can cause big problems later
		Especially if the user decides to use dialog boxes or assert()!
	*/
	WIN_FlushMessageQueue();
}