src/haptic/darwin/SDL_syshaptic.c
author Edgar Simo <bobbens@gmail.com>
Wed, 30 Jul 2008 14:48:34 +0000
branchgsoc2008_force_feedback
changeset 2554 2681a04c2d3d
parent 2553 3f853f075bc0
child 2555 f5bcc926bac4
permissions -rw-r--r--
Warn about using button triggers.
     1 /*
     2     SDL - Simple DirectMedia Layer
     3     Copyright (C) 2008 Edgar Simo
     4 
     5     This library is free software; you can redistribute it and/or
     6     modify it under the terms of the GNU Lesser General Public
     7     License as published by the Free Software Foundation; either
     8     version 2.1 of the License, or (at your option) any later version.
     9 
    10     This library is distributed in the hope that it will be useful,
    11     but WITHOUT ANY WARRANTY; without even the implied warranty of
    12     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    13     Lesser General Public License for more details.
    14 
    15     You should have received a copy of the GNU Lesser General Public
    16     License along with this library; if not, write to the Free Software
    17     Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
    18 
    19     Sam Lantinga
    20     slouken@libsdl.org
    21 */
    22 #include "SDL_config.h"
    23 
    24 #ifdef SDL_HAPTIC_IOKIT
    25 
    26 #include "SDL_haptic.h"
    27 #include "../SDL_syshaptic.h"
    28 #include "SDL_joystick.h"
    29 #include "../../joystick/SDL_sysjoystick.h" /* For the real SDL_Joystick */
    30 /*#include "../../joystick/dawrin/SDL_sysjoystick_c.h"*/ /* For joystick hwdata */ 
    31 
    32 #include <IOKit/IOKitLib.h>
    33 #include <IOKit/hid/IOHIDKeys.h>
    34 #include <ForceFeedback/ForceFeedback.h>
    35 #include <ForceFeedback/ForceFeedbackConstants.h>
    36 
    37 
    38 #define MAX_HAPTICS  32
    39 
    40 
    41 /*
    42  * List of available haptic devices.
    43  */
    44 static struct
    45 {
    46    char name[256];
    47    io_service_t dev;
    48    SDL_Haptic *haptic;
    49 } SDL_hapticlist[MAX_HAPTICS];
    50 
    51 
    52 /*
    53  * Haptic system hardware data.
    54  */
    55 struct haptic_hwdata
    56 {
    57    FFDeviceObjectReference device; /* Hardware device. */
    58 };
    59 
    60 
    61 /*
    62  * Haptic system effect data.
    63  */
    64 struct haptic_hweffect
    65 {
    66    FFEffectObjectReference ref; /* Reference. */
    67    struct FFEFFECT effect; /* Hardware effect. */
    68 };
    69 
    70 /*
    71  * Prototypes.
    72  */
    73 static void SDL_SYS_HapticFreeFFEFFECT(FFEFFECT * effect, int type);
    74 static int HIDGetDeviceProduct(io_service_t dev, char * name);
    75 
    76 
    77 /* 
    78  * Like strerror but for force feedback errors.
    79  */
    80 static const char *
    81 FFStrError(HRESULT err)
    82 {
    83    switch (err) {
    84       case FFERR_DEVICEFULL:
    85          return "device full";
    86       /*case FFERR_DEVICENOTREG:
    87          return "device not registered";*/
    88       case FFERR_DEVICEPAUSED:
    89          return "device paused";
    90       case FFERR_DEVICERELEASED:
    91          return "device released";
    92       case FFERR_EFFECTPLAYING:
    93          return "effect playing";
    94       case FFERR_EFFECTTYPEMISMATCH:
    95          return "effect type mismatch";
    96       case FFERR_EFFECTTYPENOTSUPPORTED:
    97          return "effect type not supported";
    98       case FFERR_GENERIC:
    99          return "undetermined error";
   100       case FFERR_HASEFFECTS:
   101          return "device has effects";
   102       case FFERR_INCOMPLETEEFFECT:
   103          return "incomplete effect";
   104       case FFERR_INTERNAL:
   105          return "internal fault";
   106       case FFERR_INVALIDDOWNLOADID:
   107          return "invalid download id";
   108       case FFERR_INVALIDPARAM:
   109          return "invalid parameter";
   110       case FFERR_MOREDATA:
   111          return "more data";
   112       case FFERR_NOINTERFACE:
   113          return "interface not supported";
   114       case FFERR_NOTDOWNLOADED:
   115          return "effect is not downloaded";
   116       case FFERR_NOTINITIALIZED:
   117          return "object has not been initialized";
   118       case FFERR_OUTOFMEMORY:
   119          return "out of memory";
   120       case FFERR_UNPLUGGED:
   121          return "device is unplugged";
   122       case FFERR_UNSUPPORTED:
   123          return "function call unsupported";
   124       case FFERR_UNSUPPORTEDAXIS:
   125          return "axis unsupported";
   126 
   127       default:
   128          return "unknown error";
   129    }
   130 }
   131 
   132 
   133 /*
   134  * Initializes the haptic subsystem.
   135  */
   136 int
   137 SDL_SYS_HapticInit(void)
   138 {
   139    int numhaptics;
   140    IOReturn result;
   141    io_iterator_t iter;
   142    CFDictionaryRef match;
   143    io_service_t device;
   144 
   145    /* Clear all the memory. */
   146    SDL_memset(SDL_hapticlist, 0, sizeof(SDL_hapticlist));
   147 
   148    /* Get HID devices. */
   149    match = IOServiceMatching(kIOHIDDeviceKey);
   150    if (match == NULL) {
   151       SDL_SetError("Haptic: Failed to get IOServiceMatching.");
   152       return -1;
   153    }
   154 
   155    /* Now search I/O Registry for matching devices. */
   156    result = IOServiceGetMatchingServices(kIOMasterPortDefault, match, &iter);
   157    if (result != kIOReturnSuccess) {
   158       SDL_SetError("Haptic: Couldn't create a HID object iterator.");
   159       return -1;
   160    }
   161    /* IOServiceGetMatchingServices consumes dictionary. */
   162 
   163    numhaptics = 0;
   164    while ((device = IOIteratorNext(iter)) != IO_OBJECT_NULL) {
   165 
   166       /* Check for force feedback. */
   167       if (FFIsForceFeedback(device) == FF_OK) {
   168          HIDGetDeviceProduct(device, SDL_hapticlist[numhaptics].name);
   169          SDL_hapticlist[numhaptics].dev = device;
   170          SDL_hapticlist[numhaptics].haptic = NULL;
   171          numhaptics++;
   172       }
   173       else { /* Free the unused device. */
   174          IOObjectRelease(device);
   175       }
   176 
   177       /* Reached haptic limit. */
   178       if (numhaptics >= MAX_HAPTICS)
   179          break;
   180    }
   181    IOObjectRelease(iter);
   182 
   183    return numhaptics;
   184 }
   185 
   186 
   187 /*
   188  * Return the name of a haptic device, does not need to be opened.
   189  */
   190 const char *
   191 SDL_SYS_HapticName(int index)
   192 {
   193    return SDL_hapticlist[index].name;
   194 }
   195 
   196 /*
   197  * Gets the device's product name.
   198  */
   199 static int
   200 HIDGetDeviceProduct(io_service_t dev, char *name)
   201 {
   202    CFMutableDictionaryRef hidProperties, usbProperties;
   203    io_registry_entry_t parent1, parent2;
   204    kern_return_t ret;
   205 
   206    hidProperties = usbProperties = 0;
   207 
   208    ret = IORegistryEntryCreateCFProperties(dev, &hidProperties,
   209                                            kCFAllocatorDefault,
   210                                            kNilOptions);
   211    if ((ret != KERN_SUCCESS) || !hidProperties) {
   212       SDL_SetError("Haptic: Unable to create CFProperties.");
   213       return -1;
   214    }
   215 
   216    /* Mac OS X currently is not mirroring all USB properties to HID page so need to look at USB device page also
   217     * get dictionary for usb properties: step up two levels and get CF dictionary for USB properties
   218     */
   219    if ((KERN_SUCCESS ==
   220             IORegistryEntryGetParentEntry(dev, kIOServicePlane, &parent1))
   221          && (KERN_SUCCESS ==
   222             IORegistryEntryGetParentEntry(parent1, kIOServicePlane, &parent2))
   223          && (KERN_SUCCESS ==
   224             IORegistryEntryCreateCFProperties(parent2, &usbProperties,
   225                                               kCFAllocatorDefault,
   226                                               kNilOptions))) {
   227       if (usbProperties) {
   228          CFTypeRef refCF = 0;
   229          /* get device info
   230           * try hid dictionary first, if fail then go to usb dictionary
   231           */
   232 
   233 
   234          /* Get product name */
   235          refCF = CFDictionaryGetValue(hidProperties, CFSTR(kIOHIDProductKey));
   236          if (!refCF)
   237             refCF =
   238                CFDictionaryGetValue(usbProperties, CFSTR("USB Product Name"));
   239          if (refCF) {
   240             if (!CFStringGetCString(refCF, name, 256,
   241                                     CFStringGetSystemEncoding())) {
   242                SDL_SetError("CFStringGetCString error retrieving pDevice->product.");
   243                return -1;
   244             }
   245          }
   246 
   247          CFRelease(usbProperties);
   248       }
   249       else {
   250          SDL_SetError("IORegistryEntryCreateCFProperties failed to create usbProperties.");
   251          return -1;
   252       }
   253 
   254       /* Release stuff. */
   255       if (kIOReturnSuccess != IOObjectRelease(parent2)) {
   256          SDL_SetError("IOObjectRelease error with parent2.");
   257       }
   258       if (kIOReturnSuccess != IOObjectRelease(parent1))  {
   259          SDL_SetError("IOObjectRelease error with parent1.");
   260       }
   261    }
   262    else {
   263       SDL_SetError("Haptic: Error getting registry entries.");
   264       return -1;
   265    }
   266 
   267    return 0;
   268 }
   269 
   270 
   271 #define FF_TEST(ff, s) \
   272 if (features.supportedEffects & ff) supported |= s
   273 /*
   274  * Gets supported features.
   275  */
   276 static unsigned int
   277 GetSupportedFeatures(FFDeviceObjectReference device,
   278                      int *neffects, int *nplaying, int *naxes)
   279 {
   280    HRESULT ret;
   281    FFCAPABILITIES features;
   282    unsigned int supported;
   283    Uint32 val;
   284 
   285    ret = FFDeviceGetForceFeedbackCapabilities(device, &features);
   286    if (ret != FF_OK) {
   287       SDL_SetError("Haptic: Unable to get device's supported features.");
   288       return 0;
   289    }
   290 
   291    supported = 0;
   292 
   293    /* Get maximum effects. */
   294    *neffects = features.storageCapacity;
   295    *nplaying = features.playbackCapacity;
   296 
   297    /* Test for effects. */
   298    FF_TEST(FFCAP_ET_CONSTANTFORCE, SDL_HAPTIC_CONSTANT);
   299    FF_TEST(FFCAP_ET_RAMPFORCE,     SDL_HAPTIC_RAMP);
   300    FF_TEST(FFCAP_ET_SQUARE,        SDL_HAPTIC_SQUARE);
   301    FF_TEST(FFCAP_ET_SINE,          SDL_HAPTIC_SINE);
   302    FF_TEST(FFCAP_ET_TRIANGLE,      SDL_HAPTIC_TRIANGLE);
   303    FF_TEST(FFCAP_ET_SAWTOOTHUP,    SDL_HAPTIC_SAWTOOTHUP);
   304    FF_TEST(FFCAP_ET_SAWTOOTHDOWN,  SDL_HAPTIC_SAWTOOTHDOWN);
   305    FF_TEST(FFCAP_ET_SPRING,        SDL_HAPTIC_SPRING);
   306    FF_TEST(FFCAP_ET_DAMPER,        SDL_HAPTIC_DAMPER);
   307    FF_TEST(FFCAP_ET_INERTIA,       SDL_HAPTIC_INERTIA);
   308    FF_TEST(FFCAP_ET_FRICTION,      SDL_HAPTIC_FRICTION);
   309    FF_TEST(FFCAP_ET_CUSTOMFORCE,   SDL_HAPTIC_CUSTOM);
   310 
   311    /* Check if supports gain. */
   312    ret = FFDeviceGetForceFeedbackProperty( device, FFPROP_FFGAIN,
   313                                            &val, sizeof(val));
   314    if (ret == FF_OK) supported |= SDL_HAPTIC_GAIN;
   315    else if (ret != FFERR_UNSUPPORTED) {
   316       SDL_SetError("Haptic: Unable to get if device supports gain: %s.",
   317                    FFStrError(ret));
   318       return 0;
   319    }
   320 
   321    /* Checks if supports autocenter. */
   322    ret = FFDeviceGetForceFeedbackProperty(device, FFPROP_AUTOCENTER,
   323                                           &val, sizeof(val));
   324    if (ret == FF_OK) supported |= SDL_HAPTIC_AUTOCENTER;
   325    else if (ret != FFERR_UNSUPPORTED) {
   326       SDL_SetError("Haptic: Unable to get if device supports autocenter: %s.",
   327                    FFStrError(ret));
   328       return 0;
   329    }
   330 
   331    /* Check for axes, we have an artificial limit on axes */
   332    *naxes = ((features.numFfAxes) > 3) ?
   333          3 : features.numFfAxes;
   334 
   335    /* Always supported features. */
   336    supported |= SDL_HAPTIC_STATUS;
   337    return supported;
   338 }
   339 
   340 
   341 /*
   342  * Opens the haptic device from the file descriptor.
   343  */
   344 static int
   345 SDL_SYS_HapticOpenFromService(SDL_Haptic * haptic, io_service_t service)
   346 {
   347    HRESULT ret;
   348 
   349    /* Allocate the hwdata */
   350    haptic->hwdata = (struct haptic_hwdata *)
   351          SDL_malloc(sizeof(*haptic->hwdata));
   352    if (haptic->hwdata == NULL) {
   353       SDL_OutOfMemory();
   354       goto creat_err;
   355    }
   356    SDL_memset(haptic->hwdata, 0, sizeof(*haptic->hwdata));
   357   
   358    /* Open the device */
   359    ret = FFCreateDevice( service, &haptic->hwdata->device);
   360    if (ret != FF_OK) {
   361       SDL_SetError("Haptic: Unable to create device from service: %s.",
   362                    FFStrError(ret));
   363       goto creat_err;
   364    }
   365 
   366    /* Get supported features. */
   367    haptic->supported = GetSupportedFeatures( haptic->hwdata->device,
   368                                              &haptic->neffects, &haptic->nplaying,
   369                                              &haptic->naxes );
   370    if (haptic->supported == 0) { /* Error since device supports nothing. */
   371       goto open_err;
   372    }
   373 
   374 
   375    /* Reset and then enable actuators. */
   376    ret = FFDeviceSendForceFeedbackCommand( haptic->hwdata->device,
   377                                            FFSFFC_RESET );
   378    if (ret != FF_OK) {
   379       SDL_SetError("Haptic: Unable to reset device: %s.", FFStrError(ret));
   380       goto open_err;
   381    }
   382    ret = FFDeviceSendForceFeedbackCommand( haptic->hwdata->device,
   383                                            FFSFFC_SETACTUATORSON  );
   384    if (ret != FF_OK) {
   385       SDL_SetError("Haptic: Unable to enable actuators: %s.", FFStrError(ret));
   386       goto open_err;
   387    }
   388 
   389 
   390    /* Allocate effects memory. */
   391    haptic->effects = (struct haptic_effect *)
   392          SDL_malloc(sizeof(struct haptic_effect) * haptic->neffects);
   393    if (haptic->effects == NULL) {
   394       SDL_OutOfMemory();
   395       goto open_err;
   396    }
   397    /* Clear the memory */
   398    SDL_memset(haptic->effects, 0,
   399          sizeof(struct haptic_effect) * haptic->neffects);
   400    
   401    return 0;
   402    
   403    /* Error handling */
   404 open_err:
   405    FFReleaseDevice(haptic->hwdata->device);
   406 creat_err:
   407    if (haptic->hwdata != NULL) {
   408       free(haptic->hwdata);
   409       haptic->hwdata = NULL;                                              
   410    }
   411    return -1;
   412 
   413 }
   414 
   415 
   416 /*
   417  * Opens a haptic device for usage.
   418  */
   419 int
   420 SDL_SYS_HapticOpen(SDL_Haptic * haptic)
   421 {
   422    return SDL_SYS_HapticOpenFromService(haptic,
   423                 SDL_hapticlist[haptic->index].dev);
   424 }
   425 
   426 
   427 /*
   428  * Opens a haptic device from first mouse it finds for usage.
   429  */
   430 int
   431 SDL_SYS_HapticMouse(void)
   432 {
   433    return -1;
   434 }
   435 
   436 
   437 /*
   438  * Checks to see if a joystick has haptic features.
   439  */
   440 int
   441 SDL_SYS_JoystickIsHaptic(SDL_Joystick * joystick)
   442 {
   443    return SDL_FALSE;
   444 }
   445 
   446 
   447 /*
   448  * Checks to see if the haptic device and joystick and in reality the same.
   449  */
   450 int
   451 SDL_SYS_JoystickSameHaptic(SDL_Haptic * haptic, SDL_Joystick * joystick)
   452 {
   453    return 0;
   454 }
   455 
   456 
   457 /*
   458  * Opens a SDL_Haptic from a SDL_Joystick.
   459  */
   460 int
   461 SDL_SYS_HapticOpenFromJoystick(SDL_Haptic * haptic, SDL_Joystick * joystick)
   462 {
   463    return -1;
   464 }
   465 
   466 
   467 /*
   468  * Closes the haptic device.
   469  */
   470 void
   471 SDL_SYS_HapticClose(SDL_Haptic * haptic)
   472 {
   473    int i;
   474 
   475    if (haptic->hwdata) {
   476 
   477       /* Free the effects. */
   478       for (i=0; i<haptic->neffects; i++) {        
   479          if (haptic->effects[i].hweffect != NULL) {
   480             SDL_SYS_HapticFreeFFEFFECT(&haptic->effects[i].hweffect->effect,
   481                                        haptic->effects[i].effect.type);
   482             SDL_free(haptic->effects[i].hweffect);
   483          } 
   484       }    
   485       SDL_free(haptic->effects);
   486       haptic->neffects = 0;
   487 
   488       /* Clean up */
   489       FFReleaseDevice(haptic->hwdata->device);
   490 
   491       /* Free */
   492       SDL_free(haptic->hwdata);
   493       haptic->hwdata = NULL;
   494    }
   495 }
   496 
   497 
   498 /* 
   499  * Clean up after system specific haptic stuff
   500  */
   501 void
   502 SDL_SYS_HapticQuit(void)
   503 {
   504    int i;
   505 
   506    for (i=0; i < SDL_numhaptics; i++) {
   507       /* Opened and not closed haptics are leaked, this is on purpose.
   508        * Close your haptic devices after usage. */
   509 
   510       /* Free the io_service_t */
   511       IOObjectRelease(SDL_hapticlist[i].dev);
   512    }
   513 }
   514 
   515 
   516 /*
   517  * Converts an SDL trigger button to an FFEFFECT trigger button.
   518  */
   519 static DWORD
   520 FFGetTriggerButton( Uint16 button )
   521 {
   522    DWORD dwTriggerButton;
   523 
   524    dwTriggerButton = FFEB_NOTRIGGER;
   525 
   526    if (hap_constant->button != 0)
   527       dwTriggerButton = FFJOFS_BUTTON(hap_constant->button);
   528 
   529    return dwTriggerButton;
   530 }
   531 
   532 
   533 /*
   534  * Sets the direction.
   535  */
   536 static int
   537 SDL_SYS_SetDirection( FFEFFECT * effect, SDL_HapticDirection *dir, int naxes )
   538 {
   539    LONG *rglDir;
   540 
   541    /* Handle no axes a part. */
   542    if (naxes == 0) {
   543       effect->rglDirection = NULL;
   544       return 0;
   545    }
   546 
   547    /* Has axes. */
   548    rglDir = SDL_malloc( sizeof(LONG) * naxes );
   549    if (rglDir == NULL) {
   550       SDL_OutOfMemory();
   551       return -1;
   552    }
   553    SDL_memset( rglDir, 0, sizeof(LONG) * naxes );
   554    effect->rglDirection = rglDir;
   555 
   556    switch (dir->type) {
   557       case SDL_HAPTIC_POLAR:
   558          effect->dwFlags |= FFEFF_POLAR;
   559          rglDir[0] = dir->dir[0];
   560          return 0;
   561       case SDL_HAPTIC_CARTESIAN:
   562          effect->dwFlags |= FFEFF_CARTESIAN;
   563          rglDir[0] = dir->dir[0];
   564          rglDir[1] = dir->dir[1];
   565          rglDir[2] = dir->dir[2];
   566          return 0;
   567       case SDL_HAPTIC_SPHERICAL:
   568          effect->dwFlags |= FFEFF_SPHERICAL;
   569          rglDir[0] = dir->dir[0];
   570          rglDir[1] = dir->dir[1];
   571          rglDir[2] = dir->dir[2];
   572          return 0;
   573 
   574       default:
   575          SDL_SetError("Haptic: Unknown direction type.");
   576          return -1;
   577    }
   578 }
   579 
   580 #define CONVERT(x)   (((x)*10000) / 0xFFFF )
   581 /*
   582  * Creates the FFEFFECT from a SDL_HapticEffect.
   583  */
   584 static int
   585 SDL_SYS_ToFFEFFECT( SDL_Haptic * haptic, FFEFFECT * dest, SDL_HapticEffect * src )
   586 {
   587    int i;
   588    FFCONSTANTFORCE *constant;
   589    FFPERIODIC *periodic;
   590    FFCONDITION *condition; /* Actually an array of conditions - one per axis. */
   591    FFRAMPFORCE *ramp;
   592    FFCUSTOMFORCE *custom;
   593    FFENVELOPE *envelope;
   594    SDL_HapticConstant *hap_constant;
   595    SDL_HapticPeriodic *hap_periodic;
   596    SDL_HapticCondition *hap_condition;
   597    SDL_HapticRamp *hap_ramp;
   598    SDL_HapticCustom *hap_custom;
   599    DWORD *axes;
   600 
   601    /* Set global stuff. */
   602    SDL_memset(dest, 0, sizeof(FFEFFECT));
   603    dest->dwSize = sizeof(FFEFFECT); /* Set the structure size. */
   604    dest->dwSamplePeriod = 0; /* Not used by us. */
   605    dest->dwGain = 10000; /* Gain is set globally, not locally. */
   606 
   607    /* Envelope. */
   608    envelope = SDL_malloc( sizeof(FFENVELOPE) );
   609    if (envelope == NULL) {
   610       SDL_OutOfMemory();
   611       return -1;
   612    }
   613    SDL_memset(envelope, 0, sizeof(FFENVELOPE));
   614    dest->lpEnvelope = envelope;
   615    envelope->dwSize = sizeof(FFENVELOPE); /* Always should be this. */
   616 
   617    /* Axes. */
   618    dest->cAxes = haptic->naxes;
   619    if (dest->cAxes > 0) {
   620       axes = SDL_malloc(sizeof(DWORD) * dest->cAxes);
   621       if (axes == NULL) {
   622          SDL_OutOfMemory();
   623          return -1;
   624       }
   625       axes[0] = FFJOFS_X; /* Always at least one axis. */
   626       if (dest->cAxes > 1) {
   627          axes[1] = FFJOFS_Y;
   628       }
   629       if (dest->cAxes > 2) {
   630          axes[2] = FFJOFS_Z;
   631       }
   632       dest->rgdwAxes = axes;
   633    }
   634 
   635 
   636    /* The big type handling switch, even bigger then linux's version. */
   637    switch (src->type) {
   638       case SDL_HAPTIC_CONSTANT:
   639          hap_constant = &src->constant;
   640          constant = SDL_malloc( sizeof(FFCONSTANTFORCE) );
   641          if (constant == NULL) {
   642             SDL_OutOfMemory();
   643             return -1;
   644          }
   645          SDL_memset(constant, 0, sizeof(FFCONSTANTFORCE));
   646 
   647          /* Specifics */
   648          constant->lMagnitude = CONVERT(hap_constant->level);
   649          dest->cbTypeSpecificParams = sizeof(FFCONSTANTFORCE); 
   650          dest->lpvTypeSpecificParams = constant;
   651 
   652          /* Generics */
   653          dest->dwDuration = hap_constant->length * 1000; /* In microseconds. */
   654          dest->dwTriggerButton = FFGetTriggerButton(hap_constant->button);
   655          dest->dwTriggerRepeatInterval = hap_constant->interval;
   656          dest->dwStartDelay = hap_constant->delay * 1000; /* In microseconds. */
   657 
   658          /* Direction. */
   659          if (SDL_SYS_SetDirection(dest, &hap_constant->direction, dest->cAxes) < 0) {
   660             return -1;
   661          }
   662          
   663          /* Envelope */
   664          envelope->dwAttackLevel = CONVERT(hap_constant->attack_level);
   665          envelope->dwAttackTime = hap_constant->attack_length * 1000;
   666          envelope->dwFadeLevel = CONVERT(hap_constant->fade_level);
   667          envelope->dwFadeTime = hap_constant->fade_length * 1000;
   668 
   669          break;
   670 
   671       case SDL_HAPTIC_SINE:
   672       case SDL_HAPTIC_SQUARE:
   673       case SDL_HAPTIC_TRIANGLE:
   674       case SDL_HAPTIC_SAWTOOTHUP:
   675       case SDL_HAPTIC_SAWTOOTHDOWN:
   676          hap_periodic = &src->periodic;
   677          periodic = SDL_malloc(sizeof(FFPERIODIC));
   678          if (periodic == NULL) {
   679             SDL_OutOfMemory();
   680             return -1;
   681          }
   682          SDL_memset(periodic, 0, sizeof(FFPERIODIC));
   683 
   684          /* Specifics */
   685          periodic->dwMagnitude = CONVERT(hap_periodic->magnitude);
   686          periodic->lOffset = CONVERT(hap_periodic->offset);
   687          periodic->dwPhase = hap_periodic->phase;
   688          periodic->dwPeriod = hap_periodic->period * 1000;
   689          dest->cbTypeSpecificParams = sizeof(FFPERIODIC);
   690          dest->lpvTypeSpecificParams = periodic;
   691 
   692          /* Generics */
   693          dest->dwDuration = hap_periodic->length * 1000; /* In microseconds. */
   694          dest->dwTriggerButton = FFGetTriggerButton(hap_periodic->button);
   695          dest->dwTriggerRepeatInterval = hap_periodic->interval;
   696          dest->dwStartDelay = hap_periodic->delay * 1000; /* In microseconds. */
   697          
   698          /* Direction. */
   699          if (SDL_SYS_SetDirection(dest, &hap_periodic->direction, dest->cAxes) < 0) {
   700             return -1;
   701          }
   702          
   703          /* Envelope */
   704          envelope->dwAttackLevel = CONVERT(hap_periodic->attack_level);
   705          envelope->dwAttackTime = hap_periodic->attack_length * 1000;
   706          envelope->dwFadeLevel = CONVERT(hap_periodic->fade_level);
   707          envelope->dwFadeTime = hap_periodic->fade_length * 1000;
   708 
   709          break;
   710 
   711       case SDL_HAPTIC_SPRING:
   712       case SDL_HAPTIC_DAMPER:
   713       case SDL_HAPTIC_INERTIA:
   714       case SDL_HAPTIC_FRICTION:
   715          hap_condition = &src->condition;
   716          condition = SDL_malloc(sizeof(FFCONDITION) * dest->cAxes);
   717          if (condition == NULL) {
   718             SDL_OutOfMemory();
   719             return -1;
   720          }
   721          SDL_memset(condition, 0, sizeof(FFCONDITION));
   722 
   723          /* Specifics */
   724          for (i=0; i<dest->cAxes; i++) {
   725             condition[i].lOffset = CONVERT(hap_condition->center[i]);
   726             condition[i].lPositiveCoefficient = CONVERT(hap_condition->right_coeff[i]);
   727             condition[i].lNegativeCoefficient = CONVERT(hap_condition->left_coeff[i]);
   728             condition[i].dwPositiveSaturation = CONVERT(hap_condition->right_sat[i]);
   729             condition[i].dwNegativeSaturation = CONVERT(hap_condition->left_sat[i]);
   730             condition[i].lDeadBand = CONVERT(hap_condition->deadband[i]);
   731          }
   732          dest->cbTypeSpecificParams = sizeof(FFCONDITION) * dest->cAxes;
   733          dest->lpvTypeSpecificParams = condition;
   734 
   735          /* Generics */
   736          dest->dwDuration = hap_condition->length * 1000; /* In microseconds. */
   737          dest->dwTriggerButton = FFGetTriggerButton(hap_condition->button);
   738          dest->dwTriggerRepeatInterval = hap_condition->interval;
   739          dest->dwStartDelay = hap_condition->delay * 1000; /* In microseconds. */
   740 
   741          /* Direction. */
   742          if (SDL_SYS_SetDirection(dest, &hap_condition->direction, dest->cAxes) < 0) {
   743             return -1;                
   744          }                            
   745                                       
   746          /* Envelope */
   747 /* TODO Check is envelope actually used.
   748          envelope->dwAttackLevel = CONVERT(hap_condition->attack_level);
   749          envelope->dwAttackTime = hap_condition->attack_length * 1000;
   750          envelope->dwFadeLevel = CONVERT(hap_condition->fade_level);
   751          envelope->dwFadeTime = hap_condition->fade_length * 1000;
   752 */
   753 
   754          break;
   755 
   756       case SDL_HAPTIC_RAMP:
   757          hap_ramp = &src->ramp;
   758          ramp = SDL_malloc(sizeof(FFRAMPFORCE));
   759          if (ramp == NULL) {
   760             SDL_OutOfMemory();
   761             return -1;
   762          }
   763          SDL_memset(ramp, 0, sizeof(FFRAMPFORCE));
   764 
   765          /* Specifics */
   766          ramp->lStart = CONVERT(hap_ramp->start);
   767          ramp->lEnd = CONVERT(hap_ramp->end);
   768          dest->cbTypeSpecificParams = sizeof(FFRAMPFORCE);
   769          dest->lpvTypeSpecificParams = ramp;
   770 
   771          /* Generics */
   772          dest->dwDuration = hap_ramp->length * 1000; /* In microseconds. */
   773          dest->dwTriggerButton = FFGetTriggerButton(hap_ramp->button);
   774          dest->dwTriggerRepeatInterval = hap_ramp->interval;
   775          dest->dwStartDelay = hap_ramp->delay * 1000; /* In microseconds. */
   776 
   777          /* Direction. */
   778          if (SDL_SYS_SetDirection(dest, &hap_ramp->direction, dest->cAxes) < 0) {
   779             return -1;
   780          }
   781 
   782          /* Envelope */
   783          envelope->dwAttackLevel = CONVERT(hap_ramp->attack_level);
   784          envelope->dwAttackTime = hap_ramp->attack_length * 1000;
   785          envelope->dwFadeLevel = CONVERT(hap_ramp->fade_level);
   786          envelope->dwFadeTime = hap_ramp->fade_length * 1000;
   787 
   788          break;
   789 
   790       case SDL_HAPTIC_CUSTOM:
   791          hap_custom = &src->custom;
   792          custom = SDL_malloc(sizeof(FFCUSTOMFORCE));
   793          if (custom == NULL) {
   794             SDL_OutOfMemory();
   795             return -1;
   796          }
   797          SDL_memset(custom, 0, sizeof(FFCUSTOMFORCE));
   798 
   799          /* Specifics */
   800          custom->cChannels = hap_custom->channels;
   801          custom->dwSamplePeriod = hap_custom->period * 1000;
   802          custom->cSamples = hap_custom->samples;
   803          custom->rglForceData = SDL_malloc(sizeof(LONG)*custom->cSamples*custom->cChannels);
   804          for (i=0; i<hap_custom->samples*hap_custom->channels; i++) { /* Copy data. */
   805             custom->rglForceData[i] = CONVERT(hap_custom->data[i]);
   806          }
   807          dest->cbTypeSpecificParams = sizeof(FFCUSTOMFORCE);
   808          dest->lpvTypeSpecificParams = custom;
   809 
   810          /* Generics */
   811          dest->dwDuration = hap_custom->length * 1000; /* In microseconds. */
   812          dest->dwTriggerButton = FFGetTriggerButton(hap_custom->button);
   813          dest->dwTriggerRepeatInterval = hap_custom->interval;
   814          dest->dwStartDelay = hap_custom->delay * 1000; /* In microseconds. */
   815 
   816          /* Direction. */
   817          if (SDL_SYS_SetDirection(dest, &hap_custom->direction, dest->cAxes) < 0) {
   818             return -1;
   819          }
   820          
   821          /* Envelope */
   822          envelope->dwAttackLevel = CONVERT(hap_custom->attack_level);
   823          envelope->dwAttackTime = hap_custom->attack_length * 1000;
   824          envelope->dwFadeLevel = CONVERT(hap_custom->fade_level);
   825          envelope->dwFadeTime = hap_custom->fade_length * 1000;
   826 
   827          break;
   828 
   829 
   830       default:
   831          SDL_SetError("Haptic: Unknown effect type.");
   832          return -1;
   833    }
   834 
   835    return 0;
   836 }
   837 
   838 
   839 /*
   840  * Frees an FFEFFECT allocated by SDL_SYS_ToFFEFFECT.
   841  */
   842 static void
   843 SDL_SYS_HapticFreeFFEFFECT( FFEFFECT * effect, int type )
   844 {
   845    FFCUSTOMFORCE *custom;
   846 
   847    if (effect->lpEnvelope != NULL) {
   848       SDL_free(effect->lpEnvelope);
   849       effect->lpEnvelope = NULL;
   850    }
   851    if (effect->rgdwAxes != NULL) {
   852       SDL_free(effect->rgdwAxes);
   853       effect->rgdwAxes = NULL;
   854    }
   855    if (effect->lpvTypeSpecificParams != NULL) {
   856       if (type == SDL_HAPTIC_CUSTOM) { /* Must free the custom data. */
   857          custom = (FFCUSTOMFORCE*) effect->lpvTypeSpecificParams;
   858          SDL_free(custom->rglForceData);
   859          custom->rglForceData = NULL;
   860       }
   861       SDL_free(effect->lpvTypeSpecificParams);
   862       effect->lpvTypeSpecificParams = NULL;
   863    }
   864    if (effect->rglDirection != NULL) {
   865       SDL_free(effect->rglDirection);
   866       effect->rglDirection = NULL;
   867    }
   868 }
   869 
   870 
   871 /*
   872  * Gets the effect type from the generic SDL haptic effect wrapper.
   873  */
   874 CFUUIDRef
   875 SDL_SYS_HapticEffectType( Uint16 type )
   876 {
   877    switch (type) {
   878       case SDL_HAPTIC_CONSTANT:
   879          return kFFEffectType_ConstantForce_ID;
   880 
   881       case SDL_HAPTIC_RAMP:
   882          return kFFEffectType_RampForce_ID;
   883 
   884       case SDL_HAPTIC_SQUARE:
   885          return kFFEffectType_Square_ID;
   886 
   887       case SDL_HAPTIC_SINE:
   888          return kFFEffectType_Sine_ID;
   889 
   890       case SDL_HAPTIC_TRIANGLE:
   891          return kFFEffectType_Triangle_ID;
   892 
   893       case SDL_HAPTIC_SAWTOOTHUP:
   894          return kFFEffectType_SawtoothUp_ID;
   895 
   896       case SDL_HAPTIC_SAWTOOTHDOWN:
   897          return kFFEffectType_SawtoothDown_ID;
   898 
   899       case SDL_HAPTIC_SPRING:
   900          return kFFEffectType_Spring_ID;
   901 
   902       case SDL_HAPTIC_DAMPER:
   903          return kFFEffectType_Damper_ID;
   904 
   905       case SDL_HAPTIC_INERTIA:
   906          return kFFEffectType_Inertia_ID;
   907 
   908       case SDL_HAPTIC_FRICTION:
   909          return kFFEffectType_Friction_ID;
   910 
   911       case SDL_HAPTIC_CUSTOM:
   912          return kFFEffectType_CustomForce_ID;
   913 
   914       default:
   915          SDL_SetError("Haptic: Unknown effect type.");
   916          return NULL;
   917    }
   918 }
   919 
   920 
   921 /*
   922  * Creates a new haptic effect.
   923  */
   924 int
   925 SDL_SYS_HapticNewEffect(SDL_Haptic * haptic, struct haptic_effect * effect,
   926       SDL_HapticEffect * base)
   927 {
   928    HRESULT ret;
   929    CFUUIDRef type;
   930 
   931    /* Alloc the effect. */
   932    effect->hweffect = (struct haptic_hweffect *)
   933          SDL_malloc(sizeof(struct haptic_hweffect));
   934    if (effect->hweffect == NULL) {
   935       SDL_OutOfMemory();
   936       goto err_hweffect;
   937    }
   938 
   939    /* Get the type. */
   940    type = SDL_SYS_HapticEffectType(base->type);
   941    if (type == NULL) {
   942       goto err_hweffect;
   943    }
   944 
   945    /* Get the effect. */
   946    if (SDL_SYS_ToFFEFFECT(haptic, &effect->hweffect->effect, base) < 0) {
   947       goto err_effectdone;
   948    }
   949 
   950    /* Create the actual effect. */
   951    ret = FFDeviceCreateEffect(haptic->hwdata->device, type,
   952          &effect->hweffect->effect, &effect->hweffect->ref);
   953    if (ret != FF_OK) {
   954       SDL_SetError("Haptic: Unable to create effect: %s.", FFStrError(ret));
   955       goto err_effectdone;
   956    }
   957 
   958    return 0;
   959 
   960 err_effectdone:
   961    SDL_SYS_HapticFreeFFEFFECT(&effect->hweffect->effect, base->type);
   962 err_hweffect:
   963    if (effect->hweffect != NULL) {
   964       SDL_free(effect->hweffect);
   965       effect->hweffect = NULL;
   966    }
   967    return -1;
   968 }
   969 
   970 
   971 /*
   972  * Updates an effect.
   973  */
   974 int
   975 SDL_SYS_HapticUpdateEffect(SDL_Haptic * haptic,
   976       struct haptic_effect * effect, SDL_HapticEffect * data)
   977 {
   978    HRESULT ret;
   979    FFEffectParameterFlag flags;
   980    FFEFFECT temp;
   981 
   982    /* Get the effect. */
   983    SDL_memset(&temp, 0, sizeof(FFEFFECT));
   984    if (SDL_SYS_ToFFEFFECT(haptic, &temp, data) < 0) {
   985       goto err_update;
   986    }
   987 
   988    /* Set the flags.  Might be worthwhile to diff temp with loaded effect and
   989     *  only change those parameters. */
   990    flags = FFEP_ALLPARAMS;
   991 
   992    /* Create the actual effect. */
   993    ret = FFEffectSetParameters(effect->hweffect->ref, &temp, flags);
   994    if (ret != FF_OK) {
   995       SDL_SetError("Haptic: Unable to update effect: %s.", FFStrError(ret));
   996       goto err_update;
   997    }
   998 
   999    /* Copy it over. */
  1000    SDL_SYS_HapticFreeFFEFFECT(&effect->hweffect->effect, data->type);
  1001    SDL_memcpy(&effect->hweffect->effect, &temp, sizeof(FFEFFECT));
  1002 
  1003    return 0;
  1004 
  1005 err_update:
  1006    SDL_SYS_HapticFreeFFEFFECT(&temp, data->type);
  1007    return -1;
  1008 }
  1009 
  1010 
  1011 /*
  1012  * Runs an effect.
  1013  */
  1014 int
  1015 SDL_SYS_HapticRunEffect(SDL_Haptic * haptic, struct haptic_effect * effect,
  1016                         Uint32 iterations)
  1017 {
  1018    HRESULT ret;
  1019    Uint32 iter;
  1020 
  1021    /* Check if it's infinite. */
  1022    if (iterations == SDL_HAPTIC_INFINITY) {
  1023       iter = FF_INFINITE;
  1024    }
  1025    else
  1026       iter = iterations;
  1027 
  1028    /* Run the effect. */
  1029    ret = FFEffectStart(effect->hweffect->ref, iter, 0);
  1030    if (ret != FF_OK) {
  1031       SDL_SetError("Haptic: Unable to run the effect: %s.", FFStrError(ret));
  1032       return -1;
  1033    }
  1034 
  1035    return 0;
  1036 }
  1037 
  1038 
  1039 /*
  1040  * Stops an effect.
  1041  */
  1042 int
  1043 SDL_SYS_HapticStopEffect(SDL_Haptic * haptic, struct haptic_effect * effect)
  1044 {
  1045    HRESULT ret;
  1046 
  1047    ret = FFEffectStop(effect->hweffect->ref);
  1048    if (ret != FF_OK) {
  1049       SDL_SetError("Haptic: Unable to stop the effect: %s.", FFStrError(ret));
  1050       return -1;
  1051    }
  1052 
  1053    return 0;
  1054 }
  1055 
  1056 
  1057 /*
  1058  * Frees the effect.
  1059  */
  1060 void
  1061 SDL_SYS_HapticDestroyEffect(SDL_Haptic * haptic, struct haptic_effect * effect)
  1062 {
  1063    HRESULT ret;
  1064 
  1065    ret = FFDeviceReleaseEffect(haptic->hwdata->device, effect->hweffect->ref);
  1066    if (ret != FF_OK) {
  1067       SDL_SetError("Haptic: Error removing the effect from the device: %s.",
  1068                    FFStrError(ret));
  1069    }
  1070    SDL_free(effect->hweffect->effect.lpvTypeSpecificParams);
  1071    effect->hweffect->effect.lpvTypeSpecificParams = NULL;
  1072    SDL_free(effect->hweffect);
  1073    effect->hweffect = NULL;
  1074 }
  1075 
  1076 
  1077 /*
  1078  * Gets the status of a haptic effect.
  1079  */
  1080 int
  1081 SDL_SYS_HapticGetEffectStatus(SDL_Haptic * haptic, struct haptic_effect * effect)
  1082 {
  1083    HRESULT ret;
  1084    FFEffectStatusFlag status;
  1085 
  1086    ret = FFEffectGetEffectStatus(effect->hweffect->ref, &status);
  1087    if (ret != FF_OK) {
  1088       SDL_SetError("Haptic: Unable to get effect status: %s.", FFStrError(ret));
  1089       return -1;
  1090    }
  1091 
  1092    if (status == 0) return SDL_FALSE;
  1093    return SDL_TRUE; /* Assume it's playing or emulated. */
  1094 }
  1095 
  1096 
  1097 /*
  1098  * Sets the gain.
  1099  */
  1100 int
  1101 SDL_SYS_HapticSetGain(SDL_Haptic * haptic, int gain)
  1102 {
  1103    HRESULT ret;
  1104    Uint32 val;
  1105 
  1106    val = gain * 100; /* Mac OS X uses 0 to 10,000 */
  1107    ret = FFDeviceSetForceFeedbackProperty(haptic->hwdata->device, FFPROP_FFGAIN, &val);
  1108    if (ret != FF_OK) {
  1109       SDL_SetError("Haptic: Error setting gain: %s.", FFStrError(ret));
  1110       return -1;
  1111    }
  1112 
  1113    return 0;
  1114 }
  1115 
  1116 
  1117 /*
  1118  * Sets the autocentering.
  1119  */
  1120 int
  1121 SDL_SYS_HapticSetAutocenter(SDL_Haptic * haptic, int autocenter)
  1122 {
  1123    HRESULT ret;
  1124    Uint32 val;
  1125 
  1126    /* Mac OS X only has 0 (off) and 1 (on) */
  1127    if (autocenter == 0) val = 0;
  1128    else val = 1;
  1129 
  1130    ret = FFDeviceSetForceFeedbackProperty(haptic->hwdata->device,
  1131                FFPROP_AUTOCENTER, &val);
  1132    if (ret != FF_OK) {
  1133       SDL_SetError("Haptic: Error setting autocenter: %s.", FFStrError(ret));
  1134       return -1;
  1135    }
  1136   
  1137    return 0;
  1138 
  1139 }
  1140 
  1141 
  1142 #endif /* SDL_HAPTIC_IOKIT */