bus_sdl.c 38.5 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
/*
 * Plug and Play support for hid devices found through SDL2
 *
 * Copyright 2017 CodeWeavers, Aric Stewart
 *
 * 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
 */

#include "config.h"
22
#include "wine/port.h"
23 24 25 26
#include <errno.h>
#include <fcntl.h>
#include <stdarg.h>
#include <stdlib.h>
27 28 29 30 31 32
#ifdef HAVE_UNISTD_H
# include <unistd.h>
#endif
#ifdef HAVE_SDL2_SDL_H
# include <SDL2/SDL.h>
#endif
33 34 35 36 37 38 39 40

#define NONAMELESSUNION

#include "ntstatus.h"
#define WIN32_NO_STATUS
#include "windef.h"
#include "winbase.h"
#include "winnls.h"
41
#include "winreg.h"
42 43
#include "winternl.h"
#include "ddk/wdm.h"
44 45
#include "ddk/hidtypes.h"
#include "wine/library.h"
46
#include "wine/debug.h"
47 48
#include "wine/unicode.h"
#include "hidusage.h"
49
#include "controller.h"
50 51 52 53 54 55

#ifdef WORDS_BIGENDIAN
# define LE_WORD(x) RtlUshortByteSwap(x)
#else
# define LE_WORD(x) (x)
#endif
56 57 58 59 60 61 62

#include "bus.h"

WINE_DEFAULT_DEBUG_CHANNEL(plugplay);

#ifdef SONAME_LIBSDL2

63 64 65 66
WINE_DECLARE_DEBUG_CHANNEL(hid_report);

static const WCHAR sdl_busidW[] = {'S','D','L','J','O','Y',0};

67 68
static DWORD map_controllers = 0;

69
static void *sdl_handle = NULL;
70 71
static HANDLE deviceloop_handle;
static UINT quit_event = -1;
72 73 74 75 76

#ifdef SONAME_LIBSDL2
#define MAKE_FUNCPTR(f) static typeof(f) * p##f = NULL
MAKE_FUNCPTR(SDL_GetError);
MAKE_FUNCPTR(SDL_Init);
77
MAKE_FUNCPTR(SDL_JoystickClose);
78 79 80 81 82 83 84 85
MAKE_FUNCPTR(SDL_JoystickEventState);
MAKE_FUNCPTR(SDL_JoystickGetGUID);
MAKE_FUNCPTR(SDL_JoystickGetGUIDString);
MAKE_FUNCPTR(SDL_JoystickInstanceID);
MAKE_FUNCPTR(SDL_JoystickName);
MAKE_FUNCPTR(SDL_JoystickNumAxes);
MAKE_FUNCPTR(SDL_JoystickOpen);
MAKE_FUNCPTR(SDL_WaitEvent);
86 87 88
MAKE_FUNCPTR(SDL_JoystickNumButtons);
MAKE_FUNCPTR(SDL_JoystickNumBalls);
MAKE_FUNCPTR(SDL_JoystickNumHats);
89 90
MAKE_FUNCPTR(SDL_JoystickGetAxis);
MAKE_FUNCPTR(SDL_JoystickGetHat);
91
MAKE_FUNCPTR(SDL_IsGameController);
92
MAKE_FUNCPTR(SDL_GameControllerClose);
93
MAKE_FUNCPTR(SDL_GameControllerGetAxis);
94
MAKE_FUNCPTR(SDL_GameControllerGetButton);
95 96 97
MAKE_FUNCPTR(SDL_GameControllerName);
MAKE_FUNCPTR(SDL_GameControllerOpen);
MAKE_FUNCPTR(SDL_GameControllerEventState);
98 99 100 101 102 103 104 105 106 107 108 109
MAKE_FUNCPTR(SDL_HapticClose);
MAKE_FUNCPTR(SDL_HapticDestroyEffect);
MAKE_FUNCPTR(SDL_HapticNewEffect);
MAKE_FUNCPTR(SDL_HapticOpenFromJoystick);
MAKE_FUNCPTR(SDL_HapticQuery);
MAKE_FUNCPTR(SDL_HapticRumbleInit);
MAKE_FUNCPTR(SDL_HapticRumblePlay);
MAKE_FUNCPTR(SDL_HapticRumbleSupported);
MAKE_FUNCPTR(SDL_HapticRunEffect);
MAKE_FUNCPTR(SDL_HapticStopAll);
MAKE_FUNCPTR(SDL_JoystickIsHaptic);
MAKE_FUNCPTR(SDL_memset);
110
MAKE_FUNCPTR(SDL_GameControllerAddMapping);
111 112
MAKE_FUNCPTR(SDL_RegisterEvents);
MAKE_FUNCPTR(SDL_PushEvent);
113 114 115 116 117 118 119 120
#endif
static Uint16 (*pSDL_JoystickGetProduct)(SDL_Joystick * joystick);
static Uint16 (*pSDL_JoystickGetProductVersion)(SDL_Joystick * joystick);
static Uint16 (*pSDL_JoystickGetVendor)(SDL_Joystick * joystick);

struct platform_private
{
    SDL_Joystick *sdl_joystick;
121
    SDL_GameController *sdl_controller;
122
    SDL_JoystickID id;
123

124
    int button_start;
125 126
    int axis_start;
    int ball_start;
127
    int hat_bit_offs; /* hatswitches are reported in the same bytes as buttons */
128 129 130

    int report_descriptor_size;
    BYTE *report_descriptor;
131 132 133

    int buffer_length;
    BYTE *report_buffer;
134 135 136

    SDL_Haptic *sdl_haptic;
    int haptic_effect_id;
137 138 139 140 141 142 143
};

static inline struct platform_private *impl_from_DEVICE_OBJECT(DEVICE_OBJECT *device)
{
    return (struct platform_private *)get_platform_private(device);
}

144
static const BYTE REPORT_AXIS_TAIL[] = {
145 146 147 148
    0x17, 0x00, 0x00, 0x00, 0x00,   /* LOGICAL_MINIMUM (0) */
    0x27, 0xff, 0xff, 0x00, 0x00,   /* LOGICAL_MAXIMUM (65535) */
    0x37, 0x00, 0x00, 0x00, 0x00,   /* PHYSICAL_MINIMUM (0) */
    0x47, 0xff, 0xff, 0x00, 0x00,   /* PHYSICAL_MAXIMUM (65535) */
149 150 151 152
    0x75, 0x10,         /* REPORT_SIZE (16) */
    0x95, 0x00,         /* REPORT_COUNT (?) */
    0x81, 0x02,         /* INPUT (Data,Var,Abs) */
};
153
#define IDX_ABS_AXIS_COUNT 23
154

155
#define CONTROLLER_NUM_BUTTONS 11
156

157 158 159
static const BYTE CONTROLLER_BUTTONS[] = {
    0x05, 0x09, /* USAGE_PAGE (Button) */
    0x19, 0x01, /* USAGE_MINIMUM (Button 1) */
160
    0x29, CONTROLLER_NUM_BUTTONS, /* USAGE_MAXIMUM (Button 11) */
161 162 163 164
    0x15, 0x00, /* LOGICAL_MINIMUM (0) */
    0x25, 0x01, /* LOGICAL_MAXIMUM (1) */
    0x35, 0x00, /* LOGICAL_MINIMUM (0) */
    0x45, 0x01, /* LOGICAL_MAXIMUM (1) */
165
    0x95, CONTROLLER_NUM_BUTTONS, /* REPORT_COUNT (11) */
166 167 168 169 170 171 172 173 174 175
    0x75, 0x01, /* REPORT_SIZE (1) */
    0x81, 0x02, /* INPUT (Data,Var,Abs) */
};

static const BYTE CONTROLLER_AXIS [] = {
    0x05, 0x01,         /* USAGE_PAGE (Generic Desktop) */
    0x09, 0x30,         /* USAGE (X) */
    0x09, 0x31,         /* USAGE (Y) */
    0x09, 0x33,         /* USAGE (RX) */
    0x09, 0x34,         /* USAGE (RY) */
176 177 178 179
    0x17, 0x00, 0x00, 0x00, 0x00,   /* LOGICAL_MINIMUM (0) */
    0x27, 0xff, 0xff, 0x00, 0x00,   /* LOGICAL_MAXIMUM (65535) */
    0x37, 0x00, 0x00, 0x00, 0x00,   /* PHYSICAL_MINIMUM (0) */
    0x47, 0xff, 0xff, 0x00, 0x00,   /* PHYSICAL_MAXIMUM (65535) */
180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197
    0x75, 0x10,         /* REPORT_SIZE (16) */
    0x95, 0x04,         /* REPORT_COUNT (4) */
    0x81, 0x02,         /* INPUT (Data,Var,Abs) */
};

static const BYTE CONTROLLER_TRIGGERS [] = {
    0x05, 0x01,         /* USAGE_PAGE (Generic Desktop) */
    0x09, 0x32,         /* USAGE (Z) */
    0x09, 0x35,         /* USAGE (RZ) */
    0x16, 0x00, 0x00,   /* LOGICAL_MINIMUM (0) */
    0x26, 0xff, 0x7f,   /* LOGICAL_MAXIMUM (32767) */
    0x36, 0x00, 0x00,   /* PHYSICAL_MINIMUM (0) */
    0x46, 0xff, 0x7f,   /* PHYSICAL_MAXIMUM (32767) */
    0x75, 0x10,         /* REPORT_SIZE (16) */
    0x95, 0x02,         /* REPORT_COUNT (2) */
    0x81, 0x02,         /* INPUT (Data,Var,Abs) */
};

198 199
#define CONTROLLER_NUM_AXES 6

200 201
#define CONTROLLER_NUM_HATSWITCHES 1

202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223
static const BYTE HAPTIC_RUMBLE[] = {
    0x06, 0x00, 0xff,   /* USAGE PAGE (vendor-defined) */
    0x09, 0x01,         /* USAGE (1) */
    0x85, 0x00,         /* REPORT_ID (0) */
    /* padding */
    0x95, 0x02,         /* REPORT_COUNT (2) */
    0x75, 0x08,         /* REPORT_SIZE (8) */
    0x91, 0x02,         /* OUTPUT (Data,Var,Abs) */
    /* actuators */
    0x15, 0x00,         /* LOGICAL MINIMUM (0) */
    0x25, 0xff,         /* LOGICAL MAXIMUM (255) */
    0x35, 0x00,         /* PHYSICAL MINIMUM (0) */
    0x45, 0xff,         /* PHYSICAL MAXIMUM (255) */
    0x75, 0x08,         /* REPORT_SIZE (8) */
    0x95, 0x02,         /* REPORT_COUNT (2) */
    0x91, 0x02,         /* OUTPUT (Data,Var,Abs) */
    /* padding */
    0x95, 0x02,         /* REPORT_COUNT (3) */
    0x75, 0x08,         /* REPORT_SIZE (8) */
    0x91, 0x02,         /* OUTPUT (Data,Var,Abs) */
};

224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250
static BYTE *add_axis_block(BYTE *report_ptr, BYTE count, BYTE page, const BYTE *usages, BOOL absolute)
{
    int i;
    memcpy(report_ptr, REPORT_AXIS_HEADER, sizeof(REPORT_AXIS_HEADER));
    report_ptr[IDX_AXIS_PAGE] = page;
    report_ptr += sizeof(REPORT_AXIS_HEADER);
    for (i = 0; i < count; i++)
    {
        memcpy(report_ptr, REPORT_AXIS_USAGE, sizeof(REPORT_AXIS_USAGE));
        report_ptr[IDX_AXIS_USAGE] = usages[i];
        report_ptr += sizeof(REPORT_AXIS_USAGE);
    }
    if (absolute)
    {
        memcpy(report_ptr, REPORT_AXIS_TAIL, sizeof(REPORT_AXIS_TAIL));
        report_ptr[IDX_ABS_AXIS_COUNT] = count;
        report_ptr += sizeof(REPORT_AXIS_TAIL);
    }
    else
    {
        memcpy(report_ptr, REPORT_REL_AXIS_TAIL, sizeof(REPORT_REL_AXIS_TAIL));
        report_ptr[IDX_REL_AXIS_COUNT] = count;
        report_ptr += sizeof(REPORT_REL_AXIS_TAIL);
    }
    return report_ptr;
}

251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267
static void set_button_value(struct platform_private *ext, int index, int value)
{
    int byte_index = ext->button_start + index / 8;
    int bit_index = index % 8;
    BYTE mask = 1 << bit_index;

    if (value)
    {
        ext->report_buffer[byte_index] = ext->report_buffer[byte_index] | mask;
    }
    else
    {
        mask = ~mask;
        ext->report_buffer[byte_index] = ext->report_buffer[byte_index] & mask;
    }
}

268 269 270
static void set_axis_value(struct platform_private *ext, int index, short value)
{
    int offset;
271
    offset = ext->axis_start + index * sizeof(WORD);
272 273 274 275 276 277 278 279 280 281 282 283 284 285

    switch (index)
    {
    case SDL_CONTROLLER_AXIS_LEFTX:
    case SDL_CONTROLLER_AXIS_LEFTY:
    case SDL_CONTROLLER_AXIS_RIGHTX:
    case SDL_CONTROLLER_AXIS_RIGHTY:
        *((WORD*)&ext->report_buffer[offset]) = LE_WORD(value) + 32768;
        break;
    case SDL_CONTROLLER_AXIS_TRIGGERLEFT:
    case SDL_CONTROLLER_AXIS_TRIGGERRIGHT:
        *((WORD*)&ext->report_buffer[offset]) = LE_WORD(value);
        break;
    }
286 287 288 289 290
}

static void set_ball_value(struct platform_private *ext, int index, int value1, int value2)
{
    int offset;
291
    offset = ext->ball_start + (index * sizeof(WORD));
292 293 294 295
    if (value1 > 127) value1 = 127;
    if (value1 < -127) value1 = -127;
    if (value2 > 127) value2 = 127;
    if (value2 < -127) value2 = -127;
296 297
    *((WORD*)&ext->report_buffer[offset]) = LE_WORD(value1);
    *((WORD*)&ext->report_buffer[offset + sizeof(WORD)]) = LE_WORD(value2);
298 299 300 301
}

static void set_hat_value(struct platform_private *ext, int index, int value)
{
302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322
    int byte = ext->button_start + (ext->hat_bit_offs + 4 * index) / 8;
    int bit_offs = (ext->hat_bit_offs + 4 * index) % 8;
    int num_low_bits, num_high_bits;
    unsigned char val, low_mask, high_mask;

    /* 4-bit hatswitch value is packed into button bytes */
    if (bit_offs <= 4)
    {
        num_low_bits = 4;
        num_high_bits = 0;
        low_mask = 0xf;
        high_mask = 0;
    }
    else
    {
        num_low_bits = 8 - bit_offs;
        num_high_bits = 4 - num_low_bits;
        low_mask = (1 << num_low_bits) - 1;
        high_mask = (1 << num_high_bits) - 1;
    }

323 324
    switch (value)
    {
325 326 327
        /* 8 1 2
         * 7 0 3
         * 6 5 4 */
328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345
        case SDL_HAT_CENTERED: val = 0; break;
        case SDL_HAT_UP: val = 1; break;
        case SDL_HAT_RIGHTUP: val = 2; break;
        case SDL_HAT_RIGHT: val = 3; break;
        case SDL_HAT_RIGHTDOWN: val = 4; break;
        case SDL_HAT_DOWN: val = 5; break;
        case SDL_HAT_LEFTDOWN: val = 6; break;
        case SDL_HAT_LEFT: val = 7; break;
        case SDL_HAT_LEFTUP: val = 8; break;
        default: return;
    }

    ext->report_buffer[byte] &= ~(low_mask << bit_offs);
    ext->report_buffer[byte] |= (val & low_mask) << bit_offs;
    if (high_mask)
    {
        ext->report_buffer[byte + 1] &= ~high_mask;
        ext->report_buffer[byte + 1] |= val & high_mask;
346 347 348
    }
}

349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382
static int test_haptic(struct platform_private *ext)
{
    int rc = 0;
    if (pSDL_JoystickIsHaptic(ext->sdl_joystick))
    {
        ext->sdl_haptic = pSDL_HapticOpenFromJoystick(ext->sdl_joystick);
        if (ext->sdl_haptic &&
            ((pSDL_HapticQuery(ext->sdl_haptic) & SDL_HAPTIC_LEFTRIGHT) != 0 ||
             pSDL_HapticRumbleSupported(ext->sdl_haptic)))
        {
            pSDL_HapticStopAll(ext->sdl_haptic);
            pSDL_HapticRumbleInit(ext->sdl_haptic);
            rc = sizeof(HAPTIC_RUMBLE);
            ext->haptic_effect_id = -1;
        }
        else
        {
            pSDL_HapticClose(ext->sdl_haptic);
            ext->sdl_haptic = NULL;
        }
    }
    return rc;
}

static int build_haptic(struct platform_private *ext, BYTE *report_ptr)
{
    if (ext->sdl_haptic)
    {
        memcpy(report_ptr, HAPTIC_RUMBLE, sizeof(HAPTIC_RUMBLE));
        return (sizeof(HAPTIC_RUMBLE));
    }
    return 0;
}

383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426
static BOOL build_report_descriptor(struct platform_private *ext)
{
    BYTE *report_ptr;
    INT i, descript_size;
    INT report_size;
    INT button_count, axis_count, ball_count, hat_count;
    static const BYTE device_usage[2] = {HID_USAGE_PAGE_GENERIC, HID_USAGE_GENERIC_GAMEPAD};
    static const BYTE controller_usages[] = {
        HID_USAGE_GENERIC_X,
        HID_USAGE_GENERIC_Y,
        HID_USAGE_GENERIC_Z,
        HID_USAGE_GENERIC_RX,
        HID_USAGE_GENERIC_RY,
        HID_USAGE_GENERIC_RZ,
        HID_USAGE_GENERIC_SLIDER,
        HID_USAGE_GENERIC_DIAL,
        HID_USAGE_GENERIC_WHEEL};
    static const BYTE joystick_usages[] = {
        HID_USAGE_GENERIC_X,
        HID_USAGE_GENERIC_Y,
        HID_USAGE_GENERIC_Z,
        HID_USAGE_GENERIC_RZ,
        HID_USAGE_GENERIC_RX,
        HID_USAGE_GENERIC_RY,
        HID_USAGE_GENERIC_SLIDER,
        HID_USAGE_GENERIC_DIAL,
        HID_USAGE_GENERIC_WHEEL};

    descript_size = sizeof(REPORT_HEADER) + sizeof(REPORT_TAIL);
    report_size = 0;

    axis_count = pSDL_JoystickNumAxes(ext->sdl_joystick);
    if (axis_count > 6)
    {
        FIXME("Clamping joystick to 6 axis\n");
        axis_count = 6;
    }

    ext->axis_start = report_size;
    if (axis_count)
    {
        descript_size += sizeof(REPORT_AXIS_HEADER);
        descript_size += (sizeof(REPORT_AXIS_USAGE) * axis_count);
        descript_size += sizeof(REPORT_AXIS_TAIL);
427
        report_size += (sizeof(WORD) * axis_count);
428 429 430 431 432 433 434 435 436 437 438 439 440 441
    }

    ball_count = pSDL_JoystickNumBalls(ext->sdl_joystick);
    ext->ball_start = report_size;
    if (ball_count)
    {
        if ((ball_count*2) + axis_count > 9)
        {
            FIXME("Capping ball + axis at 9\n");
            ball_count = (9-axis_count)/2;
        }
        descript_size += sizeof(REPORT_AXIS_HEADER);
        descript_size += (sizeof(REPORT_AXIS_USAGE) * ball_count * 2);
        descript_size += sizeof(REPORT_REL_AXIS_TAIL);
442
        report_size += (sizeof(WORD) * 2 * ball_count);
443 444
    }

445 446 447 448 449 450 451 452
    /* For now lump all buttons just into incremental usages, Ignore Keys */
    button_count = pSDL_JoystickNumButtons(ext->sdl_joystick);
    ext->button_start = report_size;
    if (button_count)
    {
        descript_size += sizeof(REPORT_BUTTONS);
    }

453
    hat_count = pSDL_JoystickNumHats(ext->sdl_joystick);
454
    ext->hat_bit_offs = button_count;
455 456 457 458 459
    if (hat_count)
    {
        descript_size += sizeof(REPORT_HATSWITCH);
    }

460 461
    report_size += (button_count + hat_count * 4 + 7) / 8;

462 463
    descript_size += test_haptic(ext);

464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490
    TRACE("Report Descriptor will be %i bytes\n", descript_size);
    TRACE("Report will be %i bytes\n", report_size);

    ext->report_descriptor = HeapAlloc(GetProcessHeap(), 0, descript_size);
    if (!ext->report_descriptor)
    {
        ERR("Failed to alloc report descriptor\n");
        return FALSE;
    }
    report_ptr = ext->report_descriptor;

    memcpy(report_ptr, REPORT_HEADER, sizeof(REPORT_HEADER));
    report_ptr[IDX_HEADER_PAGE] = device_usage[0];
    report_ptr[IDX_HEADER_USAGE] = device_usage[1];
    report_ptr += sizeof(REPORT_HEADER);
    if (axis_count)
    {
        if (axis_count == 6 && button_count >= 14)
            report_ptr = add_axis_block(report_ptr, axis_count, HID_USAGE_PAGE_GENERIC, controller_usages, TRUE);
        else
            report_ptr = add_axis_block(report_ptr, axis_count, HID_USAGE_PAGE_GENERIC, joystick_usages, TRUE);

    }
    if (ball_count)
    {
        report_ptr = add_axis_block(report_ptr, ball_count * 2, HID_USAGE_PAGE_GENERIC, &joystick_usages[axis_count], FALSE);
    }
491 492 493 494
    if (button_count)
    {
        report_ptr = add_button_block(report_ptr, 1, button_count);
    }
495 496 497
    if (hat_count)
        report_ptr = add_hatswitch(report_ptr, hat_count);

498
    report_ptr += build_haptic(ext, report_ptr);
499 500 501
    memcpy(report_ptr, REPORT_TAIL, sizeof(REPORT_TAIL));

    ext->report_descriptor_size = descript_size;
502 503 504 505 506 507 508 509 510 511 512 513 514 515
    ext->buffer_length = report_size;
    ext->report_buffer = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, report_size);
    if (ext->report_buffer == NULL)
    {
        ERR("Failed to alloc report buffer\n");
        HeapFree(GetProcessHeap(), 0, ext->report_descriptor);
        return FALSE;
    }

    /* Initialize axis in the report */
    for (i = 0; i < axis_count; i++)
        set_axis_value(ext, i, pSDL_JoystickGetAxis(ext->sdl_joystick, i));
    for (i = 0; i < hat_count; i++)
        set_hat_value(ext, i, pSDL_JoystickGetHat(ext->sdl_joystick, i));
516 517 518 519

    return TRUE;
}

520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546
static SHORT compose_dpad_value(SDL_GameController *joystick)
{
    if (pSDL_GameControllerGetButton(joystick, SDL_CONTROLLER_BUTTON_DPAD_UP))
    {
        if (pSDL_GameControllerGetButton(joystick, SDL_CONTROLLER_BUTTON_DPAD_RIGHT))
            return SDL_HAT_RIGHTUP;
        if (pSDL_GameControllerGetButton(joystick, SDL_CONTROLLER_BUTTON_DPAD_LEFT))
            return SDL_HAT_LEFTUP;
        return SDL_HAT_UP;
    }

    if (pSDL_GameControllerGetButton(joystick, SDL_CONTROLLER_BUTTON_DPAD_DOWN))
    {
        if (pSDL_GameControllerGetButton(joystick, SDL_CONTROLLER_BUTTON_DPAD_RIGHT))
            return SDL_HAT_RIGHTDOWN;
        if (pSDL_GameControllerGetButton(joystick, SDL_CONTROLLER_BUTTON_DPAD_LEFT))
            return SDL_HAT_LEFTDOWN;
        return SDL_HAT_DOWN;
    }

    if (pSDL_GameControllerGetButton(joystick, SDL_CONTROLLER_BUTTON_DPAD_RIGHT))
        return SDL_HAT_RIGHT;
    if (pSDL_GameControllerGetButton(joystick, SDL_CONTROLLER_BUTTON_DPAD_LEFT))
        return SDL_HAT_LEFT;
    return SDL_HAT_CENTERED;
}

547 548 549 550 551
static BOOL build_mapped_report_descriptor(struct platform_private *ext)
{
    BYTE *report_ptr;
    INT i, descript_size;

552 553
    static const int BUTTON_BIT_COUNT = CONTROLLER_NUM_BUTTONS + CONTROLLER_NUM_HATSWITCHES * 4;

554 555 556
    descript_size = sizeof(REPORT_HEADER) + sizeof(REPORT_TAIL);
    descript_size += sizeof(CONTROLLER_AXIS);
    descript_size += sizeof(CONTROLLER_TRIGGERS);
557
    descript_size += sizeof(CONTROLLER_BUTTONS);
558
    descript_size += sizeof(REPORT_HATSWITCH);
559
    descript_size += sizeof(REPORT_PADDING);
560 561
    if (BUTTON_BIT_COUNT % 8 != 0)
        descript_size += sizeof(REPORT_PADDING);
562
    descript_size += test_haptic(ext);
563

564 565
    ext->axis_start = 0;
    ext->button_start = CONTROLLER_NUM_AXES * sizeof(WORD);
566
    ext->hat_bit_offs = CONTROLLER_NUM_BUTTONS;
567

568
    ext->buffer_length = (BUTTON_BIT_COUNT + 7) / 8
569 570
        + CONTROLLER_NUM_AXES * sizeof(WORD)
        + 2/* unknown constant*/;
571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590

    TRACE("Report Descriptor will be %i bytes\n", descript_size);
    TRACE("Report will be %i bytes\n", ext->buffer_length);

    ext->report_descriptor = HeapAlloc(GetProcessHeap(), 0, descript_size);
    if (!ext->report_descriptor)
    {
        ERR("Failed to alloc report descriptor\n");
        return FALSE;
    }
    report_ptr = ext->report_descriptor;

    memcpy(report_ptr, REPORT_HEADER, sizeof(REPORT_HEADER));
    report_ptr[IDX_HEADER_PAGE] = HID_USAGE_PAGE_GENERIC;
    report_ptr[IDX_HEADER_USAGE] = HID_USAGE_GENERIC_GAMEPAD;
    report_ptr += sizeof(REPORT_HEADER);
    memcpy(report_ptr, CONTROLLER_AXIS, sizeof(CONTROLLER_AXIS));
    report_ptr += sizeof(CONTROLLER_AXIS);
    memcpy(report_ptr, CONTROLLER_TRIGGERS, sizeof(CONTROLLER_TRIGGERS));
    report_ptr += sizeof(CONTROLLER_TRIGGERS);
591 592
    memcpy(report_ptr, CONTROLLER_BUTTONS, sizeof(CONTROLLER_BUTTONS));
    report_ptr += sizeof(CONTROLLER_BUTTONS);
593
    report_ptr = add_hatswitch(report_ptr, 1);
594 595
    if (BUTTON_BIT_COUNT % 8 != 0)
        report_ptr = add_padding_block(report_ptr, 8 - (BUTTON_BIT_COUNT % 8));/* unused bits between hatswitch and following constant */
596
    report_ptr = add_padding_block(report_ptr, 16);/* unknown constant */
597
    report_ptr += build_haptic(ext, report_ptr);
598 599 600 601 602 603 604 605 606 607 608 609 610 611 612
    memcpy(report_ptr, REPORT_TAIL, sizeof(REPORT_TAIL));

    ext->report_descriptor_size = descript_size;
    ext->report_buffer = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, ext->buffer_length);
    if (ext->report_buffer == NULL)
    {
        ERR("Failed to alloc report buffer\n");
        HeapFree(GetProcessHeap(), 0, ext->report_descriptor);
        return FALSE;
    }

    /* Initialize axis in the report */
    for (i = SDL_CONTROLLER_AXIS_LEFTX; i < SDL_CONTROLLER_AXIS_MAX; i++)
        set_axis_value(ext, i, pSDL_GameControllerGetAxis(ext->sdl_controller, i));

613 614
    set_hat_value(ext, 0, compose_dpad_value(ext->sdl_controller));

615
    /* unknown constant */
616 617
    ext->report_buffer[14] = 0x89;
    ext->report_buffer[15] = 0xc5;
618

619 620 621
    return TRUE;
}

622 623 624 625 626 627 628 629 630
static int compare_platform_device(DEVICE_OBJECT *device, void *platform_dev)
{
    SDL_JoystickID id1 = impl_from_DEVICE_OBJECT(device)->id;
    SDL_JoystickID id2 = PtrToUlong(platform_dev);
    return (id1 != id2);
}

static NTSTATUS get_reportdescriptor(DEVICE_OBJECT *device, BYTE *buffer, DWORD length, DWORD *out_length)
{
631 632 633 634 635 636 637 638 639 640
    struct platform_private *ext = impl_from_DEVICE_OBJECT(device);

    *out_length = ext->report_descriptor_size;

    if (length < ext->report_descriptor_size)
        return STATUS_BUFFER_TOO_SMALL;

    memcpy(buffer, ext->report_descriptor, ext->report_descriptor_size);

    return STATUS_SUCCESS;
641 642 643 644 645 646 647 648 649 650
}

static NTSTATUS get_string(DEVICE_OBJECT *device, DWORD index, WCHAR *buffer, DWORD length)
{
    struct platform_private *ext = impl_from_DEVICE_OBJECT(device);
    const char* str = NULL;

    switch (index)
    {
        case HID_STRING_ID_IPRODUCT:
651 652 653 654
            if (ext->sdl_controller)
                str = pSDL_GameControllerName(ext->sdl_controller);
            else
                str = pSDL_JoystickName(ext->sdl_joystick);
655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680
            break;
        case HID_STRING_ID_IMANUFACTURER:
            str = "SDL";
            break;
        case HID_STRING_ID_ISERIALNUMBER:
            str = "000000";
            break;
        default:
            ERR("Unhandled string index %i\n", index);
    }

    if (str && str[0])
        MultiByteToWideChar(CP_ACP, 0, str, -1, buffer, length);
    else
        buffer[0] = 0;

    return STATUS_SUCCESS;
}

static NTSTATUS begin_report_processing(DEVICE_OBJECT *device)
{
    return STATUS_SUCCESS;
}

static NTSTATUS set_output_report(DEVICE_OBJECT *device, UCHAR id, BYTE *report, DWORD length, ULONG_PTR *written)
{
681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722
    struct platform_private *ext = impl_from_DEVICE_OBJECT(device);

    if (ext->sdl_haptic && id == 0)
    {
        WORD left = report[2] * 128;
        WORD right = report[3] * 128;

        if (ext->haptic_effect_id >= 0)
        {
            pSDL_HapticDestroyEffect(ext->sdl_haptic, ext->haptic_effect_id);
            ext->haptic_effect_id = -1;
        }
        pSDL_HapticStopAll(ext->sdl_haptic);
        if (left != 0 || right != 0)
        {
            SDL_HapticEffect effect;

            pSDL_memset( &effect, 0, sizeof(SDL_HapticEffect) );
            effect.type = SDL_HAPTIC_LEFTRIGHT;
            effect.leftright.length = -1;
            effect.leftright.large_magnitude = left;
            effect.leftright.small_magnitude = right;

            ext->haptic_effect_id = pSDL_HapticNewEffect(ext->sdl_haptic, &effect);
            if (ext->haptic_effect_id >= 0)
            {
                pSDL_HapticRunEffect(ext->sdl_haptic, ext->haptic_effect_id, 1);
            }
            else
            {
                float i = (float)((left + right)/2.0) / 32767.0;
                pSDL_HapticRumblePlay(ext->sdl_haptic, i, -1);
            }
        }
        *written = length;
        return STATUS_SUCCESS;
    }
    else
    {
        *written = 0;
        return STATUS_NOT_IMPLEMENTED;
    }
723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747
}

static NTSTATUS get_feature_report(DEVICE_OBJECT *device, UCHAR id, BYTE *report, DWORD length, ULONG_PTR *read)
{
    *read = 0;
    return STATUS_NOT_IMPLEMENTED;
}

static NTSTATUS set_feature_report(DEVICE_OBJECT *device, UCHAR id, BYTE *report, DWORD length, ULONG_PTR *written)
{
    *written = 0;
    return STATUS_NOT_IMPLEMENTED;
}

static const platform_vtbl sdl_vtbl =
{
    compare_platform_device,
    get_reportdescriptor,
    get_string,
    begin_report_processing,
    set_output_report,
    get_feature_report,
    set_feature_report,
};

748 749 750 751 752
static int compare_joystick_id(DEVICE_OBJECT *device, void* context)
{
    return impl_from_DEVICE_OBJECT(device)->id - PtrToUlong(context);
}

753 754 755 756 757
static BOOL set_report_from_event(SDL_Event *event)
{
    DEVICE_OBJECT *device;
    struct platform_private *private;
    /* All the events coming in will have 'which' as a 3rd field */
758 759
    SDL_JoystickID id = ((SDL_JoyButtonEvent*)event)->which;
    device = bus_enumerate_hid_devices(&sdl_vtbl, compare_joystick_id, ULongToPtr(id));
760 761
    if (!device)
    {
762
        ERR("Failed to find device at index %i\n",id);
763 764 765
        return FALSE;
    }
    private = impl_from_DEVICE_OBJECT(device);
766 767 768 769 770
    if (private->sdl_controller)
    {
        /* We want mapped events */
        return TRUE;
    }
771 772 773 774 775 776 777 778

    switch(event->type)
    {
        case SDL_JOYBUTTONDOWN:
        case SDL_JOYBUTTONUP:
        {
            SDL_JoyButtonEvent *ie = &event->jbutton;

779
            set_button_value(private, ie->button, ie->state);
780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810

            process_hid_report(device, private->report_buffer, private->buffer_length);
            break;
        }
        case SDL_JOYAXISMOTION:
        {
            SDL_JoyAxisEvent *ie = &event->jaxis;

            if (ie->axis < 6)
            {
                set_axis_value(private, ie->axis, ie->value);
                process_hid_report(device, private->report_buffer, private->buffer_length);
            }
            break;
        }
        case SDL_JOYBALLMOTION:
        {
            SDL_JoyBallEvent *ie = &event->jball;

            set_ball_value(private, ie->ball, ie->xrel, ie->yrel);
            process_hid_report(device, private->report_buffer, private->buffer_length);
            break;
        }
        case SDL_JOYHATMOTION:
        {
            SDL_JoyHatEvent *ie = &event->jhat;

            set_hat_value(private, ie->hat, ie->value);
            process_hid_report(device, private->report_buffer, private->buffer_length);
            break;
        }
811 812 813 814 815 816 817 818 819 820 821
        default:
            ERR("TODO: Process Report (0x%x)\n",event->type);
    }
    return FALSE;
}

static BOOL set_mapped_report_from_event(SDL_Event *event)
{
    DEVICE_OBJECT *device;
    struct platform_private *private;
    /* All the events coming in will have 'which' as a 3rd field */
822 823
    SDL_JoystickID id = ((SDL_ControllerButtonEvent*)event)->which;
    device = bus_enumerate_hid_devices(&sdl_vtbl, compare_joystick_id, ULongToPtr(id));
824 825
    if (!device)
    {
826
        ERR("Failed to find device at index %i\n",id);
827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846
        return FALSE;
    }
    private = impl_from_DEVICE_OBJECT(device);

    switch(event->type)
    {
        case SDL_CONTROLLERBUTTONDOWN:
        case SDL_CONTROLLERBUTTONUP:
        {
            int usage = -1;
            SDL_ControllerButtonEvent *ie = &event->cbutton;

            switch (ie->button)
            {
                case SDL_CONTROLLER_BUTTON_A: usage = 0; break;
                case SDL_CONTROLLER_BUTTON_B: usage = 1; break;
                case SDL_CONTROLLER_BUTTON_X: usage = 2; break;
                case SDL_CONTROLLER_BUTTON_Y: usage = 3; break;
                case SDL_CONTROLLER_BUTTON_LEFTSHOULDER: usage = 4; break;
                case SDL_CONTROLLER_BUTTON_RIGHTSHOULDER: usage = 5; break;
847 848 849 850
                case SDL_CONTROLLER_BUTTON_BACK: usage = 6; break;
                case SDL_CONTROLLER_BUTTON_START: usage = 7; break;
                case SDL_CONTROLLER_BUTTON_LEFTSTICK: usage = 8; break;
                case SDL_CONTROLLER_BUTTON_RIGHTSTICK: usage = 9; break;
851
                case SDL_CONTROLLER_BUTTON_GUIDE: usage = 10; break;
852 853 854 855 856 857 858 859 860

                case SDL_CONTROLLER_BUTTON_DPAD_UP:
                case SDL_CONTROLLER_BUTTON_DPAD_DOWN:
                case SDL_CONTROLLER_BUTTON_DPAD_LEFT:
                case SDL_CONTROLLER_BUTTON_DPAD_RIGHT:
                    set_hat_value(private, 0, compose_dpad_value(private->sdl_controller));
                    process_hid_report(device, private->report_buffer, private->buffer_length);
                    break;

861 862 863 864 865 866
                default:
                    ERR("Unknown Button %i\n",ie->button);
            }

            if (usage >= 0)
            {
867
                set_button_value(private, usage, ie->state);
868 869 870 871 872 873 874 875 876 877 878 879
                process_hid_report(device, private->report_buffer, private->buffer_length);
            }
            break;
        }
        case SDL_CONTROLLERAXISMOTION:
        {
            SDL_ControllerAxisEvent *ie = &event->caxis;

            set_axis_value(private, ie->axis, ie->value);
            process_hid_report(device, private->report_buffer, private->buffer_length);
            break;
        }
880 881 882 883 884 885
        default:
            ERR("TODO: Process Report (%x)\n",event->type);
    }
    return FALSE;
}

886
static void try_remove_device(SDL_JoystickID id)
887 888
{
    DEVICE_OBJECT *device = NULL;
889 890 891 892
    struct platform_private *private;
    SDL_Joystick *sdl_joystick;
    SDL_GameController *sdl_controller;
    SDL_Haptic *sdl_haptic;
893

894
    device = bus_enumerate_hid_devices(&sdl_vtbl, compare_joystick_id, ULongToPtr(id));
895 896
    if (!device) return;

897 898 899 900 901
    private = impl_from_DEVICE_OBJECT(device);
    sdl_joystick = private->sdl_joystick;
    sdl_controller = private->sdl_controller;
    sdl_haptic = private->sdl_haptic;

902
    bus_unlink_hid_device(device);
903
    IoInvalidateDeviceRelations(bus_pdo, BusRelations);
904 905

    bus_remove_hid_device(device);
906 907 908 909 910 911

    pSDL_JoystickClose(sdl_joystick);
    if (sdl_controller)
        pSDL_GameControllerClose(sdl_controller);
    if (sdl_haptic)
        pSDL_HapticClose(sdl_haptic);
912 913
}

914
static void try_add_device(unsigned int index)
915 916 917 918 919 920
{
    DWORD vid = 0, pid = 0, version = 0;
    DEVICE_OBJECT *device = NULL;
    WCHAR serial[34] = {0};
    char guid_str[34];
    BOOL is_xbox_gamepad;
921
    WORD input = -1;
922 923 924 925

    SDL_Joystick* joystick;
    SDL_JoystickID id;
    SDL_JoystickGUID guid;
926
    SDL_GameController *controller = NULL;
927 928 929 930 931 932 933

    if ((joystick = pSDL_JoystickOpen(index)) == NULL)
    {
        WARN("Unable to open sdl device %i: %s\n", index, pSDL_GetError());
        return;
    }

934 935 936
    if (map_controllers && pSDL_IsGameController(index))
        controller = pSDL_GameControllerOpen(index);

937
    id = pSDL_JoystickInstanceID(joystick);
938 939 940 941 942

    if (pSDL_JoystickGetProductVersion != NULL) {
        vid = pSDL_JoystickGetVendor(joystick);
        pid = pSDL_JoystickGetProduct(joystick);
        version = pSDL_JoystickGetProductVersion(joystick);
943 944 945
    }
    else
    {
946 947 948
        vid = 0x01;
        pid = pSDL_JoystickInstanceID(joystick) + 1;
        version = 0;
949 950 951 952 953 954
    }

    guid = pSDL_JoystickGetGUID(joystick);
    pSDL_JoystickGetGUIDString(guid, guid_str, sizeof(guid_str));
    MultiByteToWideChar(CP_ACP, 0, guid_str, -1, serial, sizeof(guid_str));

955 956 957
    if (controller)
    {
        TRACE("Found sdl game controller %i (vid %04x, pid %04x, version %u, serial %s)\n",
958
              id, vid, pid, version, debugstr_w(serial));
959 960 961 962 963 964 965
        is_xbox_gamepad = TRUE;
    }
    else
    {
        int button_count, axis_count;

        TRACE("Found sdl device %i (vid %04x, pid %04x, version %u, serial %s)\n",
966
              id, vid, pid, version, debugstr_w(serial));
967

968
        axis_count = pSDL_JoystickNumAxes(joystick);
969
        button_count = pSDL_JoystickNumButtons(joystick);
970 971
        is_xbox_gamepad = (axis_count == 6  && button_count >= 14);
    }
972 973
    if (is_xbox_gamepad)
        input = 0;
974

975 976
    device = bus_create_hid_device(sdl_busidW, vid, pid, input, version, index,
            serial, is_xbox_gamepad, &sdl_vtbl, sizeof(struct platform_private));
977 978 979

    if (device)
    {
980
        BOOL rc;
981 982
        struct platform_private *private = impl_from_DEVICE_OBJECT(device);
        private->sdl_joystick = joystick;
983
        private->sdl_controller = controller;
984
        private->id = id;
985 986 987 988 989
        if (controller)
            rc = build_mapped_report_descriptor(private);
        else
            rc = build_report_descriptor(private);
        if (!rc)
990 991
        {
            ERR("Building report descriptor failed, removing device\n");
992
            bus_unlink_hid_device(device);
993 994 995 996
            bus_remove_hid_device(device);
            HeapFree(GetProcessHeap(), 0, serial);
            return;
        }
997
        IoInvalidateDeviceRelations(bus_pdo, BusRelations);
998 999 1000
    }
    else
    {
1001
        WARN("Ignoring device %i\n", id);
1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012
    }
}

static void process_device_event(SDL_Event *event)
{
    TRACE_(hid_report)("Received action %x\n", event->type);

    if (event->type == SDL_JOYDEVICEADDED)
        try_add_device(((SDL_JoyDeviceEvent*)event)->which);
    else if (event->type == SDL_JOYDEVICEREMOVED)
        try_remove_device(((SDL_JoyDeviceEvent*)event)->which);
1013 1014
    else if (event->type >= SDL_JOYAXISMOTION && event->type <= SDL_JOYBUTTONUP)
        set_report_from_event(event);
1015 1016
    else if (event->type >= SDL_CONTROLLERAXISMOTION && event->type <= SDL_CONTROLLERBUTTONUP)
        set_mapped_report_from_event(event);
1017 1018 1019 1020
}

static DWORD CALLBACK deviceloop_thread(void *args)
{
1021
    HANDLE init_done = args;
1022 1023
    SDL_Event event;

1024
    if (pSDL_Init(SDL_INIT_GAMECONTROLLER|SDL_INIT_HAPTIC) < 0)
1025
    {
1026
        ERR("Can't init SDL: %s\n", pSDL_GetError());
1027 1028 1029 1030
        return STATUS_UNSUCCESSFUL;
    }

    pSDL_JoystickEventState(SDL_ENABLE);
1031
    pSDL_GameControllerEventState(SDL_ENABLE);
1032

1033 1034 1035
    /* Process mappings */
    if (pSDL_GameControllerAddMapping != NULL)
    {
1036 1037 1038 1039
        HKEY key;
        static const WCHAR szPath[] = {'m','a','p',0};

        if (!RegOpenKeyExW(driver_key, szPath, 0, KEY_ENUMERATE_SUB_KEYS, &key))
1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077
        {
            DWORD index = 0;
            CHAR *buffer = NULL;
            DWORD buffer_len = 0;
            LSTATUS rc;

            do {
                CHAR name[255];
                DWORD name_len;
                DWORD type;
                DWORD data_len = buffer_len;

                name_len = sizeof(name);
                rc = RegEnumValueA(key, index, name, &name_len, NULL, &type, (LPBYTE)buffer, &data_len);
                if (rc == ERROR_MORE_DATA || buffer == NULL)
                {
                    if (buffer)
                        buffer = HeapReAlloc(GetProcessHeap(), 0, buffer, data_len);
                    else
                        buffer = HeapAlloc(GetProcessHeap(), 0, data_len);
                    buffer_len = data_len;

                    name_len = sizeof(name);
                    rc = RegEnumValueA(key, index, name, &name_len, NULL, &type, (LPBYTE)buffer, &data_len);
                }

                if (rc == STATUS_SUCCESS)
                {
                    TRACE("Setting mapping %s...\n",debugstr_an(buffer,29));
                    pSDL_GameControllerAddMapping(buffer);
                    index ++;
                }
            } while (rc == STATUS_SUCCESS);
            HeapFree(GetProcessHeap(), 0, buffer);
            NtClose(key);
        }
    }

1078
    SetEvent(init_done);
1079

1080 1081 1082 1083 1084 1085
    while (1) {
        while (pSDL_WaitEvent(&event) != 0) {
            if (event.type == quit_event) {
                TRACE("Device thread exiting\n");
                return 0;
            }
1086
            process_device_event(&event);
1087 1088
        }
    }
1089 1090
}

1091 1092
void sdl_driver_unload( void )
{
1093 1094
    SDL_Event event;

1095
    TRACE("Unload Driver\n");
1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114

    if (!deviceloop_handle)
        return;

    quit_event = pSDL_RegisterEvents(1);
    if (quit_event == -1) {
        ERR("error registering quit event\n");
        return;
    }

    event.type = quit_event;
    if (pSDL_PushEvent(&event) != 1) {
        ERR("error pushing quit event\n");
        return;
    }

    WaitForSingleObject(deviceloop_handle, INFINITE);
    CloseHandle(deviceloop_handle);
    wine_dlclose(sdl_handle, NULL, 0);
1115 1116
}

1117
NTSTATUS sdl_driver_init(void)
1118
{
1119 1120 1121
    static const WCHAR controller_modeW[] = {'M','a','p',' ','C','o','n','t','r','o','l','l','e','r','s',0};
    static const UNICODE_STRING controller_mode = {sizeof(controller_modeW) - sizeof(WCHAR), sizeof(controller_modeW), (WCHAR*)controller_modeW};

1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134
    HANDLE events[2];
    DWORD result;

    if (sdl_handle == NULL)
    {
        sdl_handle = wine_dlopen(SONAME_LIBSDL2, RTLD_NOW, NULL, 0);
        if (!sdl_handle) {
            WARN("could not load %s\n", SONAME_LIBSDL2);
            return STATUS_UNSUCCESSFUL;
        }
#define LOAD_FUNCPTR(f) if((p##f = wine_dlsym(sdl_handle, #f, NULL, 0)) == NULL){WARN("Can't find symbol %s\n", #f); goto sym_not_found;}
        LOAD_FUNCPTR(SDL_GetError);
        LOAD_FUNCPTR(SDL_Init);
1135
        LOAD_FUNCPTR(SDL_JoystickClose);
1136 1137 1138 1139 1140 1141 1142 1143
        LOAD_FUNCPTR(SDL_JoystickEventState);
        LOAD_FUNCPTR(SDL_JoystickGetGUID);
        LOAD_FUNCPTR(SDL_JoystickGetGUIDString);
        LOAD_FUNCPTR(SDL_JoystickInstanceID);
        LOAD_FUNCPTR(SDL_JoystickName);
        LOAD_FUNCPTR(SDL_JoystickNumAxes);
        LOAD_FUNCPTR(SDL_JoystickOpen);
        LOAD_FUNCPTR(SDL_WaitEvent);
1144 1145 1146
        LOAD_FUNCPTR(SDL_JoystickNumButtons);
        LOAD_FUNCPTR(SDL_JoystickNumBalls);
        LOAD_FUNCPTR(SDL_JoystickNumHats);
1147 1148
        LOAD_FUNCPTR(SDL_JoystickGetAxis);
        LOAD_FUNCPTR(SDL_JoystickGetHat);
1149
        LOAD_FUNCPTR(SDL_IsGameController);
1150
        LOAD_FUNCPTR(SDL_GameControllerClose);
1151
        LOAD_FUNCPTR(SDL_GameControllerGetAxis);
1152
        LOAD_FUNCPTR(SDL_GameControllerGetButton);
1153 1154 1155
        LOAD_FUNCPTR(SDL_GameControllerName);
        LOAD_FUNCPTR(SDL_GameControllerOpen);
        LOAD_FUNCPTR(SDL_GameControllerEventState);
1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167
        LOAD_FUNCPTR(SDL_HapticClose);
        LOAD_FUNCPTR(SDL_HapticDestroyEffect);
        LOAD_FUNCPTR(SDL_HapticNewEffect);
        LOAD_FUNCPTR(SDL_HapticOpenFromJoystick);
        LOAD_FUNCPTR(SDL_HapticQuery);
        LOAD_FUNCPTR(SDL_HapticRumbleInit);
        LOAD_FUNCPTR(SDL_HapticRumblePlay);
        LOAD_FUNCPTR(SDL_HapticRumbleSupported);
        LOAD_FUNCPTR(SDL_HapticRunEffect);
        LOAD_FUNCPTR(SDL_HapticStopAll);
        LOAD_FUNCPTR(SDL_JoystickIsHaptic);
        LOAD_FUNCPTR(SDL_memset);
1168
        LOAD_FUNCPTR(SDL_GameControllerAddMapping);
1169 1170
        LOAD_FUNCPTR(SDL_RegisterEvents);
        LOAD_FUNCPTR(SDL_PushEvent);
1171 1172 1173 1174 1175 1176
#undef LOAD_FUNCPTR
        pSDL_JoystickGetProduct = wine_dlsym(sdl_handle, "SDL_JoystickGetProduct", NULL, 0);
        pSDL_JoystickGetProductVersion = wine_dlsym(sdl_handle, "SDL_JoystickGetProductVersion", NULL, 0);
        pSDL_JoystickGetVendor = wine_dlsym(sdl_handle, "SDL_JoystickGetVendor", NULL, 0);
    }

1177
    map_controllers = check_bus_option(&controller_mode, 1);
1178

1179
    if (!(events[0] = CreateEventW(NULL, TRUE, FALSE, NULL)))
1180 1181
    {
        WARN("CreateEvent failed\n");
1182
        return STATUS_UNSUCCESSFUL;
1183
    }
1184
    if (!(events[1] = CreateThread(NULL, 0, deviceloop_thread, events[0], 0, NULL)))
1185
    {
1186
        WARN("CreateThread failed\n");
1187
        CloseHandle(events[0]);
1188
        return STATUS_UNSUCCESSFUL;
1189 1190 1191 1192 1193 1194 1195
    }

    result = WaitForMultipleObjects(2, events, FALSE, INFINITE);
    CloseHandle(events[0]);
    if (result == WAIT_OBJECT_0)
    {
        TRACE("Initialization successful\n");
1196
        deviceloop_handle = events[1];
1197 1198
        return STATUS_SUCCESS;
    }
1199
    CloseHandle(events[1]);
1200 1201 1202 1203

sym_not_found:
    wine_dlclose(sdl_handle, NULL, 0);
    sdl_handle = NULL;
1204 1205 1206 1207 1208
    return STATUS_UNSUCCESSFUL;
}

#else

1209
NTSTATUS sdl_driver_init(void)
1210 1211 1212 1213
{
    return STATUS_NOT_IMPLEMENTED;
}

1214 1215 1216 1217 1218
void sdl_driver_unload( void )
{
    TRACE("Stub: Unload Driver\n");
}

1219
#endif /* SONAME_LIBSDL2 */