WinRT: merged with SDL 2.0.0 codebase (aka. SDL hg rev d6a8fa507a45)

This commit is contained in:
David Ludwig
2013-08-12 22:29:55 -04:00
768 changed files with 31941 additions and 111045 deletions

158
src/SDL.c
View File

@@ -25,25 +25,29 @@
#include "SDL.h"
#include "SDL_bits.h"
#include "SDL_revision.h"
#include "SDL_fatal.h"
#include "SDL_assert_c.h"
#include "events/SDL_events_c.h"
#include "haptic/SDL_haptic_c.h"
#include "joystick/SDL_joystick_c.h"
/* Initialization/Cleanup routines */
#if !SDL_TIMERS_DISABLED
extern void SDL_StartTicks(void);
extern int SDL_TimerInit(void);
extern void SDL_TimerQuit(void);
extern void SDL_InitTicks(void);
#endif
#if defined(__WIN32__)
#if SDL_VIDEO_DRIVER_WINDOWS
extern int SDL_HelperWindowCreate(void);
extern int SDL_HelperWindowDestroy(void);
#endif
/* The initialized subsystems */
static Uint32 ticks_started = 0;
#ifdef SDL_MAIN_NEEDED
static SDL_bool SDL_MainIsReady = SDL_FALSE;
#else
static SDL_bool SDL_MainIsReady = SDL_TRUE;
#endif
static SDL_bool SDL_bInMainQuit = SDL_FALSE;
static Uint8 SDL_SubsystemRefCount[ 32 ];
@@ -89,18 +93,60 @@ SDL_PrivateShouldQuitSubsystem(Uint32 subsystem) {
return SDL_SubsystemRefCount[subsystem_index] == 1 || SDL_bInMainQuit;
}
void
SDL_SetMainReady(void)
{
SDL_MainIsReady = SDL_TRUE;
}
int
SDL_InitSubSystem(Uint32 flags)
{
#if !SDL_TIMERS_DISABLED
if (!ticks_started) {
SDL_StartTicks();
ticks_started = 1;
if (!SDL_MainIsReady) {
SDL_SetError("Application didn't initialize properly, did you include SDL_main.h in the file containing your main() function?");
return -1;
}
/* Clear the error message */
SDL_ClearError();
#if SDL_VIDEO_DRIVER_WINDOWS
if (SDL_HelperWindowCreate() < 0) {
return -1;
}
#endif
#if !SDL_TIMERS_DISABLED
SDL_InitTicks();
#endif
if ((flags & SDL_INIT_GAMECONTROLLER)) {
/* game controller implies joystick */
flags |= SDL_INIT_JOYSTICK;
}
if ((flags & (SDL_INIT_VIDEO|SDL_INIT_JOYSTICK))) {
/* video or joystick implies events */
flags |= SDL_INIT_EVENTS;
}
/* Initialize the event subsystem */
if ((flags & SDL_INIT_EVENTS)) {
#if !SDL_EVENTS_DISABLED
if (SDL_PrivateShouldInitSubsystem(SDL_INIT_EVENTS)) {
if (SDL_StartEventLoop() < 0) {
return (-1);
}
SDL_QuitInit();
}
SDL_PrivateSubsystemRefCountIncr(SDL_INIT_EVENTS);
#else
return SDL_SetError("SDL not built with events support");
#endif
}
/* Initialize the timer subsystem */
if ((flags & SDL_INIT_TIMER) ){
if ((flags & SDL_INIT_TIMER)){
#if !SDL_TIMERS_DISABLED
if (SDL_PrivateShouldInitSubsystem(SDL_INIT_TIMER)) {
if (SDL_TimerInit() < 0) {
@@ -113,8 +159,8 @@ SDL_InitSubSystem(Uint32 flags)
#endif
}
/* Initialize the video/event subsystem */
if ((flags & SDL_INIT_VIDEO) ){
/* Initialize the video subsystem */
if ((flags & SDL_INIT_VIDEO)){
#if !SDL_VIDEO_DISABLED
if (SDL_PrivateShouldInitSubsystem(SDL_INIT_VIDEO)) {
if (SDL_VideoInit(NULL) < 0) {
@@ -128,7 +174,7 @@ SDL_InitSubSystem(Uint32 flags)
}
/* Initialize the audio subsystem */
if ((flags & SDL_INIT_AUDIO) ){
if ((flags & SDL_INIT_AUDIO)){
#if !SDL_AUDIO_DISABLED
if (SDL_PrivateShouldInitSubsystem(SDL_INIT_AUDIO)) {
if (SDL_AudioInit(NULL) < 0) {
@@ -141,13 +187,8 @@ SDL_InitSubSystem(Uint32 flags)
#endif
}
if ((flags & SDL_INIT_GAMECONTROLLER)) {
// Game controller implies Joystick.
flags |= SDL_INIT_JOYSTICK;
}
/* Initialize the joystick subsystem */
if ((flags & SDL_INIT_JOYSTICK) ){
if ((flags & SDL_INIT_JOYSTICK)){
#if !SDL_JOYSTICK_DISABLED
if (SDL_PrivateShouldInitSubsystem(SDL_INIT_JOYSTICK)) {
if (SDL_JoystickInit() < 0) {
@@ -160,7 +201,7 @@ SDL_InitSubSystem(Uint32 flags)
#endif
}
if ((flags & SDL_INIT_GAMECONTROLLER) ){
if ((flags & SDL_INIT_GAMECONTROLLER)){
#if !SDL_JOYSTICK_DISABLED
if (SDL_PrivateShouldInitSubsystem(SDL_INIT_GAMECONTROLLER)) {
if (SDL_GameControllerInit() < 0) {
@@ -174,7 +215,7 @@ SDL_InitSubSystem(Uint32 flags)
}
/* Initialize the haptic subsystem */
if ((flags & SDL_INIT_HAPTIC) ){
if ((flags & SDL_INIT_HAPTIC)){
#if !SDL_HAPTIC_DISABLED
if (SDL_PrivateShouldInitSubsystem(SDL_INIT_HAPTIC)) {
if (SDL_HapticInit() < 0) {
@@ -193,30 +234,7 @@ SDL_InitSubSystem(Uint32 flags)
int
SDL_Init(Uint32 flags)
{
if (SDL_AssertionsInit() < 0) {
return -1;
}
/* Clear the error message */
SDL_ClearError();
#if defined(__WIN32__)
if (SDL_HelperWindowCreate() < 0) {
return -1;
}
#endif
/* Initialize the desired subsystems */
if (SDL_InitSubSystem(flags) < 0) {
return (-1);
}
/* Everything is initialized */
if (!(flags & SDL_INIT_NOPARACHUTE)) {
SDL_InstallParachute();
}
return (0);
return SDL_InitSubSystem(flags);
}
void
@@ -225,19 +243,22 @@ SDL_QuitSubSystem(Uint32 flags)
/* Shut down requested initialized subsystems */
#if !SDL_JOYSTICK_DISABLED
if ((flags & SDL_INIT_GAMECONTROLLER)) {
// Game controller implies Joystick.
/* game controller implies joystick */
flags |= SDL_INIT_JOYSTICK;
if (SDL_PrivateShouldQuitSubsystem(SDL_INIT_GAMECONTROLLER)) {
SDL_GameControllerQuit();
}
}
SDL_PrivateSubsystemRefCountDecr(SDL_INIT_GAMECONTROLLER);
}
if ((flags & SDL_INIT_JOYSTICK)) {
/* joystick implies events */
flags |= SDL_INIT_EVENTS;
if (SDL_PrivateShouldQuitSubsystem(SDL_INIT_JOYSTICK)) {
SDL_JoystickQuit();
}
SDL_JoystickQuit();
}
SDL_PrivateSubsystemRefCountDecr(SDL_INIT_JOYSTICK);
}
#endif
@@ -245,8 +266,8 @@ SDL_QuitSubSystem(Uint32 flags)
#if !SDL_HAPTIC_DISABLED
if ((flags & SDL_INIT_HAPTIC)) {
if (SDL_PrivateShouldQuitSubsystem(SDL_INIT_HAPTIC)) {
SDL_HapticQuit();
}
SDL_HapticQuit();
}
SDL_PrivateSubsystemRefCountDecr(SDL_INIT_HAPTIC);
}
#endif
@@ -254,17 +275,20 @@ SDL_QuitSubSystem(Uint32 flags)
#if !SDL_AUDIO_DISABLED
if ((flags & SDL_INIT_AUDIO)) {
if (SDL_PrivateShouldQuitSubsystem(SDL_INIT_AUDIO)) {
SDL_AudioQuit();
}
SDL_AudioQuit();
}
SDL_PrivateSubsystemRefCountDecr(SDL_INIT_AUDIO);
}
#endif
#if !SDL_VIDEO_DISABLED
if ((flags & SDL_INIT_VIDEO)) {
/* video implies events */
flags |= SDL_INIT_EVENTS;
if (SDL_PrivateShouldQuitSubsystem(SDL_INIT_VIDEO)) {
SDL_VideoQuit();
}
SDL_VideoQuit();
}
SDL_PrivateSubsystemRefCountDecr(SDL_INIT_VIDEO);
}
#endif
@@ -272,11 +296,21 @@ SDL_QuitSubSystem(Uint32 flags)
#if !SDL_TIMERS_DISABLED
if ((flags & SDL_INIT_TIMER)) {
if (SDL_PrivateShouldQuitSubsystem(SDL_INIT_TIMER)) {
SDL_TimerQuit();
}
SDL_TimerQuit();
}
SDL_PrivateSubsystemRefCountDecr(SDL_INIT_TIMER);
}
#endif
#if !SDL_EVENTS_DISABLED
if ((flags & SDL_INIT_EVENTS)) {
if (SDL_PrivateShouldQuitSubsystem(SDL_INIT_EVENTS)) {
SDL_QuitQuit();
SDL_StopEventLoop();
}
SDL_PrivateSubsystemRefCountDecr(SDL_INIT_EVENTS);
}
#endif
}
Uint32
@@ -310,14 +344,11 @@ SDL_Quit(void)
SDL_bInMainQuit = SDL_TRUE;
/* Quit all subsystems */
#if defined(__WIN32__)
#if SDL_VIDEO_DRIVER_WINDOWS
SDL_HelperWindowDestroy();
#endif
SDL_QuitSubSystem(SDL_INIT_EVERYTHING);
/* Uninstall any parachute signal handlers */
SDL_UninstallParachute();
SDL_ClearHints();
SDL_AssertionsQuit();
SDL_LogResetPriorities();
@@ -359,9 +390,6 @@ SDL_GetPlatform()
return "AIX";
#elif __ANDROID__
return "Android";
#elif __HAIKU__
/* Haiku must appear here before BeOS, since it also defines __BEOS__ */
return "Haiku";
#elif __BEOS__
return "BeOS";
#elif __BSDI__
@@ -370,6 +398,8 @@ SDL_GetPlatform()
return "Dreamcast";
#elif __FREEBSD__
return "FreeBSD";
#elif __HAIKU__
return "Haiku";
#elif __HPUX__
return "HP-UX";
#elif __IRIX__
@@ -399,7 +429,7 @@ SDL_GetPlatform()
#elif __WIN32__
return "Windows";
#elif __IPHONEOS__
return "iPhone OS";
return "iOS";
#elif __PSP__
return "PlayStation Portable";
#else

View File

@@ -327,12 +327,6 @@ SDL_ReportAssertion(SDL_assert_data *data, const char *func, const char *file,
}
int SDL_AssertionsInit(void)
{
/* this is a no-op at the moment. */
return 0;
}
void SDL_AssertionsQuit(void)
{
SDL_GenerateAssertionReport();

View File

@@ -19,7 +19,6 @@
3. This notice may not be removed or altered from any source distribution.
*/
extern int SDL_AssertionsInit(void);
extern void SDL_AssertionsQuit(void);
/* vi: set ts=4 sw=4 expandtab: */

View File

@@ -31,12 +31,12 @@
#if SDL_THREADS_DISABLED
/* The default (non-thread-safe) global error variable */
static SDL_error SDL_global_error;
#define SDL_GetErrBuf() (&SDL_global_error)
#define SDL_GetErrBuf() (&SDL_global_error)
#else
extern SDL_error *SDL_GetErrBuf(void);
#endif /* SDL_THREADS_DISABLED */
#define SDL_ERRBUFIZE 1024
#define SDL_ERRBUFIZE 1024
/* Private functions */
@@ -57,7 +57,7 @@ SDL_SetError(const char *fmt, ...)
/* Ignore call if invalid format pointer was passed */
if (fmt == NULL) return -1;
/* Copy in the key, mark error as valid */
error = SDL_GetErrBuf();
error->error = 1;

View File

@@ -27,8 +27,8 @@
#ifndef _SDL_error_c_h
#define _SDL_error_c_h
#define ERR_MAX_STRLEN 128
#define ERR_MAX_ARGS 5
#define ERR_MAX_STRLEN 128
#define ERR_MAX_ARGS 5
typedef struct SDL_error
{

View File

@@ -1,139 +0,0 @@
/*
Simple DirectMedia Layer
Copyright (C) 1997-2013 Sam Lantinga <slouken@libsdl.org>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#include "SDL_config.h"
/* General fatal signal handling code for SDL */
#ifdef HAVE_SIGNAL_H
#include <signal.h>
#include "SDL.h"
#include "SDL_fatal.h"
/* This installs some signal handlers for the more common fatal signals,
so that if the programmer is lazy, the app doesn't die so horribly if
the program crashes.
*/
static void
SDL_Parachute(int sig)
{
signal(sig, SIG_DFL);
SDL_Quit();
raise(sig);
}
static const int SDL_fatal_signals[] = {
SIGSEGV,
#ifdef SIGBUS
SIGBUS,
#endif
#ifdef SIGFPE
SIGFPE,
#endif
#ifdef SIGQUIT
SIGQUIT,
#endif
0
};
void
SDL_InstallParachute(void)
{
/* Set a handler for any fatal signal not already handled */
int i;
#ifdef HAVE_SIGACTION
struct sigaction action;
for (i = 0; SDL_fatal_signals[i]; ++i) {
sigaction(SDL_fatal_signals[i], NULL, &action);
if (action.sa_handler == SIG_DFL) {
action.sa_handler = SDL_Parachute;
sigaction(SDL_fatal_signals[i], &action, NULL);
}
}
#ifdef SIGALRM
/* Set SIGALRM to be ignored -- necessary on Solaris */
sigaction(SIGALRM, NULL, &action);
if (action.sa_handler == SIG_DFL) {
action.sa_handler = SIG_IGN;
sigaction(SIGALRM, &action, NULL);
}
#endif
#else
void (*ohandler) (int);
for (i = 0; SDL_fatal_signals[i]; ++i) {
ohandler = signal(SDL_fatal_signals[i], SDL_Parachute);
if (ohandler != SIG_DFL) {
signal(SDL_fatal_signals[i], ohandler);
}
}
#endif /* HAVE_SIGACTION */
return;
}
void
SDL_UninstallParachute(void)
{
/* Remove a handler for any fatal signal handled */
int i;
#ifdef HAVE_SIGACTION
struct sigaction action;
for (i = 0; SDL_fatal_signals[i]; ++i) {
sigaction(SDL_fatal_signals[i], NULL, &action);
if (action.sa_handler == SDL_Parachute) {
action.sa_handler = SIG_DFL;
sigaction(SDL_fatal_signals[i], &action, NULL);
}
}
#else
void (*ohandler) (int);
for (i = 0; SDL_fatal_signals[i]; ++i) {
ohandler = signal(SDL_fatal_signals[i], SIG_DFL);
if (ohandler != SDL_Parachute) {
signal(SDL_fatal_signals[i], ohandler);
}
}
#endif /* HAVE_SIGACTION */
}
#else
/* No signals on this platform, nothing to do.. */
void
SDL_InstallParachute(void)
{
return;
}
void
SDL_UninstallParachute(void)
{
return;
}
#endif /* HAVE_SIGNAL_H */
/* vi: set ts=4 sw=4 expandtab: */

View File

@@ -21,43 +21,35 @@
#include "SDL_config.h"
#include "SDL_hints.h"
#include "SDL_hints_c.h"
#include "SDL_error.h"
/* Assuming there aren't many hints set and they aren't being queried in
critical performance paths, we'll just use a linked list here.
critical performance paths, we'll just use linked lists here.
*/
typedef struct SDL_HintWatch {
SDL_HintCallback callback;
void *userdata;
struct SDL_HintWatch *next;
} SDL_HintWatch;
typedef struct SDL_Hint {
char *name;
char *value;
SDL_HintPriority priority;
SDL_HintChangedCb callback;
SDL_HintWatch *callbacks;
struct SDL_Hint *next;
} SDL_Hint;
static SDL_Hint *SDL_hints;
SDL_bool
SDL_RegisterHintChangedCb(const char *name, SDL_HintChangedCb hintCb)
{
SDL_Hint *hint;
for (hint = SDL_hints; hint; hint = hint->next) {
if (SDL_strcmp(name, hint->name) == 0) {
hint->callback = hintCb;
return SDL_TRUE;
}
}
return SDL_FALSE;
}
SDL_bool
SDL_SetHintWithPriority(const char *name, const char *value,
SDL_HintPriority priority)
{
const char *env;
SDL_Hint *hint;
SDL_HintWatch *entry;
if (!name || !value) {
return SDL_FALSE;
@@ -73,12 +65,21 @@ SDL_SetHintWithPriority(const char *name, const char *value,
if (priority < hint->priority) {
return SDL_FALSE;
}
if (SDL_strcmp(hint->value, value) != 0) {
if (hint->callback != NULL) {
(*hint->callback)(name, hint->value, value);
if (!hint->value || !value || SDL_strcmp(hint->value, value) != 0) {
for (entry = hint->callbacks; entry; ) {
/* Save the next entry in case this one is deleted */
SDL_HintWatch *next = entry->next;
entry->callback(entry->userdata, name, hint->value, value);
entry = next;
}
if (hint->value) {
SDL_free(hint->value);
}
if (value) {
hint->value = SDL_strdup(value);
} else {
hint->value = NULL;
}
SDL_free(hint->value);
hint->value = SDL_strdup(value);
}
hint->priority = priority;
return SDL_TRUE;
@@ -91,9 +92,9 @@ SDL_SetHintWithPriority(const char *name, const char *value,
return SDL_FALSE;
}
hint->name = SDL_strdup(name);
hint->value = SDL_strdup(value);
hint->value = value ? SDL_strdup(value) : NULL;
hint->priority = priority;
hint->callback = NULL;
hint->callbacks = NULL;
hint->next = SDL_hints;
SDL_hints = hint;
return SDL_TRUE;
@@ -123,16 +124,100 @@ SDL_GetHint(const char *name)
return env;
}
void
SDL_AddHintCallback(const char *name, SDL_HintCallback callback, void *userdata)
{
SDL_Hint *hint;
SDL_HintWatch *entry;
const char *value;
if (!name || !*name) {
SDL_InvalidParamError("name");
return;
}
if (!callback) {
SDL_InvalidParamError("callback");
return;
}
SDL_DelHintCallback(name, callback, userdata);
entry = (SDL_HintWatch *)SDL_malloc(sizeof(*entry));
entry->callback = callback;
entry->userdata = userdata;
for (hint = SDL_hints; hint; hint = hint->next) {
if (SDL_strcmp(name, hint->name) == 0) {
break;
}
}
if (!hint) {
/* Need to add a hint entry for this watcher */
hint = (SDL_Hint *)SDL_malloc(sizeof(*hint));
if (!hint) {
return;
}
hint->name = SDL_strdup(name);
hint->value = NULL;
hint->priority = SDL_HINT_DEFAULT;
hint->callbacks = NULL;
hint->next = SDL_hints;
SDL_hints = hint;
}
/* Add it to the callbacks for this hint */
entry->next = hint->callbacks;
hint->callbacks = entry;
/* Now call it with the current value */
value = SDL_GetHint(name);
callback(userdata, name, value, value);
}
void
SDL_DelHintCallback(const char *name, SDL_HintCallback callback, void *userdata)
{
SDL_Hint *hint;
SDL_HintWatch *entry, *prev;
for (hint = SDL_hints; hint; hint = hint->next) {
if (SDL_strcmp(name, hint->name) == 0) {
prev = NULL;
for (entry = hint->callbacks; entry; entry = entry->next) {
if (callback == entry->callback && userdata == entry->userdata) {
if (prev) {
prev->next = entry->next;
} else {
hint->callbacks = entry->next;
}
SDL_free(entry);
break;
}
prev = entry;
}
return;
}
}
}
void SDL_ClearHints(void)
{
SDL_Hint *hint;
SDL_HintWatch *entry;
while (SDL_hints) {
hint = SDL_hints;
SDL_hints = hint->next;
SDL_free(hint->name);
SDL_free(hint->value);
if (hint->value) {
SDL_free(hint->value);
}
for (entry = hint->callbacks; entry; ) {
SDL_HintWatch *freeable = entry;
entry = entry->next;
SDL_free(freeable);
}
SDL_free(hint);
}
}

View File

@@ -1,34 +0,0 @@
/*
Simple DirectMedia Layer
Copyright (C) 1997-2013 Sam Lantinga <slouken@libsdl.org>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#ifndef _SDL_hints_c_h
#define _SDL_hints_c_h
/**
* \brief A callback function that is optionally called when a hint changes
*/
typedef void (*SDL_HintChangedCb)(const char *name, const char *oldValue, const char *newValue);
extern SDL_bool SDL_RegisterHintChangedCb(const char *name, SDL_HintChangedCb hintCb);
#endif /* _SDL_hints_c_h */
/* vi: set ts=4 sw=4 expandtab: */

View File

@@ -39,6 +39,9 @@
#define DEFAULT_APPLICATION_PRIORITY SDL_LOG_PRIORITY_INFO
#define DEFAULT_TEST_PRIORITY SDL_LOG_PRIORITY_VERBOSE
/* Forward definition of error function */
extern int SDL_SetError(const char *fmt, ...);
typedef struct SDL_LogLevel
{
int category;
@@ -138,7 +141,7 @@ SDL_LogGetPriority(int category)
}
if (category == SDL_LOG_CATEGORY_TEST) {
return SDL_test_priority;
return SDL_test_priority;
} else if (category == SDL_LOG_CATEGORY_APPLICATION) {
return SDL_application_priority;
} else if (category == SDL_LOG_CATEGORY_ASSERT) {
@@ -263,6 +266,7 @@ void
SDL_LogMessageV(int category, SDL_LogPriority priority, const char *fmt, va_list ap)
{
char *message;
size_t len;
/* Nothing to do if we don't have an output function */
if (!SDL_log_function) {
@@ -283,27 +287,91 @@ SDL_LogMessageV(int category, SDL_LogPriority priority, const char *fmt, va_list
if (!message) {
return;
}
SDL_vsnprintf(message, SDL_MAX_LOG_MESSAGE, fmt, ap);
/* Chop off final endline. */
len = SDL_strlen(message);
if ((len > 0) && (message[len-1] == '\n')) {
message[--len] = '\0';
if ((len > 0) && (message[len-1] == '\r')) { /* catch "\r\n", too. */
message[--len] = '\0';
}
}
SDL_log_function(SDL_log_userdata, category, priority, message);
SDL_stack_free(message);
}
#if defined(__WIN32__)
/* Flag tracking the attachment of the console: 0=unattached, 1=attached, -1=error */
static int consoleAttached = 0;
/* Handle to stderr output of console. */
static HANDLE stderrHandle = NULL;
#endif
static void
SDL_LogOutput(void *userdata, int category, SDL_LogPriority priority,
const char *message)
{
#if defined(__WIN32__) || defined(__WINRT__)
/* Way too many allocations here, urgh */
/* Note: One can't call SDL_SetError here, since that function itself logs. */
{
char *output;
size_t length;
LPTSTR tstr;
BOOL attachResult;
DWORD attachError;
unsigned long charsWritten;
length = SDL_strlen(SDL_priority_prefixes[priority]) + 2 + SDL_strlen(message) + 1;
/* Maybe attach console and get stderr handle */
if (consoleAttached == 0) {
attachResult = AttachConsole(ATTACH_PARENT_PROCESS);
if (!attachResult) {
attachError = GetLastError();
if (attachError == ERROR_INVALID_HANDLE) {
OutputDebugString(TEXT("Parent process has no console"));
consoleAttached = -1;
} else if (attachError == ERROR_GEN_FAILURE) {
OutputDebugString(TEXT("Could not attach to console of parent process"));
consoleAttached = -1;
} else if (attachError == ERROR_ACCESS_DENIED) {
/* Already attached */
consoleAttached = 1;
} else {
OutputDebugString(TEXT("Error attaching console"));
consoleAttached = -1;
}
} else {
/* Newly attached */
consoleAttached = 1;
}
if (consoleAttached == 1) {
stderrHandle = GetStdHandle(STD_ERROR_HANDLE);
}
}
length = SDL_strlen(SDL_priority_prefixes[priority]) + 2 + SDL_strlen(message) + 1 + 1;
output = SDL_stack_alloc(char, length);
SDL_snprintf(output, length, "%s: %s", SDL_priority_prefixes[priority], message);
SDL_snprintf(output, length, "%s: %s\n", SDL_priority_prefixes[priority], message);
tstr = WIN_UTF8ToString(output);
/* Output to debugger */
OutputDebugString(tstr);
/* Screen output to stderr, if console was attached. */
if (consoleAttached == 1) {
if (!WriteConsole(stderrHandle, tstr, lstrlen(tstr), &charsWritten, NULL)) {
OutputDebugString(TEXT("Error calling WriteConsole"));
}
if (charsWritten == ERROR_NOT_ENOUGH_MEMORY) {
OutputDebugString(TEXT("Insufficient heap memory to write message"));
}
}
SDL_free(tstr);
SDL_stack_free(output);
}
@@ -314,7 +382,9 @@ SDL_LogOutput(void *userdata, int category, SDL_LogPriority priority,
SDL_snprintf(tag, SDL_arraysize(tag), "SDL/%s", GetCategoryPrefix(category));
__android_log_write(SDL_android_priority[priority], tag, message);
}
#elif defined(__APPLE__)
#elif defined(__APPLE__) && defined(SDL_VIDEO_DRIVER_COCOA)
/* Technically we don't need SDL_VIDEO_DRIVER_COCOA, but that's where this function is defined for now.
*/
extern void SDL_NSLog(const char *text);
{
char *text;
@@ -328,19 +398,12 @@ SDL_LogOutput(void *userdata, int category, SDL_LogPriority priority,
}
}
#elif defined(__PSP__)
//Simple Log System for PSP
{
unsigned int length;
char* output;
FILE* pFile;
length = SDL_strlen(SDL_priority_prefixes[priority]) + 2 + SDL_strlen(message) + 1;
output = SDL_stack_alloc(char, length);
SDL_snprintf(output, length, "%s: %s", SDL_priority_prefixes[priority], message);
pFile = fopen ("SDL_Log.txt", "a");
fwrite (output, strlen (output), 1, pFile);
SDL_stack_free(output);
fclose (pFile);
}
{
FILE* pFile;
pFile = fopen ("SDL_Log.txt", "a");
fprintf(pFile, "%s: %s\n", SDL_priority_prefixes[priority], message);
fclose (pFile);
}
#endif
#if HAVE_STDIO_H
fprintf(stderr, "%s: %s\n", SDL_priority_prefixes[priority], message);

View File

@@ -29,8 +29,8 @@
*/
#undef SDL_AtomicCAS
#undef SDL_AtomicCASPtr
/*
/*
If any of the operations are not provided then we must emulate some
of them. That means we need a nice implementation of spin locks
that avoids the "one big lock" problem. We use a vector of spin
@@ -40,7 +40,7 @@
To generate the index of the lock we first shift by 3 bits to get
rid on the zero bits that result from 32 and 64 bit allignment of
data. We then mask off all but 5 bits and use those 5 bits as an
index into the table.
index into the table.
Picking the lock this way insures that accesses to the same data at
the same time will go to the same lock. OTOH, accesses to different
@@ -101,4 +101,18 @@ SDL_AtomicCASPtr(void **a, void *oldval, void *newval)
return retval;
}
#if defined(__GNUC__) && defined(__arm__) && \
(defined(__ARM_ARCH_6__) || defined(__ARM_ARCH_6J__) || defined(__ARM_ARCH_6K__) || defined(__ARM_ARCH_6T2__) || defined(__ARM_ARCH_6Z__) || defined(__ARM_ARCH_6ZK__))
__asm__(
" .align 2\n"
" .globl _SDL_MemoryBarrierRelease\n"
" .globl _SDL_MemoryBarrierAcquire\n"
"_SDL_MemoryBarrierRelease:\n"
"_SDL_MemoryBarrierAcquire:\n"
" mov r0, #0\n"
" mcr p15, 0, r0, c7, c10, 5\n"
" bx lr\n"
);
#endif /* __GNUC__ && __arm__ && ARMV6 */
/* vi: set ts=4 sw=4 expandtab: */

View File

@@ -76,11 +76,11 @@ SDL_AtomicTryLock(SDL_SpinLock *lock)
return (result == 0);
#elif defined(__GNUC__) && (defined(__i386__) || defined(__x86_64__))
int result;
__asm__ __volatile__(
int result;
__asm__ __volatile__(
"lock ; xchgl %0, (%1)\n"
: "=r" (result) : "r" (lock), "0" (1) : "cc", "memory");
return (result == 0);
return (result == 0);
#elif defined(__MACOSX__) || defined(__IPHONEOS__)
/* Maybe used for PowerPC, but the Intel asm or gcc atomics are favored. */
@@ -114,10 +114,10 @@ SDL_AtomicUnlock(SDL_SpinLock *lock)
#elif HAVE_GCC_ATOMICS || HAVE_GCC_SYNC_LOCK_TEST_AND_SET
__sync_lock_release(lock);
#elif HAVE_PTHREAD_SPINLOCK
pthread_spin_unlock(lock);
#else
*lock = 0;
#endif

View File

@@ -67,6 +67,7 @@ extern AudioBootStrap NDSAUD_bootstrap;
extern AudioBootStrap FUSIONSOUND_bootstrap;
extern AudioBootStrap ANDROIDAUD_bootstrap;
extern AudioBootStrap PSPAUD_bootstrap;
extern AudioBootStrap SNDIO_bootstrap;
/* Available audio drivers */
static const AudioBootStrap *const bootstrap[] = {
@@ -76,6 +77,9 @@ static const AudioBootStrap *const bootstrap[] = {
#if SDL_AUDIO_DRIVER_ALSA
&ALSA_bootstrap,
#endif
#if SDL_AUDIO_DRIVER_SNDIO
&SNDIO_bootstrap,
#endif
#if SDL_AUDIO_DRIVER_BSD
&BSD_AUDIO_bootstrap,
#endif
@@ -356,9 +360,7 @@ SDL_RunAudio(void *devicep)
device->convert.len_mult;
}
#endif
/* stream_len = device->convert.len; */
stream_len = device->spec.size;
stream_len = device->convert.len;
} else {
stream_len = device->spec.size;
}
@@ -457,15 +459,11 @@ SDL_RunAudio(void *devicep)
}
} else {
/* Otherwise, do not use the streamer. This is the old code. */
const int silence = (int) device->spec.silence;
/* Loop, filling the audio buffers */
while (device->enabled) {
if (device->paused) {
SDL_Delay(delay);
continue;
}
/* Fill the current buffer with sound */
if (device->convert.needed) {
if (device->convert.buf) {
@@ -481,7 +479,11 @@ SDL_RunAudio(void *devicep)
}
SDL_LockMutex(device->mixer_lock);
(*fill) (udata, stream, stream_len);
if (device->paused) {
SDL_memset(stream, silence, stream_len);
} else {
(*fill) (udata, stream, stream_len);
}
SDL_UnlockMutex(device->mixer_lock);
/* Convert the audio if necessary */
@@ -954,12 +956,6 @@ open_audio_device(const char *devname, int iscapture,
return 0;
}
/* If the audio driver changes the buffer size, accept it */
if (device->spec.samples != obtained->samples) {
obtained->samples = device->spec.samples;
SDL_CalculateAudioSpec(obtained);
}
/* See if we need to do any conversion */
build_cvt = SDL_FALSE;
if (obtained->freq != device->spec.freq) {
@@ -983,6 +979,16 @@ open_audio_device(const char *devname, int iscapture,
build_cvt = SDL_TRUE;
}
}
/* If the audio driver changes the buffer size, accept it.
This needs to be done after the format is modified above,
otherwise it might not have the correct buffer size.
*/
if (device->spec.samples != obtained->samples) {
obtained->samples = device->spec.samples;
SDL_CalculateAudioSpec(obtained);
}
if (build_cvt) {
/* Build an audio conversion block */
if (SDL_BuildAudioCVT(&device->convert,
@@ -994,7 +1000,7 @@ open_audio_device(const char *devname, int iscapture,
return 0;
}
if (device->convert.needed) {
device->convert.len = (int) (((double) obtained->size) /
device->convert.len = (int) (((double) device->spec.size) /
device->convert.len_ratio);
device->convert.buf =
@@ -1110,7 +1116,9 @@ SDL_PauseAudioDevice(SDL_AudioDeviceID devid, int pause_on)
{
SDL_AudioDevice *device = get_audio_device(devid);
if (device) {
current_audio.impl.LockDevice(device);
device->paused = pause_on;
current_audio.impl.UnlockDevice(device);
}
}
@@ -1173,8 +1181,15 @@ void
SDL_AudioQuit(void)
{
SDL_AudioDeviceID i;
if (!current_audio.name) { /* not initialized?! */
return;
}
for (i = 0; i < SDL_arraysize(open_devices); i++) {
SDL_CloseAudioDevice(i);
if (open_devices[i] != NULL) {
SDL_CloseAudioDevice(i+1);
}
}
/* Free the driver data */

View File

@@ -293,10 +293,9 @@ SDL_ConvertStereo(SDL_AudioCVT * cvt, SDL_AudioFormat format)
const type *src = (const type *) (cvt->buf + cvt->len_cvt); \
type *dst = (type *) (cvt->buf + cvt->len_cvt * 2); \
for (i = cvt->len_cvt / sizeof(type); i; --i) { \
const type val = *src; \
src -= 1; \
dst -= 2; \
dst[0] = dst[1] = val; \
dst[0] = dst[1] = *src; \
} \
}
@@ -972,7 +971,7 @@ SDL_BuildAudioCVT(SDL_AudioCVT * cvt,
if (cvt == NULL) {
return SDL_InvalidParamError("cvt");
}
/* there are no unsigned types over 16 bits, so catch this up front. */
if ((SDL_AUDIO_BITSIZE(src_fmt) > 16) && (!SDL_AUDIO_ISSIGNED(src_fmt))) {
return SDL_SetError("Invalid source format");

View File

@@ -40,10 +40,10 @@
#endif
#endif
#ifndef _PATH_DEV_DSP24
#define _PATH_DEV_DSP24 "/dev/sound/dsp"
#define _PATH_DEV_DSP24 "/dev/sound/dsp"
#endif
#ifndef _PATH_DEV_AUDIO
#define _PATH_DEV_AUDIO "/dev/audio"
#define _PATH_DEV_AUDIO "/dev/audio"
#endif
static inline void

View File

@@ -20,6 +20,6 @@
*/
#include "SDL_config.h"
#define SDL_AllocAudioMem SDL_malloc
#define SDL_FreeAudioMem SDL_free
#define SDL_AllocAudioMem SDL_malloc
#define SDL_FreeAudioMem SDL_free
/* vi: set ts=4 sw=4 expandtab: */

View File

@@ -82,8 +82,8 @@ static const Uint8 mix8[] = {
};
/* The volume ranges from 0 - 128 */
#define ADJUST_VOLUME(s, v) (s = (s*v)/SDL_MIX_MAXVOLUME)
#define ADJUST_VOLUME_U8(s, v) (s = (((s-128)*v)/SDL_MIX_MAXVOLUME)+128)
#define ADJUST_VOLUME(s, v) (s = (s*v)/SDL_MIX_MAXVOLUME)
#define ADJUST_VOLUME_U8(s, v) (s = (((s-128)*v)/SDL_MIX_MAXVOLUME)+128)
void

View File

@@ -28,7 +28,7 @@
/* The SDL audio driver */
typedef struct SDL_AudioDevice SDL_AudioDevice;
#define _THIS SDL_AudioDevice *_this
#define _THIS SDL_AudioDevice *_this
/* Used by audio targets during DetectDevices() */
typedef void (*SDL_AddAudioDevice)(const char *name);

View File

@@ -273,6 +273,11 @@ IMA_ADPCM_nibble(struct IMA_ADPCM_decodestate *state, Uint8 nybble)
Sint32 delta, step;
/* Compute difference and new sample value */
if (state->index > 88) {
state->index = 88;
} else if (state->index < 0) {
state->index = 0;
}
step = step_table[state->index];
delta = step >> 3;
if (nybble & 0x04)
@@ -287,11 +292,6 @@ IMA_ADPCM_nibble(struct IMA_ADPCM_decodestate *state, Uint8 nybble)
/* Update index value */
state->index += index_table[nybble];
if (state->index > 88) {
state->index = 88;
} else if (state->index < 0) {
state->index = 0;
}
/* Clamp output sample */
if (state->sample > max_audioval) {

View File

@@ -25,26 +25,26 @@
/*******************************************/
/* Define values for Microsoft WAVE format */
/*******************************************/
#define RIFF 0x46464952 /* "RIFF" */
#define WAVE 0x45564157 /* "WAVE" */
#define FACT 0x74636166 /* "fact" */
#define LIST 0x5453494c /* "LIST" */
#define FMT 0x20746D66 /* "fmt " */
#define DATA 0x61746164 /* "data" */
#define PCM_CODE 0x0001
#define MS_ADPCM_CODE 0x0002
#define IEEE_FLOAT_CODE 0x0003
#define IMA_ADPCM_CODE 0x0011
#define MP3_CODE 0x0055
#define WAVE_MONO 1
#define WAVE_STEREO 2
#define RIFF 0x46464952 /* "RIFF" */
#define WAVE 0x45564157 /* "WAVE" */
#define FACT 0x74636166 /* "fact" */
#define LIST 0x5453494c /* "LIST" */
#define FMT 0x20746D66 /* "fmt " */
#define DATA 0x61746164 /* "data" */
#define PCM_CODE 0x0001
#define MS_ADPCM_CODE 0x0002
#define IEEE_FLOAT_CODE 0x0003
#define IMA_ADPCM_CODE 0x0011
#define MP3_CODE 0x0055
#define WAVE_MONO 1
#define WAVE_STEREO 2
/* Normally, these three chunks come consecutively in a WAVE file */
typedef struct WaveFMT
{
/* Not saved in the chunk we read:
Uint32 FMTchunk;
Uint32 fmtlen;
Uint32 FMTchunk;
Uint32 fmtlen;
*/
Uint16 encoding;
Uint16 channels; /* 1 = mono, 2 = stereo */
@@ -61,4 +61,5 @@ typedef struct Chunk
Uint32 length;
Uint8 *data;
} Chunk;
/* vi: set ts=4 sw=4 expandtab: */

View File

@@ -155,7 +155,7 @@ static void
UnloadALSALibrary(void)
{
if (alsa_handle != NULL) {
SDL_UnloadObject(alsa_handle);
SDL_UnloadObject(alsa_handle);
alsa_handle = NULL;
}
}
@@ -643,7 +643,7 @@ ALSA_OpenDevice(_THIS, const char *devname, int iscapture)
ALSA_CloseDevice(this);
return SDL_OutOfMemory();
}
SDL_memset(this->hidden->mixbuf, this->spec.silence, this->spec.size);
SDL_memset(this->hidden->mixbuf, this->spec.silence, this->hidden->mixlen);
/* Switch to blocking mode for playback */
ALSA_snd_pcm_nonblock(pcm_handle, 0);

View File

@@ -20,15 +20,15 @@
*/
#include "SDL_config.h"
#ifndef _ALSA_PCM_audio_h
#define _ALSA_PCM_audio_h
#ifndef _SDL_ALSA_audio_h
#define _SDL_ALSA_audio_h
#include <alsa/asoundlib.h>
#include "../SDL_sysaudio.h"
/* Hidden "this" pointer for the audio functions */
#define _THIS SDL_AudioDevice *this
#define _THIS SDL_AudioDevice *this
struct SDL_PrivateAudioData
{
@@ -40,6 +40,6 @@ struct SDL_PrivateAudioData
int mixlen;
};
#endif /* _ALSA_PCM_audio_h */
#endif /* _SDL_ALSA_audio_h */
/* vi: set ts=4 sw=4 expandtab: */

View File

@@ -38,59 +38,52 @@ static int
AndroidAUD_OpenDevice(_THIS, const char *devname, int iscapture)
{
SDL_AudioFormat test_format;
int valid_datatype = 0;
if (iscapture) {
//TODO: implement capture
return SDL_SetError("Capture not supported on Android");
/* TODO: implement capture */
return SDL_SetError("Capture not supported on Android");
}
if (audioDevice != NULL) {
return SDL_SetError("Only one audio device at a time please!");
return SDL_SetError("Only one audio device at a time please!");
}
audioDevice = this;
this->hidden = SDL_malloc(sizeof(*(this->hidden)));
if (!this->hidden) {
return SDL_OutOfMemory();
}
SDL_memset(this->hidden, 0, (sizeof *this->hidden));
test_format = SDL_FirstAudioFormat(this->spec.format);
while (test_format != 0) { // no "UNKNOWN" constant
while (test_format != 0) { /* no "UNKNOWN" constant */
if ((test_format == AUDIO_U8) || (test_format == AUDIO_S16LSB)) {
this->spec.format = test_format;
break;
}
test_format = SDL_NextAudioFormat();
}
if (test_format == 0) {
// Didn't find a compatible format :(
return SDL_SetError("No compatible audio format!");
/* Didn't find a compatible format :( */
return SDL_SetError("No compatible audio format!");
}
if (this->spec.channels > 1) {
this->spec.channels = 2;
this->spec.channels = 2;
} else {
this->spec.channels = 1;
this->spec.channels = 1;
}
if (this->spec.freq < 8000) {
this->spec.freq = 8000;
this->spec.freq = 8000;
}
if (this->spec.freq > 48000) {
this->spec.freq = 48000;
this->spec.freq = 48000;
}
// TODO: pass in/return a (Java) device ID, also whether we're opening for input or output
/* TODO: pass in/return a (Java) device ID, also whether we're opening for input or output */
this->spec.samples = Android_JNI_OpenAudioDevice(this->spec.freq, this->spec.format == AUDIO_U8 ? 0 : 1, this->spec.channels, this->spec.samples);
SDL_CalculateAudioSpec(&this->spec);
if (this->spec.samples == 0) {
// Init failed?
return SDL_SetError("Java-side initialization failed!");
/* Init failed? */
return SDL_SetError("Java-side initialization failed!");
}
return 0;
@@ -111,14 +104,13 @@ AndroidAUD_GetDeviceBuf(_THIS)
static void
AndroidAUD_CloseDevice(_THIS)
{
if (this->hidden != NULL) {
SDL_free(this->hidden);
this->hidden = NULL;
}
Android_JNI_CloseAudioDevice();
/* At this point SDL_CloseAudioDevice via close_audio_device took care of terminating the audio thread
so it's safe to terminate the Java side buffer and AudioTrack
*/
Android_JNI_CloseAudioDevice();
if (audioDevice == this) {
audioDevice = NULL;
audioDevice = NULL;
}
}
@@ -132,8 +124,7 @@ AndroidAUD_Init(SDL_AudioDriverImpl * impl)
impl->CloseDevice = AndroidAUD_CloseDevice;
/* and the capabilities */
impl->ProvidesOwnCallbackThread = 1;
impl->HasCaptureSupport = 0; //TODO
impl->HasCaptureSupport = 0; /* TODO */
impl->OnlyHasDefaultOutputDevice = 1;
impl->OnlyHasDefaultInputDevice = 1;
@@ -144,13 +135,7 @@ AudioBootStrap ANDROIDAUD_bootstrap = {
"android", "SDL Android audio driver", AndroidAUD_Init, 0
};
/* Called by the Java code to start the audio processing on a thread */
void
Android_RunAudioThread()
{
SDL_RunAudio(audioDevice);
}
#endif /* SDL_AUDIO_DRIVER_ANDROID */
/* vi: set ts=4 sw=4 expandtab: */

View File

@@ -26,12 +26,14 @@
#include "../SDL_sysaudio.h"
/* Hidden "this" pointer for the audio functions */
#define _THIS SDL_AudioDevice *this
#define _THIS SDL_AudioDevice *this
struct SDL_PrivateAudioData
{
};
static void AndroidAUD_CloseDevice(_THIS);
#endif /* _SDL_androidaudio_h */
/* vi: set ts=4 sw=4 expandtab: */

View File

@@ -28,7 +28,7 @@
#include "../SDL_sysaudio.h"
/* Hidden "this" pointer for the audio functions */
#define _THIS SDL_AudioDevice *this
#define _THIS SDL_AudioDevice *this
struct SDL_PrivateAudioData
{
@@ -46,7 +46,7 @@ struct SDL_PrivateAudioData
float frame_ticks;
float next_frame;
};
#define FUDGE_TICKS 10 /* The scheduler overhead ticks per frame */
#define FUDGE_TICKS 10 /* The scheduler overhead ticks per frame */
#endif /* _SDL_artscaudio_h */
/* vi: set ts=4 sw=4 expandtab: */

View File

@@ -26,7 +26,7 @@
#include "../SDL_sysaudio.h"
/* Hidden "this" pointer for the audio functions */
#define _THIS SDL_AudioDevice *_this
#define _THIS SDL_AudioDevice *_this
struct SDL_PrivateAudioData
{

View File

@@ -25,7 +25,7 @@
#include "../SDL_sysaudio.h"
#define _THIS SDL_AudioDevice *this
#define _THIS SDL_AudioDevice *this
struct SDL_PrivateAudioData
{
@@ -44,7 +44,7 @@ struct SDL_PrivateAudioData
float next_frame;
};
#define FUDGE_TICKS 10 /* The scheduler overhead ticks per frame */
#define FUDGE_TICKS 10 /* The scheduler overhead ticks per frame */
#endif /* _SDL_bsdaudio_h */

View File

@@ -308,8 +308,8 @@ inputCallback(void *inRefCon,
UInt32 inBusNumber, UInt32 inNumberFrames,
AudioBufferList * ioData)
{
//err = AudioUnitRender(afr->fAudioUnit, ioActionFlags, inTimeStamp, inBusNumber, inNumberFrames, afr->fAudioBuffer);
// !!! FIXME: write me!
/* err = AudioUnitRender(afr->fAudioUnit, ioActionFlags, inTimeStamp, inBusNumber, inNumberFrames, afr->fAudioBuffer); */
/* !!! FIXME: write me! */
return noErr;
}
@@ -380,7 +380,7 @@ prepare_audiounit(_THIS, const char *devname, int iscapture,
return 0;
}
#endif
SDL_zero(desc);
desc.componentType = kAudioUnitType_Output;
desc.componentManufacturer = kAudioUnitManufacturer_Apple;

View File

@@ -32,9 +32,6 @@
#if MACOSX_COREAUDIO
#include <CoreAudio/CoreAudio.h>
#include <CoreServices/CoreServices.h>
#if MAC_OS_X_VERSION_MAX_ALLOWED <= 1050
#include <AudioUnit/AUNTComponent.h>
#endif
#else
#include <AudioToolbox/AudioToolbox.h>
#endif
@@ -42,7 +39,7 @@
#include <AudioUnit/AudioUnit.h>
/* Hidden "this" pointer for the audio functions */
#define _THIS SDL_AudioDevice *this
#define _THIS SDL_AudioDevice *this
struct SDL_PrivateAudioData
{

View File

@@ -30,6 +30,10 @@
#include "../SDL_audio_c.h"
#include "SDL_directsound.h"
#ifndef WAVE_FORMAT_IEEE_FLOAT
#define WAVE_FORMAT_IEEE_FLOAT 0x0003
#endif
/* DirectX function pointers for audio */
static void* DSoundDLL = NULL;
typedef HRESULT(WINAPI*fnDirectSoundCreate8)(LPGUID,LPDIRECTSOUND*,LPUNKNOWN);
@@ -342,7 +346,7 @@ DSOUND_CloseDevice(_THIS)
number of audio chunks available in the created buffer.
*/
static int
CreateSecondary(_THIS, HWND focus, WAVEFORMATEX * wavefmt)
CreateSecondary(_THIS, HWND focus)
{
LPDIRECTSOUND sndObj = this->hidden->sound;
LPDIRECTSOUNDBUFFER *sndbuf = &this->hidden->mixbuf;
@@ -352,6 +356,24 @@ CreateSecondary(_THIS, HWND focus, WAVEFORMATEX * wavefmt)
DSBUFFERDESC format;
LPVOID pvAudioPtr1, pvAudioPtr2;
DWORD dwAudioBytes1, dwAudioBytes2;
WAVEFORMATEX wfmt;
SDL_zero(wfmt);
if (SDL_AUDIO_ISFLOAT(this->spec.format)) {
wfmt.wFormatTag = WAVE_FORMAT_IEEE_FLOAT;
} else {
wfmt.wFormatTag = WAVE_FORMAT_PCM;
}
wfmt.wBitsPerSample = SDL_AUDIO_BITSIZE(this->spec.format);
wfmt.nChannels = this->spec.channels;
wfmt.nSamplesPerSec = this->spec.freq;
wfmt.nBlockAlign = wfmt.nChannels * (wfmt.wBitsPerSample / 8);
wfmt.nAvgBytesPerSec = wfmt.nSamplesPerSec * wfmt.nBlockAlign;
/* Update the fragment size as size in bytes */
SDL_CalculateAudioSpec(&this->spec);
/* Try to set primary mixing privileges */
if (focus) {
@@ -367,7 +389,7 @@ CreateSecondary(_THIS, HWND focus, WAVEFORMATEX * wavefmt)
}
/* Try to create the secondary buffer */
SDL_memset(&format, 0, sizeof(format));
SDL_zero(format);
format.dwSize = sizeof(format);
format.dwFlags = DSBCAPS_GETCURRENTPOSITION2;
if (!focus) {
@@ -382,12 +404,12 @@ CreateSecondary(_THIS, HWND focus, WAVEFORMATEX * wavefmt)
DSBSIZE_MIN / numchunks, DSBSIZE_MAX / numchunks);
}
format.dwReserved = 0;
format.lpwfxFormat = wavefmt;
format.lpwfxFormat = &wfmt;
result = IDirectSound_CreateSoundBuffer(sndObj, &format, sndbuf, NULL);
if (result != DS_OK) {
return SetDSerror("DirectSound CreateSoundBuffer", result);
}
IDirectSoundBuffer_SetFormat(*sndbuf, wavefmt);
IDirectSoundBuffer_SetFormat(*sndbuf, &wfmt);
/* Silence the initial audio buffer */
result = IDirectSoundBuffer_Lock(*sndbuf, 0, format.dwBufferBytes,
@@ -433,8 +455,8 @@ static int
DSOUND_OpenDevice(_THIS, const char *devname, int iscapture)
{
HRESULT result;
WAVEFORMATEX waveformat;
int valid_format = 0;
SDL_bool valid_format = SDL_FALSE;
SDL_bool tried_format = SDL_FALSE;
SDL_AudioFormat test_format = SDL_FirstAudioFormat(this->spec.format);
FindDevGUIDData devguid;
LPGUID guid = NULL;
@@ -461,36 +483,6 @@ DSOUND_OpenDevice(_THIS, const char *devname, int iscapture)
}
SDL_memset(this->hidden, 0, (sizeof *this->hidden));
while ((!valid_format) && (test_format)) {
switch (test_format) {
case AUDIO_U8:
case AUDIO_S16:
case AUDIO_S32:
this->spec.format = test_format;
valid_format = 1;
break;
}
test_format = SDL_NextAudioFormat();
}
if (!valid_format) {
DSOUND_CloseDevice(this);
return SDL_SetError("DirectSound: Unsupported audio format");
}
SDL_memset(&waveformat, 0, sizeof(waveformat));
waveformat.wFormatTag = WAVE_FORMAT_PCM;
waveformat.wBitsPerSample = SDL_AUDIO_BITSIZE(this->spec.format);
waveformat.nChannels = this->spec.channels;
waveformat.nSamplesPerSec = this->spec.freq;
waveformat.nBlockAlign =
waveformat.nChannels * (waveformat.wBitsPerSample / 8);
waveformat.nAvgBytesPerSec =
waveformat.nSamplesPerSec * waveformat.nBlockAlign;
/* Update the fragment size as size in bytes */
SDL_CalculateAudioSpec(&this->spec);
/* Open the audio device */
result = pDirectSoundCreate8(guid, &this->hidden->sound, NULL);
if (result != DS_OK) {
@@ -498,11 +490,29 @@ DSOUND_OpenDevice(_THIS, const char *devname, int iscapture)
return SetDSerror("DirectSoundCreate", result);
}
/* Create the audio buffer to which we write */
this->hidden->num_buffers = CreateSecondary(this, NULL, &waveformat);
if (this->hidden->num_buffers < 0) {
while ((!valid_format) && (test_format)) {
switch (test_format) {
case AUDIO_U8:
case AUDIO_S16:
case AUDIO_S32:
case AUDIO_F32:
tried_format = SDL_TRUE;
this->spec.format = test_format;
this->hidden->num_buffers = CreateSecondary(this, NULL);
if (this->hidden->num_buffers > 0) {
valid_format = SDL_TRUE;
}
break;
}
test_format = SDL_NextAudioFormat();
}
if (!valid_format) {
DSOUND_CloseDevice(this);
return -1;
if (tried_format) {
return -1; // CreateSecondary() should have called SDL_SetError().
}
return SDL_SetError("DirectSound: Unsupported audio format");
}
/* The buffer will auto-start playing in DSOUND_WaitDevice() */

View File

@@ -28,7 +28,7 @@
#include "../SDL_sysaudio.h"
/* Hidden "this" pointer for the audio functions */
#define _THIS SDL_AudioDevice *this
#define _THIS SDL_AudioDevice *this
/* The DirectSound objects */
struct SDL_PrivateAudioData

View File

@@ -19,47 +19,47 @@
/* Error codes not yet included in Win32 API header files */
#ifndef MAKE_HRESULT
#define MAKE_HRESULT(sev,fac,code) \
((HRESULT)(((unsigned long)(sev)<<31) | ((unsigned long)(fac)<<16) | ((unsigned long)(code))))
((HRESULT)(((unsigned long)(sev)<<31) | ((unsigned long)(fac)<<16) | ((unsigned long)(code))))
#endif
#ifndef S_OK
#define S_OK (HRESULT)0x00000000L
#define S_OK (HRESULT)0x00000000L
#endif
#ifndef SUCCEEDED
#define SUCCEEDED(x) ((HRESULT)(x) >= 0)
#define SUCCEEDED(x) ((HRESULT)(x) >= 0)
#endif
#ifndef FAILED
#define FAILED(x) ((HRESULT)(x)<0)
#define FAILED(x) ((HRESULT)(x)<0)
#endif
#ifndef E_FAIL
#define E_FAIL (HRESULT)0x80000008L
#define E_FAIL (HRESULT)0x80000008L
#endif
#ifndef E_NOINTERFACE
#define E_NOINTERFACE (HRESULT)0x80004002L
#define E_NOINTERFACE (HRESULT)0x80004002L
#endif
#ifndef E_OUTOFMEMORY
#define E_OUTOFMEMORY (HRESULT)0x8007000EL
#define E_OUTOFMEMORY (HRESULT)0x8007000EL
#endif
#ifndef E_INVALIDARG
#define E_INVALIDARG (HRESULT)0x80070057L
#define E_INVALIDARG (HRESULT)0x80070057L
#endif
#ifndef E_NOTIMPL
#define E_NOTIMPL (HRESULT)0x80004001L
#define E_NOTIMPL (HRESULT)0x80004001L
#endif
#ifndef REGDB_E_CLASSNOTREG
#define REGDB_E_CLASSNOTREG (HRESULT)0x80040154L
#define REGDB_E_CLASSNOTREG (HRESULT)0x80040154L
#endif
/* Severity codes */
#ifndef SEVERITY_ERROR
#define SEVERITY_ERROR 1
#define SEVERITY_ERROR 1
#endif
/* Error facility codes */
#ifndef FACILITY_WIN32
#define FACILITY_WIN32 7
#define FACILITY_WIN32 7
#endif
#ifndef FIELD_OFFSET

View File

@@ -114,6 +114,10 @@ DISKAUD_OpenDevice(_THIS, const char *devname, int iscapture)
}
SDL_memset(this->hidden, 0, sizeof(*this->hidden));
this->hidden->mixlen = this->spec.size;
this->hidden->write_delay =
(envr) ? SDL_atoi(envr) : DISKDEFAULT_WRITEDELAY;
/* Open the audio device */
this->hidden->output = SDL_RWFromFile(fname, "wb");
if (this->hidden->output == NULL) {
@@ -129,10 +133,6 @@ DISKAUD_OpenDevice(_THIS, const char *devname, int iscapture)
}
SDL_memset(this->hidden->mixbuf, this->spec.silence, this->spec.size);
this->hidden->mixlen = this->spec.size;
this->hidden->write_delay =
(envr) ? SDL_atoi(envr) : DISKDEFAULT_WRITEDELAY;
#if HAVE_STDIO_H
fprintf(stderr,
"WARNING: You are using the SDL disk writer audio driver!\n"

View File

@@ -27,7 +27,7 @@
#include "../SDL_sysaudio.h"
/* Hidden "this" pointer for the audio functions */
#define _THIS SDL_AudioDevice *this
#define _THIS SDL_AudioDevice *this
struct SDL_PrivateAudioData
{

View File

@@ -161,7 +161,7 @@ DSP_OpenDevice(_THIS, const char *devname, int iscapture)
break;
#if 0
/*
* These formats are not used by any real life systems so they are not
* These formats are not used by any real life systems so they are not
* needed here.
*/
case AUDIO_S8:

View File

@@ -26,7 +26,7 @@
#include "../SDL_sysaudio.h"
/* Hidden "this" pointer for the audio functions */
#define _THIS SDL_AudioDevice *this
#define _THIS SDL_AudioDevice *this
struct SDL_PrivateAudioData
{
@@ -37,7 +37,7 @@ struct SDL_PrivateAudioData
Uint8 *mixbuf;
int mixlen;
};
#define FUDGE_TICKS 10 /* The scheduler overhead ticks per frame */
#define FUDGE_TICKS 10 /* The scheduler overhead ticks per frame */
#endif /* _SDL_dspaudio_h */
/* vi: set ts=4 sw=4 expandtab: */

View File

@@ -26,7 +26,7 @@
#include "../SDL_sysaudio.h"
/* Hidden "this" pointer for the audio functions */
#define _THIS SDL_AudioDevice *this
#define _THIS SDL_AudioDevice *this
struct SDL_PrivateAudioData
{

View File

@@ -40,7 +40,7 @@
#include "SDL_name.h"
#include "SDL_loadso.h"
#else
#define SDL_NAME(X) X
#define SDL_NAME(X) X
#endif
#ifdef SDL_AUDIO_DRIVER_ESD_DYNAMIC
@@ -123,7 +123,7 @@ ESD_WaitDevice(_THIS)
/* Check to see if the thread-parent process is still alive */
{
static int cnt = 0;
/* Note that this only works with thread implementations
/* Note that this only works with thread implementations
that use a different process id for each thread.
*/
/* Check every 10 loops */

View File

@@ -26,7 +26,7 @@
#include "../SDL_sysaudio.h"
/* Hidden "this" pointer for the audio functions */
#define _THIS SDL_AudioDevice *this
#define _THIS SDL_AudioDevice *this
struct SDL_PrivateAudioData
{
@@ -44,7 +44,7 @@ struct SDL_PrivateAudioData
float frame_ticks;
float next_frame;
};
#define FUDGE_TICKS 10 /* The scheduler overhead ticks per frame */
#define FUDGE_TICKS 10 /* The scheduler overhead ticks per frame */
#endif /* _SDL_esdaudio_h */
/* vi: set ts=4 sw=4 expandtab: */

View File

@@ -37,13 +37,13 @@
#include <fusionsound/fusionsound_version.h>
//#define SDL_AUDIO_DRIVER_FUSIONSOUND_DYNAMIC "libfusionsound.so"
/* #define SDL_AUDIO_DRIVER_FUSIONSOUND_DYNAMIC "libfusionsound.so" */
#ifdef SDL_AUDIO_DRIVER_FUSIONSOUND_DYNAMIC
#include "SDL_name.h"
#include "SDL_loadso.h"
#else
#define SDL_NAME(X) X
#define SDL_NAME(X) X
#endif
#if (FUSIONSOUND_MAJOR_VERSION == 1) && (FUSIONSOUND_MINOR_VERSION < 1)
@@ -51,7 +51,7 @@ typedef DFBResult DirectResult;
#endif
/* Buffers to use - more than 2 gives a lot of latency */
#define FUSION_BUFFERS (2)
#define FUSION_BUFFERS (2)
#ifdef SDL_AUDIO_DRIVER_FUSIONSOUND_DYNAMIC

View File

@@ -28,7 +28,7 @@
#include "../SDL_sysaudio.h"
/* Hidden "this" pointer for the audio functions */
#define _THIS SDL_AudioDevice *this
#define _THIS SDL_AudioDevice *this
struct SDL_PrivateAudioData
{

View File

@@ -33,7 +33,7 @@
#include "../SDL_sysaudio.h"
/* Hidden "this" pointer for the audio functions */
#define _THIS SDL_AudioDevice *this
#define _THIS SDL_AudioDevice *this
struct SDL_PrivateAudioData
{

View File

@@ -48,13 +48,13 @@
#include <sys/audio.h>
/* Open the audio device for playback, and don't block if busy */
/* #define OPEN_FLAGS (O_WRONLY|O_NONBLOCK) */
#define OPEN_FLAGS O_WRONLY
/* #define OPEN_FLAGS (O_WRONLY|O_NONBLOCK) */
#define OPEN_FLAGS O_WRONLY
/* Get the name of the audio device we use for output */
#ifndef _PATH_DEV_DSP
#define _PATH_DEV_DSP "/dev/%caud%c/%c"
#define _PATH_DEV_DSP "/dev/%caud%c/%c"
#endif
static char devsettings[][3] = {

View File

@@ -26,7 +26,7 @@
#include "../SDL_sysaudio.h"
/* Hidden "this" pointer for the audio functions */
#define _THIS SDL_AudioDevice *this
#define _THIS SDL_AudioDevice *this
struct SDL_PrivateAudioData
{
@@ -41,7 +41,7 @@ struct SDL_PrivateAudioData
float frame_ticks;
float next_frame;
};
#define FUDGE_TICKS 10 /* The scheduler overhead ticks per frame */
#define FUDGE_TICKS 10 /* The scheduler overhead ticks per frame */
#endif /* _SDL_paudaudio_h */
/* vi: set ts=4 sw=4 expandtab: */

View File

@@ -42,28 +42,28 @@
static int
PSPAUD_OpenDevice(_THIS, const char *devname, int iscapture)
{
int format, mixlen, i;
int format, mixlen, i;
this->hidden = (struct SDL_PrivateAudioData *)
SDL_malloc(sizeof(*this->hidden));
if (this->hidden == NULL) {
return SDL_OutOfMemory();
}
SDL_memset(this->hidden, 0, sizeof(*this->hidden));
switch (this->spec.format & 0xff) {
case 8:
case 16:
this->spec.format = AUDIO_S16LSB;
break;
default:
return SDL_SetError("Unsupported audio format");
}
switch (this->spec.format & 0xff) {
case 8:
case 16:
this->spec.format = AUDIO_S16LSB;
break;
default:
return SDL_SetError("Unsupported audio format");
}
/* The sample count must be a multiple of 64. */
this->spec.samples = PSP_AUDIO_SAMPLE_ALIGN(this->spec.samples);
this->spec.freq = 44100;
/* The sample count must be a multiple of 64. */
this->spec.samples = PSP_AUDIO_SAMPLE_ALIGN(this->spec.samples);
this->spec.freq = 44100;
/* Update the fragment size as size in bytes. */
// SDL_CalculateAudioSpec(this->spec); MOD
/* Update the fragment size as size in bytes. */
// SDL_CalculateAudioSpec(this->spec); MOD
switch (this->spec.format) {
case AUDIO_U8:
this->spec.silence = 0x80;
@@ -75,86 +75,86 @@ PSPAUD_OpenDevice(_THIS, const char *devname, int iscapture)
this->spec.size = SDL_AUDIO_BITSIZE(this->spec.format) / 8;
this->spec.size *= this->spec.channels;
this->spec.size *= this->spec.samples;
//==========================================
/* Allocate the mixing buffer. Its size and starting address must
be a multiple of 64 bytes. Our sample count is already a multiple of
64, so spec->size should be a multiple of 64 as well. */
mixlen = this->spec.size * NUM_BUFFERS;
this->hidden->rawbuf = (Uint8 *) memalign(64, mixlen);
if (this->hidden->rawbuf == NULL) {
return SDL_SetError("Couldn't allocate mixing buffer");
}
/* Allocate the mixing buffer. Its size and starting address must
be a multiple of 64 bytes. Our sample count is already a multiple of
64, so spec->size should be a multiple of 64 as well. */
mixlen = this->spec.size * NUM_BUFFERS;
this->hidden->rawbuf = (Uint8 *) memalign(64, mixlen);
if (this->hidden->rawbuf == NULL) {
return SDL_SetError("Couldn't allocate mixing buffer");
}
/* Setup the hardware channel. */
if (this->spec.channels == 1) {
format = PSP_AUDIO_FORMAT_MONO;
} else {
format = PSP_AUDIO_FORMAT_STEREO;
}
this->hidden->channel = sceAudioChReserve(PSP_AUDIO_NEXT_CHANNEL, this->spec.samples, format);
if (this->hidden->channel < 0) {
free(this->hidden->rawbuf);
this->hidden->rawbuf = NULL;
return SDL_SetError("Couldn't reserve hardware channel");
}
/* Setup the hardware channel. */
if (this->spec.channels == 1) {
format = PSP_AUDIO_FORMAT_MONO;
} else {
format = PSP_AUDIO_FORMAT_STEREO;
}
this->hidden->channel = sceAudioChReserve(PSP_AUDIO_NEXT_CHANNEL, this->spec.samples, format);
if (this->hidden->channel < 0) {
free(this->hidden->rawbuf);
this->hidden->rawbuf = NULL;
return SDL_SetError("Couldn't reserve hardware channel");
}
memset(this->hidden->rawbuf, 0, mixlen);
for (i = 0; i < NUM_BUFFERS; i++) {
this->hidden->mixbufs[i] = &this->hidden->rawbuf[i * this->spec.size];
}
memset(this->hidden->rawbuf, 0, mixlen);
for (i = 0; i < NUM_BUFFERS; i++) {
this->hidden->mixbufs[i] = &this->hidden->rawbuf[i * this->spec.size];
}
this->hidden->next_buffer = 0;
return 0;
this->hidden->next_buffer = 0;
return 0;
}
static void PSPAUD_PlayDevice(_THIS)
{
Uint8 *mixbuf = this->hidden->mixbufs[this->hidden->next_buffer];
Uint8 *mixbuf = this->hidden->mixbufs[this->hidden->next_buffer];
if (this->spec.channels == 1) {
sceAudioOutputBlocking(this->hidden->channel, PSP_AUDIO_VOLUME_MAX, mixbuf);
} else {
sceAudioOutputPannedBlocking(this->hidden->channel, PSP_AUDIO_VOLUME_MAX, PSP_AUDIO_VOLUME_MAX, mixbuf);
}
if (this->spec.channels == 1) {
sceAudioOutputBlocking(this->hidden->channel, PSP_AUDIO_VOLUME_MAX, mixbuf);
} else {
sceAudioOutputPannedBlocking(this->hidden->channel, PSP_AUDIO_VOLUME_MAX, PSP_AUDIO_VOLUME_MAX, mixbuf);
}
this->hidden->next_buffer = (this->hidden->next_buffer + 1) % NUM_BUFFERS;
this->hidden->next_buffer = (this->hidden->next_buffer + 1) % NUM_BUFFERS;
}
/* This function waits until it is possible to write a full sound buffer */
static void PSPAUD_WaitDevice(_THIS)
{
/* Because we block when sending audio, there's no need for this function to do anything. */
/* Because we block when sending audio, there's no need for this function to do anything. */
}
static Uint8 *PSPAUD_GetDeviceBuf(_THIS)
{
return this->hidden->mixbufs[this->hidden->next_buffer];
return this->hidden->mixbufs[this->hidden->next_buffer];
}
static void PSPAUD_CloseDevice(_THIS)
{
if (this->hidden->channel >= 0) {
sceAudioChRelease(this->hidden->channel);
this->hidden->channel = -1;
}
if (this->hidden->channel >= 0) {
sceAudioChRelease(this->hidden->channel);
this->hidden->channel = -1;
}
if (this->hidden->rawbuf != NULL) {
free(this->hidden->rawbuf);
this->hidden->rawbuf = NULL;
}
if (this->hidden->rawbuf != NULL) {
free(this->hidden->rawbuf);
this->hidden->rawbuf = NULL;
}
}
static void PSPAUD_ThreadInit(_THIS)
{
/* Increase the priority of this audio thread by 1 to put it
ahead of other SDL threads. */
SceUID thid;
SceKernelThreadInfo status;
thid = sceKernelGetThreadId();
status.size = sizeof(SceKernelThreadInfo);
if (sceKernelReferThreadStatus(thid, &status) == 0) {
sceKernelChangeThreadPriority(thid, status.currentPriority - 1);
}
/* Increase the priority of this audio thread by 1 to put it
ahead of other SDL threads. */
SceUID thid;
SceKernelThreadInfo status;
thid = sceKernelGetThreadId();
status.size = sizeof(SceKernelThreadInfo);
if (sceKernelReferThreadStatus(thid, &status) == 0) {
sceKernelChangeThreadPriority(thid, status.currentPriority - 1);
}
}
@@ -162,17 +162,17 @@ static int
PSPAUD_Init(SDL_AudioDriverImpl * impl)
{
// Set the function pointers
// Set the function pointers
impl->OpenDevice = PSPAUD_OpenDevice;
impl->PlayDevice = PSPAUD_PlayDevice;
impl->WaitDevice = PSPAUD_WaitDevice;
impl->GetDeviceBuf = PSPAUD_GetDeviceBuf;
impl->GetDeviceBuf = PSPAUD_GetDeviceBuf;
impl->WaitDone = PSPAUD_WaitDevice;
impl->CloseDevice = PSPAUD_CloseDevice;
impl->ThreadInit = PSPAUD_ThreadInit;
//PSP audio device
impl->OnlyHasDefaultOutputDevice = 1;
impl->OnlyHasDefaultOutputDevice = 1;
/*
impl->HasCaptureSupport = 1;

View File

@@ -25,19 +25,19 @@
#include "../SDL_sysaudio.h"
/* Hidden "this" pointer for the video functions */
#define _THIS SDL_AudioDevice *this
#define _THIS SDL_AudioDevice *this
#define NUM_BUFFERS 2
struct SDL_PrivateAudioData {
/* The hardware output channel. */
int channel;
/* The raw allocated mixing buffer. */
Uint8 *rawbuf;
/* Individual mixing buffers. */
Uint8 *mixbufs[NUM_BUFFERS];
/* Index of the next available mixing buffer. */
int next_buffer;
/* The hardware output channel. */
int channel;
/* The raw allocated mixing buffer. */
Uint8 *rawbuf;
/* Individual mixing buffers. */
Uint8 *mixbufs[NUM_BUFFERS];
/* Index of the next available mixing buffer. */
int next_buffer;
};
#endif /* _SDL_pspaudio_h */

View File

@@ -49,7 +49,7 @@
#if (PA_API_VERSION < 12)
/** Return non-zero if the passed state is one of the connected states */
static inline int PA_CONTEXT_IS_GOOD(pa_context_state_t x) {
static __inline__ int PA_CONTEXT_IS_GOOD(pa_context_state_t x) {
return
x == PA_CONTEXT_CONNECTING ||
x == PA_CONTEXT_AUTHORIZING ||
@@ -57,7 +57,7 @@ static inline int PA_CONTEXT_IS_GOOD(pa_context_state_t x) {
x == PA_CONTEXT_READY;
}
/** Return non-zero if the passed state is one of the connected states */
static inline int PA_STREAM_IS_GOOD(pa_stream_state_t x) {
static __inline__ int PA_STREAM_IS_GOOD(pa_stream_state_t x) {
return
x == PA_STREAM_CREATING ||
x == PA_STREAM_READY;
@@ -65,6 +65,7 @@ static inline int PA_STREAM_IS_GOOD(pa_stream_state_t x) {
#endif /* pulseaudio <= 0.9.10 */
static const char *(*PULSEAUDIO_pa_get_library_version) (void);
static pa_simple *(*PULSEAUDIO_pa_simple_new) (const char *, const char *,
pa_stream_direction_t, const char *, const char *, const pa_sample_spec *,
const pa_channel_map *, const pa_buffer_attr *, int *);
@@ -131,7 +132,7 @@ static void
UnloadPulseAudioLibrary(void)
{
if (pulseaudio_handle != NULL) {
SDL_UnloadObject(pulseaudio_handle);
SDL_UnloadObject(pulseaudio_handle);
pulseaudio_handle = NULL;
}
}
@@ -177,6 +178,7 @@ LoadPulseAudioLibrary(void)
static int
load_pulseaudio_syms(void)
{
SDL_PULSEAUDIO_SYM(pa_get_library_version);
SDL_PULSEAUDIO_SYM(pa_simple_new);
SDL_PULSEAUDIO_SYM(pa_simple_free);
SDL_PULSEAUDIO_SYM(pa_mainloop_new);
@@ -322,6 +324,28 @@ PULSEAUDIO_CloseDevice(_THIS)
}
static __inline__ int
squashVersion(const int major, const int minor, const int patch)
{
return ((major & 0xFF) << 16) | ((minor & 0xFF) << 8) | (patch & 0xFF);
}
/* Workaround for older pulse: pa_context_new() must have non-NULL appname */
static const char *
getAppName(void)
{
const char *verstr = PULSEAUDIO_pa_get_library_version();
if (verstr != NULL) {
int maj, min, patch;
if (SDL_sscanf(verstr, "%d.%d.%d", &maj, &min, &patch) == 3) {
if (squashVersion(maj, min, patch) >= squashVersion(0, 9, 15)) {
return NULL; /* 0.9.15+ handles NULL correctly. */
}
}
}
return "SDL Application"; /* oh well. */
}
static int
PULSEAUDIO_OpenDevice(_THIS, const char *devname, int iscapture)
{
@@ -360,6 +384,18 @@ PULSEAUDIO_OpenDevice(_THIS, const char *devname, int iscapture)
case AUDIO_S16MSB:
paspec.format = PA_SAMPLE_S16BE;
break;
case AUDIO_S32LSB:
paspec.format = PA_SAMPLE_S32LE;
break;
case AUDIO_S32MSB:
paspec.format = PA_SAMPLE_S32BE;
break;
case AUDIO_F32LSB:
paspec.format = PA_SAMPLE_FLOAT32LE;
break;
case AUDIO_F32MSB:
paspec.format = PA_SAMPLE_FLOAT32BE;
break;
default:
paspec.format = PA_SAMPLE_INVALID;
break;
@@ -420,7 +456,7 @@ PULSEAUDIO_OpenDevice(_THIS, const char *devname, int iscapture)
}
h->mainloop_api = PULSEAUDIO_pa_mainloop_get_api(h->mainloop);
h->context = PULSEAUDIO_pa_context_new(h->mainloop_api, NULL);
h->context = PULSEAUDIO_pa_context_new(h->mainloop_api, getAppName());
if (!h->context) {
PULSEAUDIO_CloseDevice(this);
return SDL_SetError("pa_context_new() failed");

View File

@@ -0,0 +1,329 @@
/*
Simple DirectMedia Layer
Copyright (C) 1997-2013 Sam Lantinga <slouken@libsdl.org>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#include "SDL_config.h"
#if SDL_AUDIO_DRIVER_SNDIO
/* OpenBSD sndio target */
#if HAVE_STDIO_H
#include <stdio.h>
#endif
#ifdef HAVE_SIGNAL_H
#include <signal.h>
#endif
#include <unistd.h>
#include "SDL_audio.h"
#include "../SDL_audiomem.h"
#include "../SDL_audio_c.h"
#include "SDL_sndioaudio.h"
#ifdef SDL_AUDIO_DRIVER_SNDIO_DYNAMIC
#include "SDL_loadso.h"
#endif
static struct sio_hdl * (*SNDIO_sio_open)(const char *, unsigned int, int);
static void (*SNDIO_sio_close)(struct sio_hdl *);
static int (*SNDIO_sio_setpar)(struct sio_hdl *, struct sio_par *);
static int (*SNDIO_sio_getpar)(struct sio_hdl *, struct sio_par *);
static int (*SNDIO_sio_start)(struct sio_hdl *);
static int (*SNDIO_sio_stop)(struct sio_hdl *);
static size_t (*SNDIO_sio_read)(struct sio_hdl *, void *, size_t);
static size_t (*SNDIO_sio_write)(struct sio_hdl *, const void *, size_t);
static void (*SNDIO_sio_initpar)(struct sio_par *);
#ifdef SDL_AUDIO_DRIVER_SNDIO_DYNAMIC
static const char *sndio_library = SDL_AUDIO_DRIVER_SNDIO_DYNAMIC;
static void *sndio_handle = NULL;
static int
load_sndio_sym(const char *fn, void **addr)
{
*addr = SDL_LoadFunction(sndio_handle, fn);
if (*addr == NULL) {
/* Don't call SDL_SetError(): SDL_LoadFunction already did. */
return 0;
}
return 1;
}
/* cast funcs to char* first, to please GCC's strict aliasing rules. */
#define SDL_SNDIO_SYM(x) \
if (!load_sndio_sym(#x, (void **) (char *) &SNDIO_##x)) return -1
#else
#define SDL_SNDIO_SYM(x) SNDIO_##x = x
#endif
static int
load_sndio_syms(void)
{
SDL_SNDIO_SYM(sio_open);
SDL_SNDIO_SYM(sio_close);
SDL_SNDIO_SYM(sio_setpar);
SDL_SNDIO_SYM(sio_getpar);
SDL_SNDIO_SYM(sio_start);
SDL_SNDIO_SYM(sio_stop);
SDL_SNDIO_SYM(sio_read);
SDL_SNDIO_SYM(sio_write);
SDL_SNDIO_SYM(sio_initpar);
return 0;
}
#undef SDL_SNDIO_SYM
#ifdef SDL_AUDIO_DRIVER_SNDIO_DYNAMIC
static void
UnloadSNDIOLibrary(void)
{
if (sndio_handle != NULL) {
SDL_UnloadObject(sndio_handle);
sndio_handle = NULL;
}
}
static int
LoadSNDIOLibrary(void)
{
int retval = 0;
if (sndio_handle == NULL) {
sndio_handle = SDL_LoadObject(sndio_library);
if (sndio_handle == NULL) {
retval = -1;
/* Don't call SDL_SetError(): SDL_LoadObject already did. */
} else {
retval = load_sndio_syms();
if (retval < 0) {
UnloadSNDIOLibrary();
}
}
}
return retval;
}
#else
static void
UnloadSNDIOLibrary(void)
{
}
static int
LoadSNDIOLibrary(void)
{
load_sndio_syms();
return 0;
}
#endif /* SDL_AUDIO_DRIVER_SNDIO_DYNAMIC */
static void
SNDIO_WaitDevice(_THIS)
{
/* no-op; SNDIO_sio_write() blocks if necessary. */
}
static void
SNDIO_PlayDevice(_THIS)
{
const int written = SNDIO_sio_write(this->hidden->dev,
this->hidden->mixbuf,
this->hidden->mixlen);
/* If we couldn't write, assume fatal error for now */
if ( written == 0 ) {
this->enabled = 0;
}
#ifdef DEBUG_AUDIO
fprintf(stderr, "Wrote %d bytes of audio data\n", written);
#endif
}
static Uint8 *
SNDIO_GetDeviceBuf(_THIS)
{
return this->hidden->mixbuf;
}
static void
SNDIO_WaitDone(_THIS)
{
SNDIO_sio_stop(this->hidden->dev);
}
static void
SNDIO_CloseDevice(_THIS)
{
if (this->hidden != NULL) {
if (this->hidden->mixbuf != NULL) {
SDL_FreeAudioMem(this->hidden->mixbuf);
this->hidden->mixbuf = NULL;
}
if ( this->hidden->dev != NULL ) {
SNDIO_sio_close(this->hidden->dev);
this->hidden->dev = NULL;
}
SDL_free(this->hidden);
this->hidden = NULL;
}
}
static int
SNDIO_OpenDevice(_THIS, const char *devname, int iscapture)
{
SDL_AudioFormat test_format = SDL_FirstAudioFormat(this->spec.format);
struct sio_par par;
int status;
this->hidden = (struct SDL_PrivateAudioData *)
SDL_malloc(sizeof(*this->hidden));
if (this->hidden == NULL) {
return SDL_OutOfMemory();
}
SDL_memset(this->hidden, 0, sizeof(*this->hidden));
this->hidden->mixlen = this->spec.size;
/* !!! FIXME: SIO_DEVANY can be a specific device... */
if ((this->hidden->dev = SNDIO_sio_open(NULL, SIO_PLAY, 0)) == NULL) {
SNDIO_CloseDevice(this);
return SDL_SetError("sio_open() failed");
}
SNDIO_sio_initpar(&par);
par.rate = this->spec.freq;
par.pchan = this->spec.channels;
par.round = this->spec.samples;
par.appbufsz = par.round * 2;
/* Try for a closest match on audio format */
status = -1;
while (test_format && (status < 0)) {
if (!SDL_AUDIO_ISFLOAT(test_format)) {
par.le = SDL_AUDIO_ISLITTLEENDIAN(test_format) ? 1 : 0;
par.sig = SDL_AUDIO_ISSIGNED(test_format) ? 1 : 0;
par.bits = SDL_AUDIO_BITSIZE(test_format);
if (SNDIO_sio_setpar(this->hidden->dev, &par) == 1) {
status = 0;
break;
}
}
test_format = SDL_NextAudioFormat();
}
if (status < 0) {
SNDIO_CloseDevice(this);
return SDL_SetError("sndio: Couldn't find any hardware audio formats");
}
if (SNDIO_sio_getpar(this->hidden->dev, &par) == 0) {
SNDIO_CloseDevice(this);
return SDL_SetError("sio_getpar() failed");
}
if ((par.bits == 32) && (par.sig) && (par.le))
this->spec.format = AUDIO_S32LSB;
else if ((par.bits == 32) && (par.sig) && (!par.le))
this->spec.format = AUDIO_S32MSB;
else if ((par.bits == 16) && (par.sig) && (par.le))
this->spec.format = AUDIO_S16LSB;
else if ((par.bits == 16) && (par.sig) && (!par.le))
this->spec.format = AUDIO_S16MSB;
else if ((par.bits == 16) && (!par.sig) && (par.le))
this->spec.format = AUDIO_U16LSB;
else if ((par.bits == 16) && (!par.sig) && (!par.le))
this->spec.format = AUDIO_U16MSB;
else if ((par.bits == 8) && (par.sig))
this->spec.format = AUDIO_S8;
else if ((par.bits == 8) && (!par.sig))
this->spec.format = AUDIO_U8;
else {
SNDIO_CloseDevice(this);
return SDL_SetError("sndio: Got unsupported hardware audio format.");
}
this->spec.freq = par.rate;
this->spec.channels = par.pchan;
this->spec.samples = par.round;
/* Calculate the final parameters for this audio specification */
SDL_CalculateAudioSpec(&this->spec);
/* Allocate mixing buffer */
this->hidden->mixlen = this->spec.size;
this->hidden->mixbuf = (Uint8 *) SDL_AllocAudioMem(this->hidden->mixlen);
if (this->hidden->mixbuf == NULL) {
SNDIO_CloseDevice(this);
return SDL_OutOfMemory();
}
SDL_memset(this->hidden->mixbuf, this->spec.silence, this->hidden->mixlen);
if (!SNDIO_sio_start(this->hidden->dev)) {
return SDL_SetError("sio_start() failed");
}
/* We're ready to rock and roll. :-) */
return 0;
}
static void
SNDIO_Deinitialize(void)
{
UnloadSNDIOLibrary();
}
static int
SNDIO_Init(SDL_AudioDriverImpl * impl)
{
if (LoadSNDIOLibrary() < 0) {
return 0;
}
/* Set the function pointers */
impl->OpenDevice = SNDIO_OpenDevice;
impl->WaitDevice = SNDIO_WaitDevice;
impl->PlayDevice = SNDIO_PlayDevice;
impl->GetDeviceBuf = SNDIO_GetDeviceBuf;
impl->WaitDone = SNDIO_WaitDone;
impl->CloseDevice = SNDIO_CloseDevice;
impl->Deinitialize = SNDIO_Deinitialize;
impl->OnlyHasDefaultOutputDevice = 1; /* !!! FIXME: sndio can handle multiple devices. */
return 1; /* this audio target is available. */
}
AudioBootStrap SNDIO_bootstrap = {
"sndio", "OpenBSD sndio", SNDIO_Init, 0
};
#endif /* SDL_AUDIO_DRIVER_SNDIO */
/* vi: set ts=4 sw=4 expandtab: */

View File

@@ -0,0 +1,45 @@
/*
Simple DirectMedia Layer
Copyright (C) 1997-2013 Sam Lantinga <slouken@libsdl.org>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#include "SDL_config.h"
#ifndef _SDL_sndioaudio_h
#define _SDL_sndioaudio_h
#include <sndio.h>
#include "../SDL_sysaudio.h"
/* Hidden "this" pointer for the audio functions */
#define _THIS SDL_AudioDevice *this
struct SDL_PrivateAudioData
{
/* The audio device handle */
struct sio_hdl *dev;
/* Raw mixing buffer */
Uint8 *mixbuf;
int mixlen;
};
#endif /* _SDL_sndioaudio_h */
/* vi: set ts=4 sw=4 expandtab: */

View File

@@ -47,7 +47,7 @@
/* Open the audio device for playback, and don't block if busy */
#if defined(AUDIO_GETINFO) && !defined(AUDIO_GETBUFINFO)
#if defined(AUDIO_GETINFO) && !defined(AUDIO_GETBUFINFO)
#define AUDIO_GETBUFINFO AUDIO_GETINFO
#endif
@@ -82,7 +82,7 @@ static void
SUNAUDIO_WaitDevice(_THIS)
{
#ifdef AUDIO_GETBUFINFO
#define SLEEP_FUDGE 10 /* 10 ms scheduling fudge factor */
#define SLEEP_FUDGE 10 /* 10 ms scheduling fudge factor */
audio_info_t info;
Sint32 left;

View File

@@ -26,7 +26,7 @@
#include "../SDL_sysaudio.h"
/* Hidden "this" pointer for the audio functions */
#define _THIS SDL_AudioDevice *this
#define _THIS SDL_AudioDevice *this
struct SDL_PrivateAudioData
{

View File

@@ -32,6 +32,10 @@
#include "../SDL_audio_c.h"
#include "SDL_winmm.h"
#ifndef WAVE_FORMAT_IEEE_FLOAT
#define WAVE_FORMAT_IEEE_FLOAT 0x0003
#endif
#define DETECT_DEV_IMPL(typ, capstyp) \
static void DetectWave##typ##Devs(SDL_AddAudioDevice addfn) { \
const UINT devcount = wave##typ##GetNumDevs(); \
@@ -162,16 +166,6 @@ WINMM_CloseDevice(_THIS)
this->hidden->audio_sem = 0;
}
if (this->hidden->hin) {
waveInClose(this->hidden->hin);
this->hidden->hin = 0;
}
if (this->hidden->hout) {
waveOutClose(this->hidden->hout);
this->hidden->hout = 0;
}
/* Clean up mixing buffers */
for (i = 0; i < NUM_BUFFERS; ++i) {
if (this->hidden->wavebuf[i].dwUser != 0xFFFF) {
@@ -188,11 +182,45 @@ WINMM_CloseDevice(_THIS)
this->hidden->mixbuf = NULL;
}
if (this->hidden->hin) {
waveInClose(this->hidden->hin);
this->hidden->hin = 0;
}
if (this->hidden->hout) {
waveOutClose(this->hidden->hout);
this->hidden->hout = 0;
}
SDL_free(this->hidden);
this->hidden = NULL;
}
}
static SDL_bool
PrepWaveFormat(_THIS, UINT_PTR devId, WAVEFORMATEX *pfmt, const int iscapture)
{
SDL_zerop(pfmt);
if (SDL_AUDIO_ISFLOAT(this->spec.format)) {
pfmt->wFormatTag = WAVE_FORMAT_IEEE_FLOAT;
} else {
pfmt->wFormatTag = WAVE_FORMAT_PCM;
}
pfmt->wBitsPerSample = SDL_AUDIO_BITSIZE(this->spec.format);
pfmt->nChannels = this->spec.channels;
pfmt->nSamplesPerSec = this->spec.freq;
pfmt->nBlockAlign = pfmt->nChannels * (pfmt->wBitsPerSample / 8);
pfmt->nAvgBytesPerSec = pfmt->nSamplesPerSec * pfmt->nBlockAlign;
if (iscapture) {
return (waveInOpen(0, devId, pfmt, 0, 0, WAVE_FORMAT_QUERY) == 0);
} else {
return (waveOutOpen(0, devId, pfmt, 0, 0, WAVE_FORMAT_QUERY) == 0);
}
}
static int
WINMM_OpenDevice(_THIS, const char *devname, int iscapture)
{
@@ -250,17 +278,28 @@ WINMM_OpenDevice(_THIS, const char *devname, int iscapture)
for (i = 0; i < NUM_BUFFERS; ++i)
this->hidden->wavebuf[i].dwUser = 0xFFFF;
if (this->spec.channels > 2)
this->spec.channels = 2; /* !!! FIXME: is this right? */
/* Check the buffer size -- minimum of 1/4 second (word aligned) */
if (this->spec.samples < (this->spec.freq / 4))
this->spec.samples = ((this->spec.freq / 4) + 3) & ~3;
while ((!valid_datatype) && (test_format)) {
valid_datatype = 1;
this->spec.format = test_format;
switch (test_format) {
case AUDIO_U8:
case AUDIO_S16:
case AUDIO_S32:
break; /* valid. */
case AUDIO_F32:
this->spec.format = test_format;
if (PrepWaveFormat(this, devId, &waveformat, iscapture)) {
valid_datatype = 1;
} else {
test_format = SDL_NextAudioFormat();
}
break;
default:
valid_datatype = 0;
test_format = SDL_NextAudioFormat();
break;
}
@@ -271,25 +310,6 @@ WINMM_OpenDevice(_THIS, const char *devname, int iscapture)
return SDL_SetError("Unsupported audio format");
}
/* Set basic WAVE format parameters */
SDL_memset(&waveformat, '\0', sizeof(waveformat));
waveformat.wFormatTag = WAVE_FORMAT_PCM;
waveformat.wBitsPerSample = SDL_AUDIO_BITSIZE(this->spec.format);
if (this->spec.channels > 2)
this->spec.channels = 2; /* !!! FIXME: is this right? */
waveformat.nChannels = this->spec.channels;
waveformat.nSamplesPerSec = this->spec.freq;
waveformat.nBlockAlign =
waveformat.nChannels * (waveformat.wBitsPerSample / 8);
waveformat.nAvgBytesPerSec =
waveformat.nSamplesPerSec * waveformat.nBlockAlign;
/* Check the buffer size -- minimum of 1/4 second (word aligned) */
if (this->spec.samples < (this->spec.freq / 4))
this->spec.samples = ((this->spec.freq / 4) + 3) & ~3;
/* Update the fragment size as size in bytes */
SDL_CalculateAudioSpec(&this->spec);

View File

@@ -26,7 +26,7 @@
#include "../SDL_sysaudio.h"
/* Hidden "this" pointer for the audio functions */
#define _THIS SDL_AudioDevice *this
#define _THIS SDL_AudioDevice *this
#define NUM_BUFFERS 2 /* -- Don't lower this! */

File diff suppressed because it is too large Load Diff

View File

@@ -31,13 +31,14 @@ extern "C" {
/* Interface from the SDL library into the Android Java activity */
extern SDL_bool Android_JNI_CreateContext(int majorVersion, int minorVersion, int red, int green, int blue, int alpha, int buffer, int depth, int stencil, int buffers, int samples);
extern SDL_bool Android_JNI_DeleteContext(void);
extern void Android_JNI_SwapWindow();
extern void Android_JNI_SetActivityTitle(const char *title);
extern SDL_bool Android_JNI_GetAccelerometerValues(float values[3]);
extern void Android_JNI_ShowTextInput(SDL_Rect *inputRect);
extern void Android_JNI_HideTextInput();
// Audio support
/* Audio support */
extern int Android_JNI_OpenAudioDevice(int sampleRate, int is16Bit, int channelCount, int desiredBufferFrames);
extern void* Android_JNI_GetAudioBuffer();
extern void Android_JNI_WriteAudioBuffer();
@@ -60,13 +61,12 @@ SDL_bool Android_JNI_HasClipboardText();
/* Power support */
int Android_JNI_GetPowerInfo(int* plugged, int* charged, int* battery, int* seconds, int* percent);
// Threads
/* Threads */
#include <jni.h>
static void Android_JNI_ThreadDestroyed(void*);
JNIEnv *Android_JNI_GetEnv(void);
int Android_JNI_SetupThread(void);
// Generic messages
/* Generic messages */
int Android_JNI_SendMessage(int command, int param);
/* Ends C function definitions when using C++ */

View File

@@ -33,6 +33,9 @@
#endif
#include "../video/SDL_sysvideo.h"
/* An arbitrary limit so we don't have unbounded growth */
#define SDL_MAX_QUEUED_EVENTS 65535
/* Public data -- the event filter */
SDL_EventFilter SDL_EventOK = NULL;
void *SDL_EventOKParam;
@@ -53,17 +56,31 @@ static SDL_DisabledEventBlock *SDL_disabled_events[256];
static Uint32 SDL_userevents = SDL_USEREVENT;
/* Private data -- event queue */
#define MAXEVENTS 128
typedef struct _SDL_EventEntry
{
SDL_Event event;
SDL_SysWMmsg msg;
struct _SDL_EventEntry *prev;
struct _SDL_EventEntry *next;
} SDL_EventEntry;
typedef struct _SDL_SysWMEntry
{
SDL_SysWMmsg msg;
struct _SDL_SysWMEntry *next;
} SDL_SysWMEntry;
static struct
{
SDL_mutex *lock;
int active;
int head;
int tail;
SDL_Event event[MAXEVENTS];
int wmmsg_next;
struct SDL_SysWMmsg wmmsg[MAXEVENTS];
} SDL_EventQ = { NULL, 1 };
volatile SDL_bool active;
volatile int count;
SDL_EventEntry *head;
SDL_EventEntry *tail;
SDL_EventEntry *free;
SDL_SysWMEntry *wmmsg_used;
SDL_SysWMEntry *wmmsg_free;
} SDL_EventQ = { NULL, SDL_TRUE };
static __inline__ SDL_bool
@@ -85,18 +102,42 @@ void
SDL_StopEventLoop(void)
{
int i;
SDL_EventQ.active = 0;
SDL_EventEntry *entry;
SDL_SysWMEntry *wmmsg;
if (SDL_EventQ.lock) {
SDL_DestroyMutex(SDL_EventQ.lock);
SDL_EventQ.lock = NULL;
SDL_LockMutex(SDL_EventQ.lock);
}
SDL_EventQ.active = SDL_FALSE;
/* Clean out EventQ */
SDL_EventQ.head = 0;
SDL_EventQ.tail = 0;
SDL_EventQ.wmmsg_next = 0;
for (entry = SDL_EventQ.head; entry; ) {
SDL_EventEntry *next = entry->next;
SDL_free(entry);
entry = next;
}
for (entry = SDL_EventQ.free; entry; ) {
SDL_EventEntry *next = entry->next;
SDL_free(entry);
entry = next;
}
for (wmmsg = SDL_EventQ.wmmsg_used; wmmsg; ) {
SDL_SysWMEntry *next = wmmsg->next;
SDL_free(wmmsg);
wmmsg = next;
}
for (wmmsg = SDL_EventQ.wmmsg_free; wmmsg; ) {
SDL_SysWMEntry *next = wmmsg->next;
SDL_free(wmmsg);
wmmsg = next;
}
SDL_EventQ.count = 0;
SDL_EventQ.head = NULL;
SDL_EventQ.tail = NULL;
SDL_EventQ.free = NULL;
SDL_EventQ.wmmsg_used = NULL;
SDL_EventQ.wmmsg_free = NULL;
/* Clear disabled event state */
for (i = 0; i < SDL_arraysize(SDL_disabled_events); ++i) {
@@ -111,6 +152,13 @@ SDL_StopEventLoop(void)
SDL_event_watchers = tmp->next;
SDL_free(tmp);
}
SDL_EventOK = NULL;
if (SDL_EventQ.lock) {
SDL_UnlockMutex(SDL_EventQ.lock);
SDL_DestroyMutex(SDL_EventQ.lock);
SDL_EventQ.lock = NULL;
}
}
/* This function (and associated calls) may be called more than once */
@@ -133,13 +181,12 @@ SDL_StartEventLoop(void)
}
#endif /* !SDL_THREADS_DISABLED */
/* No filter to start with, process most event types */
SDL_EventOK = NULL;
/* Process most event types */
SDL_EventState(SDL_TEXTINPUT, SDL_DISABLE);
SDL_EventState(SDL_TEXTEDITING, SDL_DISABLE);
SDL_EventState(SDL_SYSWMEVENT, SDL_DISABLE);
SDL_EventQ.active = 1;
SDL_EventQ.active = SDL_TRUE;
return (0);
}
@@ -149,55 +196,70 @@ SDL_StartEventLoop(void)
static int
SDL_AddEvent(SDL_Event * event)
{
int tail, added;
SDL_EventEntry *entry;
tail = (SDL_EventQ.tail + 1) % MAXEVENTS;
if (tail == SDL_EventQ.head) {
/* Overflow, drop event */
added = 0;
} else {
SDL_EventQ.event[SDL_EventQ.tail] = *event;
if (event->type == SDL_SYSWMEVENT) {
/* Note that it's possible to lose an event */
int next = SDL_EventQ.wmmsg_next;
SDL_EventQ.wmmsg[next] = *event->syswm.msg;
SDL_EventQ.event[SDL_EventQ.tail].syswm.msg =
&SDL_EventQ.wmmsg[next];
SDL_EventQ.wmmsg_next = (next + 1) % MAXEVENTS;
}
SDL_EventQ.tail = tail;
added = 1;
if (SDL_EventQ.count >= SDL_MAX_QUEUED_EVENTS) {
SDL_SetError("Event queue is full (%d events)", SDL_EventQ.count);
return 0;
}
return (added);
if (SDL_EventQ.free == NULL) {
entry = (SDL_EventEntry *)SDL_malloc(sizeof(*entry));
if (!entry) {
return 0;
}
} else {
entry = SDL_EventQ.free;
SDL_EventQ.free = entry->next;
}
entry->event = *event;
if (event->type == SDL_SYSWMEVENT) {
entry->msg = *event->syswm.msg;
entry->event.syswm.msg = &entry->msg;
}
if (SDL_EventQ.tail) {
SDL_EventQ.tail->next = entry;
entry->prev = SDL_EventQ.tail;
SDL_EventQ.tail = entry;
entry->next = NULL;
} else {
SDL_assert(!SDL_EventQ.head);
SDL_EventQ.head = entry;
SDL_EventQ.tail = entry;
entry->prev = NULL;
entry->next = NULL;
}
++SDL_EventQ.count;
return 1;
}
/* Cut an event, and return the next valid spot, or the tail */
/* -- called with the queue locked */
static int
SDL_CutEvent(int spot)
/* Remove an event from the queue -- called with the queue locked */
static void
SDL_CutEvent(SDL_EventEntry *entry)
{
if (spot == SDL_EventQ.head) {
SDL_EventQ.head = (SDL_EventQ.head + 1) % MAXEVENTS;
return (SDL_EventQ.head);
} else if ((spot + 1) % MAXEVENTS == SDL_EventQ.tail) {
SDL_EventQ.tail = spot;
return (SDL_EventQ.tail);
} else
/* We cut the middle -- shift everything over */
{
int here, next;
/* This can probably be optimized with SDL_memcpy() -- careful! */
if (--SDL_EventQ.tail < 0) {
SDL_EventQ.tail = MAXEVENTS - 1;
}
for (here = spot; here != SDL_EventQ.tail; here = next) {
next = (here + 1) % MAXEVENTS;
SDL_EventQ.event[here] = SDL_EventQ.event[next];
}
return (spot);
if (entry->prev) {
entry->prev->next = entry->next;
}
/* NOTREACHED */
if (entry->next) {
entry->next->prev = entry->prev;
}
if (entry == SDL_EventQ.head) {
SDL_assert(entry->prev == NULL);
SDL_EventQ.head = entry->next;
}
if (entry == SDL_EventQ.tail) {
SDL_assert(entry->next == NULL);
SDL_EventQ.tail = entry->prev;
}
entry->next = SDL_EventQ.free;
SDL_EventQ.free = entry;
SDL_assert(SDL_EventQ.count > 0);
--SDL_EventQ.count;
}
/* Lock the event queue, take a peep at it, and unlock it */
@@ -209,6 +271,10 @@ SDL_PeepEvents(SDL_Event * events, int numevents, SDL_eventaction action,
/* Don't look after we've quit */
if (!SDL_EventQ.active) {
/* We get a few spurious events at shutdown, so don't warn then */
if (action != SDL_ADDEVENT) {
SDL_SetError("The event system has been shut down");
}
return (-1);
}
/* Lock the event queue */
@@ -219,8 +285,10 @@ SDL_PeepEvents(SDL_Event * events, int numevents, SDL_eventaction action,
used += SDL_AddEvent(&events[i]);
}
} else {
SDL_EventEntry *entry, *next;
SDL_SysWMEntry *wmmsg, *wmmsg_next;
SDL_Event tmpevent;
int spot;
Uint32 type;
/* If 'events' is NULL, just see if they exist */
if (events == NULL) {
@@ -228,18 +296,44 @@ SDL_PeepEvents(SDL_Event * events, int numevents, SDL_eventaction action,
numevents = 1;
events = &tmpevent;
}
spot = SDL_EventQ.head;
while ((used < numevents) && (spot != SDL_EventQ.tail)) {
Uint32 type = SDL_EventQ.event[spot].type;
/* Clean out any used wmmsg data
FIXME: Do we want to retain the data for some period of time?
*/
for (wmmsg = SDL_EventQ.wmmsg_used; wmmsg; wmmsg = wmmsg_next) {
wmmsg_next = wmmsg->next;
wmmsg->next = SDL_EventQ.wmmsg_free;
SDL_EventQ.wmmsg_free = wmmsg;
}
SDL_EventQ.wmmsg_used = NULL;
for (entry = SDL_EventQ.head; entry && used < numevents; entry = next) {
next = entry->next;
type = entry->event.type;
if (minType <= type && type <= maxType) {
events[used++] = SDL_EventQ.event[spot];
if (action == SDL_GETEVENT) {
spot = SDL_CutEvent(spot);
} else {
spot = (spot + 1) % MAXEVENTS;
events[used] = entry->event;
if (entry->event.type == SDL_SYSWMEVENT) {
/* We need to copy the wmmsg somewhere safe.
For now we'll guarantee it's valid at least until
the next call to SDL_PeepEvents()
*/
SDL_SysWMEntry *wmmsg;
if (SDL_EventQ.wmmsg_free) {
wmmsg = SDL_EventQ.wmmsg_free;
SDL_EventQ.wmmsg_free = wmmsg->next;
} else {
wmmsg = (SDL_SysWMEntry *)SDL_malloc(sizeof(*wmmsg));
}
wmmsg->msg = *entry->event.syswm.msg;
wmmsg->next = SDL_EventQ.wmmsg_used;
SDL_EventQ.wmmsg_used = wmmsg;
events[used].syswm.msg = &wmmsg->msg;
}
++used;
if (action == SDL_GETEVENT) {
SDL_CutEvent(entry);
}
} else {
spot = (spot + 1) % MAXEVENTS;
}
}
}
@@ -286,13 +380,13 @@ SDL_FlushEvents(Uint32 minType, Uint32 maxType)
/* Lock the event queue */
if (SDL_LockMutex(SDL_EventQ.lock) == 0) {
int spot = SDL_EventQ.head;
while (spot != SDL_EventQ.tail) {
Uint32 type = SDL_EventQ.event[spot].type;
SDL_EventEntry *entry, *next;
Uint32 type;
for (entry = SDL_EventQ.head; entry; entry = next) {
next = entry->next;
type = entry->event.type;
if (minType <= type && type <= maxType) {
spot = SDL_CutEvent(spot);
} else {
spot = (spot + 1) % MAXEVENTS;
SDL_CutEvent(entry);
}
}
SDL_UnlockMutex(SDL_EventQ.lock);
@@ -365,7 +459,9 @@ int
SDL_PushEvent(SDL_Event * event)
{
SDL_EventWatcher *curr;
event->common.timestamp = SDL_GetTicks();
if (SDL_EventOK && !SDL_EventOK(SDL_EventOKParam, event)) {
return 0;
}
@@ -386,12 +482,11 @@ SDL_PushEvent(SDL_Event * event)
void
SDL_SetEventFilter(SDL_EventFilter filter, void *userdata)
{
SDL_Event bitbucket;
/* Set filter and discard pending events */
SDL_EventOK = filter;
SDL_EventOK = NULL;
SDL_FlushEvents(SDL_FIRSTEVENT, SDL_LASTEVENT);
SDL_EventOKParam = userdata;
while (SDL_PollEvent(&bitbucket) > 0);
SDL_EventOK = filter;
}
SDL_bool
@@ -447,18 +542,15 @@ void
SDL_FilterEvents(SDL_EventFilter filter, void *userdata)
{
if (SDL_LockMutex(SDL_EventQ.lock) == 0) {
int spot;
spot = SDL_EventQ.head;
while (spot != SDL_EventQ.tail) {
if (filter(userdata, &SDL_EventQ.event[spot])) {
spot = (spot + 1) % MAXEVENTS;
} else {
spot = SDL_CutEvent(spot);
SDL_EventEntry *entry, *next;
for (entry = SDL_EventQ.head; entry; entry = next) {
next = entry->next;
if (!filter(userdata, &entry->event)) {
SDL_CutEvent(entry);
}
}
SDL_UnlockMutex(SDL_EventQ.lock);
}
SDL_UnlockMutex(SDL_EventQ.lock);
}
Uint8
@@ -507,7 +599,7 @@ SDL_RegisterEvents(int numevents)
{
Uint32 event_base;
if (SDL_userevents+numevents <= SDL_LASTEVENT) {
if ((numevents > 0) && (SDL_userevents+numevents <= SDL_LASTEVENT)) {
event_base = SDL_userevents;
SDL_userevents += numevents;
} else {
@@ -516,8 +608,20 @@ SDL_RegisterEvents(int numevents)
return event_base;
}
/* This is a generic event handler.
*/
int
SDL_SendAppEvent(SDL_EventType eventType)
{
int posted;
posted = 0;
if (SDL_GetEventState(eventType) == SDL_ENABLE) {
SDL_Event event;
event.type = eventType;
posted = (SDL_PushEvent(&event) > 0);
}
return (posted);
}
int
SDL_SendSysWMEvent(SDL_SysWMmsg * message)
{

View File

@@ -36,6 +36,7 @@ extern int SDL_StartEventLoop(void);
extern void SDL_StopEventLoop(void);
extern void SDL_QuitInterrupt(void);
extern int SDL_SendAppEvent(SDL_EventType eventType);
extern int SDL_SendSysWMEvent(SDL_SysWMmsg * message);
extern int SDL_QuitInit(void);

View File

@@ -11,11 +11,11 @@
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
@@ -35,13 +35,10 @@
#include <stdio.h>
#include <math.h>
//TODO: Replace with malloc
/* TODO: Replace with malloc */
#define MAXPATHSIZE 1024
#define DOLLARNPOINTS 64
#define DOLLARSIZE 256
@@ -394,11 +391,12 @@ static int dollarNormalize(const SDL_DollarPath *path,SDL_FloatPoint *points)
static float dollarRecognize(const SDL_DollarPath *path,int *bestTempl,SDL_GestureTouch* touch)
{
SDL_FloatPoint points[DOLLARNPOINTS];
int i;
float bestDiff = 10000;
SDL_memset(points, 0, sizeof(points));
dollarNormalize(path,points);
//PrintPath(points);

View File

@@ -774,7 +774,6 @@ SDL_SendKeyboardKey(Uint8 state, SDL_Scancode scancode)
event.key.keysym.scancode = scancode;
event.key.keysym.sym = keyboard->keymap[scancode];
event.key.keysym.mod = modstate;
event.key.keysym.unicode = 0;
event.key.windowID = keyboard->focus ? keyboard->focus->id : 0;
posted = (SDL_PushEvent(&event) > 0);
}
@@ -829,7 +828,7 @@ SDL_KeyboardQuit(void)
{
}
Uint8 *
const Uint8 *
SDL_GetKeyboardState(int *numkeys)
{
SDL_Keyboard *keyboard = &SDL_keyboard;
@@ -860,7 +859,7 @@ SDL_Keycode
SDL_GetKeyFromScancode(SDL_Scancode scancode)
{
SDL_Keyboard *keyboard = &SDL_keyboard;
if (scancode < SDL_SCANCODE_UNKNOWN || scancode >= SDL_NUM_SCANCODES) {
SDL_InvalidParamError("scancode");
return 0;
@@ -890,7 +889,7 @@ SDL_GetScancodeName(SDL_Scancode scancode)
const char *name;
if (scancode < SDL_SCANCODE_UNKNOWN || scancode >= SDL_NUM_SCANCODES) {
SDL_InvalidParamError("scancode");
return "";
return "";
}
name = SDL_scancode_names[scancode];
@@ -902,24 +901,24 @@ SDL_GetScancodeName(SDL_Scancode scancode)
SDL_Scancode SDL_GetScancodeFromName(const char *name)
{
int i;
int i;
if (!name || !*name) {
SDL_InvalidParamError("name");
return SDL_SCANCODE_UNKNOWN;
}
if (!name || !*name) {
SDL_InvalidParamError("name");
return SDL_SCANCODE_UNKNOWN;
}
for (i = 0; i < SDL_arraysize(SDL_scancode_names); ++i) {
if (!SDL_scancode_names[i]) {
continue;
}
if (SDL_strcasecmp(name, SDL_scancode_names[i]) == 0) {
return (SDL_Scancode)i;
}
}
for (i = 0; i < SDL_arraysize(SDL_scancode_names); ++i) {
if (!SDL_scancode_names[i]) {
continue;
}
if (SDL_strcasecmp(name, SDL_scancode_names[i]) == 0) {
return (SDL_Scancode)i;
}
}
SDL_InvalidParamError("name");
return SDL_SCANCODE_UNKNOWN;
SDL_InvalidParamError("name");
return SDL_SCANCODE_UNKNOWN;
}
const char *
@@ -964,51 +963,51 @@ SDL_GetKeyName(SDL_Keycode key)
SDL_Keycode
SDL_GetKeyFromName(const char *name)
{
SDL_Keycode key;
SDL_Keycode key;
/* Check input */
if (name == NULL) return SDLK_UNKNOWN;
/* If it's a single UTF-8 character, then that's the keycode itself */
key = *(const unsigned char *)name;
if (key >= 0xF0) {
if (SDL_strlen(name) == 4) {
int i = 0;
key = (Uint16)(name[i]&0x07) << 18;
key |= (Uint16)(name[++i]&0x3F) << 12;
key |= (Uint16)(name[++i]&0x3F) << 6;
key |= (Uint16)(name[++i]&0x3F);
return key;
}
return SDLK_UNKNOWN;
} else if (key >= 0xE0) {
if (SDL_strlen(name) == 3) {
int i = 0;
key = (Uint16)(name[i]&0x0F) << 12;
key |= (Uint16)(name[++i]&0x3F) << 6;
key |= (Uint16)(name[++i]&0x3F);
return key;
}
return SDLK_UNKNOWN;
} else if (key >= 0xC0) {
if (SDL_strlen(name) == 2) {
int i = 0;
key = (Uint16)(name[i]&0x1F) << 6;
key |= (Uint16)(name[++i]&0x3F);
return key;
}
return SDLK_UNKNOWN;
} else {
if (SDL_strlen(name) == 1) {
if (key >= 'A' && key <= 'Z') {
key += 32;
}
return key;
}
/* Get the scancode for this name, and the associated keycode */
return SDL_default_keymap[SDL_GetScancodeFromName(name)];
}
/* If it's a single UTF-8 character, then that's the keycode itself */
key = *(const unsigned char *)name;
if (key >= 0xF0) {
if (SDL_strlen(name) == 4) {
int i = 0;
key = (Uint16)(name[i]&0x07) << 18;
key |= (Uint16)(name[++i]&0x3F) << 12;
key |= (Uint16)(name[++i]&0x3F) << 6;
key |= (Uint16)(name[++i]&0x3F);
return key;
}
return SDLK_UNKNOWN;
} else if (key >= 0xE0) {
if (SDL_strlen(name) == 3) {
int i = 0;
key = (Uint16)(name[i]&0x0F) << 12;
key |= (Uint16)(name[++i]&0x3F) << 6;
key |= (Uint16)(name[++i]&0x3F);
return key;
}
return SDLK_UNKNOWN;
} else if (key >= 0xC0) {
if (SDL_strlen(name) == 2) {
int i = 0;
key = (Uint16)(name[i]&0x1F) << 6;
key |= (Uint16)(name[++i]&0x3F);
return key;
}
return SDLK_UNKNOWN;
} else {
if (SDL_strlen(name) == 1) {
if (key >= 'A' && key <= 'Z') {
key += 32;
}
return key;
}
/* Get the scancode for this name, and the associated keycode */
return SDL_default_keymap[SDL_GetScancodeFromName(name)];
}
}
/* vi: set ts=4 sw=4 expandtab: */

View File

@@ -33,6 +33,8 @@
/* The mouse state */
static SDL_Mouse SDL_mouse;
static int
SDL_PrivateSendMouseMotion(SDL_Window * window, SDL_MouseID mouseID, int relative, int x, int y);
/* Public functions */
int
@@ -154,27 +156,39 @@ SDL_UpdateMouseFocus(SDL_Window * window, int x, int y, Uint32 buttonstate)
#endif
if (window == mouse->focus) {
#ifdef DEBUG_MOUSE
printf("Mouse left window, synthesizing focus lost event\n");
printf("Mouse left window, synthesizing move & focus lost event\n");
#endif
SDL_PrivateSendMouseMotion(window, mouse->mouseID, 0, x, y);
SDL_SetMouseFocus(NULL);
}
return SDL_FALSE;
}
if (window != mouse->focus) {
mouse->last_x = x;
mouse->last_y = y;
#ifdef DEBUG_MOUSE
printf("Mouse entered window, synthesizing focus gain event\n");
printf("Mouse entered window, synthesizing focus gain & move event\n");
#endif
SDL_SetMouseFocus(window);
SDL_SetMouseFocus(window);
SDL_PrivateSendMouseMotion(window, mouse->mouseID, 0, x, y);
}
return SDL_TRUE;
}
int
SDL_SendMouseMotion(SDL_Window * window, SDL_MouseID mouseID, int relative, int x, int y)
{
if (window && !relative) {
SDL_Mouse *mouse = SDL_GetMouse();
if (!SDL_UpdateMouseFocus(window, x, y, mouse->buttonstate)) {
return 0;
}
}
return SDL_PrivateSendMouseMotion(window, mouseID, relative, x, y);
}
static int
SDL_PrivateSendMouseMotion(SDL_Window * window, SDL_MouseID mouseID, int relative, int x, int y)
{
SDL_Mouse *mouse = SDL_GetMouse();
int posted;
@@ -182,12 +196,6 @@ SDL_SendMouseMotion(SDL_Window * window, SDL_MouseID mouseID, int relative, int
int yrel;
int x_max = 0, y_max = 0;
if (window && !relative) {
if (!SDL_UpdateMouseFocus(window, x, y, mouse->buttonstate)) {
return 0;
}
}
/* relative motion is calculated regarding the system cursor last position */
if (relative) {
xrel = x;
@@ -353,6 +361,23 @@ SDL_SendMouseWheel(SDL_Window * window, SDL_MouseID mouseID, int x, int y)
void
SDL_MouseQuit(void)
{
SDL_Cursor *cursor, *next;
SDL_Mouse *mouse = SDL_GetMouse();
SDL_ShowCursor(1);
cursor = mouse->cursors;
while (cursor) {
next = cursor->next;
SDL_FreeCursor(cursor);
cursor = next;
}
if (mouse->def_cursor && mouse->FreeCursor) {
mouse->FreeCursor(mouse->def_cursor);
}
SDL_zerop(mouse);
}
Uint32
@@ -389,12 +414,12 @@ void
SDL_WarpMouseInWindow(SDL_Window * window, int x, int y)
{
SDL_Mouse *mouse = SDL_GetMouse();
if ( window == NULL )
window = mouse->focus;
if ( window == NULL )
return;
if ( window == NULL )
window = mouse->focus;
if ( window == NULL )
return;
if (mouse->WarpMouse) {
mouse->WarpMouse(window, x, y);
@@ -407,6 +432,8 @@ int
SDL_SetRelativeMouseMode(SDL_bool enabled)
{
SDL_Mouse *mouse = SDL_GetMouse();
SDL_Window *focusWindow = SDL_GetKeyboardFocus();
int original_x = mouse->x, original_y = mouse->y;
if (enabled == mouse->relative_mode) {
return 0;
@@ -416,6 +443,14 @@ SDL_SetRelativeMouseMode(SDL_bool enabled)
return SDL_Unsupported();
}
if (enabled && focusWindow) {
/* Center it in the focused window to prevent clicks from going through
* to background windows.
*/
SDL_SetMouseFocus(focusWindow);
SDL_WarpMouseInWindow(focusWindow, focusWindow->w/2, focusWindow->h/2);
}
if (mouse->SetRelativeMouseMode(enabled) < 0) {
return -1;
}
@@ -425,8 +460,8 @@ SDL_SetRelativeMouseMode(SDL_bool enabled)
if (enabled) {
/* Save the expected mouse position */
mouse->original_x = mouse->x;
mouse->original_y = mouse->y;
mouse->original_x = original_x;
mouse->original_y = original_y;
} else if (mouse->focus) {
/* Restore the expected mouse position */
SDL_WarpMouseInWindow(mouse->focus, mouse->original_x, mouse->original_y);
@@ -554,13 +589,13 @@ SDL_CreateSystemCursor(SDL_SystemCursor id)
return NULL;
}
cursor = mouse->CreateSystemCursor(id);
cursor = mouse->CreateSystemCursor(id);
if (cursor) {
cursor->next = mouse->cursors;
mouse->cursors = cursor;
}
return cursor;
return cursor;
}
/* SDL_SetCursor(NULL) can be used to force the cursor redraw,
@@ -618,6 +653,17 @@ SDL_GetCursor(void)
return mouse->cur_cursor;
}
SDL_Cursor *
SDL_GetDefaultCursor(void)
{
SDL_Mouse *mouse = SDL_GetMouse();
if (!mouse) {
return NULL;
}
return mouse->def_cursor;
}
void
SDL_FreeCursor(SDL_Cursor * cursor)
{

View File

@@ -39,7 +39,7 @@ typedef struct
SDL_Cursor *(*CreateCursor) (SDL_Surface * surface, int hot_x, int hot_y);
/* Create a system cursor */
SDL_Cursor *(*CreateSystemCursor) (SDL_SystemCursor id);
SDL_Cursor *(*CreateSystemCursor) (SDL_SystemCursor id);
/* Show the specified cursor, or hide if cursor is NULL */
int (*ShowCursor) (SDL_Cursor * cursor);
@@ -73,6 +73,9 @@ typedef struct
SDL_Cursor *def_cursor;
SDL_Cursor *cur_cursor;
SDL_bool cursor_shown;
/* Driver-dependent data. */
void *driverdata;
} SDL_Mouse;

View File

@@ -114,15 +114,7 @@ SDL_QuitQuit(void)
int
SDL_SendQuit(void)
{
int posted;
posted = 0;
if (SDL_GetEventState(SDL_QUIT) == SDL_ENABLE) {
SDL_Event event;
event.type = SDL_QUIT;
posted = (SDL_PushEvent(&event) > 0);
}
return (posted);
return SDL_SendAppEvent(SDL_QUIT);
}
/* vi: set ts=4 sw=4 expandtab: */

View File

@@ -24,7 +24,8 @@
/* Useful functions and variables from SDL_sysevents.c */
#ifdef __BEOS__ /* The Be event loop runs in a separate thread */
#if defined(__BEOS__) || defined(__HAIKU__)
/* The Be and Haiku event loops run in a separate thread */
#define MUST_THREAD_EVENTS
#endif

View File

@@ -39,7 +39,7 @@ SDL_TouchInit(void)
}
int
SDL_GetNumTouchDevices()
SDL_GetNumTouchDevices(void)
{
return SDL_num_touch;
}
@@ -165,7 +165,7 @@ SDL_AddTouch(SDL_TouchID touchID, const char *name)
return index;
}
static int
static int
SDL_AddFinger(SDL_Touch *touch, SDL_FingerID fingerid, float x, float y, float pressure)
{
SDL_Finger *finger;
@@ -258,7 +258,7 @@ SDL_SendTouch(SDL_TouchID id, SDL_FingerID fingerid,
event.tfinger.touchId = id;
event.tfinger.fingerId = fingerid;
/* I don't trust the coordinates passed on fingerUp */
event.tfinger.x = finger->x;
event.tfinger.x = finger->x;
event.tfinger.y = finger->y;
event.tfinger.dx = 0;
event.tfinger.dy = 0;
@@ -287,7 +287,7 @@ SDL_SendTouchMotion(SDL_TouchID id, SDL_FingerID fingerid,
finger = SDL_GetFinger(touch,fingerid);
if (!finger) {
return SDL_SendTouch(id, fingerid, SDL_TRUE, x, y, pressure);
return SDL_SendTouch(id, fingerid, SDL_TRUE, x, y, pressure);
}
xrel = x - finger->x;
@@ -306,7 +306,7 @@ SDL_SendTouchMotion(SDL_TouchID id, SDL_FingerID fingerid,
finger->x = x;
finger->y = y;
finger->pressure = pressure;
/* Post the event, if desired */
posted = 0;
if (SDL_GetEventState(SDL_FINGERMOTION) == SDL_ENABLE) {
@@ -317,7 +317,7 @@ SDL_SendTouchMotion(SDL_TouchID id, SDL_FingerID fingerid,
event.tfinger.x = x;
event.tfinger.y = y;
event.tfinger.dx = xrel;
event.tfinger.dy = yrel;
event.tfinger.dy = yrel;
event.tfinger.pressure = pressure;
posted = (SDL_PushEvent(&event) > 0);
}

View File

@@ -38,17 +38,17 @@ extern int SDL_TouchInit(void);
/* Add a touch, returning the index of the touch, or -1 if there was an error. */
extern int SDL_AddTouch(SDL_TouchID id, const char *name);
/* Get the touch with a given id */
extern SDL_Touch *SDL_GetTouch(SDL_TouchID id);
/* Send a touch down/up event for a touch */
extern int SDL_SendTouch(SDL_TouchID id, SDL_FingerID fingerid,
SDL_bool down, float x, float y, float pressure);
extern int SDL_SendTouch(SDL_TouchID id, SDL_FingerID fingerid,
SDL_bool down, float x, float y, float pressure);
/* Send a touch motion event for a touch */
extern int SDL_SendTouchMotion(SDL_TouchID id, SDL_FingerID fingerid,
float x, float y, float pressure);
float x, float y, float pressure);
/* Remove a touch */
extern void SDL_DelTouch(SDL_TouchID id);

View File

@@ -148,12 +148,14 @@ SDL_SendWindowEvent(SDL_Window * window, Uint8 windowevent, int data1,
return 0;
}
window->flags |= SDL_WINDOW_MOUSE_FOCUS;
SDL_OnWindowEnter(window);
break;
case SDL_WINDOWEVENT_LEAVE:
if (!(window->flags & SDL_WINDOW_MOUSE_FOCUS)) {
return 0;
}
window->flags &= ~SDL_WINDOW_MOUSE_FOCUS;
SDL_OnWindowLeave(window);
break;
case SDL_WINDOWEVENT_FOCUS_GAINED:
if (window->flags & SDL_WINDOW_INPUT_FOCUS) {
@@ -194,13 +196,13 @@ SDL_SendWindowEvent(SDL_Window * window, Uint8 windowevent, int data1,
posted = (SDL_PushEvent(&event) > 0);
}
if (windowevent == SDL_WINDOWEVENT_CLOSE) {
if ( !window->prev && !window->next ) {
// This is the last window in the list so send the SDL_QUIT event
SDL_SendQuit();
}
}
if (windowevent == SDL_WINDOWEVENT_CLOSE) {
if ( !window->prev && !window->next ) {
/* This is the last window in the list so send the SDL_QUIT event */
SDL_SendQuit();
}
}
return (posted);
}

View File

@@ -19,13 +19,13 @@
3. This notice may not be removed or altered from any source distribution.
*/
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* A default blank 8x8 cursor */
#define BLANK_CWIDTH 8
#define BLANK_CHEIGHT 8
#define BLANK_CHOTX 0
#define BLANK_CHOTY 0
#define BLANK_CWIDTH 8
#define BLANK_CHEIGHT 8
#define BLANK_CHOTX 0
#define BLANK_CHOTY 0
static const unsigned char blank_cdata[8] = { 0, 0, 0, 0, 0, 0, 0, 0 };
static const unsigned char blank_cmask[8] = { 0, 0, 0, 0, 0, 0, 0, 0 };

View File

@@ -19,13 +19,13 @@
3. This notice may not be removed or altered from any source distribution.
*/
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Default cursor - it happens to be the Mac cursor, but could be anything */
#define DEFAULT_CWIDTH 16
#define DEFAULT_CHEIGHT 16
#define DEFAULT_CHOTX 0
#define DEFAULT_CHOTY 0
#define DEFAULT_CWIDTH 16
#define DEFAULT_CHEIGHT 16
#define DEFAULT_CHOTX 0
#define DEFAULT_CHOTY 0
/* Added a real MacOS cursor, at the request of Luc-Olivier de Charri<72>re */
#define USE_MACOS_CURSOR

View File

@@ -91,7 +91,7 @@ static const SDL_Scancode darwin_scancode_table[] = {
/* 61 */ SDL_SCANCODE_RALT,
/* 62 */ SDL_SCANCODE_RCTRL,
/* 63 */ SDL_SCANCODE_RGUI, /* fn on portables, acts as a hardware-level modifier already, so we don't generate events for it, also XK_Meta_R */
/* 64 */ SDL_SCANCODE_UNKNOWN, /* unknown (unused?) */
/* 64 */ SDL_SCANCODE_F17,
/* 65 */ SDL_SCANCODE_KP_PERIOD,
/* 66 */ SDL_SCANCODE_UNKNOWN, /* unknown (unused?) */
/* 67 */ SDL_SCANCODE_KP_MULTIPLY,
@@ -106,8 +106,8 @@ static const SDL_Scancode darwin_scancode_table[] = {
/* 76 */ SDL_SCANCODE_KP_ENTER, /* keypad enter on external keyboards, fn-return on portables */
/* 77 */ SDL_SCANCODE_UNKNOWN, /* unknown (unused?) */
/* 78 */ SDL_SCANCODE_KP_MINUS,
/* 79 */ SDL_SCANCODE_UNKNOWN, /* unknown (unused?) */
/* 80 */ SDL_SCANCODE_UNKNOWN, /* unknown (unused?) */
/* 79 */ SDL_SCANCODE_F18,
/* 80 */ SDL_SCANCODE_F19,
/* 81 */ SDL_SCANCODE_KP_EQUALS,
/* 82 */ SDL_SCANCODE_KP_0,
/* 83 */ SDL_SCANCODE_KP_1,

View File

@@ -21,6 +21,8 @@
#include "../../include/SDL_scancode.h"
/* Windows scancode to SDL scancode mapping table */
/* derived from Microsoft scan code document, http://download.microsoft.com/download/1/6/1/161ba512-40e2-4cc9-843a-923143f3456c/scancode.doc */
/* *INDENT-OFF* */
static const SDL_Scancode windows_scancode_table[] =
{
@@ -36,18 +38,18 @@ static const SDL_Scancode windows_scancode_table[] =
SDL_SCANCODE_APOSTROPHE, SDL_SCANCODE_GRAVE, SDL_SCANCODE_LSHIFT, SDL_SCANCODE_BACKSLASH, SDL_SCANCODE_Z, SDL_SCANCODE_X, SDL_SCANCODE_C, SDL_SCANCODE_V, // 2
SDL_SCANCODE_B, SDL_SCANCODE_N, SDL_SCANCODE_M, SDL_SCANCODE_COMMA, SDL_SCANCODE_PERIOD, SDL_SCANCODE_SLASH, SDL_SCANCODE_RSHIFT, SDL_SCANCODE_PRINTSCREEN,// 3
SDL_SCANCODE_LALT, SDL_SCANCODE_SPACE, SDL_SCANCODE_CAPSLOCK, SDL_SCANCODE_F1, SDL_SCANCODE_F2, SDL_SCANCODE_F3, SDL_SCANCODE_F4, SDL_SCANCODE_F5, // 3
SDL_SCANCODE_LALT, SDL_SCANCODE_SPACE, SDL_SCANCODE_CAPSLOCK, SDL_SCANCODE_F1, SDL_SCANCODE_F2, SDL_SCANCODE_F3, SDL_SCANCODE_F4, SDL_SCANCODE_F5, // 3
SDL_SCANCODE_F6, SDL_SCANCODE_F7, SDL_SCANCODE_F8, SDL_SCANCODE_F9, SDL_SCANCODE_F10, SDL_SCANCODE_NUMLOCKCLEAR, SDL_SCANCODE_SCROLLLOCK, SDL_SCANCODE_HOME, // 4
SDL_SCANCODE_UP, SDL_SCANCODE_PAGEUP, SDL_SCANCODE_KP_MINUS, SDL_SCANCODE_LEFT, SDL_SCANCODE_KP_5, SDL_SCANCODE_RIGHT, SDL_SCANCODE_KP_PLUS, SDL_SCANCODE_END, // 4
SDL_SCANCODE_DOWN, SDL_SCANCODE_PAGEDOWN, SDL_SCANCODE_INSERT, SDL_SCANCODE_DELETE, SDL_SCANCODE_UNKNOWN, SDL_SCANCODE_UNKNOWN, SDL_SCANCODE_NONUSBACKSLASH,SDL_SCANCODE_F11, // 5
SDL_SCANCODE_F12, SDL_SCANCODE_PAUSE, SDL_SCANCODE_UNKNOWN, SDL_SCANCODE_LGUI, SDL_SCANCODE_RGUI, SDL_SCANCODE_APPLICATION, SDL_SCANCODE_UNKNOWN, SDL_SCANCODE_UNKNOWN, // 5
SDL_SCANCODE_F12, SDL_SCANCODE_PAUSE, SDL_SCANCODE_UNKNOWN, SDL_SCANCODE_LGUI, SDL_SCANCODE_RGUI, SDL_SCANCODE_APPLICATION, SDL_SCANCODE_UNKNOWN, SDL_SCANCODE_UNKNOWN, // 5
SDL_SCANCODE_UNKNOWN, SDL_SCANCODE_UNKNOWN, SDL_SCANCODE_UNKNOWN, SDL_SCANCODE_UNKNOWN, SDL_SCANCODE_UNKNOWN, SDL_SCANCODE_UNKNOWN, SDL_SCANCODE_UNKNOWN, SDL_SCANCODE_UNKNOWN, // 6
SDL_SCANCODE_UNKNOWN, SDL_SCANCODE_UNKNOWN, SDL_SCANCODE_UNKNOWN, SDL_SCANCODE_UNKNOWN, SDL_SCANCODE_UNKNOWN, SDL_SCANCODE_UNKNOWN, SDL_SCANCODE_UNKNOWN, SDL_SCANCODE_UNKNOWN, // 6
SDL_SCANCODE_UNKNOWN, SDL_SCANCODE_UNKNOWN, SDL_SCANCODE_UNKNOWN, SDL_SCANCODE_UNKNOWN, SDL_SCANCODE_F13, SDL_SCANCODE_F14, SDL_SCANCODE_F15, SDL_SCANCODE_F16, // 6
SDL_SCANCODE_F17, SDL_SCANCODE_F18, SDL_SCANCODE_F19, SDL_SCANCODE_UNKNOWN, SDL_SCANCODE_UNKNOWN, SDL_SCANCODE_UNKNOWN, SDL_SCANCODE_UNKNOWN, SDL_SCANCODE_UNKNOWN, // 6
SDL_SCANCODE_UNKNOWN, SDL_SCANCODE_UNKNOWN, SDL_SCANCODE_UNKNOWN, SDL_SCANCODE_UNKNOWN, SDL_SCANCODE_UNKNOWN, SDL_SCANCODE_UNKNOWN, SDL_SCANCODE_UNKNOWN, SDL_SCANCODE_UNKNOWN, // 7
SDL_SCANCODE_UNKNOWN, SDL_SCANCODE_UNKNOWN, SDL_SCANCODE_UNKNOWN, SDL_SCANCODE_UNKNOWN, SDL_SCANCODE_UNKNOWN, SDL_SCANCODE_UNKNOWN, SDL_SCANCODE_UNKNOWN, SDL_SCANCODE_UNKNOWN // 7
SDL_SCANCODE_UNKNOWN, SDL_SCANCODE_UNKNOWN, SDL_SCANCODE_UNKNOWN, SDL_SCANCODE_UNKNOWN, SDL_SCANCODE_UNKNOWN, SDL_SCANCODE_UNKNOWN, SDL_SCANCODE_UNKNOWN, SDL_SCANCODE_UNKNOWN, // 7
SDL_SCANCODE_UNKNOWN, SDL_SCANCODE_UNKNOWN, SDL_SCANCODE_UNKNOWN, SDL_SCANCODE_UNKNOWN, SDL_SCANCODE_UNKNOWN, SDL_SCANCODE_UNKNOWN, SDL_SCANCODE_UNKNOWN, SDL_SCANCODE_UNKNOWN // 7
};
/* *INDENT-ON* */

View File

@@ -141,8 +141,8 @@ static const SDL_Scancode xfree86_scancode_table[] = {
/* 112 */ SDL_SCANCODE_F15,
/* 113 */ SDL_SCANCODE_F16,
/* 114 */ SDL_SCANCODE_F17,
/* 115 */ SDL_SCANCODE_UNKNOWN,
/* 116 */ SDL_SCANCODE_UNKNOWN, /* is translated to XK_ISO_Level3_Shift by my X server, but I have no keyboard that generates this code, so I don't know what the correct SDL_SCANCODE_* for it is */
/* 115 */ SDL_SCANCODE_UNKNOWN,
/* 116 */ SDL_SCANCODE_UNKNOWN, /* is translated to XK_ISO_Level3_Shift by my X server, but I have no keyboard that generates this code, so I don't know what the correct SDL_SCANCODE_* for it is */
/* 117 */ SDL_SCANCODE_UNKNOWN,
/* 118 */ SDL_SCANCODE_KP_EQUALS,
/* 119 */ SDL_SCANCODE_UNKNOWN,
@@ -298,7 +298,7 @@ static const SDL_Scancode xfree86_scancode_table2[] = {
/* 118 */ SDL_SCANCODE_UNKNOWN, /* plusminus */
/* 119 */ SDL_SCANCODE_PAUSE,
/* 120 */ SDL_SCANCODE_UNKNOWN, /* XF86LaunchA */
/* 121 */ SDL_SCANCODE_UNKNOWN, /* KP_Decimal */
/* 121 */ SDL_SCANCODE_UNKNOWN, /* KP_Decimal */
/* 122 */ SDL_SCANCODE_UNKNOWN, /* Hangul */
/* 123 */ SDL_SCANCODE_UNKNOWN, /* Hangul_Hanja */
/* 124 */ SDL_SCANCODE_UNKNOWN,
@@ -325,15 +325,15 @@ static const SDL_Scancode xfree86_scancode_table2[] = {
/* 145 */ SDL_SCANCODE_UNKNOWN, /* XF86Send */
/* 146 */ SDL_SCANCODE_UNKNOWN,
/* 147 */ SDL_SCANCODE_UNKNOWN, /* XF86Xfer */
/* 148 */ SDL_SCANCODE_UNKNOWN, /* XF86Launch1 */
/* 149 */ SDL_SCANCODE_UNKNOWN, /* XF86Launch2 */
/* 148 */ SDL_SCANCODE_APP1, /* XF86Launch1 */
/* 149 */ SDL_SCANCODE_APP2, /* XF86Launch2 */
/* 150 */ SDL_SCANCODE_WWW,
/* 151 */ SDL_SCANCODE_UNKNOWN, /* XF86DOS */
/* 152 */ SDL_SCANCODE_UNKNOWN, /* XF86ScreenSaver */
/* 153 */ SDL_SCANCODE_UNKNOWN,
/* 154 */ SDL_SCANCODE_UNKNOWN, /* XF86RotateWindows */
/* 155 */ SDL_SCANCODE_MAIL,
/* 156 */ SDL_SCANCODE_UNKNOWN, /* XF86Favorites */
/* 156 */ SDL_SCANCODE_AC_BOOKMARKS, /* XF86Favorites */
/* 157 */ SDL_SCANCODE_COMPUTER,
/* 158 */ SDL_SCANCODE_AC_BACK,
/* 159 */ SDL_SCANCODE_AC_FORWARD,
@@ -348,7 +348,7 @@ static const SDL_Scancode xfree86_scancode_table2[] = {
/* 168 */ SDL_SCANCODE_UNKNOWN, /* XF86AudioRewind */
/* 169 */ SDL_SCANCODE_UNKNOWN, /* XF86Phone */
/* 170 */ SDL_SCANCODE_UNKNOWN,
/* 171 */ SDL_SCANCODE_UNKNOWN, /* XF86Tools */
/* 171 */ SDL_SCANCODE_F13, /* XF86Tools */
/* 172 */ SDL_SCANCODE_AC_HOME,
/* 173 */ SDL_SCANCODE_AC_REFRESH,
/* 174 */ SDL_SCANCODE_UNKNOWN, /* XF86Close */
@@ -360,13 +360,13 @@ static const SDL_Scancode xfree86_scancode_table2[] = {
/* 180 */ SDL_SCANCODE_UNKNOWN, /* parenright */
/* 181 */ SDL_SCANCODE_UNKNOWN, /* XF86New */
/* 182 */ SDL_SCANCODE_AGAIN,
/* 183 */ SDL_SCANCODE_UNKNOWN, /* XF86Tools */
/* 184 */ SDL_SCANCODE_UNKNOWN, /* XF86Launch5 */
/* 185 */ SDL_SCANCODE_UNKNOWN, /* XF86MenuKB */
/* 186 */ SDL_SCANCODE_UNKNOWN,
/* 187 */ SDL_SCANCODE_UNKNOWN,
/* 188 */ SDL_SCANCODE_UNKNOWN,
/* 189 */ SDL_SCANCODE_UNKNOWN,
/* 183 */ SDL_SCANCODE_F13, /* XF86Tools */
/* 184 */ SDL_SCANCODE_F14, /* XF86Launch5 */
/* 185 */ SDL_SCANCODE_F15, /* XF86Launch6 */
/* 186 */ SDL_SCANCODE_F16, /* XF86Launch7 */
/* 187 */ SDL_SCANCODE_F17, /* XF86Launch8 */
/* 188 */ SDL_SCANCODE_F18, /* XF86Launch9 */
/* 189 */ SDL_SCANCODE_F19, /* null keysym */
/* 190 */ SDL_SCANCODE_UNKNOWN,
/* 191 */ SDL_SCANCODE_UNKNOWN,
/* 192 */ SDL_SCANCODE_UNKNOWN, /* XF86TouchpadToggle */

File diff suppressed because it is too large Load Diff

View File

@@ -14,32 +14,32 @@ FILE* SDL_OpenFPFromBundleOrFallback(const char *file, const char *mode)
{
FILE* fp = NULL;
// If the file mode is writable, skip all the bundle stuff because generally the bundle is read-only.
if(strcmp("r", mode) && strcmp("rb", mode))
{
return fopen(file, mode);
}
/* If the file mode is writable, skip all the bundle stuff because generally the bundle is read-only. */
if(strcmp("r", mode) && strcmp("rb", mode))
{
return fopen(file, mode);
}
NSAutoreleasePool* autorelease_pool = [[NSAutoreleasePool alloc] init];
NSAutoreleasePool* autorelease_pool = [[NSAutoreleasePool alloc] init];
NSFileManager* file_manager = [NSFileManager defaultManager];
NSString* resource_path = [[NSBundle mainBundle] resourcePath];
NSFileManager* file_manager = [NSFileManager defaultManager];
NSString* resource_path = [[NSBundle mainBundle] resourcePath];
NSString* ns_string_file_component = [file_manager stringWithFileSystemRepresentation:file length:strlen(file)];
NSString* ns_string_file_component = [file_manager stringWithFileSystemRepresentation:file length:strlen(file)];
NSString* full_path_with_file_to_try = [resource_path stringByAppendingPathComponent:ns_string_file_component];
if([file_manager fileExistsAtPath:full_path_with_file_to_try])
{
fp = fopen([full_path_with_file_to_try fileSystemRepresentation], mode);
}
else
{
fp = fopen(file, mode);
}
NSString* full_path_with_file_to_try = [resource_path stringByAppendingPathComponent:ns_string_file_component];
if([file_manager fileExistsAtPath:full_path_with_file_to_try])
{
fp = fopen([full_path_with_file_to_try fileSystemRepresentation], mode);
}
else
{
fp = fopen(file, mode);
}
[autorelease_pool drain];
[autorelease_pool drain];
return fp;
return fp;
}
#endif

View File

@@ -23,7 +23,7 @@
#include "SDL_syshaptic.h"
#include "SDL_haptic_c.h"
#include "../joystick/SDL_joystick_c.h" /* For SDL_PrivateJoystickValid */
#include "SDL_assert.h"
Uint8 SDL_numhaptics = 0;
SDL_Haptic **SDL_haptics = NULL;
@@ -149,18 +149,23 @@ SDL_HapticOpen(int device_index)
return NULL;
}
/* Add haptic to list */
for (i = 0; SDL_haptics[i]; i++)
/* Skip to next haptic */ ;
if (i >= SDL_numhaptics) {
SDL_free(haptic);
SDL_SetError("Haptic: Trying to add device past the number originally detected");
return NULL;
}
SDL_haptics[i] = haptic;
++haptic->ref_count;
/* Disable autocenter and set gain to max. */
if (haptic->supported & SDL_HAPTIC_GAIN)
SDL_HapticSetGain(haptic, 100);
if (haptic->supported & SDL_HAPTIC_AUTOCENTER)
SDL_HapticSetAutocenter(haptic, 0);
/* Add haptic to list */
++haptic->ref_count;
for (i = 0; SDL_haptics[i]; i++)
/* Skip to next haptic */ ;
SDL_haptics[i] = haptic;
return haptic;
}
@@ -173,6 +178,13 @@ SDL_HapticOpened(int device_index)
{
int i, opened;
/* Make sure it's valid. */
if ((device_index < 0) || (device_index >= SDL_numhaptics)) {
SDL_SetError("Haptic: There are %d haptic devices available",
SDL_numhaptics);
return 0;
}
opened = 0;
for (i = 0; SDL_haptics[i]; i++) {
if (SDL_haptics[i]->index == (Uint8) device_index) {
@@ -262,6 +274,13 @@ SDL_HapticOpenFromJoystick(SDL_Joystick * joystick)
int i;
SDL_Haptic *haptic;
/* Make sure there is room. */
if (SDL_numhaptics <= 0) {
SDL_SetError("Haptic: There are %d haptic devices available",
SDL_numhaptics);
return NULL;
}
/* Must be a valid joystick */
if (!SDL_PrivateJoystickValid(joystick)) {
SDL_SetError("Haptic: Joystick isn't valid.");
@@ -299,10 +318,15 @@ SDL_HapticOpenFromJoystick(SDL_Joystick * joystick)
}
/* Add haptic to list */
++haptic->ref_count;
for (i = 0; SDL_haptics[i]; i++)
/* Skip to next haptic */ ;
if (i >= SDL_numhaptics) {
SDL_free(haptic);
SDL_SetError("Haptic: Trying to add device past the number originally detected");
return NULL;
}
SDL_haptics[i] = haptic;
++haptic->ref_count;
return haptic;
}
@@ -397,7 +421,7 @@ unsigned int
SDL_HapticQuery(SDL_Haptic * haptic)
{
if (!ValidHaptic(haptic)) {
return -1;
return 0; /* same as if no effects were supported */
}
return haptic->supported;
@@ -699,32 +723,18 @@ SDL_HapticStopAll(SDL_Haptic * haptic)
return SDL_SYS_HapticStopAll(haptic);
}
static void
SDL_HapticRumbleCreate(SDL_HapticEffect * efx)
{
SDL_memset(efx, 0, sizeof(SDL_HapticEffect));
efx->type = SDL_HAPTIC_SINE;
efx->periodic.period = 1000;
efx->periodic.magnitude = 0x4000;
efx->periodic.length = 5000;
efx->periodic.attack_length = 0;
efx->periodic.fade_length = 0;
}
/*
* Checks to see if rumble is supported.
*/
int
SDL_HapticRumbleSupported(SDL_Haptic * haptic)
{
SDL_HapticEffect efx;
if (!ValidHaptic(haptic)) {
return -1;
}
SDL_HapticRumbleCreate(&efx);
return SDL_HapticEffectSupported(haptic, &efx);
/* Most things can use SINE, but XInput only has LEFTRIGHT. */
return ((haptic->supported & (SDL_HAPTIC_SINE|SDL_HAPTIC_LEFTRIGHT)) != 0);
}
/*
@@ -733,6 +743,8 @@ SDL_HapticRumbleSupported(SDL_Haptic * haptic)
int
SDL_HapticRumbleInit(SDL_Haptic * haptic)
{
SDL_HapticEffect *efx = &haptic->rumble_effect;
if (!ValidHaptic(haptic)) {
return -1;
}
@@ -742,8 +754,23 @@ SDL_HapticRumbleInit(SDL_Haptic * haptic)
return 0;
}
/* Copy over. */
SDL_HapticRumbleCreate(&haptic->rumble_effect);
SDL_zerop(efx);
if (haptic->supported & SDL_HAPTIC_SINE) {
efx->type = SDL_HAPTIC_SINE;
efx->periodic.period = 1000;
efx->periodic.magnitude = 0x4000;
efx->periodic.length = 5000;
efx->periodic.attack_length = 0;
efx->periodic.fade_length = 0;
} else if (haptic->supported & SDL_HAPTIC_LEFTRIGHT) { /* XInput? */
efx->type = SDL_HAPTIC_LEFTRIGHT;
efx->leftright.length = 5000;
efx->leftright.large_magnitude = 0x4000;
efx->leftright.small_magnitude = 0x4000;
} else {
return SDL_SetError("Device doesn't support rumble");
}
haptic->rumble_id = SDL_HapticNewEffect(haptic, &haptic->rumble_effect);
if (haptic->rumble_id >= 0) {
return 0;
@@ -757,7 +784,8 @@ SDL_HapticRumbleInit(SDL_Haptic * haptic)
int
SDL_HapticRumblePlay(SDL_Haptic * haptic, float strength, Uint32 length)
{
SDL_HapticPeriodic *efx;
SDL_HapticEffect *efx;
Sint16 magnitude;
if (!ValidHaptic(haptic)) {
return -1;
@@ -770,16 +798,25 @@ SDL_HapticRumblePlay(SDL_Haptic * haptic, float strength, Uint32 length)
/* Clamp strength. */
if (strength > 1.0f) {
strength = 1.0f;
}
else if (strength < 0.0f) {
} else if (strength < 0.0f) {
strength = 0.0f;
}
magnitude = (Sint16)(32767.0f*strength);
/* New effect. */
efx = &haptic->rumble_effect.periodic;
efx->magnitude = (Sint16)(32767.0f*strength);
efx->length = length;
SDL_HapticUpdateEffect(haptic, haptic->rumble_id, &haptic->rumble_effect);
efx = &haptic->rumble_effect;
if (efx->type == SDL_HAPTIC_SINE) {
efx->periodic.magnitude = magnitude;
efx->periodic.length = length;
} else if (efx->type == SDL_HAPTIC_LEFTRIGHT) {
efx->leftright.small_magnitude = efx->leftright.large_magnitude = magnitude;
efx->leftright.length = length;
} else {
SDL_assert(0 && "This should have been caught elsewhere");
}
if (SDL_HapticUpdateEffect(haptic, haptic->rumble_id, &haptic->rumble_effect) < 0) {
return -1;
}
return SDL_HapticRunEffect(haptic, haptic->rumble_id, 1);
}
@@ -801,4 +838,3 @@ SDL_HapticRumbleStop(SDL_Haptic * haptic)
return SDL_HapticStopEffect(haptic, haptic->rumble_id);
}

View File

@@ -56,10 +56,10 @@ struct _SDL_Haptic
SDL_HapticEffect rumble_effect; /* Rumble effect. */
};
/*
/*
* Scans the system for haptic devices.
*
* Returns 0 on success, -1 on error.
* Returns number of devices on success, -1 on error.
*/
extern int SDL_SYS_HapticInit(void);

View File

@@ -35,7 +35,7 @@
#include <ForceFeedback/ForceFeedbackConstants.h>
#ifndef IO_OBJECT_NULL
#define IO_OBJECT_NULL ((io_service_t)0)
#define IO_OBJECT_NULL ((io_service_t)0)
#endif
#define MAX_HAPTICS 32
@@ -49,7 +49,7 @@ static struct
char name[256]; /* Name of the device. */
io_service_t dev; /* Node we use to create the device. */
SDL_Haptic *haptic; /* Haptic currently assosciated with it. */
SDL_Haptic *haptic; /* Haptic currently associated with it. */
/* Usage pages for determining if it's a mouse or not. */
long usage;
@@ -83,7 +83,7 @@ static void SDL_SYS_HapticFreeFFEFFECT(FFEFFECT * effect, int type);
static int HIDGetDeviceProduct(io_service_t dev, char *name);
/*
/*
* Like strerror but for force feedback errors.
*/
static const char *
@@ -259,7 +259,7 @@ HIDGetDeviceProduct(io_service_t dev, char *name)
}
/* Mac OS X currently is not mirroring all USB properties to HID page so need to look at USB device page also
* get dictionary for usb properties: step up two levels and get CF dictionary for USB properties
* get dictionary for USB properties: step up two levels and get CF dictionary for USB properties
*/
if ((KERN_SUCCESS ==
IORegistryEntryGetParentEntry(dev, kIOServicePlane, &parent1))
@@ -272,7 +272,7 @@ HIDGetDeviceProduct(io_service_t dev, char *name)
if (usbProperties) {
CFTypeRef refCF = 0;
/* get device info
* try hid dictionary first, if fail then go to usb dictionary
* try hid dictionary first, if fail then go to USB dictionary
*/
@@ -342,7 +342,8 @@ GetSupportedFeatures(SDL_Haptic * haptic)
/* Test for effects. */
FF_TEST(FFCAP_ET_CONSTANTFORCE, SDL_HAPTIC_CONSTANT);
FF_TEST(FFCAP_ET_RAMPFORCE, SDL_HAPTIC_RAMP);
FF_TEST(FFCAP_ET_SQUARE, SDL_HAPTIC_SQUARE);
/* !!! FIXME: put this back when we have more bits in 2.1 */
/*FF_TEST(FFCAP_ET_SQUARE, SDL_HAPTIC_SQUARE);*/
FF_TEST(FFCAP_ET_SINE, SDL_HAPTIC_SINE);
FF_TEST(FFCAP_ET_TRIANGLE, SDL_HAPTIC_TRIANGLE);
FF_TEST(FFCAP_ET_SAWTOOTHUP, SDL_HAPTIC_SAWTOOTHUP);
@@ -562,7 +563,7 @@ SDL_SYS_HapticClose(SDL_Haptic * haptic)
}
/*
/*
* Clean up after system specific haptic stuff
*/
void
@@ -708,7 +709,7 @@ SDL_SYS_ToFFEFFECT(SDL_Haptic * haptic, FFEFFECT * dest,
}
/* The big type handling switch, even bigger then linux's version. */
/* The big type handling switch, even bigger then Linux's version. */
switch (src->type) {
case SDL_HAPTIC_CONSTANT:
hap_constant = &src->constant;
@@ -750,7 +751,8 @@ SDL_SYS_ToFFEFFECT(SDL_Haptic * haptic, FFEFFECT * dest,
break;
case SDL_HAPTIC_SINE:
case SDL_HAPTIC_SQUARE:
/* !!! FIXME: put this back when we have more bits in 2.1 */
/*case SDL_HAPTIC_SQUARE:*/
case SDL_HAPTIC_TRIANGLE:
case SDL_HAPTIC_SAWTOOTHUP:
case SDL_HAPTIC_SAWTOOTHDOWN:
@@ -978,8 +980,9 @@ SDL_SYS_HapticEffectType(Uint16 type)
case SDL_HAPTIC_RAMP:
return kFFEffectType_RampForce_ID;
case SDL_HAPTIC_SQUARE:
return kFFEffectType_Square_ID;
/* !!! FIXME: put this back when we have more bits in 2.1 */
/*case SDL_HAPTIC_SQUARE:
return kFFEffectType_Square_ID;*/
case SDL_HAPTIC_SINE:
return kFFEffectType_Sine_ID;

View File

@@ -29,8 +29,7 @@
static int
SDL_SYS_LogicError(void)
{
SDL_SetError("Logic error: No haptic devices available.");
return 0;
return SDL_SetError("Logic error: No haptic devices available.");
}
@@ -52,8 +51,7 @@ SDL_SYS_HapticName(int index)
int
SDL_SYS_HapticOpen(SDL_Haptic * haptic)
{
SDL_SYS_LogicError();
return -1;
return SDL_SYS_LogicError();
}
@@ -74,8 +72,7 @@ SDL_SYS_JoystickIsHaptic(SDL_Joystick * joystick)
int
SDL_SYS_HapticOpenFromJoystick(SDL_Haptic * haptic, SDL_Joystick * joystick)
{
SDL_SYS_LogicError();
return -1;
return SDL_SYS_LogicError();
}
@@ -104,8 +101,7 @@ int
SDL_SYS_HapticNewEffect(SDL_Haptic * haptic,
struct haptic_effect *effect, SDL_HapticEffect * base)
{
SDL_SYS_LogicError();
return -1;
return SDL_SYS_LogicError();
}
@@ -114,8 +110,7 @@ SDL_SYS_HapticUpdateEffect(SDL_Haptic * haptic,
struct haptic_effect *effect,
SDL_HapticEffect * data)
{
SDL_SYS_LogicError();
return -1;
return SDL_SYS_LogicError();
}
@@ -123,16 +118,14 @@ int
SDL_SYS_HapticRunEffect(SDL_Haptic * haptic, struct haptic_effect *effect,
Uint32 iterations)
{
SDL_SYS_LogicError();
return -1;
return SDL_SYS_LogicError();
}
int
SDL_SYS_HapticStopEffect(SDL_Haptic * haptic, struct haptic_effect *effect)
{
SDL_SYS_LogicError();
return -1;
return SDL_SYS_LogicError();
}
@@ -148,47 +141,39 @@ int
SDL_SYS_HapticGetEffectStatus(SDL_Haptic * haptic,
struct haptic_effect *effect)
{
SDL_SYS_LogicError();
return -1;
return SDL_SYS_LogicError();
}
int
SDL_SYS_HapticSetGain(SDL_Haptic * haptic, int gain)
{
SDL_SYS_LogicError();
return -1;
return SDL_SYS_LogicError();
}
int
SDL_SYS_HapticSetAutocenter(SDL_Haptic * haptic, int autocenter)
{
SDL_SYS_LogicError();
return -1;
return SDL_SYS_LogicError();
}
int
SDL_SYS_HapticPause(SDL_Haptic * haptic)
{
SDL_SYS_LogicError();
return -1;
return SDL_SYS_LogicError();
}
int
SDL_SYS_HapticUnpause(SDL_Haptic * haptic)
{
SDL_SYS_LogicError();
return -1;
return SDL_SYS_LogicError();
}
int
SDL_SYS_HapticStopAll(SDL_Haptic * haptic)
{
SDL_SYS_LogicError();
return -1;
return SDL_SYS_LogicError();
}
#endif /* SDL_HAPTIC_DUMMY || SDL_HAPTIC_DISABLED */

View File

@@ -99,7 +99,8 @@ EV_IsHaptic(int fd)
/* Convert supported features to SDL_HAPTIC platform-neutral features. */
EV_TEST(FF_CONSTANT, SDL_HAPTIC_CONSTANT);
EV_TEST(FF_SINE, SDL_HAPTIC_SINE);
EV_TEST(FF_SQUARE, SDL_HAPTIC_SQUARE);
/* !!! FIXME: put this back when we have more bits in 2.1 */
/*EV_TEST(FF_SQUARE, SDL_HAPTIC_SQUARE);*/
EV_TEST(FF_TRIANGLE, SDL_HAPTIC_TRIANGLE);
EV_TEST(FF_SAW_UP, SDL_HAPTIC_SAWTOOTHUP);
EV_TEST(FF_SAW_DOWN, SDL_HAPTIC_SAWTOOTHDOWN);
@@ -111,6 +112,7 @@ EV_IsHaptic(int fd)
EV_TEST(FF_CUSTOM, SDL_HAPTIC_CUSTOM);
EV_TEST(FF_GAIN, SDL_HAPTIC_GAIN);
EV_TEST(FF_AUTOCENTER, SDL_HAPTIC_AUTOCENTER);
EV_TEST(FF_RUMBLE, SDL_HAPTIC_LEFTRIGHT);
/* Return what it supports. */
return ret;
@@ -155,7 +157,7 @@ SDL_SYS_HapticInit(void)
numhaptics = 0;
/*
/*
* Limit amount of checks to MAX_HAPTICS since we may or may not have
* permission to some or all devices.
*/
@@ -371,7 +373,7 @@ SDL_SYS_JoystickIsHaptic(SDL_Joystick * joystick)
int
SDL_SYS_JoystickSameHaptic(SDL_Haptic * haptic, SDL_Joystick * joystick)
{
/* We are assuming linux is using evdev which should trump the old
/* We are assuming Linux is using evdev which should trump the old
* joystick methods. */
if (SDL_strcmp(joystick->hwdata->fname, haptic->hwdata->fname) == 0) {
return 1;
@@ -446,7 +448,7 @@ SDL_SYS_HapticClose(SDL_Haptic * haptic)
}
/*
/*
* Clean up after system specific haptic stuff
*/
void
@@ -498,44 +500,44 @@ SDL_SYS_ToDirection(SDL_HapticDirection * dir)
switch (dir->type) {
case SDL_HAPTIC_POLAR:
/* Linux directions start from south.
(and range from 0 to 0xFFFF)
Quoting include/linux/input.h, line 926:
Direction of the effect is encoded as follows:
0 deg -> 0x0000 (down)
90 deg -> 0x4000 (left)
180 deg -> 0x8000 (up)
270 deg -> 0xC000 (right)
*/
tmp = (((18000 + dir->dir[0]) % 36000) * 0xFFFF) / 36000; // convert to range [0,0xFFFF]
(and range from 0 to 0xFFFF)
Quoting include/linux/input.h, line 926:
Direction of the effect is encoded as follows:
0 deg -> 0x0000 (down)
90 deg -> 0x4000 (left)
180 deg -> 0x8000 (up)
270 deg -> 0xC000 (right)
*/
tmp = (((18000 + dir->dir[0]) % 36000) * 0xFFFF) / 36000; /* convert to range [0,0xFFFF] */
return (Uint16) tmp;
case SDL_HAPTIC_SPHERICAL:
/*
We convert to polar, because that's the only supported direction on Linux.
The first value of a spherical direction is practically the same as a
Polar direction, except that we have to add 90 degrees. It is the angle
from EAST {1,0} towards SOUTH {0,1}.
--> add 9000
--> finally add 18000 and convert to [0,0xFFFF] as in case SDL_HAPTIC_POLAR.
*/
tmp = ((dir->dir[0]) + 9000) % 36000; /* Convert to polars */
tmp = (((18000 + tmp) % 36000) * 0xFFFF) / 36000; // convert to range [0,0xFFFF]
case SDL_HAPTIC_SPHERICAL:
/*
We convert to polar, because that's the only supported direction on Linux.
The first value of a spherical direction is practically the same as a
Polar direction, except that we have to add 90 degrees. It is the angle
from EAST {1,0} towards SOUTH {0,1}.
--> add 9000
--> finally add 18000 and convert to [0,0xFFFF] as in case SDL_HAPTIC_POLAR.
*/
tmp = ((dir->dir[0]) + 9000) % 36000; /* Convert to polars */
tmp = (((18000 + tmp) % 36000) * 0xFFFF) / 36000; /* convert to range [0,0xFFFF] */
return (Uint16) tmp;
case SDL_HAPTIC_CARTESIAN:
f = atan2(dir->dir[1], dir->dir[0]);
/*
atan2 takes the parameters: Y-axis-value and X-axis-value (in that order)
- Y-axis-value is the second coordinate (from center to SOUTH)
- X-axis-value is the first coordinate (from center to EAST)
We add 36000, because atan2 also returns negative values. Then we practically
have the first spherical value. Therefore we proceed as in case
SDL_HAPTIC_SPHERICAL and add another 9000 to get the polar value.
--> add 45000 in total
--> finally add 18000 and convert to [0,0xFFFF] as in case SDL_HAPTIC_POLAR.
*/
tmp = (((int) (f * 18000. / M_PI)) + 45000) % 36000;
tmp = (((18000 + tmp) % 36000) * 0xFFFF) / 36000; // convert to range [0,0xFFFF]
/*
atan2 takes the parameters: Y-axis-value and X-axis-value (in that order)
- Y-axis-value is the second coordinate (from center to SOUTH)
- X-axis-value is the first coordinate (from center to EAST)
We add 36000, because atan2 also returns negative values. Then we practically
have the first spherical value. Therefore we proceed as in case
SDL_HAPTIC_SPHERICAL and add another 9000 to get the polar value.
--> add 45000 in total
--> finally add 18000 and convert to [0,0xFFFF] as in case SDL_HAPTIC_POLAR.
*/
tmp = (((int) (f * 18000. / M_PI)) + 45000) % 36000;
tmp = (((18000 + tmp) % 36000) * 0xFFFF) / 36000; /* convert to range [0,0xFFFF] */
return (Uint16) tmp;
default:
@@ -548,7 +550,7 @@ SDL_SYS_ToDirection(SDL_HapticDirection * dir)
#define CLAMP(x) (((x) > 32767) ? 32767 : x)
/*
* Initializes the linux effect struct from a haptic_effect.
* Initializes the Linux effect struct from a haptic_effect.
* Values above 32767 (for unsigned) are unspecified so we must clamp.
*/
static int
@@ -559,6 +561,7 @@ SDL_SYS_ToFFEffect(struct ff_effect *dest, SDL_HapticEffect * src)
SDL_HapticPeriodic *periodic;
SDL_HapticCondition *condition;
SDL_HapticRamp *ramp;
SDL_HapticLeftRight *leftright;
/* Clear up */
SDL_memset(dest, 0, sizeof(struct ff_effect));
@@ -596,7 +599,8 @@ SDL_SYS_ToFFEffect(struct ff_effect *dest, SDL_HapticEffect * src)
break;
case SDL_HAPTIC_SINE:
case SDL_HAPTIC_SQUARE:
/* !!! FIXME: put this back when we have more bits in 2.1 */
/*case SDL_HAPTIC_SQUARE:*/
case SDL_HAPTIC_TRIANGLE:
case SDL_HAPTIC_SAWTOOTHUP:
case SDL_HAPTIC_SAWTOOTHDOWN:
@@ -620,8 +624,9 @@ SDL_SYS_ToFFEffect(struct ff_effect *dest, SDL_HapticEffect * src)
/* Periodic */
if (periodic->type == SDL_HAPTIC_SINE)
dest->u.periodic.waveform = FF_SINE;
else if (periodic->type == SDL_HAPTIC_SQUARE)
dest->u.periodic.waveform = FF_SQUARE;
/* !!! FIXME: put this back when we have more bits in 2.1 */
/*else if (periodic->type == SDL_HAPTIC_SQUARE)
dest->u.periodic.waveform = FF_SQUARE;*/
else if (periodic->type == SDL_HAPTIC_TRIANGLE)
dest->u.periodic.waveform = FF_TRIANGLE;
else if (periodic->type == SDL_HAPTIC_SAWTOOTHUP)
@@ -725,6 +730,27 @@ SDL_SYS_ToFFEffect(struct ff_effect *dest, SDL_HapticEffect * src)
break;
case SDL_HAPTIC_LEFTRIGHT:
leftright = &src->leftright;
/* Header */
dest->type = FF_RUMBLE;
dest->direction = 0;
/* Replay */
dest->replay.length = (leftright->length == SDL_HAPTIC_INFINITY) ?
0 : CLAMP(leftright->length);
/* Trigger */
dest->trigger.button = 0;
dest->trigger.interval = 0;
/* Rumble */
dest->u.rumble.strong_magnitude = leftright->large_magnitude;
dest->u.rumble.weak_magnitude = leftright->small_magnitude;
break;
default:
return SDL_SetError("Haptic: Unknown effect type.");

View File

@@ -23,6 +23,9 @@
#ifdef SDL_HAPTIC_DINPUT
#include "SDL_assert.h"
#include "SDL_thread.h"
#include "SDL_mutex.h"
#include "SDL_timer.h"
#include "SDL_hints.h"
#include "SDL_haptic.h"
#include "../SDL_syshaptic.h"
@@ -41,8 +44,8 @@ static struct
char *name;
SDL_Haptic *haptic;
DIDEVCAPS capabilities;
Uint8 bXInputHaptic; // Supports force feedback via XInput.
Uint8 userid; // XInput userid index for this joystick
Uint8 bXInputHaptic; /* Supports force feedback via XInput. */
Uint8 userid; /* XInput userid index for this joystick */
} SDL_hapticlist[MAX_HAPTICS];
@@ -53,9 +56,13 @@ struct haptic_hwdata
{
LPDIRECTINPUTDEVICE8 device;
DWORD axes[3]; /* Axes to use. */
int is_joystick; /* Device is loaded as joystick. */
Uint8 bXInputHaptic; // Supports force feedback via XInput.
Uint8 userid; // XInput userid index for this joystick
SDL_bool is_joystick; /* Device is loaded as joystick. */
Uint8 bXInputHaptic; /* Supports force feedback via XInput. */
Uint8 userid; /* XInput userid index for this joystick */
SDL_Thread *thread;
SDL_mutex *mutex;
volatile Uint32 stopTicks;
volatile int stopThread;
};
@@ -92,7 +99,8 @@ static int DI_GUIDIsSame(const GUID * a, const GUID * b);
static int SDL_SYS_HapticOpenFromInstance(SDL_Haptic * haptic,
DIDEVICEINSTANCE instance);
static int SDL_SYS_HapticOpenFromDevice8(SDL_Haptic * haptic,
LPDIRECTINPUTDEVICE8 device8);
LPDIRECTINPUTDEVICE8 device8,
SDL_bool is_joystick);
static int SDL_SYS_HapticOpenFromXInput(SDL_Haptic * haptic, Uint8 userid);
static DWORD DIGetTriggerButton(Uint16 button);
static int SDL_SYS_SetDirection(DIEFFECT * effect, SDL_HapticDirection * dir,
@@ -101,13 +109,15 @@ static int SDL_SYS_ToDIEFFECT(SDL_Haptic * haptic, DIEFFECT * dest,
SDL_HapticEffect * src);
static void SDL_SYS_HapticFreeDIEFFECT(DIEFFECT * effect, int type);
static REFGUID SDL_SYS_HapticEffectType(SDL_HapticEffect * effect);
static int SDLCALL SDL_RunXInputHaptic(void *arg);
/* Callbacks. */
static BOOL CALLBACK EnumHapticsCallback(const DIDEVICEINSTANCE *
pdidInstance, VOID * pContext);
static BOOL CALLBACK DI_EffectCallback(LPCDIEFFECTINFO pei, LPVOID pv);
/*
/*
* Like SDL_SetError but for DX error codes.
*/
static int
@@ -293,7 +303,8 @@ DI_EffectCallback(LPCDIEFFECTINFO pei, LPVOID pv)
EFFECT_TEST(GUID_ConstantForce, SDL_HAPTIC_CONSTANT);
EFFECT_TEST(GUID_CustomForce, SDL_HAPTIC_CUSTOM);
EFFECT_TEST(GUID_Sine, SDL_HAPTIC_SINE);
EFFECT_TEST(GUID_Square, SDL_HAPTIC_SQUARE);
/* !!! FIXME: put this back when we have more bits in 2.1 */
/*EFFECT_TEST(GUID_Square, SDL_HAPTIC_SQUARE);*/
EFFECT_TEST(GUID_Triangle, SDL_HAPTIC_TRIANGLE);
EFFECT_TEST(GUID_SawtoothUp, SDL_HAPTIC_SAWTOOTHUP);
EFFECT_TEST(GUID_SawtoothDown, SDL_HAPTIC_SAWTOOTHDOWN);
@@ -342,61 +353,44 @@ SDL_SYS_HapticOpenFromInstance(SDL_Haptic * haptic, DIDEVICEINSTANCE instance)
HRESULT ret;
int ret2;
LPDIRECTINPUTDEVICE8 device;
/* Allocate the hwdata */
haptic->hwdata = (struct haptic_hwdata *)
SDL_malloc(sizeof(*haptic->hwdata));
if (haptic->hwdata == NULL) {
SDL_OutOfMemory();
goto creat_err;
}
SDL_memset(haptic->hwdata, 0, sizeof(*haptic->hwdata));
LPDIRECTINPUTDEVICE8 device8;
/* Open the device */
ret = IDirectInput8_CreateDevice(dinput, &instance.guidInstance,
&device, NULL);
if (FAILED(ret)) {
DI_SetError("Creating DirectInput device", ret);
goto creat_err;
return -1;
}
/* Now get the IDirectInputDevice8 interface, instead. */
ret = IDirectInputDevice8_QueryInterface(device,
&IID_IDirectInputDevice8,
(LPVOID *) & haptic->hwdata->
device);
(LPVOID *) &device8);
/* Done with the temporary one now. */
IDirectInputDevice8_Release(device);
if (FAILED(ret)) {
DI_SetError("Querying DirectInput interface", ret);
goto creat_err;
return -1;
}
ret2 = SDL_SYS_HapticOpenFromDevice8(haptic, haptic->hwdata->device);
ret2 = SDL_SYS_HapticOpenFromDevice8(haptic, device8, SDL_FALSE);
if (ret2 < 0) {
goto query_err;
IDirectInputDevice8_Release(device8);
return -1;
}
return 0;
query_err:
IDirectInputDevice8_Release(haptic->hwdata->device);
creat_err:
if (haptic->hwdata != NULL) {
SDL_free(haptic->hwdata);
haptic->hwdata = NULL;
}
return -1;
}
static int
SDL_SYS_HapticOpenFromXInput(SDL_Haptic * haptic, Uint8 userid)
{
char threadName[32];
XINPUT_VIBRATION vibration = { 0, 0 }; /* stop any current vibration */
XINPUTSETSTATE(userid, &vibration);
/* !!! FIXME: we can probably do more than SINE if we figure out how to set up the left and right motors properly. */
haptic->supported = SDL_HAPTIC_SINE;
haptic->supported = SDL_HAPTIC_LEFTRIGHT;
haptic->neffects = 1;
haptic->nplaying = 1;
@@ -422,6 +416,30 @@ SDL_SYS_HapticOpenFromXInput(SDL_Haptic * haptic, Uint8 userid)
haptic->hwdata->bXInputHaptic = 1;
haptic->hwdata->userid = userid;
haptic->hwdata->mutex = SDL_CreateMutex();
if (haptic->hwdata->mutex == NULL) {
SDL_free(haptic->effects);
SDL_free(haptic->hwdata);
haptic->effects = NULL;
return SDL_SetError("Couldn't create XInput haptic mutex");
}
SDL_snprintf(threadName, sizeof (threadName), "SDLXInputDev%d", (int) userid);
#if defined(__WIN32__) && !defined(HAVE_LIBC) /* !!! FIXME: this is nasty. */
#undef SDL_CreateThread
haptic->hwdata->thread = SDL_CreateThread(SDL_RunXInputHaptic, threadName, haptic->hwdata, NULL, NULL);
#else
haptic->hwdata->thread = SDL_CreateThread(SDL_RunXInputHaptic, threadName, haptic->hwdata);
#endif
if (haptic->hwdata->thread == NULL) {
SDL_DestroyMutex(haptic->hwdata->mutex);
SDL_free(haptic->effects);
SDL_free(haptic->hwdata);
haptic->effects = NULL;
return SDL_SetError("Couldn't create XInput haptic thread");
}
return 0;
}
@@ -433,17 +451,25 @@ SDL_SYS_HapticOpenFromXInput(SDL_Haptic * haptic, Uint8 userid)
* - Set data format.
* - Acquire exclusiveness.
* - Reset actuators.
* - Get supported featuers.
* - Get supported features.
*/
static int
SDL_SYS_HapticOpenFromDevice8(SDL_Haptic * haptic,
LPDIRECTINPUTDEVICE8 device8)
LPDIRECTINPUTDEVICE8 device8, SDL_bool is_joystick)
{
HRESULT ret;
DIPROPDWORD dipdw;
/* Allocate the hwdata */
haptic->hwdata = (struct haptic_hwdata *)SDL_malloc(sizeof(*haptic->hwdata));
if (haptic->hwdata == NULL) {
return SDL_OutOfMemory();
}
SDL_memset(haptic->hwdata, 0, sizeof(*haptic->hwdata));
/* We'll use the device8 from now on. */
haptic->hwdata->device = device8;
haptic->hwdata->is_joystick = is_joystick;
/* Grab it exclusively to use force feedback stuff. */
ret = IDirectInputDevice8_SetCooperativeLevel(haptic->hwdata->device,
@@ -645,7 +671,7 @@ SDL_SYS_JoystickSameHaptic(SDL_Haptic * haptic, SDL_Joystick * joystick)
int
SDL_SYS_HapticOpenFromJoystick(SDL_Haptic * haptic, SDL_Joystick * joystick)
{
int i, ret;
int i;
HRESULT idret;
DIDEVICEINSTANCE joy_instance;
joy_instance.dwSize = sizeof(DIDEVICEINSTANCE);
@@ -657,49 +683,24 @@ SDL_SYS_HapticOpenFromJoystick(SDL_Haptic * haptic, SDL_Joystick * joystick)
if ((SDL_hapticlist[i].bXInputHaptic) && (SDL_hapticlist[i].userid == userid)) {
SDL_assert(joystick->hwdata->bXInputHaptic);
haptic->index = i;
break;
return SDL_SYS_HapticOpenFromXInput(haptic, SDL_hapticlist[haptic->index].userid);
}
}
} else {
for (i=0; i<SDL_numhaptics; i++) {
idret = IDirectInputDevice8_GetDeviceInfo(joystick->hwdata->InputDevice,
&joy_instance);
idret = IDirectInputDevice8_GetDeviceInfo(joystick->hwdata->InputDevice, &joy_instance);
if (FAILED(idret)) {
return -1;
}
if (DI_GUIDIsSame(&SDL_hapticlist[i].instance.guidInstance,
&joy_instance.guidInstance)) {
haptic->index = i;
break;
return SDL_SYS_HapticOpenFromDevice8(haptic, joystick->hwdata->InputDevice, SDL_TRUE);
}
}
}
if (i >= SDL_numhaptics) {
return -1;
}
/* Allocate the hwdata */
haptic->hwdata = (struct haptic_hwdata *)
SDL_malloc(sizeof(*haptic->hwdata));
if (haptic->hwdata == NULL) {
return SDL_OutOfMemory();
}
SDL_memset(haptic->hwdata, 0, sizeof(*haptic->hwdata));
/* Now open the device. */
if (!joystick->hwdata->bXInputHaptic) {
ret = SDL_SYS_HapticOpenFromDevice8(haptic, joystick->hwdata->InputDevice);
if (ret < 0) {
return -1;
}
}
/* It's using the joystick device. */
haptic->hwdata->is_joystick = 1;
haptic->hwdata->bXInputHaptic = joystick->hwdata->bXInputHaptic;
haptic->hwdata->userid = joystick->hwdata->userid;
return 0;
/* No match to our haptic list */
return -1;
}
@@ -717,7 +718,11 @@ SDL_SYS_HapticClose(SDL_Haptic * haptic)
haptic->neffects = 0;
/* Clean up */
if (!haptic->hwdata->bXInputHaptic) {
if (haptic->hwdata->bXInputHaptic) {
haptic->hwdata->stopThread = 1;
SDL_WaitThread(haptic->hwdata->thread, NULL);
SDL_DestroyMutex(haptic->hwdata->mutex);
} else {
IDirectInputDevice8_Unacquire(haptic->hwdata->device);
/* Only release if isn't grabbed by a joystick. */
if (haptic->hwdata->is_joystick == 0) {
@@ -732,7 +737,7 @@ SDL_SYS_HapticClose(SDL_Haptic * haptic)
}
/*
/*
* Clean up after system specific haptic stuff
*/
void
@@ -888,7 +893,7 @@ SDL_SYS_ToDIEFFECT(SDL_Haptic * haptic, DIEFFECT * dest,
}
/* The big type handling switch, even bigger then linux's version. */
/* The big type handling switch, even bigger then Linux's version. */
switch (src->type) {
case SDL_HAPTIC_CONSTANT:
hap_constant = &src->constant;
@@ -930,7 +935,8 @@ SDL_SYS_ToDIEFFECT(SDL_Haptic * haptic, DIEFFECT * dest,
break;
case SDL_HAPTIC_SINE:
case SDL_HAPTIC_SQUARE:
/* !!! FIXME: put this back when we have more bits in 2.1 */
/*case SDL_HAPTIC_SQUARE:*/
case SDL_HAPTIC_TRIANGLE:
case SDL_HAPTIC_SAWTOOTHUP:
case SDL_HAPTIC_SAWTOOTHDOWN:
@@ -1158,8 +1164,9 @@ SDL_SYS_HapticEffectType(SDL_HapticEffect * effect)
case SDL_HAPTIC_RAMP:
return &GUID_RampForce;
case SDL_HAPTIC_SQUARE:
return &GUID_Square;
/* !!! FIXME: put this back when we have more bits in 2.1 */
/*case SDL_HAPTIC_SQUARE:
return &GUID_Square;*/
case SDL_HAPTIC_SINE:
return &GUID_Sine;
@@ -1205,7 +1212,7 @@ SDL_SYS_HapticNewEffect(SDL_Haptic * haptic, struct haptic_effect *effect,
HRESULT ret;
REFGUID type = SDL_SYS_HapticEffectType(base);
if (type == NULL) {
if ((type == NULL) && (!haptic->hwdata->bXInputHaptic)) {
goto err_hweffect;
}
@@ -1220,7 +1227,7 @@ SDL_SYS_HapticNewEffect(SDL_Haptic * haptic, struct haptic_effect *effect,
SDL_zerop(effect->hweffect);
if (haptic->hwdata->bXInputHaptic) {
SDL_assert(base->type == SDL_HAPTIC_SINE); /* should catch this at higher level */
SDL_assert(base->type == SDL_HAPTIC_LEFTRIGHT); /* should catch this at higher level */
return SDL_SYS_HapticUpdateEffect(haptic, effect, base);
}
@@ -1264,19 +1271,15 @@ SDL_SYS_HapticUpdateEffect(SDL_Haptic * haptic,
DIEFFECT temp;
if (haptic->hwdata->bXInputHaptic) {
// !!! FIXME: this isn't close to right. We only support "sine" effects,
// !!! FIXME: we ignore most of the parameters, and we probably get
// !!! FIXME: the ones we don't ignore wrong, too.
// !!! FIXME: if I had a better understanding of how the two motors
// !!! FIXME: could be used in unison, perhaps I could implement other
// !!! FIXME: effect types?
/* From MSDN:
"Note that the right motor is the high-frequency motor, the left
motor is the low-frequency motor. They do not always need to be
set to the same amount, as they provide different effects." */
XINPUT_VIBRATION *vib = &effect->hweffect->vibration;
SDL_assert(data->type == SDL_HAPTIC_SINE);
vib->wLeftMotorSpeed = vib->wRightMotorSpeed = data->periodic.magnitude * 2;
SDL_assert(data->type == SDL_HAPTIC_LEFTRIGHT);
vib->wLeftMotorSpeed = data->leftright.large_magnitude;
vib->wRightMotorSpeed = data->leftright.small_magnitude;
SDL_LockMutex(haptic->hwdata->mutex);
if (haptic->hwdata->stopTicks) { /* running right now? Update it. */
XINPUTSETSTATE(haptic->hwdata->userid, vib);
}
SDL_UnlockMutex(haptic->hwdata->mutex);
return 0;
}
@@ -1327,7 +1330,11 @@ SDL_SYS_HapticRunEffect(SDL_Haptic * haptic, struct haptic_effect *effect,
if (haptic->hwdata->bXInputHaptic) {
XINPUT_VIBRATION *vib = &effect->hweffect->vibration;
return (XINPUTSETSTATE(haptic->hwdata->userid, vib) == ERROR_SUCCESS);
SDL_assert(effect->effect.type == SDL_HAPTIC_LEFTRIGHT); /* should catch this at higher level */
SDL_LockMutex(haptic->hwdata->mutex);
haptic->hwdata->stopTicks = SDL_GetTicks() + (effect->effect.leftright.length * iterations);
SDL_UnlockMutex(haptic->hwdata->mutex);
return (XINPUTSETSTATE(haptic->hwdata->userid, vib) == ERROR_SUCCESS) ? 0 : -1;
}
/* Check if it's infinite. */
@@ -1356,7 +1363,10 @@ SDL_SYS_HapticStopEffect(SDL_Haptic * haptic, struct haptic_effect *effect)
if (haptic->hwdata->bXInputHaptic) {
XINPUT_VIBRATION vibration = { 0, 0 };
return (XINPUTSETSTATE(haptic->hwdata->userid, &vibration) == ERROR_SUCCESS);
SDL_LockMutex(haptic->hwdata->mutex);
haptic->hwdata->stopTicks = 0;
SDL_UnlockMutex(haptic->hwdata->mutex);
return (XINPUTSETSTATE(haptic->hwdata->userid, &vibration) == ERROR_SUCCESS) ? 0 : -1;
}
ret = IDirectInputEffect_Stop(effect->hweffect->ref);
@@ -1515,7 +1525,10 @@ SDL_SYS_HapticStopAll(SDL_Haptic * haptic)
if (haptic->hwdata->bXInputHaptic) {
XINPUT_VIBRATION vibration = { 0, 0 };
return (XINPUTSETSTATE(haptic->hwdata->userid, &vibration) == ERROR_SUCCESS);
SDL_LockMutex(haptic->hwdata->mutex);
haptic->hwdata->stopTicks = 0;
SDL_UnlockMutex(haptic->hwdata->mutex);
return (XINPUTSETSTATE(haptic->hwdata->userid, &vibration) == ERROR_SUCCESS) ? 0 : -1;
}
/* Try to stop the effects. */
@@ -1529,4 +1542,40 @@ SDL_SYS_HapticStopAll(SDL_Haptic * haptic)
}
/* !!! FIXME: this is a hack, remove this later. */
/* Since XInput doesn't offer a way to vibrate for X time, we hook into
* SDL_PumpEvents() to check if it's time to stop vibrating with some
* frequency.
* In practice, this works for 99% of use cases. But in an ideal world,
* we do this in a separate thread so that:
* - we aren't bound to when the app chooses to pump the event queue.
* - we aren't adding more polling to the event queue
* - we can emulate all the haptic effects correctly (start on a delay,
* mix multiple effects, etc).
*
* Mostly, this is here to get rumbling to work, and all the other features
* are absent in the XInput path for now. :(
*/
static int SDLCALL
SDL_RunXInputHaptic(void *arg)
{
struct haptic_hwdata *hwdata = (struct haptic_hwdata *) arg;
while (!hwdata->stopThread) {
SDL_Delay(50);
SDL_LockMutex(hwdata->mutex);
/* If we're currently running and need to stop... */
if ((hwdata->stopTicks) && (hwdata->stopTicks < SDL_GetTicks())) {
XINPUT_VIBRATION vibration = { 0, 0 };
hwdata->stopTicks = 0;
XINPUTSETSTATE(hwdata->userid, &vibration);
}
SDL_UnlockMutex(hwdata->mutex);
}
return 0;
}
#endif /* SDL_HAPTIC_DINPUT */
/* vi: set ts=4 sw=4 expandtab: */

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,65 @@
/*
Simple DirectMedia Layer
Copyright (C) 1997-2013 Sam Lantinga <slouken@libsdl.org>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#include "SDL_config.h"
/* Default mappings we support
The easiest way to generate a new mapping is to start Steam in Big Picture
mode, configure your joystick and then look in config/config.vdf in your
Steam installation directory for the "SDL_GamepadBind" entry.
*/
static const char *s_ControllerMappings [] =
{
#ifdef SDL_JOYSTICK_DINPUT
"341a3608000000000000504944564944,Afterglow PS3 Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,",
"ffff0000000000000000504944564944,GameStop Gamepad,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b2,y:b3,",
"6d0416c2000000000000504944564944,Generic DirectInput Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,",
"6d0419c2000000000000504944564944,Logitech F710 Gamepad,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", /* Guide button doesn't seem to be sent in DInput mode. */
"88880803000000000000504944564944,PS3 Controller,a:b2,b:b1,back:b8,dpdown:h0.8,dpleft:h0.4,dpright:h0.2,dpup:h0.1,guide:b12,leftshoulder:b4,leftstick:b9,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:b7,rightx:a3,righty:a4,start:b11,x:b0,y:b3,",
"4c056802000000000000504944564944,PS3 Controller,a:b14,b:b13,back:b0,dpdown:b6,dpleft:b7,dpright:b5,dpup:b4,guide:b16,leftshoulder:b10,leftstick:b1,lefttrigger:b8,leftx:a0,lefty:a1,rightshoulder:b11,rightstick:b2,righttrigger:b9,rightx:a2,righty:a3,start:b3,x:b15,y:b12,",
"25090500000000000000504944564944,PS3 DualShock,a:b2,b:b1,back:b9,dpdown:h0.8,dpleft:h0.4,dpright:h0.2,dpup:h0.1,guide:,leftshoulder:b6,leftstick:b10,lefttrigger:b4,leftx:a0,lefty:a1,rightshoulder:b7,rightstick:b11,righttrigger:b5,rightx:a2,righty:a3,start:b8,x:b0,y:b3,",
"xinput,X360 Controller,a:b10,b:b11,back:b5,dpdown:b1,dpleft:b2,dpright:b3,dpup:b0,guide:b14,leftshoulder:b8,leftstick:b6,lefttrigger:a4,leftx:a0,lefty:a1,rightshoulder:b9,rightstick:b7,righttrigger:a5,rightx:a2,righty:a3,start:b4,x:b12,y:b13,",
#elif defined(__MACOSX__)
"0500000047532047616d657061640000,GameStop Gamepad,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b2,y:b3,",
"6d0400000000000016c2000000000000,Logitech F310 Gamepad (DInput),a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", /* Guide button doesn't seem to be sent in DInput mode. */
"6d0400000000000018c2000000000000,Logitech F510 Gamepad (DInput),a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,",
"6d040000000000001fc2000000000000,Logitech F710 Gamepad (XInput),a:b0,b:b1,back:b9,dpdown:b12,dpleft:b13,dpright:b14,dpup:b11,guide:b10,leftshoulder:b4,leftstick:b6,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b7,righttrigger:a5,rightx:a3,righty:a4,start:b8,x:b2,y:b3,",
"6d0400000000000019c2000000000000,Logitech Wireless Gamepad (DInput),a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", /* This includes F710 in DInput mode and the "Logitech Cordless RumblePad 2", at the very least. */
"4c050000000000006802000000000000,PS3 Controller,a:b14,b:b13,back:b0,dpdown:b6,dpleft:b7,dpright:b5,dpup:b4,guide:b16,leftshoulder:b10,leftstick:b1,lefttrigger:b8,leftx:a0,lefty:a1,rightshoulder:b11,rightstick:b2,righttrigger:b9,rightx:a2,righty:a3,start:b3,x:b15,y:b12,",
"5e040000000000008e02000000000000,X360 Controller,a:b0,b:b1,back:b9,dpdown:b12,dpleft:b13,dpright:b14,dpup:b11,guide:b10,leftshoulder:b4,leftstick:b6,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b7,righttrigger:a5,rightx:a3,righty:a4,start:b8,x:b2,y:b3,",
#elif defined(__LINUX__)
"0500000047532047616d657061640000,GameStop Gamepad,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b2,y:b3,",
"03000000ba2200002010000001010000,Jess Technology USB Game Controller,a:b2,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:,leftshoulder:b4,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,righttrigger:b7,rightx:a3,righty:a2,start:b9,x:b3,y:b0,",
"030000006d04000019c2000010010000,Logitech Cordless RumblePad 2,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,",
"030000006d0400001dc2000014400000,Logitech F310 Gamepad (XInput),a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,",
"030000006d0400001ec2000020200000,Logitech F510 Gamepad (XInput),a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,",
"030000006d04000019c2000011010000,Logitech F710 Gamepad (DInput),a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,", /* Guide button doesn't seem to be sent in DInput mode. */
"030000006d0400001fc2000005030000,Logitech F710 Gamepad (XInput),a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,",
"030000004c0500006802000011010000,PS3 Controller,a:b14,b:b13,back:b0,dpdown:b6,dpleft:b7,dpright:b5,dpup:b4,guide:b16,leftshoulder:b10,leftstick:b1,lefttrigger:b8,leftx:a0,lefty:a1,rightshoulder:b11,rightstick:b2,righttrigger:b9,rightx:a2,righty:a3,start:b3,x:b15,y:b12,",
"030000005e0400008e02000014010000,X360 Controller,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,",
"030000005e0400008e02000010010000,X360 Controller,a:b0,b:b1,back:b6,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,",
"030000005e0400001907000000010000,X360 Wireless Controller,a:b0,b:b1,back:b6,dpdown:b14,dpleft:b11,dpright:b12,dpup:b13,guide:b8,leftshoulder:b4,leftstick:b9,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b10,righttrigger:a5,rightx:a3,righty:a4,start:b7,x:b2,y:b3,",
#endif
NULL
};
/* vi: set ts=4 sw=4 expandtab: */

View File

@@ -22,25 +22,48 @@
/* This is the joystick API for Simple DirectMedia Layer */
#include "SDL.h"
#include "SDL_events.h"
#include "SDL_sysjoystick.h"
#include "SDL_assert.h"
#include "SDL_hints.h"
#if !SDL_EVENTS_DISABLED
#include "../events/SDL_events_c.h"
#endif
static SDL_bool SDL_joystick_allows_background_events = SDL_FALSE;
static SDL_Joystick *SDL_joysticks = NULL;
static SDL_Joystick *SDL_updating_joystick = NULL;
static void
SDL_JoystickAllowBackgroundEventsChanged(void *userdata, const char *name, const char *oldValue, const char *hint)
{
if (hint && *hint == '1') {
SDL_joystick_allows_background_events = SDL_TRUE;
} else {
SDL_joystick_allows_background_events = SDL_FALSE;
}
}
int
SDL_JoystickInit(void)
{
int status;
/* See if we should allow joystick events while in the background */
SDL_AddHintCallback(SDL_HINT_JOYSTICK_ALLOW_BACKGROUND_EVENTS,
SDL_JoystickAllowBackgroundEventsChanged, NULL);
#if !SDL_EVENTS_DISABLED
if (SDL_InitSubSystem(SDL_INIT_EVENTS) < 0) {
return -1;
}
#endif /* !SDL_EVENTS_DISABLED */
status = SDL_SYS_JoystickInit();
if (status >= 0) {
status = 0;
status = 0;
}
return (status);
}
@@ -78,26 +101,26 @@ SDL_Joystick *
SDL_JoystickOpen(int device_index)
{
SDL_Joystick *joystick;
SDL_Joystick *joysticklist;
const char *joystickname = NULL;
SDL_Joystick *joysticklist;
const char *joystickname = NULL;
if ((device_index < 0) || (device_index >= SDL_NumJoysticks())) {
SDL_SetError("There are %d joysticks available", SDL_NumJoysticks());
return (NULL);
}
joysticklist = SDL_joysticks;
/* If the joystick is already open, return it
* it is important that we have a single joystick * for each instance id
*/
while ( joysticklist )
{
if ( SDL_SYS_GetInstanceIdOfDeviceIndex(device_index) == joysticklist->instance_id ) {
joystick = joysticklist;
++joystick->ref_count;
return (joystick);
}
joysticklist = joysticklist->next;
joysticklist = SDL_joysticks;
/* If the joystick is already open, return it
* it is important that we have a single joystick * for each instance id
*/
while ( joysticklist )
{
if ( SDL_SYS_GetInstanceIdOfDeviceIndex(device_index) == joysticklist->instance_id ) {
joystick = joysticklist;
++joystick->ref_count;
return (joystick);
}
joysticklist = joysticklist->next;
}
/* Create and initialize the joystick */
@@ -113,11 +136,11 @@ SDL_JoystickOpen(int device_index)
return NULL;
}
joystickname = SDL_SYS_JoystickNameForDeviceIndex( device_index );
if ( joystickname )
joystick->name = SDL_strdup( joystickname );
else
joystick->name = NULL;
joystickname = SDL_SYS_JoystickNameForDeviceIndex( device_index );
if ( joystickname )
joystick->name = SDL_strdup( joystickname );
else
joystick->name = NULL;
if (joystick->naxes > 0) {
joystick->axes = (Sint16 *) SDL_malloc
@@ -159,11 +182,11 @@ SDL_JoystickOpen(int device_index)
/* Add joystick to list */
++joystick->ref_count;
/* Link the joystick in the list */
joystick->next = SDL_joysticks;
SDL_joysticks = joystick;
/* Link the joystick in the list */
joystick->next = SDL_joysticks;
SDL_joysticks = joystick;
SDL_SYS_JoystickUpdate( joystick );
SDL_SYS_JoystickUpdate( joystick );
return (joystick);
}
@@ -183,12 +206,12 @@ SDL_PrivateJoystickValid(SDL_Joystick * joystick)
} else {
valid = 1;
}
if ( joystick && joystick->closed )
{
valid = 0;
}
if ( joystick && joystick->closed )
{
valid = 0;
}
return valid;
}
@@ -330,29 +353,29 @@ SDL_JoystickGetButton(SDL_Joystick * joystick, int button)
/*
* Return if the joystick in question is currently attached to the system,
* \return 0 if not plugged in, 1 if still present.
* \return SDL_FALSE if not plugged in, SDL_TRUE if still present.
*/
SDL_bool
SDL_JoystickGetAttached(SDL_Joystick * joystick)
{
if (!SDL_PrivateJoystickValid(joystick)) {
if (!SDL_PrivateJoystickValid(joystick)) {
return SDL_FALSE;
}
return SDL_SYS_JoystickAttached(joystick);
return SDL_SYS_JoystickAttached(joystick);
}
/*
* Get the instance id for this opened joystick
*/
SDL_JoystickID
SDL_JoystickID
SDL_JoystickInstanceID(SDL_Joystick * joystick)
{
if (!SDL_PrivateJoystickValid(joystick)) {
if (!SDL_PrivateJoystickValid(joystick)) {
return (-1);
}
return (joystick->instance_id);
return (joystick->instance_id);
}
/*
@@ -364,7 +387,7 @@ SDL_JoystickName(SDL_Joystick * joystick)
if (!SDL_PrivateJoystickValid(joystick)) {
return (NULL);
}
return (joystick->name);
}
@@ -374,8 +397,8 @@ SDL_JoystickName(SDL_Joystick * joystick)
void
SDL_JoystickClose(SDL_Joystick * joystick)
{
SDL_Joystick *joysticklist;
SDL_Joystick *joysticklistprev;
SDL_Joystick *joysticklist;
SDL_Joystick *joysticklistprev;
if (!joystick) {
return;
@@ -391,31 +414,31 @@ SDL_JoystickClose(SDL_Joystick * joystick)
}
SDL_SYS_JoystickClose(joystick);
joysticklist = SDL_joysticks;
joysticklistprev = NULL;
while ( joysticklist )
{
if (joystick == joysticklist)
{
if ( joysticklistprev )
{
// unlink this entry
joysticklistprev->next = joysticklist->next;
}
else
{
SDL_joysticks = joystick->next;
}
break;
}
joysticklistprev = joysticklist;
joysticklist = joysticklist->next;
}
if (joystick->name)
SDL_free(joystick->name);
joysticklist = SDL_joysticks;
joysticklistprev = NULL;
while ( joysticklist )
{
if (joystick == joysticklist)
{
if ( joysticklistprev )
{
/* unlink this entry */
joysticklistprev->next = joysticklist->next;
}
else
{
SDL_joysticks = joystick->next;
}
break;
}
joysticklistprev = joysticklist;
joysticklist = joysticklist->next;
}
if (joystick->name)
SDL_free(joystick->name);
/* Free the data associated with this joystick */
if (joystick->axes) {
@@ -440,17 +463,42 @@ SDL_JoystickQuit(void)
SDL_assert(!SDL_updating_joystick);
/* Stop the event polling */
while ( SDL_joysticks )
{
SDL_joysticks->ref_count = 1;
while ( SDL_joysticks )
{
SDL_joysticks->ref_count = 1;
SDL_JoystickClose(SDL_joysticks);
}
}
/* Quit the joystick setup */
SDL_SYS_JoystickQuit();
#if !SDL_EVENTS_DISABLED
SDL_QuitSubSystem(SDL_INIT_EVENTS);
#endif
}
static SDL_bool
SDL_PrivateJoystickShouldIgnoreEvent()
{
if (SDL_joystick_allows_background_events)
{
return SDL_FALSE;
}
if (SDL_WasInit(SDL_INIT_VIDEO)) {
if (SDL_GetKeyboardFocus() == NULL) {
// Video is initialized and we don't have focus, ignore the event.
return SDL_TRUE;
} else {
return SDL_FALSE;
}
}
// Video subsystem wasn't initialized, always allow the event
return SDL_FALSE;
}
/* These are global for SDL_sysjoystick.c and SDL_events.c */
int
@@ -469,6 +517,15 @@ SDL_PrivateJoystickAxis(SDL_Joystick * joystick, Uint8 axis, Sint16 value)
}
joystick->axes[axis] = value;
/* We ignore events if we don't have keyboard focus, except for centering
* events.
*/
if (SDL_PrivateJoystickShouldIgnoreEvent()) {
if (!(joystick->closed && joystick->uncentered)) {
return 0;
}
}
/* Post the event, if desired */
posted = 0;
#if !SDL_EVENTS_DISABLED
@@ -497,6 +554,16 @@ SDL_PrivateJoystickHat(SDL_Joystick * joystick, Uint8 hat, Uint8 value)
/* Update internal joystick state */
joystick->hats[hat] = value;
/* We ignore events if we don't have keyboard focus, except for centering
* events.
*/
if (SDL_PrivateJoystickShouldIgnoreEvent()) {
if (!(joystick->closed && joystick->uncentered)) {
return 0;
}
}
/* Post the event, if desired */
posted = 0;
#if !SDL_EVENTS_DISABLED
@@ -523,6 +590,11 @@ SDL_PrivateJoystickBall(SDL_Joystick * joystick, Uint8 ball,
return 0;
}
/* We ignore events if we don't have keyboard focus. */
if (SDL_PrivateJoystickShouldIgnoreEvent()) {
return 0;
}
/* Update internal mouse state */
joystick->balls[ball].dx += xrel;
joystick->balls[ball].dy += yrel;
@@ -568,6 +640,12 @@ SDL_PrivateJoystickButton(SDL_Joystick * joystick, Uint8 button, Uint8 state)
return 0;
}
/* We ignore events if we don't have keyboard focus, except for button
* release. */
if (state == SDL_PRESSED && SDL_PrivateJoystickShouldIgnoreEvent()) {
return 0;
}
/* Update internal joystick state */
joystick->buttons[button] = state;
@@ -587,25 +665,24 @@ SDL_PrivateJoystickButton(SDL_Joystick * joystick, Uint8 button, Uint8 state)
void
SDL_JoystickUpdate(void)
{
SDL_Joystick *joystick;
joystick = SDL_joysticks;
while ( joystick )
{
SDL_Joystick *joysticknext;
/* save off the next pointer, the Update call may cause a joystick removed event
* and cause our joystick pointer to be freed
*/
joysticknext = joystick->next;
SDL_Joystick *joystick;
joystick = SDL_joysticks;
while ( joystick )
{
SDL_Joystick *joysticknext;
/* save off the next pointer, the Update call may cause a joystick removed event
* and cause our joystick pointer to be freed
*/
joysticknext = joystick->next;
SDL_updating_joystick = joystick;
SDL_SYS_JoystickUpdate( joystick );
if ( joystick->closed && joystick->uncentered )
{
int i;
joystick->uncentered = 0;
if ( joystick->closed && joystick->uncentered )
{
int i;
/* Tell the app that everything is centered/unpressed... */
for (i = 0; i < joystick->naxes; i++)
@@ -617,7 +694,8 @@ SDL_JoystickUpdate(void)
for (i = 0; i < joystick->nhats; i++)
SDL_PrivateJoystickHat(joystick, i, SDL_HAT_CENTERED);
}
joystick->uncentered = 0;
}
SDL_updating_joystick = NULL;
@@ -626,10 +704,13 @@ SDL_JoystickUpdate(void)
SDL_JoystickClose(joystick);
}
joystick = joysticknext;
}
joystick = joysticknext;
}
SDL_SYS_JoystickDetect();
/* this needs to happen AFTER walking the joystick list above, so that any
dangling hardware data from removed devices can be free'd
*/
SDL_SYS_JoystickDetect();
}
int
@@ -665,106 +746,112 @@ SDL_JoystickEventState(int state)
}
/* return 1 if you want to run the joystick update loop this frame, used by hotplug support */
SDL_bool
SDL_bool
SDL_PrivateJoystickNeedsPolling()
{
if (SDL_joysticks != NULL) {
return SDL_TRUE;
} else {
return SDL_SYS_JoystickNeedsPolling();
}
if (SDL_joysticks != NULL) {
return SDL_TRUE;
} else {
return SDL_SYS_JoystickNeedsPolling();
}
}
/* return the guid for this index */
SDL_JoystickGUID SDL_JoystickGetDeviceGUID(int device_index)
{
return SDL_SYS_JoystickGetDeviceGUID( device_index );
if ((device_index < 0) || (device_index >= SDL_NumJoysticks())) {
SDL_JoystickGUID emptyGUID;
SDL_SetError("There are %d joysticks available", SDL_NumJoysticks());
SDL_zero( emptyGUID );
return emptyGUID;
}
return SDL_SYS_JoystickGetDeviceGUID( device_index );
}
/* return the guid for this opened device */
SDL_JoystickGUID SDL_JoystickGetGUID(SDL_Joystick * joystick)
{
return SDL_SYS_JoystickGetGUID( joystick );
return SDL_SYS_JoystickGetGUID( joystick );
}
/* convert the guid to a printable string */
void SDL_JoystickGetGUIDString( SDL_JoystickGUID guid, char *pszGUID, int cbGUID )
{
static const char k_rgchHexToASCII[] = "0123456789abcdef";
int i;
static const char k_rgchHexToASCII[] = "0123456789abcdef";
int i;
if ((pszGUID == NULL) || (cbGUID <= 0)) {
return;
}
for ( i = 0; i < sizeof(guid.data) && i < (cbGUID-1); i++ )
{
// each input byte writes 2 ascii chars, and might write a null byte.
// If we don't have room for next input byte, stop
unsigned char c = guid.data[i];
for ( i = 0; i < sizeof(guid.data) && i < (cbGUID-1); i++ )
{
/* each input byte writes 2 ascii chars, and might write a null byte. */
/* If we don't have room for next input byte, stop */
unsigned char c = guid.data[i];
*pszGUID++ = k_rgchHexToASCII[ c >> 4 ];
*pszGUID++ = k_rgchHexToASCII[ c & 0x0F ];
}
*pszGUID = '\0';
*pszGUID++ = k_rgchHexToASCII[ c >> 4 ];
*pszGUID++ = k_rgchHexToASCII[ c & 0x0F ];
}
*pszGUID = '\0';
}
//-----------------------------------------------------------------------------
// Purpose: Returns the 4 bit nibble for a hex character
// Input : c -
// Output : unsigned char
//-----------------------------------------------------------------------------
/*-----------------------------------------------------------------------------
* Purpose: Returns the 4 bit nibble for a hex character
* Input : c -
* Output : unsigned char
*-----------------------------------------------------------------------------*/
static unsigned char nibble( char c )
{
if ( ( c >= '0' ) &&
( c <= '9' ) )
{
return (unsigned char)(c - '0');
}
if ( ( c >= '0' ) &&
( c <= '9' ) )
{
return (unsigned char)(c - '0');
}
if ( ( c >= 'A' ) &&
( c <= 'F' ) )
{
return (unsigned char)(c - 'A' + 0x0a);
}
if ( ( c >= 'A' ) &&
( c <= 'F' ) )
{
return (unsigned char)(c - 'A' + 0x0a);
}
if ( ( c >= 'a' ) &&
( c <= 'f' ) )
{
return (unsigned char)(c - 'a' + 0x0a);
}
if ( ( c >= 'a' ) &&
( c <= 'f' ) )
{
return (unsigned char)(c - 'a' + 0x0a);
}
// received an invalid character, and no real way to return an error
// AssertMsg1( false, "Q_nibble invalid hex character '%c' ", c );
return 0;
/* received an invalid character, and no real way to return an error */
/* AssertMsg1( false, "Q_nibble invalid hex character '%c' ", c ); */
return 0;
}
/* convert the string version of a joystick guid to the struct */
SDL_JoystickGUID SDL_JoystickGetGUIDFromString(const char *pchGUID)
{
SDL_JoystickGUID guid;
int maxoutputbytes= sizeof(guid);
int len = SDL_strlen( pchGUID );
Uint8 *p;
int i;
SDL_JoystickGUID guid;
int maxoutputbytes= sizeof(guid);
int len = SDL_strlen( pchGUID );
Uint8 *p;
int i;
// Make sure it's even
len = ( len ) & ~0x1;
/* Make sure it's even */
len = ( len ) & ~0x1;
SDL_memset( &guid, 0x00, sizeof(guid) );
SDL_memset( &guid, 0x00, sizeof(guid) );
p = (Uint8 *)&guid;
for ( i = 0;
( i < len ) && ( ( p - (Uint8 *)&guid ) < maxoutputbytes );
i+=2, p++ )
{
*p = ( nibble( pchGUID[i] ) << 4 ) | nibble( pchGUID[i+1] );
}
p = (Uint8 *)&guid;
for ( i = 0;
( i < len ) && ( ( p - (Uint8 *)&guid ) < maxoutputbytes );
i+=2, p++ )
{
*p = ( nibble( pchGUID[i] ) << 4 ) | nibble( pchGUID[i+1] );
}
return guid;
return guid;
}

View File

@@ -41,7 +41,7 @@ extern int SDL_PrivateJoystickHat(SDL_Joystick * joystick,
Uint8 hat, Uint8 value);
extern int SDL_PrivateJoystickButton(SDL_Joystick * joystick,
Uint8 button, Uint8 state);
/* Helper function to let lower sys layer tell the event system if the joystick code needs to think */
extern SDL_bool SDL_PrivateJoystickNeedsPolling();

View File

@@ -87,10 +87,10 @@ SDL_SYS_JoystickOpen(SDL_Joystick * joystick, int device_index)
joystick->nballs = 0;
joystick->naxes = 3;
return 0;
} else {
SDL_SetError("No joystick available with that index");
return (-1);
}
} else {
SDL_SetError("No joystick available with that index");
return (-1);
}
}
/* Function to determine is this joystick is attached to the system right now */
@@ -134,7 +134,7 @@ SDL_SYS_JoystickQuit(void)
SDL_JoystickGUID SDL_SYS_JoystickGetDeviceGUID( int device_index )
{
SDL_JoystickGUID guid;
// the GUID is just the first 16 chars of the name for now
/* the GUID is just the first 16 chars of the name for now */
const char *name = SDL_SYS_JoystickNameForDeviceIndex( device_index );
SDL_zero( guid );
SDL_memcpy( &guid, name, SDL_min( sizeof(guid), SDL_strlen( name ) ) );
@@ -144,7 +144,7 @@ SDL_JoystickGUID SDL_SYS_JoystickGetDeviceGUID( int device_index )
SDL_JoystickGUID SDL_SYS_JoystickGetGUID(SDL_Joystick * joystick)
{
SDL_JoystickGUID guid;
// the GUID is just the first 16 chars of the name for now
/* the GUID is just the first 16 chars of the name for now */
const char *name = joystick->name;
SDL_zero( guid );
SDL_memcpy( &guid, name, SDL_min( sizeof(guid), SDL_strlen( name ) ) );

View File

@@ -261,7 +261,7 @@ extern "C"
SDL_JoystickGUID SDL_SYS_JoystickGetDeviceGUID( int device_index )
{
SDL_JoystickGUID guid;
// the GUID is just the first 16 chars of the name for now
/* the GUID is just the first 16 chars of the name for now */
const char *name = SDL_SYS_JoystickNameForDeviceIndex( device_index );
SDL_zero( guid );
SDL_memcpy( &guid, name, SDL_min( sizeof(guid), SDL_strlen( name ) ) );
@@ -271,7 +271,7 @@ extern "C"
SDL_JoystickGUID SDL_SYS_JoystickGetGUID(SDL_Joystick * joystick)
{
SDL_JoystickGUID guid;
// the GUID is just the first 16 chars of the name for now
/* the GUID is just the first 16 chars of the name for now */
const char *name = joystick->name;
SDL_zero( guid );
SDL_memcpy( &guid, name, SDL_min( sizeof(guid), SDL_strlen( name ) ) );

View File

@@ -76,9 +76,9 @@
#include "../SDL_sysjoystick.h"
#include "../SDL_joystick_c.h"
#define MAX_UHID_JOYS 16
#define MAX_JOY_JOYS 2
#define MAX_JOYS (MAX_UHID_JOYS + MAX_JOY_JOYS)
#define MAX_UHID_JOYS 16
#define MAX_JOY_JOYS 2
#define MAX_JOYS (MAX_UHID_JOYS + MAX_JOY_JOYS)
struct report
@@ -589,7 +589,7 @@ SDL_SYS_JoystickQuit(void)
SDL_JoystickGUID SDL_SYS_JoystickGetDeviceGUID( int device_index )
{
SDL_JoystickGUID guid;
// the GUID is just the first 16 chars of the name for now
/* the GUID is just the first 16 chars of the name for now */
const char *name = SDL_SYS_JoystickNameForDeviceIndex( device_index );
SDL_zero( guid );
SDL_memcpy( &guid, name, SDL_min( sizeof(guid), SDL_strlen( name ) ) );
@@ -599,7 +599,7 @@ SDL_JoystickGUID SDL_SYS_JoystickGetDeviceGUID( int device_index )
SDL_JoystickGUID SDL_SYS_JoystickGetGUID(SDL_Joystick * joystick)
{
SDL_JoystickGUID guid;
// the GUID is just the first 16 chars of the name for now
/* the GUID is just the first 16 chars of the name for now */
const char *name = joystick->name;
SDL_zero( guid );
SDL_memcpy( &guid, name, SDL_min( sizeof(guid), SDL_strlen( name ) ) );

View File

@@ -64,6 +64,7 @@ static recDevice *gpDeviceList = NULL;
IONotificationPortRef notificationPort = 0;
/* if 1 then a device was added since the last update call */
static SDL_bool s_bDeviceAdded = SDL_FALSE;
static SDL_bool s_bDeviceRemoved = SDL_FALSE;
/* static incrementing counter for new joystick devices seen on the system. Devices should start with index 0 */
static int s_joystick_instance_id = -1;
@@ -126,6 +127,7 @@ HIDRemovalCallback(void *target, IOReturn result, void *refcon, void *sender)
{
recDevice *device = (recDevice *) refcon;
device->removed = 1;
s_bDeviceRemoved = SDL_TRUE;
}
@@ -135,14 +137,15 @@ void JoystickDeviceWasRemovedCallback( void * refcon, io_service_t service, natu
{
if( messageType == kIOMessageServiceIsTerminated && refcon )
{
recDevice *device = (recDevice *) refcon;
device->removed = 1;
}
recDevice *device = (recDevice *) refcon;
device->removed = 1;
s_bDeviceRemoved = SDL_TRUE;
}
}
/* Create and open an interface to device, required prior to extracting values or building queues.
* Note: appliction now owns the device and must close and release it prior to exiting
* Note: application now owns the device and must close and release it prior to exiting
*/
static IOReturn
@@ -183,39 +186,39 @@ HIDCreateOpenDeviceInterface(io_object_t hidDevice, recDevice * pDevice)
HIDReportErrorNum
("Failed to open pDevice->interface via open.", result);
else
{
pDevice->portIterator = 0;
{
pDevice->portIterator = 0;
// It's okay if this fails, we have another detection method below
/* It's okay if this fails, we have another detection method below */
(*(pDevice->interface))->setRemovalCallback(pDevice->interface,
HIDRemovalCallback,
pDevice, pDevice);
/* now connect notification for new devices */
pDevice->notificationPort = IONotificationPortCreate(kIOMasterPortDefault);
CFRunLoopAddSource(CFRunLoopGetCurrent(),
IONotificationPortGetRunLoopSource(pDevice->notificationPort),
kCFRunLoopDefaultMode);
// Register for notifications when a serial port is added to the system
result = IOServiceAddInterestNotification(pDevice->notificationPort,
hidDevice,
kIOGeneralInterest,
JoystickDeviceWasRemovedCallback,
pDevice,
&pDevice->portIterator);
if (kIOReturnSuccess != result) {
HIDReportErrorNum
("Failed to register for removal callback.", result);
}
}
/* now connect notification for new devices */
pDevice->notificationPort = IONotificationPortCreate(kIOMasterPortDefault);
CFRunLoopAddSource(CFRunLoopGetCurrent(),
IONotificationPortGetRunLoopSource(pDevice->notificationPort),
kCFRunLoopDefaultMode);
/* Register for notifications when a serial port is added to the system */
result = IOServiceAddInterestNotification(pDevice->notificationPort,
hidDevice,
kIOGeneralInterest,
JoystickDeviceWasRemovedCallback,
pDevice,
&pDevice->portIterator);
if (kIOReturnSuccess != result) {
HIDReportErrorNum
("Failed to register for removal callback.", result);
}
}
}
return result;
}
/* Closes and releases interface to device, should be done prior to exting application
/* Closes and releases interface to device, should be done prior to exiting application
* Note: will have no affect if device or interface do not exist
* application will "own" the device if interface is not closed
* (device may have to be plug and re-plugged in different location to get it working again without a restart)
@@ -240,12 +243,12 @@ HIDCloseReleaseInterface(recDevice * pDevice)
HIDReportErrorNum("Failed to release IOHIDDeviceInterface.",
result);
pDevice->interface = NULL;
if ( pDevice->portIterator )
{
IOObjectRelease( pDevice->portIterator );
pDevice->portIterator = 0;
}
if ( pDevice->portIterator )
{
IOObjectRelease( pDevice->portIterator );
pDevice->portIterator = 0;
}
}
return result;
}
@@ -269,36 +272,36 @@ HIDGetElementInfo(CFTypeRef refElement, recElement * pElement)
if (refType && CFNumberGetValue(refType, kCFNumberLongType, &number))
pElement->maxReport = pElement->max = number;
/*
TODO: maybe should handle the following stuff somehow?
TODO: maybe should handle the following stuff somehow?
refType = CFDictionaryGetValue (refElement, CFSTR(kIOHIDElementScaledMinKey));
if (refType && CFNumberGetValue (refType, kCFNumberLongType, &number))
pElement->scaledMin = number;
refType = CFDictionaryGetValue (refElement, CFSTR(kIOHIDElementScaledMaxKey));
if (refType && CFNumberGetValue (refType, kCFNumberLongType, &number))
pElement->scaledMax = number;
refType = CFDictionaryGetValue (refElement, CFSTR(kIOHIDElementSizeKey));
if (refType && CFNumberGetValue (refType, kCFNumberLongType, &number))
pElement->size = number;
refType = CFDictionaryGetValue (refElement, CFSTR(kIOHIDElementIsRelativeKey));
if (refType)
pElement->relative = CFBooleanGetValue (refType);
refType = CFDictionaryGetValue (refElement, CFSTR(kIOHIDElementIsWrappingKey));
if (refType)
pElement->wrapping = CFBooleanGetValue (refType);
refType = CFDictionaryGetValue (refElement, CFSTR(kIOHIDElementIsNonLinearKey));
if (refType)
pElement->nonLinear = CFBooleanGetValue (refType);
refType = CFDictionaryGetValue (refElement, CFSTR(kIOHIDElementHasPreferedStateKey));
if (refType)
pElement->preferredState = CFBooleanGetValue (refType);
refType = CFDictionaryGetValue (refElement, CFSTR(kIOHIDElementHasNullStateKey));
if (refType)
pElement->nullState = CFBooleanGetValue (refType);
refType = CFDictionaryGetValue (refElement, CFSTR(kIOHIDElementScaledMinKey));
if (refType && CFNumberGetValue (refType, kCFNumberLongType, &number))
pElement->scaledMin = number;
refType = CFDictionaryGetValue (refElement, CFSTR(kIOHIDElementScaledMaxKey));
if (refType && CFNumberGetValue (refType, kCFNumberLongType, &number))
pElement->scaledMax = number;
refType = CFDictionaryGetValue (refElement, CFSTR(kIOHIDElementSizeKey));
if (refType && CFNumberGetValue (refType, kCFNumberLongType, &number))
pElement->size = number;
refType = CFDictionaryGetValue (refElement, CFSTR(kIOHIDElementIsRelativeKey));
if (refType)
pElement->relative = CFBooleanGetValue (refType);
refType = CFDictionaryGetValue (refElement, CFSTR(kIOHIDElementIsWrappingKey));
if (refType)
pElement->wrapping = CFBooleanGetValue (refType);
refType = CFDictionaryGetValue (refElement, CFSTR(kIOHIDElementIsNonLinearKey));
if (refType)
pElement->nonLinear = CFBooleanGetValue (refType);
refType = CFDictionaryGetValue (refElement, CFSTR(kIOHIDElementHasPreferedStateKey));
if (refType)
pElement->preferredState = CFBooleanGetValue (refType);
refType = CFDictionaryGetValue (refElement, CFSTR(kIOHIDElementHasNullStateKey));
if (refType)
pElement->nullState = CFBooleanGetValue (refType);
*/
}
/* examines CF dictionary vlaue in device element hierarchy to determine if it is element of interest or a collection of more elements
/* examines CF dictionary value in device element hierarchy to determine if it is element of interest or a collection of more elements
* if element of interest allocate storage, add to list and retrieve element specific info
* if collection then pass on to deconstruction collection into additional individual elements
*/
@@ -359,6 +362,22 @@ HIDAddElement(CFTypeRef refElement, recDevice * pDevice)
}
}
break;
case kHIDPage_Simulation:
switch (usage) {
case kHIDUsage_Sim_Rudder:
case kHIDUsage_Sim_Throttle:
element = (recElement *)
NewPtrClear(sizeof(recElement));
if (element) {
pDevice->axes++;
headElement = &(pDevice->firstAxis);
}
break;
default:
break;
}
break;
case kHIDPage_Button:
element = (recElement *)
NewPtrClear(sizeof(recElement));
@@ -396,7 +415,7 @@ HIDAddElement(CFTypeRef refElement, recDevice * pDevice)
}
}
/* collects information from each array member in device element list (each array memeber = element) */
/* collects information from each array member in device element list (each array member = element) */
static void
HIDGetElementsCFArrayHandler(const void *value, void *parameter)
@@ -461,7 +480,7 @@ HIDGetDeviceInfo(io_object_t hidDevice, CFMutableDictionaryRef hidProperties,
io_registry_entry_t parent1, parent2;
/* Mac OS X currently is not mirroring all USB properties to HID page so need to look at USB device page also
* get dictionary for usb properties: step up two levels and get CF dictionary for USB properties
* get dictionary for USB properties: step up two levels and get CF dictionary for USB properties
*/
if ((KERN_SUCCESS == IORegistryEntryGetParentEntry(hidDevice, kIOServicePlane, &parent1))
&& (KERN_SUCCESS == IORegistryEntryGetParentEntry(parent1, kIOServicePlane, &parent2))
@@ -498,14 +517,14 @@ HIDGetDeviceInfo(io_object_t hidDevice, CFMutableDictionaryRef hidProperties,
}
}
refCF = CFDictionaryGetValue(hidProperties, CFSTR(kIOHIDVendorIDKey));
refCF = CFDictionaryGetValue(hidProperties, CFSTR(kIOHIDVendorIDKey));
if (refCF) {
if (!CFNumberGetValue(refCF, kCFNumberLongType, &pDevice->guid.data[0])) {
SDL_SetError("CFNumberGetValue error retrieving pDevice->guid[0]");
}
}
refCF = CFDictionaryGetValue(hidProperties, CFSTR(kIOHIDProductIDKey));
refCF = CFDictionaryGetValue(hidProperties, CFSTR(kIOHIDProductIDKey));
if (refCF) {
if (!CFNumberGetValue(refCF, kCFNumberLongType, &pDevice->guid.data[8])) {
SDL_SetError("CFNumberGetValue error retrieving pDevice->guid[8]");
@@ -570,7 +589,7 @@ HIDBuildDevice(io_object_t hidDevice)
if (kIOReturnSuccess == result) {
HIDGetDeviceInfo(hidDevice, hidProperties, pDevice); /* hidDevice used to find parents in registry tree */
HIDGetCollectionElements(hidProperties, pDevice);
pDevice->instance_id = ++s_joystick_instance_id;
pDevice->instance_id = ++s_joystick_instance_id;
} else {
DisposePtr((Ptr) pDevice);
pDevice = NULL;
@@ -637,57 +656,57 @@ HIDDisposeDevice(recDevice ** ppDevice)
/* Given an io_object_t from OSX adds a joystick device to our list if appropriate
*/
int
int
AddDeviceHelper( io_object_t ioHIDDeviceObject )
{
recDevice *device;
/* build a device record */
device = HIDBuildDevice(ioHIDDeviceObject);
if (!device)
return 0;
/* Filter device list to non-keyboard/mouse stuff */
if ((device->usagePage != kHIDPage_GenericDesktop) ||
((device->usage != kHIDUsage_GD_Joystick &&
device->usage != kHIDUsage_GD_GamePad &&
device->usage != kHIDUsage_GD_MultiAxisController))) {
/* release memory for the device */
HIDDisposeDevice(&device);
DisposePtr((Ptr) device);
return 0;
}
/* We have to do some storage of the io_service_t for
* SDL_HapticOpenFromJoystick */
if (FFIsForceFeedback(ioHIDDeviceObject) == FF_OK) {
device->ffservice = ioHIDDeviceObject;
} else {
device->ffservice = 0;
}
device->send_open_event = 1;
s_bDeviceAdded = SDL_TRUE;
/* Add device to the end of the list */
if ( !gpDeviceList )
{
gpDeviceList = device;
}
else
{
recDevice *curdevice;
curdevice = gpDeviceList;
while ( curdevice->pNext )
{
curdevice = curdevice->pNext;
}
curdevice->pNext = device;
}
return 1;
/* build a device record */
device = HIDBuildDevice(ioHIDDeviceObject);
if (!device)
return 0;
/* Filter device list to non-keyboard/mouse stuff */
if ((device->usagePage != kHIDPage_GenericDesktop) ||
((device->usage != kHIDUsage_GD_Joystick &&
device->usage != kHIDUsage_GD_GamePad &&
device->usage != kHIDUsage_GD_MultiAxisController))) {
/* release memory for the device */
HIDDisposeDevice(&device);
DisposePtr((Ptr) device);
return 0;
}
/* We have to do some storage of the io_service_t for
* SDL_HapticOpenFromJoystick */
if (FFIsForceFeedback(ioHIDDeviceObject) == FF_OK) {
device->ffservice = ioHIDDeviceObject;
} else {
device->ffservice = 0;
}
device->send_open_event = 1;
s_bDeviceAdded = SDL_TRUE;
/* Add device to the end of the list */
if ( !gpDeviceList )
{
gpDeviceList = device;
}
else
{
recDevice *curdevice;
curdevice = gpDeviceList;
while ( curdevice->pNext )
{
curdevice = curdevice->pNext;
}
curdevice->pNext = device;
}
return 1;
}
@@ -697,16 +716,16 @@ AddDeviceHelper( io_object_t ioHIDDeviceObject )
void JoystickDeviceWasAddedCallback( void *refcon, io_iterator_t iterator )
{
io_object_t ioHIDDeviceObject = 0;
while ( ( ioHIDDeviceObject = IOIteratorNext(iterator) ) )
{
if ( ioHIDDeviceObject )
{
AddDeviceHelper( ioHIDDeviceObject );
}
}
while ( ( ioHIDDeviceObject = IOIteratorNext(iterator) ) )
{
if ( ioHIDDeviceObject )
{
AddDeviceHelper( ioHIDDeviceObject );
}
}
}
/* Function to scan the system for joysticks.
* Joystick 0 should be the system default joystick.
@@ -721,7 +740,7 @@ SDL_SYS_JoystickInit(void)
io_iterator_t hidObjectIterator = 0;
CFMutableDictionaryRef hidMatchDictionary = NULL;
io_object_t ioHIDDeviceObject = 0;
io_iterator_t portIterator = 0;
io_iterator_t portIterator = 0;
if (gpDeviceList) {
return SDL_SetError("Joystick: Device list already inited.");
@@ -771,26 +790,26 @@ SDL_SYS_JoystickInit(void)
gpDeviceList = NULL;
while ((ioHIDDeviceObject = IOIteratorNext(hidObjectIterator))) {
AddDeviceHelper( ioHIDDeviceObject );
AddDeviceHelper( ioHIDDeviceObject );
}
result = IOObjectRelease(hidObjectIterator); /* release the iterator */
/* now connect notification for new devices */
notificationPort = IONotificationPortCreate(masterPort);
hidMatchDictionary = IOServiceMatching(kIOHIDDeviceKey);
CFRunLoopAddSource(CFRunLoopGetCurrent(),
IONotificationPortGetRunLoopSource(notificationPort),
kCFRunLoopDefaultMode);
// Register for notifications when a serial port is added to the system
result = IOServiceAddMatchingNotification(notificationPort,
kIOFirstMatchNotification,
hidMatchDictionary,
JoystickDeviceWasAddedCallback,
NULL,
&portIterator);
while (IOIteratorNext(portIterator)) {}; // Run out the iterator or notifications won't start (you can also use it to iterate the available devices).
/* now connect notification for new devices */
notificationPort = IONotificationPortCreate(masterPort);
hidMatchDictionary = IOServiceMatching(kIOHIDDeviceKey);
CFRunLoopAddSource(CFRunLoopGetCurrent(),
IONotificationPortGetRunLoopSource(notificationPort),
kCFRunLoopDefaultMode);
/* Register for notifications when a serial port is added to the system */
result = IOServiceAddMatchingNotification(notificationPort,
kIOFirstMatchNotification,
hidMatchDictionary,
JoystickDeviceWasAddedCallback,
NULL,
&portIterator);
while (IOIteratorNext(portIterator)) {}; /* Run out the iterator or notifications won't start (you can also use it to iterate the available devices). */
return SDL_SYS_NumJoysticks();
}
@@ -799,16 +818,17 @@ SDL_SYS_JoystickInit(void)
int
SDL_SYS_NumJoysticks()
{
recDevice *device = gpDeviceList;
recDevice *device = gpDeviceList;
int nJoySticks = 0;
while ( device )
{
nJoySticks++;
device = device->pNext;
}
return nJoySticks;
while ( device )
{
if ( !device->removed )
nJoySticks++;
device = device->pNext;
}
return nJoySticks;
}
/* Function to cause any queued joystick insertions to be processed
@@ -816,40 +836,81 @@ SDL_SYS_NumJoysticks()
void
SDL_SYS_JoystickDetect()
{
if ( s_bDeviceAdded )
{
recDevice *device = gpDeviceList;
s_bDeviceAdded = SDL_FALSE;
int device_index = 0;
// send notifications
while ( device )
{
if ( device->send_open_event )
{
device->send_open_event = 0;
if ( s_bDeviceAdded || s_bDeviceRemoved )
{
recDevice *device = gpDeviceList;
s_bDeviceAdded = SDL_FALSE;
s_bDeviceRemoved = SDL_FALSE;
int device_index = 0;
/* send notifications */
while ( device )
{
if ( device->send_open_event )
{
device->send_open_event = 0;
#if !SDL_EVENTS_DISABLED
SDL_Event event;
event.type = SDL_JOYDEVICEADDED;
if (SDL_GetEventState(event.type) == SDL_ENABLE) {
event.jdevice.which = device_index;
if ((SDL_EventOK == NULL)
|| (*SDL_EventOK) (SDL_EventOKParam, &event)) {
SDL_PushEvent(&event);
}
}
SDL_Event event;
event.type = SDL_JOYDEVICEADDED;
if (SDL_GetEventState(event.type) == SDL_ENABLE) {
event.jdevice.which = device_index;
if ((SDL_EventOK == NULL)
|| (*SDL_EventOK) (SDL_EventOKParam, &event)) {
SDL_PushEvent(&event);
}
}
#endif /* !SDL_EVENTS_DISABLED */
}
device_index++;
device = device->pNext;
}
}
}
if ( device->removed )
{
recDevice *removeDevice = device;
if ( gpDeviceList == removeDevice )
{
device = device->pNext;
gpDeviceList = device;
}
else
{
device = gpDeviceList;
while ( device->pNext != removeDevice )
{
device = device->pNext;
}
device->pNext = removeDevice->pNext;
}
#if !SDL_EVENTS_DISABLED
SDL_Event event;
event.type = SDL_JOYDEVICEREMOVED;
if (SDL_GetEventState(event.type) == SDL_ENABLE) {
event.jdevice.which = removeDevice->instance_id;
if ((SDL_EventOK == NULL)
|| (*SDL_EventOK) (SDL_EventOKParam, &event)) {
SDL_PushEvent(&event);
}
}
DisposePtr((Ptr) removeDevice);
#endif /* !SDL_EVENTS_DISABLED */
}
else
{
device = device->pNext;
device_index++;
}
}
}
}
SDL_bool
SDL_SYS_JoystickNeedsPolling()
{
return s_bDeviceAdded;
return s_bDeviceAdded || s_bDeviceRemoved;
}
/* Function to get the device-dependent name of a joystick */
@@ -861,7 +922,7 @@ SDL_SYS_JoystickNameForDeviceIndex(int device_index)
for (; device_index > 0; device_index--)
device = device->pNext;
return device->product;
return device->product;
}
/* Function to return the instance id of the joystick at device_index
@@ -871,11 +932,11 @@ SDL_SYS_GetInstanceIdOfDeviceIndex(int device_index)
{
recDevice *device = gpDeviceList;
int index;
for (index = device_index; index > 0; index--)
device = device->pNext;
return device->instance_id;
return device->instance_id;
}
/* Function to open a joystick for use.
@@ -892,14 +953,14 @@ SDL_SYS_JoystickOpen(SDL_Joystick * joystick, int device_index)
for (index = device_index; index > 0; index--)
device = device->pNext;
joystick->instance_id = device->instance_id;
joystick->instance_id = device->instance_id;
joystick->hwdata = device;
joystick->name = device->product;
joystick->name = device->product;
joystick->naxes = device->axes;
joystick->nhats = device->hats;
joystick->nballs = 0;
joystick->nbuttons = device->buttons;
joystick->naxes = device->axes;
joystick->nhats = device->hats;
joystick->nballs = 0;
joystick->nbuttons = device->buttons;
return 0;
}
@@ -909,17 +970,17 @@ SDL_SYS_JoystickOpen(SDL_Joystick * joystick, int device_index)
SDL_bool
SDL_SYS_JoystickAttached(SDL_Joystick * joystick)
{
recDevice *device = gpDeviceList;
while ( device )
{
if ( joystick->instance_id == device->instance_id )
return SDL_TRUE;
recDevice *device = gpDeviceList;
while ( device )
{
if ( joystick->instance_id == device->instance_id )
return SDL_TRUE;
device = device->pNext;
}
return SDL_FALSE;
}
return SDL_FALSE;
}
/* Function to update the state of a joystick - called as a device poll.
@@ -930,49 +991,49 @@ SDL_SYS_JoystickAttached(SDL_Joystick * joystick)
void
SDL_SYS_JoystickUpdate(SDL_Joystick * joystick)
{
recDevice *device = joystick->hwdata;
recDevice *device = joystick->hwdata;
recElement *element;
SInt32 value, range;
int i;
if ( !device )
return;
if ( !device )
return;
if (device->removed) { /* device was unplugged; ignore it. */
recDevice *devicelist = gpDeviceList;
joystick->closed = 1;
joystick->uncentered = 1;
if ( devicelist == device )
{
gpDeviceList = device->pNext;
}
else
{
while ( devicelist->pNext != device )
{
devicelist = devicelist->pNext;
}
devicelist->pNext = device->pNext;
}
DisposePtr((Ptr) device);
joystick->hwdata = NULL;
recDevice *devicelist = gpDeviceList;
joystick->closed = 1;
joystick->uncentered = 1;
if ( devicelist == device )
{
gpDeviceList = device->pNext;
}
else
{
while ( devicelist->pNext != device )
{
devicelist = devicelist->pNext;
}
devicelist->pNext = device->pNext;
}
DisposePtr((Ptr) device);
joystick->hwdata = NULL;
#if !SDL_EVENTS_DISABLED
SDL_Event event;
event.type = SDL_JOYDEVICEREMOVED;
if (SDL_GetEventState(event.type) == SDL_ENABLE) {
event.jdevice.which = joystick->instance_id;
if ((SDL_EventOK == NULL)
|| (*SDL_EventOK) (SDL_EventOKParam, &event)) {
SDL_PushEvent(&event);
}
}
SDL_Event event;
event.type = SDL_JOYDEVICEREMOVED;
if (SDL_GetEventState(event.type) == SDL_ENABLE) {
event.jdevice.which = joystick->instance_id;
if ((SDL_EventOK == NULL)
|| (*SDL_EventOK) (SDL_EventOKParam, &event)) {
SDL_PushEvent(&event);
}
}
#endif /* !SDL_EVENTS_DISABLED */
return;
}
@@ -1054,8 +1115,8 @@ SDL_SYS_JoystickUpdate(SDL_Joystick * joystick)
/* Function to close a joystick after use */
void
SDL_SYS_JoystickClose(SDL_Joystick * joystick)
{
joystick->closed = 1;
{
joystick->closed = 1;
}
/* Function to perform any system-specific joystick related cleanup */
@@ -1064,12 +1125,12 @@ SDL_SYS_JoystickQuit(void)
{
while (NULL != gpDeviceList)
gpDeviceList = HIDDisposeDevice(&gpDeviceList);
if ( notificationPort )
{
IONotificationPortDestroy( notificationPort );
notificationPort = 0;
}
if ( notificationPort )
{
IONotificationPortDestroy( notificationPort );
notificationPort = 0;
}
}
@@ -1077,16 +1138,16 @@ SDL_JoystickGUID SDL_SYS_JoystickGetDeviceGUID( int device_index )
{
recDevice *device = gpDeviceList;
int index;
for (index = device_index; index > 0; index--)
device = device->pNext;
return device->guid;
return device->guid;
}
SDL_JoystickGUID SDL_SYS_JoystickGetGUID(SDL_Joystick *joystick)
{
return joystick->hwdata->guid;
return joystick->hwdata->guid;
}
#endif /* SDL_JOYSTICK_IOKIT */

View File

@@ -59,9 +59,9 @@ struct joystick_hwdata
{
io_service_t ffservice; /* Interface for force feedback, 0 = no ff */
IOHIDDeviceInterface **interface; /* interface to device, NULL = no interface */
IONotificationPortRef notificationPort; /* port to be notified on joystick removal */
io_iterator_t portIterator; /* iterator for removal callback */
IONotificationPortRef notificationPort; /* port to be notified on joystick removal */
io_iterator_t portIterator; /* iterator for removal callback */
char product[256]; /* name of product */
long usage; /* usage page from IOUSBHID Parser.h which defines general usage */
long usagePage; /* usage within above page from IOUSBHID Parser.h which defines specific usage */
@@ -69,7 +69,7 @@ struct joystick_hwdata
long axes; /* number of axis (calculated, not reported by device) */
long buttons; /* number of buttons (calculated, not reported by device) */
long hats; /* number of hat switches (calculated, not reported by device) */
long elements; /* number of total elements (shouldbe total of above) (calculated, not reported by device) */
long elements; /* number of total elements (should be total of above) (calculated, not reported by device) */
recElement *firstAxis;
recElement *firstButton;
@@ -77,10 +77,10 @@ struct joystick_hwdata
int removed;
int uncentered;
int instance_id;
SDL_JoystickGUID guid;
Uint8 send_open_event; /* 1 if we need to send an Added event for this device */
int instance_id;
SDL_JoystickGUID guid;
Uint8 send_open_event; /* 1 if we need to send an Added event for this device */
struct joystick_hwdata *pNext; /* next device */
};

View File

@@ -110,7 +110,7 @@ SDL_SYS_JoystickQuit(void)
SDL_JoystickGUID SDL_SYS_JoystickGetDeviceGUID( int device_index )
{
SDL_JoystickGUID guid;
// the GUID is just the first 16 chars of the name for now
/* the GUID is just the first 16 chars of the name for now */
const char *name = SDL_SYS_JoystickNameForDeviceIndex( device_index );
SDL_zero( guid );
SDL_memcpy( &guid, name, SDL_min( sizeof(guid), SDL_strlen( name ) ) );
@@ -121,7 +121,7 @@ SDL_JoystickGUID SDL_SYS_JoystickGetDeviceGUID( int device_index )
SDL_JoystickGUID SDL_SYS_JoystickGetGUID(SDL_Joystick * joystick)
{
SDL_JoystickGUID guid;
// the GUID is just the first 16 chars of the name for now
/* the GUID is just the first 16 chars of the name for now */
const char *name = joystick->name;
SDL_zero( guid );
SDL_memcpy( &guid, name, SDL_min( sizeof(guid), SDL_strlen( name ) ) );

View File

@@ -28,114 +28,114 @@ static SDLUIAccelerationDelegate *sharedDelegate=nil;
@implementation SDLUIAccelerationDelegate
/*
Returns a shared instance of the SDLUIAccelerationDelegate, creating the shared delegate if it doesn't exist yet.
Returns a shared instance of the SDLUIAccelerationDelegate, creating the shared delegate if it doesn't exist yet.
*/
+(SDLUIAccelerationDelegate *)sharedDelegate {
if (sharedDelegate == nil) {
sharedDelegate = [[SDLUIAccelerationDelegate alloc] init];
}
return sharedDelegate;
if (sharedDelegate == nil) {
sharedDelegate = [[SDLUIAccelerationDelegate alloc] init];
}
return sharedDelegate;
}
/*
UIAccelerometerDelegate delegate method. Invoked by the UIAccelerometer instance when it has new data for us.
We just take the data and mark that we have new data available so that the joystick system will pump it to the
events system when SDL_SYS_JoystickUpdate is called.
*/
UIAccelerometerDelegate delegate method. Invoked by the UIAccelerometer instance when it has new data for us.
We just take the data and mark that we have new data available so that the joystick system will pump it to the
events system when SDL_SYS_JoystickUpdate is called.
*/
-(void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration {
x = acceleration.x;
y = acceleration.y;
z = acceleration.z;
hasNewData = YES;
x = acceleration.x;
y = acceleration.y;
z = acceleration.z;
hasNewData = YES;
}
/*
getLastOrientation -- put last obtained accelerometer data into Sint16 array
Called from the joystick system when it needs the accelerometer data.
Function grabs the last data sent to the accelerometer and converts it
from floating point to Sint16, which is what the joystick system expects.
To do the conversion, the data is first clamped onto the interval
[-SDL_IPHONE_MAX_G_FORCE, SDL_IPHONE_MAX_G_FORCE], then the data is multiplied
by MAX_SINT16 so that it is mapped to the full range of an Sint16.
You can customize the clamped range of this function by modifying the
SDL_IPHONE_MAX_GFORCE macro in SDL_config_iphoneos.h.
Once converted to Sint16, the accelerometer data no longer has coherent units.
You can convert the data back to units of g-force by multiplying it
in your application's code by SDL_IPHONE_MAX_GFORCE / 0x7FFF.
/*
getLastOrientation -- put last obtained accelerometer data into Sint16 array
Called from the joystick system when it needs the accelerometer data.
Function grabs the last data sent to the accelerometer and converts it
from floating point to Sint16, which is what the joystick system expects.
To do the conversion, the data is first clamped onto the interval
[-SDL_IPHONE_MAX_G_FORCE, SDL_IPHONE_MAX_G_FORCE], then the data is multiplied
by MAX_SINT16 so that it is mapped to the full range of an Sint16.
You can customize the clamped range of this function by modifying the
SDL_IPHONE_MAX_GFORCE macro in SDL_config_iphoneos.h.
Once converted to Sint16, the accelerometer data no longer has coherent units.
You can convert the data back to units of g-force by multiplying it
in your application's code by SDL_IPHONE_MAX_GFORCE / 0x7FFF.
*/
-(void)getLastOrientation:(Sint16 *)data {
#define MAX_SINT16 0x7FFF
#define MAX_SINT16 0x7FFF
/* clamp the data */
if (x > SDL_IPHONE_MAX_GFORCE) x = SDL_IPHONE_MAX_GFORCE;
else if (x < -SDL_IPHONE_MAX_GFORCE) x = -SDL_IPHONE_MAX_GFORCE;
if (y > SDL_IPHONE_MAX_GFORCE) y = SDL_IPHONE_MAX_GFORCE;
else if (y < -SDL_IPHONE_MAX_GFORCE) y = -SDL_IPHONE_MAX_GFORCE;
if (z > SDL_IPHONE_MAX_GFORCE) z = SDL_IPHONE_MAX_GFORCE;
else if (z < -SDL_IPHONE_MAX_GFORCE) z = -SDL_IPHONE_MAX_GFORCE;
/* pass in data mapped to range of SInt16 */
data[0] = (x / SDL_IPHONE_MAX_GFORCE) * MAX_SINT16;
data[1] = (y / SDL_IPHONE_MAX_GFORCE) * MAX_SINT16;
data[2] = (z / SDL_IPHONE_MAX_GFORCE) * MAX_SINT16;
/* clamp the data */
if (x > SDL_IPHONE_MAX_GFORCE) x = SDL_IPHONE_MAX_GFORCE;
else if (x < -SDL_IPHONE_MAX_GFORCE) x = -SDL_IPHONE_MAX_GFORCE;
if (y > SDL_IPHONE_MAX_GFORCE) y = SDL_IPHONE_MAX_GFORCE;
else if (y < -SDL_IPHONE_MAX_GFORCE) y = -SDL_IPHONE_MAX_GFORCE;
if (z > SDL_IPHONE_MAX_GFORCE) z = SDL_IPHONE_MAX_GFORCE;
else if (z < -SDL_IPHONE_MAX_GFORCE) z = -SDL_IPHONE_MAX_GFORCE;
/* pass in data mapped to range of SInt16 */
data[0] = (x / SDL_IPHONE_MAX_GFORCE) * MAX_SINT16;
data[1] = (y / SDL_IPHONE_MAX_GFORCE) * MAX_SINT16;
data[2] = (z / SDL_IPHONE_MAX_GFORCE) * MAX_SINT16;
}
/*
Initialize SDLUIAccelerationDelegate. Since we don't have any data yet,
just set our last received data to zero, and indicate we don't have any;
Initialize SDLUIAccelerationDelegate. Since we don't have any data yet,
just set our last received data to zero, and indicate we don't have any;
*/
-(id)init {
self = [super init];
x = y = z = 0.0;
hasNewData = NO;
return self;
self = [super init];
x = y = z = 0.0;
hasNewData = NO;
return self;
}
-(void)dealloc {
sharedDelegate = nil;
[self shutdown];
[super dealloc];
sharedDelegate = nil;
[self shutdown];
[super dealloc];
}
/*
Lets our delegate start receiving accelerometer updates.
Lets our delegate start receiving accelerometer updates.
*/
-(void)startup {
[UIAccelerometer sharedAccelerometer].delegate = self;
isRunning = YES;
[UIAccelerometer sharedAccelerometer].delegate = self;
isRunning = YES;
}
/*
Stops our delegate from receiving accelerometer updates.
Stops our delegate from receiving accelerometer updates.
*/
-(void)shutdown {
if ([UIAccelerometer sharedAccelerometer].delegate == self) {
[UIAccelerometer sharedAccelerometer].delegate = nil;
}
isRunning = NO;
if ([UIAccelerometer sharedAccelerometer].delegate == self) {
[UIAccelerometer sharedAccelerometer].delegate = nil;
}
isRunning = NO;
}
/*
Our we currently receiving accelerometer updates?
Our we currently receiving accelerometer updates?
*/
-(BOOL)isRunning {
return isRunning;
return isRunning;
}
/*
Do we have any data that hasn't been pumped into SDL's event system?
Do we have any data that hasn't been pumped into SDL's event system?
*/
-(BOOL)hasNewData {
return hasNewData;
return hasNewData;
}
/*
When the joystick system grabs the new data, it sets this to NO.
When the joystick system grabs the new data, it sets this to NO.
*/
-(void)setHasNewData:(BOOL)value {
hasNewData = value;
hasNewData = value;
}
@end

View File

@@ -97,20 +97,20 @@ SDL_bool SDL_SYS_JoystickAttached(SDL_Joystick *joystick)
void
SDL_SYS_JoystickUpdate(SDL_Joystick * joystick)
{
Sint16 orientation[3];
if ([[SDLUIAccelerationDelegate sharedDelegate] hasNewData]) {
[[SDLUIAccelerationDelegate sharedDelegate] getLastOrientation: orientation];
[[SDLUIAccelerationDelegate sharedDelegate] setHasNewData: NO];
SDL_PrivateJoystickAxis(joystick, 0, orientation[0]);
SDL_PrivateJoystickAxis(joystick, 1, orientation[1]);
SDL_PrivateJoystickAxis(joystick, 2, orientation[2]);
}
Sint16 orientation[3];
if ([[SDLUIAccelerationDelegate sharedDelegate] hasNewData]) {
[[SDLUIAccelerationDelegate sharedDelegate] getLastOrientation: orientation];
[[SDLUIAccelerationDelegate sharedDelegate] setHasNewData: NO];
SDL_PrivateJoystickAxis(joystick, 0, orientation[0]);
SDL_PrivateJoystickAxis(joystick, 1, orientation[1]);
SDL_PrivateJoystickAxis(joystick, 2, orientation[2]);
}
return;
}
@@ -118,10 +118,10 @@ SDL_SYS_JoystickUpdate(SDL_Joystick * joystick)
void
SDL_SYS_JoystickClose(SDL_Joystick * joystick)
{
if ([[SDLUIAccelerationDelegate sharedDelegate] isRunning]) {
[[SDLUIAccelerationDelegate sharedDelegate] shutdown];
}
SDL_SetError("No joystick open with that index");
if ([[SDLUIAccelerationDelegate sharedDelegate] isRunning]) {
[[SDLUIAccelerationDelegate sharedDelegate] shutdown];
}
SDL_SetError("No joystick open with that index");
}
/* Function to perform any system-specific joystick related cleanup */
@@ -133,7 +133,7 @@ SDL_SYS_JoystickQuit(void)
SDL_JoystickGUID SDL_SYS_JoystickGetDeviceGUID( int device_index )
{
SDL_JoystickGUID guid;
// the GUID is just the first 16 chars of the name for now
/* the GUID is just the first 16 chars of the name for now */
const char *name = SDL_SYS_JoystickNameForDeviceIndex( device_index );
SDL_zero( guid );
SDL_memcpy( &guid, name, SDL_min( sizeof(guid), SDL_strlen( name ) ) );
@@ -143,7 +143,7 @@ SDL_JoystickGUID SDL_SYS_JoystickGetDeviceGUID( int device_index )
SDL_JoystickGUID SDL_SYS_JoystickGetGUID(SDL_Joystick * joystick)
{
SDL_JoystickGUID guid;
// the GUID is just the first 16 chars of the name for now
/* the GUID is just the first 16 chars of the name for now */
const char *name = joystick->name;
SDL_zero( guid );
SDL_memcpy( &guid, name, SDL_min( sizeof(guid), SDL_strlen( name ) ) );

View File

@@ -510,7 +510,7 @@ void SDL_SYS_JoystickDetect()
SDL_PushEvent(&event);
}
}
#endif // !SDL_EVENTS_DISABLED
#endif /* !SDL_EVENTS_DISABLED */
}
} else if (SDL_strcmp(action, "remove") == 0) {
const int inst = MaybeRemoveDevice(devnode);
@@ -527,7 +527,7 @@ void SDL_SYS_JoystickDetect()
SDL_PushEvent(&event);
}
}
#endif // !SDL_EVENTS_DISABLED
#endif /* !SDL_EVENTS_DISABLED */
}
}
UDEV_udev_device_unref(dev);
@@ -760,7 +760,7 @@ SDL_SYS_JoystickOpen(SDL_Joystick * joystick, int device_index)
/* Get the number of buttons and axes on the joystick */
ConfigJoystick(joystick, fd);
// mark joystick as fresh and ready
/* mark joystick as fresh and ready */
joystick->hwdata->fresh = 1;
return (0);
@@ -840,7 +840,7 @@ PollAllValues(SDL_Joystick * joystick)
struct input_absinfo absinfo;
int a, b = 0;
// Poll all axis
/* Poll all axis */
for (a = ABS_X; b < ABS_MAX; a++) {
switch (a) {
case ABS_HAT0X:
@@ -851,7 +851,7 @@ PollAllValues(SDL_Joystick * joystick)
case ABS_HAT2Y:
case ABS_HAT3X:
case ABS_HAT3Y:
// ingore hats
/* ingore hats */
break;
default:
if (joystick->hwdata->abs_correct[b].used) {
@@ -938,7 +938,7 @@ HandleInputEvents(SDL_Joystick * joystick)
switch (code) {
case SYN_DROPPED :
#ifdef DEBUG_INPUT_EVENTS
printf("Event SYN_DROPPED dectected\n");
printf("Event SYN_DROPPED detected\n");
#endif
PollAllValues(joystick);
break;

View File

@@ -31,12 +31,12 @@ struct joystick_hwdata
SDL_JoystickGUID guid;
char *fname; /* Used in haptic subsystem */
/* The current linux joystick driver maps hats to two axes */
/* The current Linux joystick driver maps hats to two axes */
struct hwdata_hat
{
int axis[2];
} *hats;
/* The current linux joystick driver maps balls to two axes */
/* The current Linux joystick driver maps balls to two axes */
struct hwdata_ball
{
int axis[2];

View File

@@ -23,7 +23,7 @@
#include <pspctrl.h>
#include <pspkernel.h>
#include <stdio.h> /* For the definition of NULL */
#include <stdio.h> /* For the definition of NULL */
#include <stdlib.h>
#include "../SDL_sysjoystick.h"
@@ -41,10 +41,10 @@ static SDL_sem *pad_sem = NULL;
static SDL_Thread *thread = NULL;
static int running = 0;
static const enum PspCtrlButtons button_map[] = {
PSP_CTRL_TRIANGLE, PSP_CTRL_CIRCLE, PSP_CTRL_CROSS, PSP_CTRL_SQUARE,
PSP_CTRL_LTRIGGER, PSP_CTRL_RTRIGGER,
PSP_CTRL_DOWN, PSP_CTRL_LEFT, PSP_CTRL_UP, PSP_CTRL_RIGHT,
PSP_CTRL_SELECT, PSP_CTRL_START, PSP_CTRL_HOME, PSP_CTRL_HOLD };
PSP_CTRL_TRIANGLE, PSP_CTRL_CIRCLE, PSP_CTRL_CROSS, PSP_CTRL_SQUARE,
PSP_CTRL_LTRIGGER, PSP_CTRL_RTRIGGER,
PSP_CTRL_DOWN, PSP_CTRL_LEFT, PSP_CTRL_UP, PSP_CTRL_RIGHT,
PSP_CTRL_SELECT, PSP_CTRL_START, PSP_CTRL_HOME, PSP_CTRL_HOLD };
static int analog_map[256]; /* Map analog inputs to -32768 -> 32767 */
typedef struct
@@ -53,30 +53,30 @@ typedef struct
int y;
} point;
// 4 points define the bezier-curve.
/* 4 points define the bezier-curve. */
static point a = { 0, 0 };
static point b = { 50, 0 };
static point c = { 78, 32767 };
static point d = { 128, 32767 };
// simple linear interpolation between two points
/* simple linear interpolation between two points */
static __inline__ void lerp (point *dest, point *a, point *b, float t)
{
dest->x = a->x + (b->x - a->x)*t;
dest->y = a->y + (b->y - a->y)*t;
dest->x = a->x + (b->x - a->x)*t;
dest->y = a->y + (b->y - a->y)*t;
}
// evaluate a point on a bezier-curve. t goes from 0 to 1.0
/* evaluate a point on a bezier-curve. t goes from 0 to 1.0 */
static int calc_bezier_y(float t)
{
point ab, bc, cd, abbc, bccd, dest;
lerp (&ab, &a, &b, t); // point between a and b
lerp (&bc, &b, &c, t); // point between b and c
lerp (&cd, &c, &d, t); // point between c and d
lerp (&abbc, &ab, &bc, t); // point between ab and bc
lerp (&bccd, &bc, &cd, t); // point between bc and cd
lerp (&dest, &abbc, &bccd, t); // point on the bezier-curve
return dest.y;
point ab, bc, cd, abbc, bccd, dest;
lerp (&ab, &a, &b, t); /* point between a and b */
lerp (&bc, &b, &c, t); /* point between b and c */
lerp (&cd, &c, &d, t); /* point between c and d */
lerp (&abbc, &ab, &bc, t); /* point between ab and bc */
lerp (&bccd, &bc, &cd, t); /* point between bc and cd */
lerp (&dest, &abbc, &bccd, t); /* point on the bezier-curve */
return dest.y;
}
/*
@@ -84,14 +84,14 @@ static int calc_bezier_y(float t)
*/
int JoystickUpdate(void *data)
{
while (running) {
SDL_SemWait(pad_sem);
sceCtrlPeekBufferPositive(&pad, 1);
SDL_SemPost(pad_sem);
/* Delay 1/60th of a second */
sceKernelDelayThread(1000000 / 60);
}
return 0;
while (running) {
SDL_SemWait(pad_sem);
sceCtrlPeekBufferPositive(&pad, 1);
SDL_SemPost(pad_sem);
/* Delay 1/60th of a second */
sceKernelDelayThread(1000000 / 60);
}
return 0;
}
@@ -103,33 +103,33 @@ int JoystickUpdate(void *data)
*/
int SDL_SYS_JoystickInit(void)
{
int i;
int i;
// SDL_numjoysticks = 1;
/* SDL_numjoysticks = 1; */
/* Setup input */
sceCtrlSetSamplingCycle(0);
sceCtrlSetSamplingMode(PSP_CTRL_MODE_ANALOG);
/* Setup input */
sceCtrlSetSamplingCycle(0);
sceCtrlSetSamplingMode(PSP_CTRL_MODE_ANALOG);
/* Start thread to read data */
if((pad_sem = SDL_CreateSemaphore(1)) == NULL) {
return SDL_SetError("Can't create input semaphore");
}
running = 1;
if((thread = SDL_CreateThread(JoystickUpdate, "JoySitckThread",NULL)) == NULL) {
return SDL_SetError("Can't create input thread");
}
/* Start thread to read data */
if((pad_sem = SDL_CreateSemaphore(1)) == NULL) {
return SDL_SetError("Can't create input semaphore");
}
running = 1;
if((thread = SDL_CreateThread(JoystickUpdate, "JoySitckThread",NULL)) == NULL) {
return SDL_SetError("Can't create input thread");
}
/* Create an accurate map from analog inputs (0 to 255)
to SDL joystick positions (-32768 to 32767) */
for (i = 0; i < 128; i++)
{
float t = (float)i/127.0f;
analog_map[i+128] = calc_bezier_y(t);
analog_map[127-i] = -1 * analog_map[i+128];
}
/* Create an accurate map from analog inputs (0 to 255)
to SDL joystick positions (-32768 to 32767) */
for (i = 0; i < 128; i++)
{
float t = (float)i/127.0f;
analog_map[i+128] = calc_bezier_y(t);
analog_map[127-i] = -1 * analog_map[i+128];
}
return 1;
return 1;
}
int SDL_SYS_NumJoysticks()
@@ -161,11 +161,11 @@ SDL_JoystickID SDL_SYS_GetInstanceIdOfDeviceIndex(int device_index)
/* Function to get the device-dependent name of a joystick */
const char *SDL_SYS_JoystickName(int index)
{
if (index == 0)
return "PSP controller";
if (index == 0)
return "PSP controller";
SDL_SetError("No joystick available with that index");
return(NULL);
SDL_SetError("No joystick available with that index");
return(NULL);
}
/* Function to open a joystick for use.
@@ -175,11 +175,11 @@ const char *SDL_SYS_JoystickName(int index)
*/
int SDL_SYS_JoystickOpen(SDL_Joystick *joystick, int device_index)
{
joystick->nbuttons = 14;
joystick->naxes = 2;
joystick->nhats = 0;
joystick->nbuttons = 14;
joystick->naxes = 2;
joystick->nhats = 0;
return 0;
return 0;
}
/* Function to determine is this joystick is attached to the system right now */
@@ -195,65 +195,65 @@ SDL_bool SDL_SYS_JoystickAttached(SDL_Joystick *joystick)
void SDL_SYS_JoystickUpdate(SDL_Joystick *joystick)
{
int i;
enum PspCtrlButtons buttons;
enum PspCtrlButtons changed;
unsigned char x, y;
static enum PspCtrlButtons old_buttons = 0;
static unsigned char old_x = 0, old_y = 0;
int i;
enum PspCtrlButtons buttons;
enum PspCtrlButtons changed;
unsigned char x, y;
static enum PspCtrlButtons old_buttons = 0;
static unsigned char old_x = 0, old_y = 0;
SDL_SemWait(pad_sem);
buttons = pad.Buttons;
x = pad.Lx;
y = pad.Ly;
SDL_SemPost(pad_sem);
SDL_SemWait(pad_sem);
buttons = pad.Buttons;
x = pad.Lx;
y = pad.Ly;
SDL_SemPost(pad_sem);
/* Axes */
if(old_x != x) {
SDL_PrivateJoystickAxis(joystick, 0, analog_map[x]);
old_x = x;
}
if(old_y != y) {
SDL_PrivateJoystickAxis(joystick, 1, analog_map[y]);
old_y = y;
}
/* Axes */
if(old_x != x) {
SDL_PrivateJoystickAxis(joystick, 0, analog_map[x]);
old_x = x;
}
if(old_y != y) {
SDL_PrivateJoystickAxis(joystick, 1, analog_map[y]);
old_y = y;
}
/* Buttons */
changed = old_buttons ^ buttons;
old_buttons = buttons;
if(changed) {
for(i=0; i<sizeof(button_map)/sizeof(button_map[0]); i++) {
if(changed & button_map[i]) {
SDL_PrivateJoystickButton(
joystick, i,
(buttons & button_map[i]) ?
SDL_PRESSED : SDL_RELEASED);
}
}
}
/* Buttons */
changed = old_buttons ^ buttons;
old_buttons = buttons;
if(changed) {
for(i=0; i<sizeof(button_map)/sizeof(button_map[0]); i++) {
if(changed & button_map[i]) {
SDL_PrivateJoystickButton(
joystick, i,
(buttons & button_map[i]) ?
SDL_PRESSED : SDL_RELEASED);
}
}
}
sceKernelDelayThread(0);
sceKernelDelayThread(0);
}
/* Function to close a joystick after use */
void SDL_SYS_JoystickClose(SDL_Joystick *joystick)
{
/* Do nothing. */
/* Do nothing. */
}
/* Function to perform any system-specific joystick related cleanup */
void SDL_SYS_JoystickQuit(void)
{
/* Cleanup Threads and Semaphore. */
running = 0;
SDL_WaitThread(thread, NULL);
SDL_DestroySemaphore(pad_sem);
/* Cleanup Threads and Semaphore. */
running = 0;
SDL_WaitThread(thread, NULL);
SDL_DestroySemaphore(pad_sem);
}
SDL_JoystickGUID SDL_SYS_JoystickGetDeviceGUID( int device_index )
{
SDL_JoystickGUID guid;
// the GUID is just the first 16 chars of the name for now
/* the GUID is just the first 16 chars of the name for now */
const char *name = SDL_SYS_JoystickNameForDeviceIndex( device_index );
SDL_zero( guid );
SDL_memcpy( &guid, name, SDL_min( sizeof(guid), SDL_strlen( name ) ) );
@@ -263,7 +263,7 @@ SDL_JoystickGUID SDL_SYS_JoystickGetDeviceGUID( int device_index )
SDL_JoystickGUID SDL_SYS_JoystickGetGUID(SDL_Joystick * joystick)
{
SDL_JoystickGUID guid;
// the GUID is just the first 16 chars of the name for now
/* the GUID is just the first 16 chars of the name for now */
const char *name = joystick->name;
SDL_zero( guid );
SDL_memcpy( &guid, name, SDL_min( sizeof(guid), SDL_strlen( name ) ) );

View File

@@ -0,0 +1,61 @@
#!/usr/bin/env python
#
# Script to sort the game controller database entries in SDL_gamecontroller.c
import re
filename = "SDL_gamecontrollerdb.h"
input = open(filename)
output = open(filename + ".new", "w")
parsing_controllers = False
controllers = []
controller_guids = {}
split_pattern = re.compile(r'([^"]*")([^,]*,)([^,]*,)([^"]*)(".*)')
def save_controller(line):
global controllers
match = split_pattern.match(line)
entry = [ match.group(1), match.group(2), match.group(3) ]
bindings = sorted(match.group(4).split(","))
if (bindings[0] == ""):
bindings.pop(0)
entry.extend(",".join(bindings) + ",")
entry.append(match.group(5))
controllers.append(entry)
def write_controllers():
global controllers
global controller_guids
for entry in sorted(controllers, key=lambda entry: entry[2]):
line = "".join(entry) + "\n"
if (entry[1] in controller_guids):
print "Warning: entry '%s' is duplicate of entry '%s'" % (entry[2], controller_guids[entry[1]][2])
controller_guids[entry[1]] = entry
output.write(line)
controllers = []
controller_guids = {}
for line in input:
if ( parsing_controllers ):
if (line.startswith("{")):
output.write(line)
elif (line.startswith("#endif")):
parsing_controllers = False
write_controllers()
output.write(line)
elif (line.startswith("#")):
print "Parsing " + line.strip()
write_controllers()
output.write(line)
else:
save_controller(line)
else:
if (line.startswith("static const char *s_ControllerMappings")):
parsing_controllers = True
output.write(line)
output.close()
print "Finished writing %s.new" % filename

File diff suppressed because it is too large Load Diff

View File

@@ -23,10 +23,10 @@
#ifndef SDL_JOYSTICK_DINPUT_H
/* DirectInput joystick driver; written by Glenn Maynard, based on Andrei de
* A. Formiga's WINMM driver.
* A. Formiga's WINMM driver.
*
* Hats and sliders are completely untested; the app I'm writing this for mostly
* doesn't use them and I don't own any joysticks with them.
* doesn't use them and I don't own any joysticks with them.
*
* We don't bother to use event notification here. It doesn't seem to work
* with polled devices, and it's fine to call IDirectInputDevice2_GetDeviceData and
@@ -34,7 +34,7 @@
#include "../../core/windows/SDL_windows.h"
#define DIRECTINPUT_VERSION 0x0800 /* Need version 7 for force feedback. Need verison 8 so IDirectInput8_EnumDevices doesn't leak like a sieve... */
#define DIRECTINPUT_VERSION 0x0800 /* Need version 7 for force feedback. Need version 8 so IDirectInput8_EnumDevices doesn't leak like a sieve... */
#include <dinput.h>
#define COBJMACROS
#include <wbemcli.h>
@@ -57,7 +57,7 @@ typedef struct
DWORD dwPaddingReserved;
} XINPUT_GAMEPAD_EX;
typedef struct
typedef struct
{
DWORD dwPacketNumber;
XINPUT_GAMEPAD_EX Gamepad;
@@ -65,23 +65,23 @@ typedef struct
/* Forward decl's for XInput API's we load dynamically and use if available */
typedef DWORD (WINAPI *XInputGetState_t)
(
DWORD dwUserIndex, // [in] Index of the gamer associated with the device
XINPUT_STATE_EX* pState // [out] Receives the current state
);
(
DWORD dwUserIndex, /* [in] Index of the gamer associated with the device */
XINPUT_STATE_EX* pState /* [out] Receives the current state */
);
typedef DWORD (WINAPI *XInputSetState_t)
(
DWORD dwUserIndex, // [in] Index of the gamer associated with the device
XINPUT_VIBRATION* pVibration // [in, out] The vibration information to send to the controller
);
(
DWORD dwUserIndex, /* [in] Index of the gamer associated with the device */
XINPUT_VIBRATION* pVibration /* [in, out] The vibration information to send to the controller */
);
typedef DWORD (WINAPI *XInputGetCapabilities_t)
(
DWORD dwUserIndex, // [in] Index of the gamer associated with the device
DWORD dwFlags, // [in] Input flags that identify the device type
XINPUT_CAPABILITIES* pCapabilities // [out] Receives the capabilities
);
(
DWORD dwUserIndex, /* [in] Index of the gamer associated with the device */
DWORD dwFlags, /* [in] Input flags that identify the device type */
XINPUT_CAPABILITIES* pCapabilities /* [out] Receives the capabilities */
);
extern int WIN_LoadXInputDLL(void);
extern void WIN_UnloadXInputDLL(void);
@@ -89,11 +89,11 @@ extern void WIN_UnloadXInputDLL(void);
extern XInputGetState_t SDL_XInputGetState;
extern XInputSetState_t SDL_XInputSetState;
extern XInputGetCapabilities_t SDL_XInputGetCapabilities;
extern DWORD SDL_XInputVersion; // ((major << 16) & 0xFF00) | (minor & 0xFF)
extern DWORD SDL_XInputVersion; /* ((major << 16) & 0xFF00) | (minor & 0xFF) */
#define XINPUTGETSTATE SDL_XInputGetState
#define XINPUTSETSTATE SDL_XInputSetState
#define XINPUTGETCAPABILITIES SDL_XInputGetCapabilities
#define XINPUTGETSTATE SDL_XInputGetState
#define XINPUTSETSTATE SDL_XInputSetState
#define XINPUTGETCAPABILITIES SDL_XInputGetCapabilities
#define INVALID_XINPUT_USERID 255
#define SDL_XINPUT_MAX_DEVICES 4
@@ -102,7 +102,7 @@ extern DWORD SDL_XInputVersion; // ((major << 16) & 0xFF00) | (minor & 0xFF)
#endif
#define MAX_INPUTS 256 /* each joystick can have up to 256 inputs */
#define MAX_INPUTS 256 /* each joystick can have up to 256 inputs */
/* local types */
@@ -127,18 +127,18 @@ struct joystick_hwdata
LPDIRECTINPUTDEVICE8 InputDevice;
DIDEVCAPS Capabilities;
int buffered;
SDL_JoystickGUID guid;
SDL_JoystickGUID guid;
input_t Inputs[MAX_INPUTS];
int NumInputs;
int NumSliders;
Uint8 removed;
Uint8 send_remove_event;
Uint8 bXInputDevice; // 1 if this device supports using the xinput API rather than DirectInput
Uint8 bXInputHaptic; // Supports force feedback via XInput.
Uint8 userid; // XInput userid index for this joystick
Uint8 currentXInputSlot; // the current position to write to in XInputState below, used so we can compare old and new values
XINPUT_STATE_EX XInputState[2];
int NumSliders;
Uint8 removed;
Uint8 send_remove_event;
Uint8 bXInputDevice; /* 1 if this device supports using the xinput API rather than DirectInput */
Uint8 bXInputHaptic; /* Supports force feedback via XInput. */
Uint8 userid; /* XInput userid index for this joystick */
Uint8 currentXInputSlot; /* the current position to write to in XInputState below, used so we can compare old and new values */
XINPUT_STATE_EX XInputState[2];
};
#endif /* SDL_JOYSTICK_DINPUT_H */

View File

@@ -33,14 +33,14 @@
#include "../SDL_sysjoystick.h"
#include "../SDL_joystick_c.h"
#define MAX_JOYSTICKS 16
#define MAX_AXES 6 /* each joystick can have up to 6 axes */
#define MAX_BUTTONS 32 /* and 32 buttons */
#define AXIS_MIN -32768 /* minimum value for axis coordinate */
#define AXIS_MAX 32767 /* maximum value for axis coordinate */
#define MAX_JOYSTICKS 16
#define MAX_AXES 6 /* each joystick can have up to 6 axes */
#define MAX_BUTTONS 32 /* and 32 buttons */
#define AXIS_MIN -32768 /* minimum value for axis coordinate */
#define AXIS_MAX 32767 /* maximum value for axis coordinate */
/* limit axis to 256 possible positions to filter out noise */
#define JOY_AXIS_THRESHOLD (((AXIS_MAX)-(AXIS_MIN))/256)
#define JOY_BUTTON_FLAG(n) (1<<n)
#define JOY_BUTTON_FLAG(n) (1<<n)
/* array to hold joystick ID values */
@@ -407,7 +407,7 @@ SDL_SYS_JoystickQuit(void)
SDL_JoystickGUID SDL_SYS_JoystickGetDeviceGUID( int device_index )
{
SDL_JoystickGUID guid;
// the GUID is just the first 16 chars of the name for now
/* the GUID is just the first 16 chars of the name for now */
const char *name = SDL_SYS_JoystickNameForDeviceIndex( device_index );
SDL_zero( guid );
SDL_memcpy( &guid, name, SDL_min( sizeof(guid), SDL_strlen( name ) ) );
@@ -417,7 +417,7 @@ SDL_JoystickGUID SDL_SYS_JoystickGetDeviceGUID( int device_index )
SDL_JoystickGUID SDL_SYS_JoystickGetGUID(SDL_Joystick * joystick)
{
SDL_JoystickGUID guid;
// the GUID is just the first 16 chars of the name for now
/* the GUID is just the first 16 chars of the name for now */
const char *name = joystick->name;
SDL_zero( guid );
SDL_memcpy( &guid, name, SDL_min( sizeof(guid), SDL_strlen( name ) ) );

View File

@@ -19,73 +19,19 @@
3. This notice may not be removed or altered from any source distribution.
*/
#include "SDL_config.h"
#include "SDL_stdinc.h"
/* Math routines from uClibc: http://www.uclibc.org */
#ifdef HAVE_ATAN
#define atan SDL_uclibc_atan
#else
#define atan SDL_atan
#endif
double atan(double x);
#ifndef HAVE_ATAN2
#define __ieee754_atan2 SDL_atan2
#endif
#ifdef HAVE_COPYSIGN
#define copysign SDL_uclibc_copysign
#else
#define copysign SDL_copysign
#endif
double copysign(double x, double y);
#ifdef HAVE_COS
#define cos SDL_uclibc_cos
#else
#define cos SDL_cos
#endif
double cos(double x);
#ifdef HAVE_FABS
#define fabs SDL_uclibc_fabs
#else
#define fabs SDL_fabs
#endif
double fabs(double x);
#ifdef HAVE_FLOOR
#define floor SDL_uclibc_floor
#else
#define floor SDL_floor
#endif
double floor(double x);
#ifndef HAVE_LOG
#define __ieee754_log SDL_log
#endif
#ifndef HAVE_POW
#define __ieee754_pow SDL_pow
#endif
#ifdef HAVE_SCALBN
#define scalbn SDL_uclibc_scalbn
#else
#define scalbn SDL_scalbn
#endif
double scalbn(double x, int n);
#ifdef HAVE_SIN
#define sin SDL_uclibc_sin
#else
#define sin SDL_sin
#endif
double sin(double x);
#ifndef HAVE_SQRT
#define __ieee754_sqrt SDL_sqrt
#endif
double SDL_uclibc_atan(double x);
double SDL_uclibc_atan2(double y, double x);
double SDL_uclibc_copysign(double x, double y);
double SDL_uclibc_cos(double x);
double SDL_uclibc_fabs(double x);
double SDL_uclibc_floor(double x);
double SDL_uclibc_log(double x);
double SDL_uclibc_pow(double x, double y);
double SDL_uclibc_scalbn(double x, int n);
double SDL_uclibc_sin(double x);
double SDL_uclibc_sqrt(double x);
/* vi: set ts=4 sw=4 expandtab: */

View File

@@ -25,7 +25,21 @@
#define libm_hidden_proto(x)
#define libm_hidden_def(x)
#ifndef __HAIKU__ /* already defined in a system header. */
typedef unsigned int u_int32_t;
#endif
#define atan SDL_uclibc_atan
#define __ieee754_atan2 SDL_uclibc_atan2
#define copysign SDL_uclibc_copysign
#define cos SDL_uclibc_cos
#define fabs SDL_uclibc_fabs
#define floor SDL_uclibc_floor
#define __ieee754_log SDL_uclibc_log
#define __ieee754_pow SDL_uclibc_pow
#define scalbn SDL_uclibc_scalbn
#define sin SDL_uclibc_sin
#define __ieee754_sqrt SDL_uclibc_sqrt
/* The original fdlibm code used statements like:
n0 = ((*(int*)&one)>>29)^1; * index of high word *

Some files were not shown because too many files have changed in this diff Show More