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