25
votes

Games need low-level access to keyboard input. On Windows, there's DirectInput. But what technology do Mac OS X game developers use?

Obviously, there's enough Mac games which get keyboard input just right, without the drawbacks of the commonly known solutions:

Solution #1: Use keyUp / keyDown events

-(void)keyUp:(NSEvent*)event;
-(void)keyDown:(NSEvent*)event;

Inacceptable drawback: keyDown events are repeated based on the system preference settings for "key repeat rate" and "key repeat delay". This causes an initial keyDown event followed by a pause before it starts repeating at a rate defined by a system preference setting. This solution can not be used for continuous key events.

I wonder if the key repeat behavior can be disabled? I suppose that you could read the first keyDown key, then remember the "key with keyCode x is down" state in your class until the keyUp event is received for that key, thus bypassing the repeat delay and repeat rate issues.

Solution #2: Use Quarts Event Taps

See Quartz Event Services Reference. It seems to be sufficiently low-level.

Inacceptable drawback: requires Assistive Devices to be enabled in system preferences under Universal Access - Keyboard. While this may be on by default, there is no guarantee that it might be turned off on some systems.

I also read that Quartz event taps require the app to run as root, but found no confirmation for this.

Solution #3: Carbon Events / IOKit HID

The Carbon Event Manager Reference is marked as legacy and should not be used for new development.

Inacceptable Drawback: no one knows how long the Carbon events will continue to be supported in future Mac OS versions.

Apart from Carbon being a legacy framework, this still seems to be the best solution. But are there any other drawbacks for using Carbon Events?

Questions:

Which technology do Mac OS X game developers use for receiving low-level keyboard input events? If they use one of the above technologies, how do they work around the drawbacks I mentioned?

UPDATE:

I eventually turned to using the regular NSEvent messages and wrapped them in a neat API for polling the keyboard states.

6
Why is the repeat behavior for keyDown: unacceptable? Couldn't you just ignore the additional events until you get a keyUp;?Flyingdiver
I don't really know what the best solution is but regarding the drawback of solution #1 – NSEvent has the isARepeat method to determine whether the event is the result of an automatic key repetition. You could simply ignore those and assume the key is continuously pressed until you receive a corresponding keyUp: event.omz
I added this as a note to solution #1. What I was hoping for is a framework for game developers which would simply allow you to call a method like isKeyDown:(UInt16)virtualKeyCode.LearnCocos2D
regarding #2, found this in the doc: The location of the new event tap. Pass one of the constants listed in Event Tap Locations. Only processes running as the root user may locate an event tap at the point where HID events enter the window server; for other users, this function returns NULL. developer.apple.com/library/mac/documentation/Carbon/Reference/…Bill Yan
regarding #2, yes, I confirmed for certain event types, root privilege is needed. for example, key_down and key_up. I guess the reason is that they don't want a program to monitoring user's key input.Bill Yan

6 Answers

10
votes

I have had good luck with #3, but it requires a lot of heavy lifting if you want to support anything beyond the keyboard.

One quick point before we dive in though, Carbon and IOKit HID are two separate thing. Carbon may go away at some point. But IOKit HID is here to stay and just got a nice facelift in 10.5.

For a full example of how this stuff all fits together, take a look at https://github.com/OpenEmu/OpenEmu/blob/master/OpenEmu/OEHIDManager.m. That is a small piece of the puzzle as there are other files in there as well.

The documentation for what you're wanting to do can be found http://developer.apple.com/library/mac/#documentation/DeviceDrivers/Conceptual/HID/new_api_10_5/tn2187.html

Again, this is not going to disappear anytime soon and is completely separate from Carbon and Carbon Events.

2
votes

I'm late to this party, but here's my solution for an OSX game I'm writing using Swift. It's very simple, and seems to be working pretty well.

First you can put this code in the controller which is receiving keyboard events:

var keysDown = Set<UInt16>()

override func keyDown(e: NSEvent) {
    keysDown.insert(e.keyCode)
}

override func keyUp(e: NSEvent) {
    keysDown.remove(e.keyCode)
}

Then, other parts of the system can determine if a particular key is down:

if (keysDown.contains(49)) {
    // space bar is down
}

Or loop through all the keys which are currently pressed

for char in keysDown {

    switch char {

    case 49:
        // space
        player.jump()
    case 126:
        // up
        player.moveForward()
    case 124:
        // right
        player.turnRight()

        //   ... etc ...

    default:
        // during development I have this line so I can easily see which keys have which codes
        print(char)
    }
}

Note keysDown is a Swift Set, so you don't have to worry about duplicates or ordering. A key is either in the set or it isn't.

I'm not too sure how standardised the keycodes are. But you could offer a keyboard configuration page where the user can type keys for each action, and then save whatever keycode this happened to be.

1
votes

Ok so I'm really late to the party but I think mine is just straight to the point and resembles Mr. Howards solution above. Keep in mind this input is being used to control the camera in a SpriteKit game. This way you get smooth continuous movement and precise stopping.

let moveRight: SKAction = SKAction.repeatForever(SKAction.moveBy(x: -5000, y: 0, duration: 1.5))
...

override func keyDown(with event: NSEvent) {
    camera!.constraints = [] // remove constraints usually added by a cameraComponent.

    let ekc = event.keyCode
    if ekc == 123 { camera!.run(moveLeft, withKey: "moveLeft") }
    if ekc == 124 { camera!.run(moveRight, withKey: "moveRight") }
    if ekc == 126 { camera!.run(moveUp, withKey: "moveUp") }
    if ekc == 125 { camera!.run(moveDown, withKey: "moveDown") }

    print("keyDown: \(event.characters!) keyCode: \(event.keyCode)")
}


override func keyUp(with event: NSEvent) {
    let ekc = event.keyCode
    if ekc == 123 { camera!.removeAction(forKey: "moveLeft") }
    if ekc == 124 { camera!.removeAction(forKey: "moveRight") }
    if ekc == 126 { camera!.removeAction(forKey: "moveUp") }
    if ekc == 125 { camera!.removeAction(forKey: "moveDown") }
}
0
votes

There are also some Device Classes in polkit (Obj-C toolkit) including ...

  • HIDController to use USB HID devices
  • AppleRemote to use the Apple Remote
  • MidiController to use Midi devices
  • OSCController to use OSC compatible devices over UDP
  • SerialPort to use any serial port device
  • SC2004LCDModule to use the SC 2004 from siliconcraft.net

http://code.google.com/p/polkit/

0
votes

I found a very good example of using Quartz Event Taps.

however the problems are:

  1. for certain event types, the user needs to run the application in root privilege. for example intercepting keydown and keyup events requires root.

  2. the interception is system wide, which means when the program runs, it will capture all key events even those sent to other applications. implementation needs to be very careful in order to not to break other applications.