Fix analog axis scaling equation.
[enjoyable.git] / JSActionAnalog.m
1 //
2 // JSActionAnalog.m
3 // Enjoy
4 //
5 // Created by Sam McCall on 5/05/09.
6 //
7
8 // TODO: Dead zone should be configurable per-device.
9 #define DEAD_ZONE 0.3
10
11 #import "JSActionAnalog.h"
12
13 static float normalize(int p, int min, int max) {
14 return 2 * (p - min) / (float)(max - min) - 1;
15 }
16
17 @implementation JSActionAnalog {
18 float magnitude;
19 int rawMin;
20 int rawMax;
21 }
22
23 - (id)initWithIndex:(int)index rawMin:(int)rawMin_ rawMax:(int)rawMax_ {
24 if ((self = [super init])) {
25 self.name = [[NSString alloc] initWithFormat: @"Axis %d", index];
26 self.children = @[[[JSAction alloc] initWithName:@"Low" base:self],
27 [[JSAction alloc] initWithName:@"High" base:self]];
28 rawMax = rawMax_;
29 rawMin = rawMin_;
30 }
31 return self;
32 }
33
34 - (id)findSubActionForValue:(IOHIDValueRef)value {
35 float mag = normalize(IOHIDValueGetIntegerValue(value), rawMin, rawMax);
36 if (mag < -DEAD_ZONE)
37 return self.children[0];
38 else if (mag > DEAD_ZONE)
39 return self.children[1];
40 else
41 return nil;
42 }
43
44 - (void)notifyEvent:(IOHIDValueRef)value {
45 magnitude = normalize(IOHIDValueGetIntegerValue(value), rawMin, rawMax);
46 [self.children[0] setActive:magnitude < -DEAD_ZONE];
47 [self.children[1] setActive:magnitude > DEAD_ZONE];
48 }
49
50 - (float)magnitude {
51 return magnitude;
52 }
53
54 @end