src/haptic/darwin/SDL_syshaptic.c
author Edgar Simo <bobbens@gmail.com>
Wed, 30 Jul 2008 14:50:00 +0000
branchgsoc2008_force_feedback
changeset 2555 f5bcc926bac4
parent 2554 2681a04c2d3d
child 2556 fe346eddd3fb
permissions -rw-r--r--
Not being able to compile locally gets on my nerves.
     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 (button != 0) {
   527       dwTriggerButton = FFJOFS_BUTTON(button);
   528    }
   529 
   530    return dwTriggerButton;
   531 }
   532 
   533 
   534 /*
   535  * Sets the direction.
   536  */
   537 static int
   538 SDL_SYS_SetDirection( FFEFFECT * effect, SDL_HapticDirection *dir, int naxes )
   539 {
   540    LONG *rglDir;
   541 
   542    /* Handle no axes a part. */
   543    if (naxes == 0) {
   544       effect->rglDirection = NULL;
   545       return 0;
   546    }
   547 
   548    /* Has axes. */
   549    rglDir = SDL_malloc( sizeof(LONG) * naxes );
   550    if (rglDir == NULL) {
   551       SDL_OutOfMemory();
   552       return -1;
   553    }
   554    SDL_memset( rglDir, 0, sizeof(LONG) * naxes );
   555    effect->rglDirection = rglDir;
   556 
   557    switch (dir->type) {
   558       case SDL_HAPTIC_POLAR:
   559          effect->dwFlags |= FFEFF_POLAR;
   560          rglDir[0] = dir->dir[0];
   561          return 0;
   562       case SDL_HAPTIC_CARTESIAN:
   563          effect->dwFlags |= FFEFF_CARTESIAN;
   564          rglDir[0] = dir->dir[0];
   565          rglDir[1] = dir->dir[1];
   566          rglDir[2] = dir->dir[2];
   567          return 0;
   568       case SDL_HAPTIC_SPHERICAL:
   569          effect->dwFlags |= FFEFF_SPHERICAL;
   570          rglDir[0] = dir->dir[0];
   571          rglDir[1] = dir->dir[1];
   572          rglDir[2] = dir->dir[2];
   573          return 0;
   574 
   575       default:
   576          SDL_SetError("Haptic: Unknown direction type.");
   577          return -1;
   578    }
   579 }
   580 
   581 #define CONVERT(x)   (((x)*10000) / 0xFFFF )
   582 /*
   583  * Creates the FFEFFECT from a SDL_HapticEffect.
   584  */
   585 static int
   586 SDL_SYS_ToFFEFFECT( SDL_Haptic * haptic, FFEFFECT * dest, SDL_HapticEffect * src )
   587 {
   588    int i;
   589    FFCONSTANTFORCE *constant;
   590    FFPERIODIC *periodic;
   591    FFCONDITION *condition; /* Actually an array of conditions - one per axis. */
   592    FFRAMPFORCE *ramp;
   593    FFCUSTOMFORCE *custom;
   594    FFENVELOPE *envelope;
   595    SDL_HapticConstant *hap_constant;
   596    SDL_HapticPeriodic *hap_periodic;
   597    SDL_HapticCondition *hap_condition;
   598    SDL_HapticRamp *hap_ramp;
   599    SDL_HapticCustom *hap_custom;
   600    DWORD *axes;
   601 
   602    /* Set global stuff. */
   603    SDL_memset(dest, 0, sizeof(FFEFFECT));
   604    dest->dwSize = sizeof(FFEFFECT); /* Set the structure size. */
   605    dest->dwSamplePeriod = 0; /* Not used by us. */
   606    dest->dwGain = 10000; /* Gain is set globally, not locally. */
   607 
   608    /* Envelope. */
   609    envelope = SDL_malloc( sizeof(FFENVELOPE) );
   610    if (envelope == NULL) {
   611       SDL_OutOfMemory();
   612       return -1;
   613    }
   614    SDL_memset(envelope, 0, sizeof(FFENVELOPE));
   615    dest->lpEnvelope = envelope;
   616    envelope->dwSize = sizeof(FFENVELOPE); /* Always should be this. */
   617 
   618    /* Axes. */
   619    dest->cAxes = haptic->naxes;
   620    if (dest->cAxes > 0) {
   621       axes = SDL_malloc(sizeof(DWORD) * dest->cAxes);
   622       if (axes == NULL) {
   623          SDL_OutOfMemory();
   624          return -1;
   625       }
   626       axes[0] = FFJOFS_X; /* Always at least one axis. */
   627       if (dest->cAxes > 1) {
   628          axes[1] = FFJOFS_Y;
   629       }
   630       if (dest->cAxes > 2) {
   631          axes[2] = FFJOFS_Z;
   632       }
   633       dest->rgdwAxes = axes;
   634    }
   635 
   636 
   637    /* The big type handling switch, even bigger then linux's version. */
   638    switch (src->type) {
   639       case SDL_HAPTIC_CONSTANT:
   640          hap_constant = &src->constant;
   641          constant = SDL_malloc( sizeof(FFCONSTANTFORCE) );
   642          if (constant == NULL) {
   643             SDL_OutOfMemory();
   644             return -1;
   645          }
   646          SDL_memset(constant, 0, sizeof(FFCONSTANTFORCE));
   647 
   648          /* Specifics */
   649          constant->lMagnitude = CONVERT(hap_constant->level);
   650          dest->cbTypeSpecificParams = sizeof(FFCONSTANTFORCE); 
   651          dest->lpvTypeSpecificParams = constant;
   652 
   653          /* Generics */
   654          dest->dwDuration = hap_constant->length * 1000; /* In microseconds. */
   655          dest->dwTriggerButton = FFGetTriggerButton(hap_constant->button);
   656          dest->dwTriggerRepeatInterval = hap_constant->interval;
   657          dest->dwStartDelay = hap_constant->delay * 1000; /* In microseconds. */
   658 
   659          /* Direction. */
   660          if (SDL_SYS_SetDirection(dest, &hap_constant->direction, dest->cAxes) < 0) {
   661             return -1;
   662          }
   663          
   664          /* Envelope */
   665          envelope->dwAttackLevel = CONVERT(hap_constant->attack_level);
   666          envelope->dwAttackTime = hap_constant->attack_length * 1000;
   667          envelope->dwFadeLevel = CONVERT(hap_constant->fade_level);
   668          envelope->dwFadeTime = hap_constant->fade_length * 1000;
   669 
   670          break;
   671 
   672       case SDL_HAPTIC_SINE:
   673       case SDL_HAPTIC_SQUARE:
   674       case SDL_HAPTIC_TRIANGLE:
   675       case SDL_HAPTIC_SAWTOOTHUP:
   676       case SDL_HAPTIC_SAWTOOTHDOWN:
   677          hap_periodic = &src->periodic;
   678          periodic = SDL_malloc(sizeof(FFPERIODIC));
   679          if (periodic == NULL) {
   680             SDL_OutOfMemory();
   681             return -1;
   682          }
   683          SDL_memset(periodic, 0, sizeof(FFPERIODIC));
   684 
   685          /* Specifics */
   686          periodic->dwMagnitude = CONVERT(hap_periodic->magnitude);
   687          periodic->lOffset = CONVERT(hap_periodic->offset);
   688          periodic->dwPhase = hap_periodic->phase;
   689          periodic->dwPeriod = hap_periodic->period * 1000;
   690          dest->cbTypeSpecificParams = sizeof(FFPERIODIC);
   691          dest->lpvTypeSpecificParams = periodic;
   692 
   693          /* Generics */
   694          dest->dwDuration = hap_periodic->length * 1000; /* In microseconds. */
   695          dest->dwTriggerButton = FFGetTriggerButton(hap_periodic->button);
   696          dest->dwTriggerRepeatInterval = hap_periodic->interval;
   697          dest->dwStartDelay = hap_periodic->delay * 1000; /* In microseconds. */
   698          
   699          /* Direction. */
   700          if (SDL_SYS_SetDirection(dest, &hap_periodic->direction, dest->cAxes) < 0) {
   701             return -1;
   702          }
   703          
   704          /* Envelope */
   705          envelope->dwAttackLevel = CONVERT(hap_periodic->attack_level);
   706          envelope->dwAttackTime = hap_periodic->attack_length * 1000;
   707          envelope->dwFadeLevel = CONVERT(hap_periodic->fade_level);
   708          envelope->dwFadeTime = hap_periodic->fade_length * 1000;
   709 
   710          break;
   711 
   712       case SDL_HAPTIC_SPRING:
   713       case SDL_HAPTIC_DAMPER:
   714       case SDL_HAPTIC_INERTIA:
   715       case SDL_HAPTIC_FRICTION:
   716          hap_condition = &src->condition;
   717          condition = SDL_malloc(sizeof(FFCONDITION) * dest->cAxes);
   718          if (condition == NULL) {
   719             SDL_OutOfMemory();
   720             return -1;
   721          }
   722          SDL_memset(condition, 0, sizeof(FFCONDITION));
   723 
   724          /* Specifics */
   725          for (i=0; i<dest->cAxes; i++) {
   726             condition[i].lOffset = CONVERT(hap_condition->center[i]);
   727             condition[i].lPositiveCoefficient = CONVERT(hap_condition->right_coeff[i]);
   728             condition[i].lNegativeCoefficient = CONVERT(hap_condition->left_coeff[i]);
   729             condition[i].dwPositiveSaturation = CONVERT(hap_condition->right_sat[i]);
   730             condition[i].dwNegativeSaturation = CONVERT(hap_condition->left_sat[i]);
   731             condition[i].lDeadBand = CONVERT(hap_condition->deadband[i]);
   732          }
   733          dest->cbTypeSpecificParams = sizeof(FFCONDITION) * dest->cAxes;
   734          dest->lpvTypeSpecificParams = condition;
   735 
   736          /* Generics */
   737          dest->dwDuration = hap_condition->length * 1000; /* In microseconds. */
   738          dest->dwTriggerButton = FFGetTriggerButton(hap_condition->button);
   739          dest->dwTriggerRepeatInterval = hap_condition->interval;
   740          dest->dwStartDelay = hap_condition->delay * 1000; /* In microseconds. */
   741 
   742          /* Direction. */
   743          if (SDL_SYS_SetDirection(dest, &hap_condition->direction, dest->cAxes) < 0) {
   744             return -1;                
   745          }                            
   746                                       
   747          /* Envelope */
   748 /* TODO Check is envelope actually used.
   749          envelope->dwAttackLevel = CONVERT(hap_condition->attack_level);
   750          envelope->dwAttackTime = hap_condition->attack_length * 1000;
   751          envelope->dwFadeLevel = CONVERT(hap_condition->fade_level);
   752          envelope->dwFadeTime = hap_condition->fade_length * 1000;
   753 */
   754 
   755          break;
   756 
   757       case SDL_HAPTIC_RAMP:
   758          hap_ramp = &src->ramp;
   759          ramp = SDL_malloc(sizeof(FFRAMPFORCE));
   760          if (ramp == NULL) {
   761             SDL_OutOfMemory();
   762             return -1;
   763          }
   764          SDL_memset(ramp, 0, sizeof(FFRAMPFORCE));
   765 
   766          /* Specifics */
   767          ramp->lStart = CONVERT(hap_ramp->start);
   768          ramp->lEnd = CONVERT(hap_ramp->end);
   769          dest->cbTypeSpecificParams = sizeof(FFRAMPFORCE);
   770          dest->lpvTypeSpecificParams = ramp;
   771 
   772          /* Generics */
   773          dest->dwDuration = hap_ramp->length * 1000; /* In microseconds. */
   774          dest->dwTriggerButton = FFGetTriggerButton(hap_ramp->button);
   775          dest->dwTriggerRepeatInterval = hap_ramp->interval;
   776          dest->dwStartDelay = hap_ramp->delay * 1000; /* In microseconds. */
   777 
   778          /* Direction. */
   779          if (SDL_SYS_SetDirection(dest, &hap_ramp->direction, dest->cAxes) < 0) {
   780             return -1;
   781          }
   782 
   783          /* Envelope */
   784          envelope->dwAttackLevel = CONVERT(hap_ramp->attack_level);
   785          envelope->dwAttackTime = hap_ramp->attack_length * 1000;
   786          envelope->dwFadeLevel = CONVERT(hap_ramp->fade_level);
   787          envelope->dwFadeTime = hap_ramp->fade_length * 1000;
   788 
   789          break;
   790 
   791       case SDL_HAPTIC_CUSTOM:
   792          hap_custom = &src->custom;
   793          custom = SDL_malloc(sizeof(FFCUSTOMFORCE));
   794          if (custom == NULL) {
   795             SDL_OutOfMemory();
   796             return -1;
   797          }
   798          SDL_memset(custom, 0, sizeof(FFCUSTOMFORCE));
   799 
   800          /* Specifics */
   801          custom->cChannels = hap_custom->channels;
   802          custom->dwSamplePeriod = hap_custom->period * 1000;
   803          custom->cSamples = hap_custom->samples;
   804          custom->rglForceData = SDL_malloc(sizeof(LONG)*custom->cSamples*custom->cChannels);
   805          for (i=0; i<hap_custom->samples*hap_custom->channels; i++) { /* Copy data. */
   806             custom->rglForceData[i] = CONVERT(hap_custom->data[i]);
   807          }
   808          dest->cbTypeSpecificParams = sizeof(FFCUSTOMFORCE);
   809          dest->lpvTypeSpecificParams = custom;
   810 
   811          /* Generics */
   812          dest->dwDuration = hap_custom->length * 1000; /* In microseconds. */
   813          dest->dwTriggerButton = FFGetTriggerButton(hap_custom->button);
   814          dest->dwTriggerRepeatInterval = hap_custom->interval;
   815          dest->dwStartDelay = hap_custom->delay * 1000; /* In microseconds. */
   816 
   817          /* Direction. */
   818          if (SDL_SYS_SetDirection(dest, &hap_custom->direction, dest->cAxes) < 0) {
   819             return -1;
   820          }
   821          
   822          /* Envelope */
   823          envelope->dwAttackLevel = CONVERT(hap_custom->attack_level);
   824          envelope->dwAttackTime = hap_custom->attack_length * 1000;
   825          envelope->dwFadeLevel = CONVERT(hap_custom->fade_level);
   826          envelope->dwFadeTime = hap_custom->fade_length * 1000;
   827 
   828          break;
   829 
   830 
   831       default:
   832          SDL_SetError("Haptic: Unknown effect type.");
   833          return -1;
   834    }
   835 
   836    return 0;
   837 }
   838 
   839 
   840 /*
   841  * Frees an FFEFFECT allocated by SDL_SYS_ToFFEFFECT.
   842  */
   843 static void
   844 SDL_SYS_HapticFreeFFEFFECT( FFEFFECT * effect, int type )
   845 {
   846    FFCUSTOMFORCE *custom;
   847 
   848    if (effect->lpEnvelope != NULL) {
   849       SDL_free(effect->lpEnvelope);
   850       effect->lpEnvelope = NULL;
   851    }
   852    if (effect->rgdwAxes != NULL) {
   853       SDL_free(effect->rgdwAxes);
   854       effect->rgdwAxes = NULL;
   855    }
   856    if (effect->lpvTypeSpecificParams != NULL) {
   857       if (type == SDL_HAPTIC_CUSTOM) { /* Must free the custom data. */
   858          custom = (FFCUSTOMFORCE*) effect->lpvTypeSpecificParams;
   859          SDL_free(custom->rglForceData);
   860          custom->rglForceData = NULL;
   861       }
   862       SDL_free(effect->lpvTypeSpecificParams);
   863       effect->lpvTypeSpecificParams = NULL;
   864    }
   865    if (effect->rglDirection != NULL) {
   866       SDL_free(effect->rglDirection);
   867       effect->rglDirection = NULL;
   868    }
   869 }
   870 
   871 
   872 /*
   873  * Gets the effect type from the generic SDL haptic effect wrapper.
   874  */
   875 CFUUIDRef
   876 SDL_SYS_HapticEffectType( Uint16 type )
   877 {
   878    switch (type) {
   879       case SDL_HAPTIC_CONSTANT:
   880          return kFFEffectType_ConstantForce_ID;
   881 
   882       case SDL_HAPTIC_RAMP:
   883          return kFFEffectType_RampForce_ID;
   884 
   885       case SDL_HAPTIC_SQUARE:
   886          return kFFEffectType_Square_ID;
   887 
   888       case SDL_HAPTIC_SINE:
   889          return kFFEffectType_Sine_ID;
   890 
   891       case SDL_HAPTIC_TRIANGLE:
   892          return kFFEffectType_Triangle_ID;
   893 
   894       case SDL_HAPTIC_SAWTOOTHUP:
   895          return kFFEffectType_SawtoothUp_ID;
   896 
   897       case SDL_HAPTIC_SAWTOOTHDOWN:
   898          return kFFEffectType_SawtoothDown_ID;
   899 
   900       case SDL_HAPTIC_SPRING:
   901          return kFFEffectType_Spring_ID;
   902 
   903       case SDL_HAPTIC_DAMPER:
   904          return kFFEffectType_Damper_ID;
   905 
   906       case SDL_HAPTIC_INERTIA:
   907          return kFFEffectType_Inertia_ID;
   908 
   909       case SDL_HAPTIC_FRICTION:
   910          return kFFEffectType_Friction_ID;
   911 
   912       case SDL_HAPTIC_CUSTOM:
   913          return kFFEffectType_CustomForce_ID;
   914 
   915       default:
   916          SDL_SetError("Haptic: Unknown effect type.");
   917          return NULL;
   918    }
   919 }
   920 
   921 
   922 /*
   923  * Creates a new haptic effect.
   924  */
   925 int
   926 SDL_SYS_HapticNewEffect(SDL_Haptic * haptic, struct haptic_effect * effect,
   927       SDL_HapticEffect * base)
   928 {
   929    HRESULT ret;
   930    CFUUIDRef type;
   931 
   932    /* Alloc the effect. */
   933    effect->hweffect = (struct haptic_hweffect *)
   934          SDL_malloc(sizeof(struct haptic_hweffect));
   935    if (effect->hweffect == NULL) {
   936       SDL_OutOfMemory();
   937       goto err_hweffect;
   938    }
   939 
   940    /* Get the type. */
   941    type = SDL_SYS_HapticEffectType(base->type);
   942    if (type == NULL) {
   943       goto err_hweffect;
   944    }
   945 
   946    /* Get the effect. */
   947    if (SDL_SYS_ToFFEFFECT(haptic, &effect->hweffect->effect, base) < 0) {
   948       goto err_effectdone;
   949    }
   950 
   951    /* Create the actual effect. */
   952    ret = FFDeviceCreateEffect(haptic->hwdata->device, type,
   953          &effect->hweffect->effect, &effect->hweffect->ref);
   954    if (ret != FF_OK) {
   955       SDL_SetError("Haptic: Unable to create effect: %s.", FFStrError(ret));
   956       goto err_effectdone;
   957    }
   958 
   959    return 0;
   960 
   961 err_effectdone:
   962    SDL_SYS_HapticFreeFFEFFECT(&effect->hweffect->effect, base->type);
   963 err_hweffect:
   964    if (effect->hweffect != NULL) {
   965       SDL_free(effect->hweffect);
   966       effect->hweffect = NULL;
   967    }
   968    return -1;
   969 }
   970 
   971 
   972 /*
   973  * Updates an effect.
   974  */
   975 int
   976 SDL_SYS_HapticUpdateEffect(SDL_Haptic * haptic,
   977       struct haptic_effect * effect, SDL_HapticEffect * data)
   978 {
   979    HRESULT ret;
   980    FFEffectParameterFlag flags;
   981    FFEFFECT temp;
   982 
   983    /* Get the effect. */
   984    SDL_memset(&temp, 0, sizeof(FFEFFECT));
   985    if (SDL_SYS_ToFFEFFECT(haptic, &temp, data) < 0) {
   986       goto err_update;
   987    }
   988 
   989    /* Set the flags.  Might be worthwhile to diff temp with loaded effect and
   990     *  only change those parameters. */
   991    flags = FFEP_ALLPARAMS;
   992 
   993    /* Create the actual effect. */
   994    ret = FFEffectSetParameters(effect->hweffect->ref, &temp, flags);
   995    if (ret != FF_OK) {
   996       SDL_SetError("Haptic: Unable to update effect: %s.", FFStrError(ret));
   997       goto err_update;
   998    }
   999 
  1000    /* Copy it over. */
  1001    SDL_SYS_HapticFreeFFEFFECT(&effect->hweffect->effect, data->type);
  1002    SDL_memcpy(&effect->hweffect->effect, &temp, sizeof(FFEFFECT));
  1003 
  1004    return 0;
  1005 
  1006 err_update:
  1007    SDL_SYS_HapticFreeFFEFFECT(&temp, data->type);
  1008    return -1;
  1009 }
  1010 
  1011 
  1012 /*
  1013  * Runs an effect.
  1014  */
  1015 int
  1016 SDL_SYS_HapticRunEffect(SDL_Haptic * haptic, struct haptic_effect * effect,
  1017                         Uint32 iterations)
  1018 {
  1019    HRESULT ret;
  1020    Uint32 iter;
  1021 
  1022    /* Check if it's infinite. */
  1023    if (iterations == SDL_HAPTIC_INFINITY) {
  1024       iter = FF_INFINITE;
  1025    }
  1026    else
  1027       iter = iterations;
  1028 
  1029    /* Run the effect. */
  1030    ret = FFEffectStart(effect->hweffect->ref, iter, 0);
  1031    if (ret != FF_OK) {
  1032       SDL_SetError("Haptic: Unable to run the effect: %s.", FFStrError(ret));
  1033       return -1;
  1034    }
  1035 
  1036    return 0;
  1037 }
  1038 
  1039 
  1040 /*
  1041  * Stops an effect.
  1042  */
  1043 int
  1044 SDL_SYS_HapticStopEffect(SDL_Haptic * haptic, struct haptic_effect * effect)
  1045 {
  1046    HRESULT ret;
  1047 
  1048    ret = FFEffectStop(effect->hweffect->ref);
  1049    if (ret != FF_OK) {
  1050       SDL_SetError("Haptic: Unable to stop the effect: %s.", FFStrError(ret));
  1051       return -1;
  1052    }
  1053 
  1054    return 0;
  1055 }
  1056 
  1057 
  1058 /*
  1059  * Frees the effect.
  1060  */
  1061 void
  1062 SDL_SYS_HapticDestroyEffect(SDL_Haptic * haptic, struct haptic_effect * effect)
  1063 {
  1064    HRESULT ret;
  1065 
  1066    ret = FFDeviceReleaseEffect(haptic->hwdata->device, effect->hweffect->ref);
  1067    if (ret != FF_OK) {
  1068       SDL_SetError("Haptic: Error removing the effect from the device: %s.",
  1069                    FFStrError(ret));
  1070    }
  1071    SDL_free(effect->hweffect->effect.lpvTypeSpecificParams);
  1072    effect->hweffect->effect.lpvTypeSpecificParams = NULL;
  1073    SDL_free(effect->hweffect);
  1074    effect->hweffect = NULL;
  1075 }
  1076 
  1077 
  1078 /*
  1079  * Gets the status of a haptic effect.
  1080  */
  1081 int
  1082 SDL_SYS_HapticGetEffectStatus(SDL_Haptic * haptic, struct haptic_effect * effect)
  1083 {
  1084    HRESULT ret;
  1085    FFEffectStatusFlag status;
  1086 
  1087    ret = FFEffectGetEffectStatus(effect->hweffect->ref, &status);
  1088    if (ret != FF_OK) {
  1089       SDL_SetError("Haptic: Unable to get effect status: %s.", FFStrError(ret));
  1090       return -1;
  1091    }
  1092 
  1093    if (status == 0) return SDL_FALSE;
  1094    return SDL_TRUE; /* Assume it's playing or emulated. */
  1095 }
  1096 
  1097 
  1098 /*
  1099  * Sets the gain.
  1100  */
  1101 int
  1102 SDL_SYS_HapticSetGain(SDL_Haptic * haptic, int gain)
  1103 {
  1104    HRESULT ret;
  1105    Uint32 val;
  1106 
  1107    val = gain * 100; /* Mac OS X uses 0 to 10,000 */
  1108    ret = FFDeviceSetForceFeedbackProperty(haptic->hwdata->device, FFPROP_FFGAIN, &val);
  1109    if (ret != FF_OK) {
  1110       SDL_SetError("Haptic: Error setting gain: %s.", FFStrError(ret));
  1111       return -1;
  1112    }
  1113 
  1114    return 0;
  1115 }
  1116 
  1117 
  1118 /*
  1119  * Sets the autocentering.
  1120  */
  1121 int
  1122 SDL_SYS_HapticSetAutocenter(SDL_Haptic * haptic, int autocenter)
  1123 {
  1124    HRESULT ret;
  1125    Uint32 val;
  1126 
  1127    /* Mac OS X only has 0 (off) and 1 (on) */
  1128    if (autocenter == 0) val = 0;
  1129    else val = 1;
  1130 
  1131    ret = FFDeviceSetForceFeedbackProperty(haptic->hwdata->device,
  1132                FFPROP_AUTOCENTER, &val);
  1133    if (ret != FF_OK) {
  1134       SDL_SetError("Haptic: Error setting autocenter: %s.", FFStrError(ret));
  1135       return -1;
  1136    }
  1137   
  1138    return 0;
  1139 
  1140 }
  1141 
  1142 
  1143 #endif /* SDL_HAPTIC_IOKIT */