iPhone_Sensors.mm 35 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168
  1. #define SIMULATE_ATTITUDE_FROM_GRAVITY 1
  2. #import "iPhone_Sensors.h"
  3. #if UNITY_USES_LOCATION
  4. #import <CoreLocation/CoreLocation.h>
  5. #endif
  6. #if !PLATFORM_TVOS
  7. #import <CoreMotion/CoreMotion.h>
  8. #endif
  9. #import <GameController/GameController.h>
  10. #include "OrientationSupport.h"
  11. #include "Unity/UnityInterface.h"
  12. #include "Vector3.h"
  13. #include "Quaternion4.h"
  14. extern "C" void il2cpp_init(void);
  15. __attribute__((retain)) void keepCallAgainstIL2CPP() {
  16. // todo move to more propper location
  17. // here just to ensures LD will 'see' il2cpp.a and export il2cpp symbols from UnityFramework binary
  18. // keepCallAgainstIL2CPP wont be called
  19. il2cpp_init();
  20. }
  21. typedef void (^ControllerPausedHandler)(GCController *controller);
  22. static NSArray* QueryControllerCollection();
  23. #if PLATFORM_TVOS
  24. static bool gTVRemoteTouchesEnabled = true;
  25. static bool gTVRemoteAllowRotationInitialValue = false;
  26. static bool gTVRemoteReportsAbsoluteDpadValuesInitialValue = false;
  27. static int gTVControllerUserInteractionEnabled = 0;
  28. #endif
  29. static bool gCompensateSensors = true;
  30. bool gEnableGyroscope = false;
  31. extern "C" void UnityEnableGyroscope(bool value) { gEnableGyroscope = value; }
  32. static bool gJoysticksInited = false;
  33. #define MAX_JOYSTICKS 4
  34. static bool gPausedJoysticks[MAX_JOYSTICKS] = {false, false, false, false};
  35. static id gGameControllerClass = nil;
  36. // This defines the number of maximum acceleration events Unity will queue internally for scripts to access.
  37. UNITY_EXPORT extern "C" int UnityMaxQueuedAccelerationEvents() { return 2 * 60; } // 120 events or 2 seconds at 60Hz reporting.
  38. static ControllerPausedHandler gControllerHandler = ^(GCController *controller)
  39. {
  40. NSArray* list = QueryControllerCollection();
  41. if (list != nil)
  42. {
  43. NSUInteger idx = [list indexOfObject: controller];
  44. if (idx < MAX_JOYSTICKS)
  45. {
  46. gPausedJoysticks[idx] = !gPausedJoysticks[idx];
  47. }
  48. }
  49. };
  50. UNITY_EXPORT extern "C" bool IsCompensatingSensors() { return gCompensateSensors; }
  51. UNITY_EXPORT extern "C" void SetCompensatingSensors(bool val) { gCompensateSensors = val; }
  52. inline float UnityReorientHeading(float heading)
  53. {
  54. if (IsCompensatingSensors())
  55. {
  56. float rotateBy = 0.f;
  57. switch (UnityCurrentOrientation())
  58. {
  59. case portraitUpsideDown:
  60. rotateBy = -180.f;
  61. break;
  62. case landscapeLeft:
  63. rotateBy = -270.f;
  64. break;
  65. case landscapeRight:
  66. rotateBy = -90.f;
  67. break;
  68. default:
  69. break;
  70. }
  71. return fmodf((360.f + heading + rotateBy), 360.f);
  72. }
  73. else
  74. {
  75. return heading;
  76. }
  77. }
  78. inline Vector3f UnityReorientVector3(float x, float y, float z)
  79. {
  80. if (IsCompensatingSensors())
  81. {
  82. Vector3f res;
  83. switch (UnityCurrentOrientation())
  84. {
  85. case portraitUpsideDown:
  86. { res = (Vector3f) {-x, -y, z}; }
  87. break;
  88. case landscapeLeft:
  89. { res = (Vector3f) {-y, x, z}; }
  90. break;
  91. case landscapeRight:
  92. { res = (Vector3f) {y, -x, z}; }
  93. break;
  94. default:
  95. { res = (Vector3f) {x, y, z}; }
  96. }
  97. return res;
  98. }
  99. else
  100. {
  101. return (Vector3f) {x, y, z};
  102. }
  103. }
  104. inline Quaternion4f UnityReorientQuaternion(float x, float y, float z, float w)
  105. {
  106. if (IsCompensatingSensors())
  107. {
  108. Quaternion4f res, inp = {x, y, z, w};
  109. switch (UnityCurrentOrientation())
  110. {
  111. case landscapeLeft:
  112. QuatMultiply(res, inp, gQuatRot[1]);
  113. break;
  114. case portraitUpsideDown:
  115. QuatMultiply(res, inp, gQuatRot[2]);
  116. break;
  117. case landscapeRight:
  118. QuatMultiply(res, inp, gQuatRot[3]);
  119. break;
  120. default:
  121. res = inp;
  122. }
  123. return res;
  124. }
  125. else
  126. {
  127. return (Quaternion4f) {x, y, z, w};
  128. }
  129. }
  130. #if PLATFORM_TVOS
  131. static bool sGCMotionForwardingEnabled = false;
  132. static bool sGCMotionForwardedForCurrentFrame = false;
  133. #else
  134. static CMMotionManager* sMotionManager = nil;
  135. static NSOperationQueue* sMotionQueue = nil;
  136. #endif
  137. // Current update interval or 0.0f if not initialized. This is returned
  138. // to the user as current update interval and this value is set to 0.0f when
  139. // gyroscope is disabled.
  140. static float sUpdateInterval = 0.0f;
  141. // Update interval set by the user. Core motion will be set-up to use
  142. // this update interval after disabling and re-enabling gyroscope
  143. // so users can set update interval, disable gyroscope, enable gyroscope and
  144. // after that gyroscope will be updated at this previously set interval.
  145. #if !PLATFORM_TVOS
  146. static float sUserUpdateInterval = 1.0f / 30.0f;
  147. #endif
  148. void SensorsCleanup()
  149. {
  150. #if !PLATFORM_TVOS
  151. if (sMotionManager != nil)
  152. {
  153. [sMotionManager stopGyroUpdates];
  154. [sMotionManager stopDeviceMotionUpdates];
  155. [sMotionManager stopAccelerometerUpdates];
  156. sMotionManager = nil;
  157. }
  158. sMotionQueue = nil;
  159. #endif
  160. }
  161. UNITY_EXPORT extern "C" void UnityCoreMotionStart()
  162. {
  163. #if PLATFORM_TVOS
  164. sGCMotionForwardingEnabled = true;
  165. #else
  166. if (sMotionQueue == nil)
  167. sMotionQueue = [[NSOperationQueue alloc] init];
  168. bool initMotionManager = (sMotionManager == nil);
  169. if (initMotionManager)
  170. sMotionManager = [[CMMotionManager alloc] init];
  171. // iOS might get confused if we repeatedly enable gyroscope/motions
  172. // so we take into account the current state
  173. if (gEnableGyroscope && !sMotionManager.gyroActive && sMotionManager.gyroAvailable)
  174. {
  175. [sMotionManager startGyroUpdates];
  176. [sMotionManager setGyroUpdateInterval: sUpdateInterval];
  177. }
  178. if (gEnableGyroscope && !sMotionManager.deviceMotionActive && sMotionManager.deviceMotionAvailable)
  179. {
  180. [sMotionManager startDeviceMotionUpdates];
  181. [sMotionManager setDeviceMotionUpdateInterval: sUpdateInterval];
  182. }
  183. // we (ab)use UnityCoreMotionStart to both init sensors and restart gyro
  184. // make sure we touch accelerometer only on init
  185. if (initMotionManager && sMotionManager.accelerometerAvailable)
  186. {
  187. const int frequency = UnityGetAccelerometerFrequency();
  188. if (frequency > 0)
  189. {
  190. sMotionManager.accelerometerUpdateInterval = 1.0f / frequency;
  191. [sMotionManager startAccelerometerUpdates];
  192. }
  193. }
  194. #endif
  195. }
  196. UNITY_EXPORT extern "C" void UnityCoreMotionStop()
  197. {
  198. #if PLATFORM_TVOS
  199. sGCMotionForwardingEnabled = false;
  200. #else
  201. if (sMotionManager != nil)
  202. {
  203. [sMotionManager stopGyroUpdates];
  204. [sMotionManager stopDeviceMotionUpdates];
  205. }
  206. #endif
  207. }
  208. UNITY_EXPORT extern "C" void UnityUpdateAccelerometerData()
  209. {
  210. #if !PLATFORM_TVOS
  211. if (sMotionManager)
  212. {
  213. CMAccelerometerData* data = sMotionManager.accelerometerData;
  214. if (data != nil)
  215. {
  216. Vector3f res = UnityReorientVector3(data.acceleration.x, data.acceleration.y, data.acceleration.z);
  217. UnityDidAccelerate(res.x, res.y, res.z, data.timestamp);
  218. }
  219. }
  220. #endif
  221. }
  222. UNITY_EXPORT extern "C" void UnitySetGyroUpdateInterval(int idx, float interval)
  223. {
  224. #if !PLATFORM_TVOS
  225. static const float _MinUpdateInterval = 1.0f / 60.0f;
  226. static const float _MaxUpdateInterval = 1.0f;
  227. if (interval < _MinUpdateInterval)
  228. interval = _MinUpdateInterval;
  229. else if (interval > _MaxUpdateInterval)
  230. interval = _MaxUpdateInterval;
  231. sUserUpdateInterval = interval;
  232. if (sMotionManager)
  233. {
  234. sUpdateInterval = interval;
  235. [sMotionManager setGyroUpdateInterval: interval];
  236. [sMotionManager setDeviceMotionUpdateInterval: interval];
  237. }
  238. #endif
  239. }
  240. UNITY_EXPORT extern "C" float UnityGetGyroUpdateInterval(int idx)
  241. {
  242. return sUpdateInterval;
  243. }
  244. UNITY_EXPORT extern "C" void UnityUpdateGyroData()
  245. {
  246. #if !PLATFORM_TVOS
  247. CMRotationRate rotationRate = { 0.0, 0.0, 0.0 };
  248. CMRotationRate rotationRateUnbiased = { 0.0, 0.0, 0.0 };
  249. CMAcceleration userAcceleration = { 0.0, 0.0, 0.0 };
  250. CMAcceleration gravity = { 0.0, 0.0, 0.0 };
  251. CMQuaternion attitude = { 0.0, 0.0, 0.0, 1.0 };
  252. if (sMotionManager != nil)
  253. {
  254. CMGyroData *gyroData = sMotionManager.gyroData;
  255. CMDeviceMotion *motionData = sMotionManager.deviceMotion;
  256. if (gyroData != nil)
  257. {
  258. rotationRate = gyroData.rotationRate;
  259. }
  260. if (motionData != nil)
  261. {
  262. CMAttitude *att = motionData.attitude;
  263. attitude = att.quaternion;
  264. rotationRateUnbiased = motionData.rotationRate;
  265. userAcceleration = motionData.userAcceleration;
  266. gravity = motionData.gravity;
  267. }
  268. }
  269. Vector3f reorientedRotRate = UnityReorientVector3(rotationRate.x, rotationRate.y, rotationRate.z);
  270. UnitySensorsSetGyroRotationRate(0, reorientedRotRate.x, reorientedRotRate.y, reorientedRotRate.z);
  271. Vector3f reorientedRotRateUnbiased = UnityReorientVector3(rotationRateUnbiased.x, rotationRateUnbiased.y, rotationRateUnbiased.z);
  272. UnitySensorsSetGyroRotationRateUnbiased(0, reorientedRotRateUnbiased.x, reorientedRotRateUnbiased.y, reorientedRotRateUnbiased.z);
  273. Vector3f reorientedUserAcc = UnityReorientVector3(userAcceleration.x, userAcceleration.y, userAcceleration.z);
  274. UnitySensorsSetUserAcceleration(0, reorientedUserAcc.x, reorientedUserAcc.y, reorientedUserAcc.z);
  275. Vector3f reorientedG = UnityReorientVector3(gravity.x, gravity.y, gravity.z);
  276. UnitySensorsSetGravity(0, reorientedG.x, reorientedG.y, reorientedG.z);
  277. Quaternion4f reorientedAtt = UnityReorientQuaternion(attitude.x, attitude.y, attitude.z, attitude.w);
  278. UnitySensorsSetAttitude(0, reorientedAtt.x, reorientedAtt.y, reorientedAtt.z, reorientedAtt.w);
  279. #endif
  280. }
  281. UNITY_EXPORT extern "C" int UnityIsGyroEnabled(int idx)
  282. {
  283. #if PLATFORM_TVOS
  284. return sGCMotionForwardingEnabled;
  285. #else
  286. if (sMotionManager == nil)
  287. return 0;
  288. return sMotionManager.gyroAvailable && sMotionManager.gyroActive;
  289. #endif
  290. }
  291. UNITY_EXPORT extern "C" int UnityIsGyroAvailable()
  292. {
  293. #if PLATFORM_TVOS
  294. return true;
  295. #else
  296. if (sMotionManager != nil)
  297. return sMotionManager.gyroAvailable;
  298. #endif
  299. return 0;
  300. }
  301. // -- Joystick stuff --
  302. #pragma clang diagnostic push
  303. #pragma clang diagnostic ignored "-Wobjc-method-access"
  304. enum JoystickButtonNumbers
  305. {
  306. BTN_PAUSE = 0,
  307. BTN_DPAD_UP = 4,
  308. BTN_DPAD_RIGHT = 5,
  309. BTN_DPAD_DOWN = 6,
  310. BTN_DPAD_LEFT = 7,
  311. BTN_Y = 12,
  312. BTN_B = 13,
  313. BTN_A = 14,
  314. BTN_X = 15,
  315. BTN_L1 = 8,
  316. BTN_L2 = 10,
  317. BTN_R1 = 9,
  318. BTN_R2 = 11,
  319. BTN_MENU = 16,
  320. BTN_L3 = 17,
  321. BTN_R3 = 18,
  322. BTN_COUNT
  323. };
  324. struct JoystickButtonState
  325. {
  326. int buttonCode;
  327. bool state;
  328. bool lastRecordedState;
  329. bool StateChanged() { return state ^ lastRecordedState; }
  330. void ClearRecordedState() { lastRecordedState = false; }
  331. };
  332. JoystickButtonState gAggregatedJoystickState[BTN_COUNT];
  333. static float GetAxisValue(GCControllerAxisInput* axis)
  334. {
  335. return axis.value;
  336. }
  337. static float GetButtonValue(GCControllerButtonInput* button)
  338. {
  339. return button.value;
  340. }
  341. static BOOL GetButtonPressed(GCControllerButtonInput* button)
  342. {
  343. return button.pressed;
  344. }
  345. UNITY_EXPORT extern "C" void UnityInitJoysticks()
  346. {
  347. if (!gJoysticksInited)
  348. {
  349. NSBundle* bundle = [NSBundle bundleWithPath: @"/System/Library/Frameworks/GameController.framework"];
  350. if (bundle)
  351. {
  352. [bundle load];
  353. gGameControllerClass = NSClassFromString(@"GCController");
  354. //Apply settings that could have been set by user scripts before controller initialization
  355. #if PLATFORM_TVOS
  356. UnitySetAppleTVRemoteAllowRotation(gTVRemoteAllowRotationInitialValue);
  357. UnitySetAppleTVRemoteReportAbsoluteDpadValues(gTVRemoteReportsAbsoluteDpadValuesInitialValue);
  358. #endif
  359. }
  360. for (int i = 0; i < BTN_COUNT; i++)
  361. {
  362. const int bufSize = 128;
  363. char buf[bufSize];
  364. snprintf(buf, bufSize, "joystick button %d", i);
  365. gAggregatedJoystickState[i].buttonCode = UnityStringToKey(buf);
  366. gAggregatedJoystickState[i].state = false;
  367. gAggregatedJoystickState[i].lastRecordedState = false;
  368. }
  369. gJoysticksInited = true;
  370. }
  371. }
  372. static NSArray* QueryControllerCollection()
  373. {
  374. return gGameControllerClass != nil ? (NSArray*)[gGameControllerClass performSelector: @selector(controllers)] : nil;
  375. }
  376. static void HandleAggregatedJoystickState()
  377. {
  378. for (int i = 0; i < BTN_COUNT; i++)
  379. {
  380. // Mirror button state to the aggregate controller 0.
  381. if (gAggregatedJoystickState[i].StateChanged())
  382. {
  383. UnitySetKeyState(gAggregatedJoystickState[i].buttonCode, gAggregatedJoystickState[i].lastRecordedState);
  384. gAggregatedJoystickState[i].state = gAggregatedJoystickState[i].lastRecordedState;
  385. }
  386. gAggregatedJoystickState[i].ClearRecordedState();
  387. }
  388. }
  389. static void SetJoystickButtonState(int joyNum, int buttonNum, int state)
  390. {
  391. const int bufSize = 128;
  392. char buf[bufSize];
  393. snprintf(buf, bufSize, "joystick %d button %d", joyNum, buttonNum);
  394. UnitySetKeyState(UnityStringToKey(buf), state);
  395. if (state && buttonNum < BTN_COUNT)
  396. {
  397. gAggregatedJoystickState[buttonNum].lastRecordedState = true;
  398. }
  399. }
  400. static void ReportJoystickButton(int idx, JoystickButtonNumbers num, GCControllerButtonInput* button)
  401. {
  402. SetJoystickButtonState(idx + 1, num, GetButtonPressed(button));
  403. UnitySetJoystickPosition(idx + 1, num, GetButtonValue(button));
  404. }
  405. template<class ClassXYZ>
  406. static void ReportJoystickXYZAxes(int idx, int xaxis, int yaxis, int zaxis, const ClassXYZ& xyz)
  407. {
  408. UnitySetJoystickPosition(idx + 1, xaxis, xyz.x);
  409. UnitySetJoystickPosition(idx + 1, yaxis, xyz.y);
  410. UnitySetJoystickPosition(idx + 1, zaxis, xyz.z);
  411. }
  412. template<class ClassXYZW>
  413. static void ReportJoystickXYZWAxes(int idx, int xaxis, int yaxis, int zaxis, int waxis,
  414. const ClassXYZW& xyzw)
  415. {
  416. UnitySetJoystickPosition(idx + 1, xaxis, xyzw.x);
  417. UnitySetJoystickPosition(idx + 1, yaxis, xyzw.y);
  418. UnitySetJoystickPosition(idx + 1, zaxis, xyzw.z);
  419. UnitySetJoystickPosition(idx + 1, waxis, xyzw.w);
  420. }
  421. static GCControllerDirectionPad* GetCardinalDPad(GCMicroGamepad* gamepad)
  422. {
  423. if (![gamepad respondsToSelector: @selector(dpadsbling)])
  424. return nil;
  425. NSDictionary<NSString *, GCDeviceDirectionPad *> *dpads = [gamepad performSelector: @selector(dpadsbling)];
  426. return [dpads valueForKey: @"Cardinal Direction Pad"];
  427. }
  428. static GCControllerButtonInput* SelectPreferedButton(GCControllerButtonInput* prefered, GCControllerButtonInput* alternative)
  429. {
  430. if (prefered.isPressed)
  431. return prefered;
  432. return alternative;
  433. }
  434. static void ReportJoystickMicro(int idx, GCMicroGamepad* gamepad)
  435. {
  436. GCControllerDirectionPad* dpad = [gamepad dpad];
  437. GCControllerDirectionPad* cardinalDpad;
  438. #if PLATFORM_TVOS
  439. cardinalDpad = [[gamepad dpads] valueForKey: GCInputDirectionalCardinalDpad];
  440. #endif
  441. UnitySetJoystickPosition(idx + 1, 0, GetAxisValue([dpad xAxis]));
  442. UnitySetJoystickPosition(idx + 1, 1, -GetAxisValue([dpad yAxis]));
  443. ReportJoystickButton(idx, BTN_DPAD_UP, SelectPreferedButton([dpad up], [cardinalDpad up]));
  444. ReportJoystickButton(idx, BTN_DPAD_RIGHT, SelectPreferedButton([dpad right], [cardinalDpad right]));
  445. ReportJoystickButton(idx, BTN_DPAD_DOWN, SelectPreferedButton([dpad down], [cardinalDpad down]));
  446. ReportJoystickButton(idx, BTN_DPAD_LEFT, SelectPreferedButton([dpad left], [cardinalDpad left]));
  447. bool isDirectionalButtonPressed = false;
  448. #if PLATFORM_TVOS
  449. if (cardinalDpad)
  450. {
  451. ReportJoystickButton(idx, BTN_A, [[gamepad buttons] valueForKey: GCInputDirectionalCenterButton]);
  452. isDirectionalButtonPressed = true;
  453. }
  454. #endif
  455. if (!isDirectionalButtonPressed)
  456. ReportJoystickButton(idx, BTN_A, [gamepad buttonA]);
  457. ReportJoystickButton(idx, BTN_X, [gamepad buttonX]);
  458. }
  459. static void ReportJoystickExtended(int idx, GCExtendedGamepad* gamepad)
  460. {
  461. GCControllerDirectionPad* dpad = [gamepad dpad];
  462. ReportJoystickButton(idx, BTN_DPAD_UP, [dpad up]);
  463. ReportJoystickButton(idx, BTN_DPAD_RIGHT, [dpad right]);
  464. ReportJoystickButton(idx, BTN_DPAD_DOWN, [dpad down]);
  465. ReportJoystickButton(idx, BTN_DPAD_LEFT, [dpad left]);
  466. ReportJoystickButton(idx, BTN_A, [gamepad buttonA]);
  467. ReportJoystickButton(idx, BTN_B, [gamepad buttonB]);
  468. ReportJoystickButton(idx, BTN_Y, [gamepad buttonY]);
  469. ReportJoystickButton(idx, BTN_X, [gamepad buttonX]);
  470. ReportJoystickButton(idx, BTN_L1, [gamepad leftShoulder]);
  471. ReportJoystickButton(idx, BTN_R1, [gamepad rightShoulder]);
  472. ReportJoystickButton(idx, BTN_L2, [gamepad leftTrigger]);
  473. ReportJoystickButton(idx, BTN_R2, [gamepad rightTrigger]);
  474. ReportJoystickButton(idx, BTN_L3, [gamepad valueForKey: @"leftThumbstickButton"]);
  475. ReportJoystickButton(idx, BTN_R3, [gamepad valueForKey: @"rightThumbstickButton"]);
  476. ReportJoystickButton(idx, BTN_MENU, [gamepad valueForKey: @"buttonMenu"]);
  477. ReportJoystickButton(idx, BTN_PAUSE, [gamepad valueForKey: @"buttonOptions"]);
  478. // To avoid overwriting axis input with button input when axis index
  479. // overlaps with button enum value, handle directional input after buttons.
  480. GCControllerDirectionPad* leftStick = [gamepad leftThumbstick];
  481. GCControllerDirectionPad* rightStick = [gamepad rightThumbstick];
  482. UnitySetJoystickPosition(idx + 1, 0, GetAxisValue([leftStick xAxis]));
  483. UnitySetJoystickPosition(idx + 1, 1, -GetAxisValue([leftStick yAxis]));
  484. UnitySetJoystickPosition(idx + 1, 2, GetAxisValue([rightStick xAxis]));
  485. UnitySetJoystickPosition(idx + 1, 3, -GetAxisValue([rightStick yAxis]));
  486. }
  487. static void SimulateAttitudeViaGravityVector(const Vector3f& gravity, Quaternion4f& currentAttitude, Vector3f& rotationRate)
  488. {
  489. static Quaternion4f lastAttitude = QuatIdentity();
  490. static double lastTime = 0.0;
  491. double currentTime = [NSDate timeIntervalSinceReferenceDate];
  492. double deltaTime = lastTime - currentTime;
  493. currentAttitude = QuatRotationFromTo(gravity, VecMake(0.0f, 0.0f, -1.0f));
  494. rotationRate = VecScale(1.0f / deltaTime, QuatToEuler(QuatDifference(currentAttitude, lastAttitude)));
  495. lastAttitude = currentAttitude;
  496. lastTime = currentTime;
  497. }
  498. // Note that joystick axis numbers in documentation are shifted
  499. // by one. 1st axis is referred to by index 0, 16th by 15, etc.
  500. static void ReportJoystickMotion(int idx, GCMotion* motion)
  501. {
  502. Vector3f rotationRate = VecMake(0.0f, 0.0f, 0.0f);
  503. Quaternion4f attitude = QuatMake(0.0f, 0.0f, 0.0f, 1.0f);
  504. bool gotRotationData = false;
  505. if (motion.hasAttitudeAndRotationRate)
  506. {
  507. rotationRate = {(float)motion.rotationRate.x, (float)motion.rotationRate.y, (float)motion.rotationRate.z};
  508. attitude = {(float)motion.attitude.x, (float)motion.attitude.y, (float)motion.attitude.z, (float)motion.attitude.w};
  509. gotRotationData = true;
  510. }
  511. #if SIMULATE_ATTITUDE_FROM_GRAVITY
  512. if (!gotRotationData)
  513. SimulateAttitudeViaGravityVector(VecMake((float)motion.gravity.x, (float)motion.gravity.y, (float)motion.gravity.z), attitude, rotationRate);
  514. #endif
  515. // From docs:
  516. // gravity (x,y,z) : 16, 17, 18
  517. // user acceleration: 19, 20, 21
  518. // rotation rate: 22, 23, 24
  519. // attitude quaternion (x,y,z,w): 25, 26, 27, 28
  520. ReportJoystickXYZAxes(idx, 15, 16, 17, motion.gravity);
  521. ReportJoystickXYZAxes(idx, 18, 19, 20, motion.userAcceleration);
  522. ReportJoystickXYZAxes(idx, 21, 22, 23, rotationRate);
  523. ReportJoystickXYZWAxes(idx, 24, 25, 26, 27, attitude);
  524. #if PLATFORM_TVOS
  525. if (sGCMotionForwardingEnabled && !sGCMotionForwardedForCurrentFrame)
  526. {
  527. UnitySensorsSetGravity(0, motion.gravity.x, motion.gravity.y, motion.gravity.z);
  528. UnitySensorsSetUserAcceleration(0, motion.userAcceleration.x, motion.userAcceleration.y, motion.userAcceleration.z);
  529. UnitySensorsSetGyroRotationRate(0, rotationRate.y, rotationRate.x, rotationRate.z);
  530. UnitySensorsSetAttitude(0, attitude.x, attitude.y, attitude.z, attitude.w);
  531. UnityDidAccelerate(motion.userAcceleration.x + motion.gravity.x, motion.userAcceleration.y + motion.gravity.y, motion.userAcceleration.z + motion.gravity.z, [[NSDate date] timeIntervalSince1970]);
  532. sGCMotionForwardedForCurrentFrame = true;
  533. }
  534. #endif
  535. }
  536. static void ReportJoystick(GCController* controller, int idx)
  537. {
  538. if (controller.controllerPausedHandler == nil)
  539. controller.controllerPausedHandler = gControllerHandler;
  540. if ([controller extendedGamepad] != nil)
  541. ReportJoystickExtended(idx, [controller extendedGamepad]);
  542. else if ([controller microGamepad] != nil)
  543. ReportJoystickMicro(idx, [controller microGamepad]);
  544. else
  545. {
  546. // TODO: do something with not supported gamepad profiles
  547. }
  548. if (controller.motion != nil)
  549. ReportJoystickMotion(idx, controller.motion);
  550. // Map pause button
  551. SetJoystickButtonState(idx + 1, BTN_PAUSE, gPausedJoysticks[idx]);
  552. // Reset pause button
  553. gPausedJoysticks[idx] = false;
  554. }
  555. // On tvOS simulator we implement a fake remote as tvOS simulator
  556. // does not support controllers (yet)
  557. #if UNITY_TVOS_SIMULATOR_FAKE_REMOTE
  558. struct FakeRemoteState
  559. {
  560. bool pressedX, pressedA;
  561. bool pressedUp, pressedDown, pressedLeft, pressedRight;
  562. float xAxis, yAxis;
  563. FakeRemoteState() :
  564. pressedX(false),
  565. pressedA(false),
  566. pressedUp(false),
  567. pressedDown(false),
  568. pressedLeft(false),
  569. pressedRight(false),
  570. xAxis(0),
  571. yAxis(0)
  572. {}
  573. };
  574. static FakeRemoteState gFakeRemoteState;
  575. static void ReportFakeRemoteButton(int idx, JoystickButtonNumbers num, bool pressed)
  576. {
  577. SetJoystickButtonState(idx + 1, num, pressed);
  578. UnitySetJoystickPosition(idx + 1, num, pressed);
  579. }
  580. void ReportFakeRemote(int idx)
  581. {
  582. UnitySetJoystickPosition(idx + 1, 0, gFakeRemoteState.xAxis);
  583. UnitySetJoystickPosition(idx + 1, 1, -gFakeRemoteState.yAxis);
  584. ReportFakeRemoteButton(idx, BTN_DPAD_UP, gFakeRemoteState.pressedUp);
  585. ReportFakeRemoteButton(idx, BTN_DPAD_RIGHT, gFakeRemoteState.pressedRight);
  586. ReportFakeRemoteButton(idx, BTN_DPAD_DOWN, gFakeRemoteState.pressedDown);
  587. ReportFakeRemoteButton(idx, BTN_DPAD_LEFT, gFakeRemoteState.pressedLeft);
  588. ReportFakeRemoteButton(idx, BTN_A, gFakeRemoteState.pressedA);
  589. ReportFakeRemoteButton(idx, BTN_X, gFakeRemoteState.pressedX);
  590. }
  591. #endif
  592. UNITY_EXPORT extern "C" void UnityUpdateJoystickData()
  593. {
  594. UnityInitJoysticks();
  595. NSArray* list = QueryControllerCollection();
  596. #if PLATFORM_TVOS
  597. sGCMotionForwardedForCurrentFrame = false;
  598. #endif
  599. if (list != nil)
  600. {
  601. for (int i = 0; i < [list count]; i++)
  602. {
  603. id controller = [list objectAtIndex: i];
  604. ReportJoystick(controller, i);
  605. }
  606. }
  607. #if UNITY_TVOS_SIMULATOR_FAKE_REMOTE
  608. int remoteIndex = list != nil ? (int)[list count] : 0;
  609. ReportFakeRemote(remoteIndex);
  610. #endif
  611. // Report all aggregated joystick buttons in bulk
  612. HandleAggregatedJoystickState();
  613. }
  614. static NSString* FormatJoystickIdentifier(int idx, const char* typeString, const char* attachment, const char* vendorName)
  615. {
  616. return [NSString stringWithFormat: @"[%s,%s] joystick %d by %s", typeString, attachment, idx + 1, vendorName];
  617. }
  618. NSString* GetJoystickName(GCController* controller, int idx)
  619. {
  620. if (controller != nil)
  621. {
  622. // iOS 8 has bug, which is encountered when controller is being attached
  623. // while app is still running. It creates two instances of controller object:
  624. // one original and one "Forwarded", accesing later properties are causing crashes
  625. const char* attached = "unknown";
  626. // Controller is good one
  627. if ([[controller vendorName] rangeOfString: @"Forwarded"].location == NSNotFound)
  628. attached = (controller.attachedToDevice ? "wired" : "wireless");
  629. const char* typeString = [controller extendedGamepad] != nil ? "extended" : "basic";
  630. return FormatJoystickIdentifier(idx, typeString, attached, [[controller vendorName] UTF8String]);
  631. }
  632. return @"unknown";
  633. }
  634. UNITY_EXPORT extern "C" NSArray* UnityGetJoystickNames()
  635. {
  636. NSArray* joysticks = QueryControllerCollection();
  637. int count = joysticks != nil ? (int)[joysticks count] : 0;
  638. NSMutableArray * joystickNames = [NSMutableArray arrayWithCapacity: count];
  639. for (int i = 0; i < count; i++)
  640. {
  641. [joystickNames addObject: GetJoystickName(joysticks[i], i)];
  642. }
  643. #if UNITY_TVOS_SIMULATOR_FAKE_REMOTE
  644. [joystickNames addObject: FormatJoystickIdentifier(count, "basic", "wireless", "Unity")];
  645. #endif
  646. return joystickNames;
  647. }
  648. UNITY_EXPORT extern "C" void UnityGetJoystickAxisName(int idx, int axis, char* buffer, int maxLen)
  649. {
  650. }
  651. UNITY_EXPORT extern "C" void UnityGetNiceKeyname(int key, char* buffer, int maxLen)
  652. {
  653. }
  654. #pragma clang diagnostic pop
  655. #if UNITY_USES_LOCATION
  656. @interface LocationServiceDelegate : NSObject<CLLocationManagerDelegate>
  657. @end
  658. #endif
  659. extern "C" void
  660. UnitySetLastLocation(double timestamp,
  661. float latitude,
  662. float longitude,
  663. float altitude,
  664. float horizontalAccuracy,
  665. float verticalAccuracy);
  666. extern "C" void
  667. UnitySetLastHeading(float magneticHeading, float trueHeading, float headingAccuracy,
  668. float rawX, float rawY, float rawZ, double timestamp);
  669. #if UNITY_USES_LOCATION
  670. struct LocationServiceInfo
  671. {
  672. private:
  673. LocationServiceDelegate* delegate;
  674. CLLocationManager* locationManager;
  675. public:
  676. LocationServiceStatus locationStatus;
  677. LocationServiceStatus headingStatus;
  678. float desiredAccuracy;
  679. float distanceFilter;
  680. LocationServiceInfo();
  681. CLLocationManager* GetLocationManager();
  682. };
  683. LocationServiceInfo::LocationServiceInfo()
  684. {
  685. locationStatus = kLocationServiceStopped;
  686. desiredAccuracy = kCLLocationAccuracyKilometer;
  687. distanceFilter = 500;
  688. headingStatus = kLocationServiceStopped;
  689. }
  690. static LocationServiceInfo gLocationServiceStatus;
  691. CLLocationManager* LocationServiceInfo::GetLocationManager()
  692. {
  693. if (locationManager == nil)
  694. {
  695. locationManager = [[CLLocationManager alloc] init];
  696. delegate = [LocationServiceDelegate alloc];
  697. locationManager.delegate = delegate;
  698. }
  699. return locationManager;
  700. }
  701. #endif
  702. UNITY_EXPORT bool LocationService::IsServiceEnabledByUser()
  703. {
  704. #if UNITY_USES_LOCATION
  705. return [CLLocationManager locationServicesEnabled];
  706. #else
  707. return false;
  708. #endif
  709. }
  710. UNITY_EXPORT void LocationService::SetDesiredAccuracy(float val)
  711. {
  712. #if UNITY_USES_LOCATION
  713. gLocationServiceStatus.desiredAccuracy = val;
  714. #endif
  715. }
  716. UNITY_EXPORT float LocationService::GetDesiredAccuracy()
  717. {
  718. #if UNITY_USES_LOCATION
  719. return gLocationServiceStatus.desiredAccuracy;
  720. #else
  721. return NAN;
  722. #endif
  723. }
  724. UNITY_EXPORT void LocationService::SetDistanceFilter(float val)
  725. {
  726. #if UNITY_USES_LOCATION
  727. gLocationServiceStatus.distanceFilter = val;
  728. #endif
  729. }
  730. UNITY_EXPORT float LocationService::GetDistanceFilter()
  731. {
  732. #if UNITY_USES_LOCATION
  733. return gLocationServiceStatus.distanceFilter;
  734. #else
  735. return NAN;
  736. #endif
  737. }
  738. UNITY_EXPORT void LocationService::StartUpdatingLocation()
  739. {
  740. #if UNITY_USES_LOCATION
  741. if (gLocationServiceStatus.locationStatus != kLocationServiceRunning)
  742. {
  743. CLLocationManager* locationManager = gLocationServiceStatus.GetLocationManager();
  744. [locationManager requestWhenInUseAuthorization];
  745. locationManager.desiredAccuracy = gLocationServiceStatus.desiredAccuracy;
  746. // Set a movement threshold for new events
  747. locationManager.distanceFilter = gLocationServiceStatus.distanceFilter;
  748. #if PLATFORM_IOS
  749. [locationManager startUpdatingLocation];
  750. #else
  751. [locationManager requestLocation];
  752. #endif
  753. gLocationServiceStatus.locationStatus = kLocationServiceInitializing;
  754. }
  755. #endif
  756. }
  757. UNITY_EXPORT void LocationService::StopUpdatingLocation()
  758. {
  759. #if UNITY_USES_LOCATION
  760. if (gLocationServiceStatus.locationStatus != kLocationServiceStopped)
  761. {
  762. [gLocationServiceStatus.GetLocationManager() stopUpdatingLocation];
  763. gLocationServiceStatus.locationStatus = kLocationServiceStopped;
  764. }
  765. #endif
  766. }
  767. UNITY_EXPORT void LocationService::SetHeadingUpdatesEnabled(bool enabled)
  768. {
  769. #if PLATFORM_IOS && UNITY_USES_LOCATION
  770. if (enabled)
  771. {
  772. if (gLocationServiceStatus.headingStatus != kLocationServiceRunning &&
  773. IsHeadingAvailable())
  774. {
  775. CLLocationManager* locationManager = gLocationServiceStatus.GetLocationManager();
  776. [locationManager startUpdatingHeading];
  777. gLocationServiceStatus.headingStatus = kLocationServiceInitializing;
  778. }
  779. }
  780. else
  781. {
  782. if (gLocationServiceStatus.headingStatus != kLocationServiceStopped)
  783. {
  784. [gLocationServiceStatus.GetLocationManager() stopUpdatingHeading];
  785. gLocationServiceStatus.headingStatus = kLocationServiceStopped;
  786. }
  787. }
  788. #endif
  789. }
  790. UNITY_EXPORT bool LocationService::IsHeadingUpdatesEnabled()
  791. {
  792. #if UNITY_USES_LOCATION
  793. return (gLocationServiceStatus.headingStatus == kLocationServiceRunning);
  794. #else
  795. return false;
  796. #endif
  797. }
  798. UNITY_EXPORT LocationServiceStatus LocationService::GetLocationStatus()
  799. {
  800. #if UNITY_USES_LOCATION
  801. return (LocationServiceStatus)gLocationServiceStatus.locationStatus;
  802. #else
  803. return kLocationServiceFailed;
  804. #endif
  805. }
  806. UNITY_EXPORT LocationServiceStatus LocationService::GetHeadingStatus()
  807. {
  808. #if UNITY_USES_LOCATION
  809. return (LocationServiceStatus)gLocationServiceStatus.headingStatus;
  810. #else
  811. return kLocationServiceFailed;
  812. #endif
  813. }
  814. UNITY_EXPORT bool LocationService::IsHeadingAvailable()
  815. {
  816. #if PLATFORM_IOS && UNITY_USES_LOCATION
  817. return [CLLocationManager headingAvailable];
  818. #else
  819. return false;
  820. #endif
  821. }
  822. #if UNITY_USES_LOCATION
  823. @implementation LocationServiceDelegate
  824. - (void)locationManager:(CLLocationManager*)manager didUpdateLocations:(NSArray*)locations
  825. {
  826. CLLocation* lastLocation = locations.lastObject;
  827. gLocationServiceStatus.locationStatus = kLocationServiceRunning;
  828. UnitySetLastLocation([lastLocation.timestamp timeIntervalSince1970],
  829. lastLocation.coordinate.latitude, lastLocation.coordinate.longitude, lastLocation.altitude,
  830. lastLocation.horizontalAccuracy, lastLocation.verticalAccuracy
  831. );
  832. }
  833. #if PLATFORM_IOS
  834. - (void)locationManager:(CLLocationManager*)manager didUpdateHeading:(CLHeading*)newHeading
  835. {
  836. gLocationServiceStatus.headingStatus = kLocationServiceRunning;
  837. Vector3f reorientedRawHeading = UnityReorientVector3(newHeading.x, newHeading.y, newHeading.z);
  838. UnitySetLastHeading(UnityReorientHeading(newHeading.magneticHeading),
  839. UnityReorientHeading(newHeading.trueHeading),
  840. newHeading.headingAccuracy,
  841. reorientedRawHeading.x, reorientedRawHeading.y, reorientedRawHeading.z,
  842. [newHeading.timestamp timeIntervalSince1970]);
  843. }
  844. #endif
  845. - (BOOL)locationManagerShouldDisplayHeadingCalibration:(CLLocationManager*)manager
  846. {
  847. return NO;
  848. }
  849. - (void)locationManager:(CLLocationManager*)manager didFailWithError:(NSError*)error;
  850. {
  851. gLocationServiceStatus.locationStatus = kLocationServiceFailed;
  852. gLocationServiceStatus.headingStatus = kLocationServiceFailed;
  853. }
  854. @end
  855. #endif
  856. #if PLATFORM_TVOS
  857. GCMicroGamepad* QueryMicroController()
  858. {
  859. NSArray* list = QueryControllerCollection();
  860. for (GCController* controller in list)
  861. {
  862. if (controller.microGamepad != nil)
  863. return controller.microGamepad;
  864. }
  865. return nil;
  866. }
  867. UNITY_EXPORT extern "C" int UnityGetAppleTVRemoteTouchesEnabled()
  868. {
  869. return gTVRemoteTouchesEnabled;
  870. }
  871. UNITY_EXPORT extern "C" void UnitySetAppleTVRemoteTouchesEnabled(int val)
  872. {
  873. gTVRemoteTouchesEnabled = val;
  874. }
  875. /*
  876. TVRemoteAllowExitToMenu.
  877. Lowest bit caches the value of .controllerUserInteractionEnabled.
  878. Second lowest bit is set if .controllerUserInteractionEnabled is temporarily changed for internal purposes.
  879. */
  880. UNITY_EXPORT extern "C" int UnityGetAppleTVRemoteAllowExitToMenu()
  881. {
  882. if (gTVControllerUserInteractionEnabled & 2)
  883. return gTVControllerUserInteractionEnabled & 1;
  884. return ((GCEventViewController*)UnityGetGLViewController()).controllerUserInteractionEnabled;
  885. }
  886. /*
  887. Same as getter above, except that second lowest bit here indicates fake setting,
  888. meaning we set the value on controller, but cache the true value so getter report no changes.
  889. */
  890. UNITY_EXPORT extern "C" void UnitySetAppleTVRemoteAllowExitToMenu(int val)
  891. {
  892. bool newVal = val & 1;
  893. if (val & 2)
  894. {
  895. if (gTVControllerUserInteractionEnabled == val)
  896. return;
  897. if (0 == (gTVControllerUserInteractionEnabled & 2))
  898. {
  899. int cacheVal = ((GCEventViewController*)UnityGetGLViewController()).controllerUserInteractionEnabled;
  900. gTVControllerUserInteractionEnabled = 2 | cacheVal;
  901. }
  902. }
  903. ((GCEventViewController*)UnityGetGLViewController()).controllerUserInteractionEnabled = newVal;
  904. }
  905. UNITY_EXPORT extern "C" int UnityGetAppleTVRemoteAllowRotation()
  906. {
  907. GCMicroGamepad* controller = QueryMicroController();
  908. if (controller != nil)
  909. return controller.allowsRotation;
  910. else
  911. return false;
  912. }
  913. UNITY_EXPORT extern "C" void UnitySetAppleTVRemoteAllowRotation(int val)
  914. {
  915. GCMicroGamepad* controller = QueryMicroController();
  916. if (controller != nil)
  917. controller.allowsRotation = val;
  918. else
  919. gTVRemoteAllowRotationInitialValue = val;
  920. }
  921. UNITY_EXPORT extern "C" int UnityGetAppleTVRemoteReportAbsoluteDpadValues()
  922. {
  923. GCMicroGamepad* controller = QueryMicroController();
  924. if (controller != nil)
  925. return controller.reportsAbsoluteDpadValues;
  926. else
  927. return false;
  928. }
  929. UNITY_EXPORT extern "C" void UnitySetAppleTVRemoteReportAbsoluteDpadValues(int val)
  930. {
  931. NSArray* list = QueryControllerCollection();
  932. for (GCController* controller in list)
  933. {
  934. if (controller.microGamepad != nil)
  935. controller.microGamepad.reportsAbsoluteDpadValues = val;
  936. else
  937. gTVRemoteReportsAbsoluteDpadValuesInitialValue = val;
  938. }
  939. }
  940. #endif
  941. #if UNITY_TVOS_SIMULATOR_FAKE_REMOTE
  942. static void FakeRemoteStateSetButton(UIPressType type, bool state)
  943. {
  944. switch (type)
  945. {
  946. case UIPressTypeUpArrow: gFakeRemoteState.pressedUp = state; return;
  947. case UIPressTypeDownArrow: gFakeRemoteState.pressedDown = state; return;
  948. case UIPressTypeLeftArrow: gFakeRemoteState.pressedLeft = state; return;
  949. case UIPressTypeRightArrow: gFakeRemoteState.pressedRight = state; return;
  950. case UIPressTypeSelect: gFakeRemoteState.pressedA = state; return;
  951. case UIPressTypePlayPause: gFakeRemoteState.pressedX = state; return;
  952. }
  953. }
  954. void ReportSimulatedRemoteButtonPress(UIPressType type)
  955. {
  956. FakeRemoteStateSetButton(type, true);
  957. }
  958. void ReportSimulatedRemoteButtonRelease(UIPressType type)
  959. {
  960. FakeRemoteStateSetButton(type, false);
  961. }
  962. static float FakeRemoteMapTouchToAxis(float pos, float bounds)
  963. {
  964. float halfRange = bounds / 2;
  965. return (pos - halfRange) / halfRange;
  966. }
  967. void ReportSimulatedRemoteTouchesBegan(UIView* view, NSSet* touches)
  968. {
  969. ReportSimulatedRemoteTouchesMoved(view, touches);
  970. }
  971. void ReportSimulatedRemoteTouchesMoved(UIView* view, NSSet* touches)
  972. {
  973. for (UITouch* touch in touches)
  974. {
  975. gFakeRemoteState.xAxis = FakeRemoteMapTouchToAxis([touch locationInView: view].x, view.bounds.size.width);
  976. gFakeRemoteState.yAxis = FakeRemoteMapTouchToAxis([touch locationInView: view].y, view.bounds.size.height);
  977. // We assume that at most single touch is received.
  978. break;
  979. }
  980. }
  981. void ReportSimulatedRemoteTouchesEnded(UIView* view, NSSet* touches)
  982. {
  983. gFakeRemoteState.xAxis = 0;
  984. gFakeRemoteState.yAxis = 0;
  985. }
  986. #endif