from geometry to pixels

Hacking 3D Touch Support into SDL2

I was playing around with SDL2 recently as it allows for simple cross platform development between desktop OSes (Linux, Windows, MacOS X) and even Android and iOS. Not using the native APIs has the disadvantage that new features are not available instantly and this is also the case for 3D Touch (aka ForceTouch) of the latest iPhone 6s. So let’s change that!

An SDL2 touch event already has a field for pressure, however, on iOS it is always set to 1.0f. Apples UITouch object provides two values: the current pressure and the maximal pressure. To not change the SDL2 events I normalised the pressure from 0.0f to 1.0f – however future devices might be able to detect a larger range of forces and “maximal pressure” (1.0f) on those might be more than the developer intended now. So maybe you want to use both values or the “raw” pressure value in production code – for some quick internal test programs a normalised value was more convenient for me.

If you are using SDL2 on iOS, you will probably already have downloaded the sources and compiled the library with XCode (e.g. using XCode-iOS/SDL/SDL.xcodeproj). Open it up again and replace the file src/video/uikit/SDL_uikitview.m with this version, compile it for the actual device and use the generated library in your projects (I don’t see the need to replace the lib for the simulator until it simulated 3D touch as well, but you can do that). Just as a reminder for myself, the lib will get created in ~/Library/Developer/Xcode/DerivedData/SDL-SOME_STRING/Build/Products/Debug-iphoneos/libSDL2.a (depending on the build settings).

When you compare the hacked file to the original (which was based on SDL 2.0.3), you will see, that it’s simple to get the force added: Look for all calls to SDL_SendTouchMotion and SDL_SendTouch, those will generate the SDL events and so far always reported a force of 1.0f. You can get the force from the UITouch event quite simple: float pressure = [touch force] / (float)[touch maximumPossibleForce]; Those are also the lines you want to change if you like to get the unnormalised force.

Note that this hack requires iOS 9.0 or later.

, ,

Leave a Reply

Your email address will not be published. Required fields are marked *