PlatformiOS.mm 52 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734
  1. #ifndef GP_NO_PLATFORM
  2. #ifdef __APPLE__
  3. #include "Base.h"
  4. #include "Platform.h"
  5. #include "FileSystem.h"
  6. #include "Game.h"
  7. #include "Form.h"
  8. #include "ScriptController.h"
  9. #include <unistd.h>
  10. #include <sys/time.h>
  11. #import <UIKit/UIKit.h>
  12. #import <GameKit/GameKit.h>
  13. #import <QuartzCore/QuartzCore.h>
  14. #import <CoreMotion/CoreMotion.h>
  15. #import <OpenGLES/EAGL.h>
  16. #import <OpenGLES/EAGLDrawable.h>
  17. #import <OpenGLES/ES2/gl.h>
  18. #import <OpenGLES/ES2/glext.h>
  19. #import <mach/mach_time.h>
  20. #define UIInterfaceOrientationEnum(x) ([x isEqualToString:@"UIInterfaceOrientationPortrait"]?UIInterfaceOrientationPortrait: \
  21. ([x isEqualToString:@"UIInterfaceOrientationPortraitUpsideDown"]?UIInterfaceOrientationPortraitUpsideDown: \
  22. ([x isEqualToString:@"UIInterfaceOrientationLandscapeLeft"]?UIInterfaceOrientationLandscapeLeft: \
  23. UIInterfaceOrientationLandscapeRight)))
  24. #define DeviceOrientedSize(o) ((o == UIInterfaceOrientationPortrait || o == UIInterfaceOrientationPortraitUpsideDown)? \
  25. CGSizeMake([[UIScreen mainScreen] bounds].size.width * [[UIScreen mainScreen] scale], [[UIScreen mainScreen] bounds].size.height * [[UIScreen mainScreen] scale]): \
  26. CGSizeMake([[UIScreen mainScreen] bounds].size.height * [[UIScreen mainScreen] scale], [[UIScreen mainScreen] bounds].size.width * [[UIScreen mainScreen] scale]))
  27. using namespace std;
  28. using namespace gameplay;
  29. // UIScreen bounds are provided as if device was in portrait mode Gameplay defaults to landscape
  30. extern const int WINDOW_WIDTH = [[UIScreen mainScreen] bounds].size.height * [[UIScreen mainScreen] scale];
  31. extern const int WINDOW_HEIGHT = [[UIScreen mainScreen] bounds].size.width * [[UIScreen mainScreen] scale];
  32. extern const int WINDOW_SCALE = [[UIScreen mainScreen] scale];
  33. int __argc = 0;
  34. char** __argv = 0;
  35. @class AppDelegate;
  36. @class View;
  37. static AppDelegate *__appDelegate = NULL;
  38. static View* __view = NULL;
  39. class TouchPoint
  40. {
  41. public:
  42. unsigned int hashId;
  43. int x;
  44. int y;
  45. bool down;
  46. TouchPoint()
  47. {
  48. hashId = 0;
  49. x = 0;
  50. y = 0;
  51. down = false;
  52. }
  53. };
  54. // gestures
  55. #define GESTURE_LONG_PRESS_DURATION_MIN 0.2
  56. #define GESTURE_LONG_PRESS_DISTANCE_MIN 10
  57. static CGPoint __gestureLongPressStartPosition;
  58. static long __gestureLongTapStartTimestamp = 0;
  59. static bool __gestureDraging = false;
  60. // more than we'd ever need, to be safe
  61. #define TOUCH_POINTS_MAX (10)
  62. static TouchPoint __touchPoints[TOUCH_POINTS_MAX];
  63. static double __timeStart;
  64. static double __timeAbsolute;
  65. static bool __vsync = WINDOW_VSYNC;
  66. static float __pitch;
  67. static float __roll;
  68. double getMachTimeInMilliseconds();
  69. int getKey(unichar keyCode);
  70. int getUnicode(int key);
  71. @interface View : UIView <UIKeyInput>
  72. {
  73. EAGLContext* context;
  74. CADisplayLink* displayLink;
  75. BOOL updateFramebuffer;
  76. GLuint defaultFramebuffer;
  77. GLuint colorRenderbuffer;
  78. GLuint depthRenderbuffer;
  79. GLint framebufferWidth;
  80. GLint framebufferHeight;
  81. GLuint multisampleFramebuffer;
  82. GLuint multisampleRenderbuffer;
  83. GLuint multisampleDepthbuffer;
  84. NSInteger swapInterval;
  85. BOOL updating;
  86. Game* game;
  87. BOOL oglDiscardSupported;
  88. UITapGestureRecognizer *_tapRecognizer;
  89. UIPinchGestureRecognizer *_pinchRecognizer;
  90. UISwipeGestureRecognizer *_swipeRecognizer;
  91. UILongPressGestureRecognizer *_longPressRecognizer;
  92. UILongPressGestureRecognizer *_longTapRecognizer;
  93. UILongPressGestureRecognizer *_dragAndDropRecognizer;
  94. }
  95. @property (readonly, nonatomic, getter=isUpdating) BOOL updating;
  96. @property (readonly, nonatomic, getter=getContext) EAGLContext* context;
  97. - (void)startGame;
  98. - (void)startUpdating;
  99. - (void)stopUpdating;
  100. - (void)update:(id)sender;
  101. - (void)setSwapInterval:(NSInteger)interval;
  102. - (int)swapInterval;
  103. - (void)swapBuffers;
  104. - (BOOL)showKeyboard;
  105. - (BOOL)dismissKeyboard;
  106. @end
  107. @interface View (Private)
  108. - (BOOL)createFramebuffer;
  109. - (void)deleteFramebuffer;
  110. @end
  111. @implementation View
  112. @synthesize updating;
  113. @synthesize context;
  114. + (Class) layerClass
  115. {
  116. return [CAEAGLLayer class];
  117. }
  118. - (id) initWithFrame:(CGRect)frame
  119. {
  120. if ((self = [super initWithFrame:frame]))
  121. {
  122. // A system version of 3.1 or greater is required to use CADisplayLink.
  123. NSString *reqSysVer = @"3.1";
  124. NSString *currSysVer = [[UIDevice currentDevice] systemVersion];
  125. if ([currSysVer compare:reqSysVer options:NSNumericSearch] != NSOrderedAscending)
  126. {
  127. // Log the system version
  128. NSLog(@"System Version: %@", currSysVer);
  129. }
  130. else
  131. {
  132. GP_ERROR("Invalid OS Version: %s\n", (currSysVer == NULL?"NULL":[currSysVer cStringUsingEncoding:NSASCIIStringEncoding]));
  133. [self release];
  134. return nil;
  135. }
  136. // Check for OS 4.0+ features
  137. if ([currSysVer compare:@"4.0" options:NSNumericSearch] != NSOrderedAscending)
  138. {
  139. oglDiscardSupported = YES;
  140. }
  141. else
  142. {
  143. oglDiscardSupported = NO;
  144. }
  145. // Configure the CAEAGLLayer and setup out the rendering context
  146. CGFloat scale = [[UIScreen mainScreen] scale];
  147. CAEAGLLayer* layer = (CAEAGLLayer *)self.layer;
  148. layer.opaque = TRUE;
  149. layer.drawableProperties = [NSDictionary dictionaryWithObjectsAndKeys:
  150. [NSNumber numberWithBool:FALSE], kEAGLDrawablePropertyRetainedBacking,
  151. kEAGLColorFormatRGBA8, kEAGLDrawablePropertyColorFormat, nil];
  152. self.contentScaleFactor = scale;
  153. layer.contentsScale = scale;
  154. context = [[EAGLContext alloc] initWithAPI:kEAGLRenderingAPIOpenGLES2];
  155. if (!context || ![EAGLContext setCurrentContext:context])
  156. {
  157. GP_ERROR("Failed to make context current.");
  158. [self release];
  159. return nil;
  160. }
  161. // Initialize Internal Defaults
  162. displayLink = nil;
  163. updateFramebuffer = YES;
  164. defaultFramebuffer = 0;
  165. colorRenderbuffer = 0;
  166. depthRenderbuffer = 0;
  167. framebufferWidth = 0;
  168. framebufferHeight = 0;
  169. multisampleFramebuffer = 0;
  170. multisampleRenderbuffer = 0;
  171. multisampleDepthbuffer = 0;
  172. swapInterval = 1;
  173. updating = FALSE;
  174. game = nil;
  175. // Set the resource path and initalize the game
  176. NSString* bundlePath = [[[NSBundle mainBundle] bundlePath] stringByAppendingString:@"/"];
  177. FileSystem::setResourcePath([bundlePath fileSystemRepresentation]);
  178. }
  179. return self;
  180. }
  181. - (void) dealloc
  182. {
  183. if (game)
  184. game->exit();
  185. [self deleteFramebuffer];
  186. if ([EAGLContext currentContext] == context)
  187. {
  188. [EAGLContext setCurrentContext:nil];
  189. }
  190. [context release];
  191. [super dealloc];
  192. }
  193. - (BOOL)canBecomeFirstResponder
  194. {
  195. // Override so we can control the keyboard
  196. return YES;
  197. }
  198. - (void) layoutSubviews
  199. {
  200. // Called on 'resize'.
  201. // Mark that framebuffer needs to be updated.
  202. // NOTE: Current disabled since we need to have a way to reset the default frame buffer handle
  203. // in FrameBuffer.cpp (for FrameBuffer:bindDefault). This means that changing orientation at
  204. // runtime is currently not supported until we fix this.
  205. //updateFramebuffer = YES;
  206. }
  207. - (BOOL)createFramebuffer
  208. {
  209. // iOS Requires all content go to a rendering buffer then it is swapped into the windows rendering surface
  210. assert(defaultFramebuffer == 0);
  211. // Create the default frame buffer
  212. GL_ASSERT( glGenFramebuffers(1, &defaultFramebuffer) );
  213. GL_ASSERT( glBindFramebuffer(GL_FRAMEBUFFER, defaultFramebuffer) );
  214. // Create a color buffer to attach to the frame buffer
  215. GL_ASSERT( glGenRenderbuffers(1, &colorRenderbuffer) );
  216. GL_ASSERT( glBindRenderbuffer(GL_RENDERBUFFER, colorRenderbuffer) );
  217. // Associate render buffer storage with CAEAGLLauyer so that the rendered content is display on our UI layer.
  218. [context renderbufferStorage:GL_RENDERBUFFER fromDrawable:(CAEAGLLayer *)self.layer];
  219. // Attach the color buffer to our frame buffer
  220. GL_ASSERT( glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, colorRenderbuffer) );
  221. // Retrieve framebuffer size
  222. GL_ASSERT( glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_WIDTH, &framebufferWidth) );
  223. GL_ASSERT( glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_HEIGHT, &framebufferHeight) );
  224. NSLog(@"width: %d, height: %d", framebufferWidth, framebufferHeight);
  225. // If multisampling is enabled in config, create and setup a multisample buffer
  226. Properties* config = Game::getInstance()->getConfig()->getNamespace("window", true);
  227. int samples = config ? config->getInt("samples") : 0;
  228. if (samples < 0)
  229. samples = 0;
  230. if (samples)
  231. {
  232. // Create multisample framebuffer
  233. GL_ASSERT( glGenFramebuffers(1, &multisampleFramebuffer) );
  234. GL_ASSERT( glBindFramebuffer(GL_FRAMEBUFFER, multisampleFramebuffer) );
  235. // Create multisample render and depth buffers
  236. GL_ASSERT( glGenRenderbuffers(1, &multisampleRenderbuffer) );
  237. GL_ASSERT( glGenRenderbuffers(1, &multisampleDepthbuffer) );
  238. // Try to find a supported multisample configuration starting with the defined sample count
  239. while (samples)
  240. {
  241. GL_ASSERT( glBindRenderbuffer(GL_RENDERBUFFER, multisampleRenderbuffer) );
  242. GL_ASSERT( glRenderbufferStorageMultisampleAPPLE(GL_RENDERBUFFER, samples, GL_RGBA8_OES, framebufferWidth, framebufferHeight) );
  243. GL_ASSERT( glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, multisampleRenderbuffer) );
  244. GL_ASSERT( glBindRenderbuffer(GL_RENDERBUFFER, multisampleDepthbuffer) );
  245. GL_ASSERT( glRenderbufferStorageMultisampleAPPLE(GL_RENDERBUFFER, samples, GL_DEPTH_COMPONENT24_OES, framebufferWidth, framebufferHeight) );
  246. GL_ASSERT( glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, multisampleDepthbuffer) );
  247. if (glCheckFramebufferStatus(GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE)
  248. break; // success!
  249. NSLog(@"Creation of multisample buffer with samples=%d failed. Attempting to use configuration with samples=%d instead: %x", samples, samples / 2, glCheckFramebufferStatus(GL_FRAMEBUFFER));
  250. samples /= 2;
  251. }
  252. //todo: __multiSampling = samples > 0;
  253. // Re-bind the default framebuffer
  254. GL_ASSERT( glBindFramebuffer(GL_FRAMEBUFFER, defaultFramebuffer) );
  255. if (samples == 0)
  256. {
  257. // Unable to find a valid/supported multisample configuratoin - fallback to no multisampling
  258. GL_ASSERT( glDeleteRenderbuffers(1, &multisampleRenderbuffer) );
  259. GL_ASSERT( glDeleteRenderbuffers(1, &multisampleDepthbuffer) );
  260. GL_ASSERT( glDeleteFramebuffers(1, &multisampleFramebuffer) );
  261. multisampleFramebuffer = multisampleRenderbuffer = multisampleDepthbuffer = 0;
  262. }
  263. }
  264. // Create default depth buffer and attach to the frame buffer.
  265. // Note: If we are using multisample buffers, we can skip depth buffer creation here since we only
  266. // need the color buffer to resolve to.
  267. if (multisampleFramebuffer == 0)
  268. {
  269. GL_ASSERT( glGenRenderbuffers(1, &depthRenderbuffer) );
  270. GL_ASSERT( glBindRenderbuffer(GL_RENDERBUFFER, depthRenderbuffer) );
  271. GL_ASSERT( glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT24_OES, framebufferWidth, framebufferHeight) );
  272. GL_ASSERT( glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, depthRenderbuffer) );
  273. }
  274. // Sanity check, ensure that the framebuffer is valid
  275. if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE)
  276. {
  277. NSLog(@"ERROR: Failed to make complete framebuffer object %x", glCheckFramebufferStatus(GL_FRAMEBUFFER));
  278. [self deleteFramebuffer];
  279. return NO;
  280. }
  281. // If multisampling is enabled, set the currently bound framebuffer to the multisample buffer
  282. // since that is the buffer code should be drawing into (and FrameBuffr::initialize will detect
  283. // and set this bound buffer as the default one during initialization.
  284. if (multisampleFramebuffer)
  285. GL_ASSERT( glBindFramebuffer(GL_FRAMEBUFFER, multisampleFramebuffer) );
  286. return YES;
  287. }
  288. - (void)deleteFramebuffer
  289. {
  290. if (context)
  291. {
  292. [EAGLContext setCurrentContext:context];
  293. if (defaultFramebuffer)
  294. {
  295. GL_ASSERT( glDeleteFramebuffers(1, &defaultFramebuffer) );
  296. defaultFramebuffer = 0;
  297. }
  298. if (colorRenderbuffer)
  299. {
  300. GL_ASSERT( glDeleteRenderbuffers(1, &colorRenderbuffer) );
  301. colorRenderbuffer = 0;
  302. }
  303. if (depthRenderbuffer)
  304. {
  305. GL_ASSERT( glDeleteRenderbuffers(1, &depthRenderbuffer) );
  306. depthRenderbuffer = 0;
  307. }
  308. if (multisampleFramebuffer)
  309. {
  310. GL_ASSERT( glDeleteFramebuffers(1, &multisampleFramebuffer) );
  311. multisampleFramebuffer = 0;
  312. }
  313. if (multisampleRenderbuffer)
  314. {
  315. GL_ASSERT( glDeleteRenderbuffers(1, &multisampleRenderbuffer) );
  316. multisampleRenderbuffer = 0;
  317. }
  318. if (multisampleDepthbuffer)
  319. {
  320. GL_ASSERT( glDeleteRenderbuffers(1, &multisampleDepthbuffer) );
  321. multisampleDepthbuffer = 0;
  322. }
  323. }
  324. }
  325. - (void)setSwapInterval:(NSInteger)interval
  326. {
  327. if (interval >= 1)
  328. {
  329. swapInterval = interval;
  330. if (updating)
  331. {
  332. [self stopUpdating];
  333. [self startUpdating];
  334. }
  335. }
  336. }
  337. - (int)swapInterval
  338. {
  339. return swapInterval;
  340. }
  341. - (void)swapBuffers
  342. {
  343. if (context)
  344. {
  345. if (multisampleFramebuffer)
  346. {
  347. // Multisampling is enabled: resolve the multisample buffer into the default framebuffer
  348. GL_ASSERT( glBindFramebuffer(GL_DRAW_FRAMEBUFFER_APPLE, defaultFramebuffer) );
  349. GL_ASSERT( glBindFramebuffer(GL_READ_FRAMEBUFFER_APPLE, multisampleFramebuffer) );
  350. GL_ASSERT( glResolveMultisampleFramebufferAPPLE() );
  351. if (oglDiscardSupported)
  352. {
  353. // Performance hint that the GL driver can discard the contents of the multisample buffers
  354. // since they have now been resolved into the default framebuffer
  355. const GLenum discards[] = { GL_COLOR_ATTACHMENT0, GL_DEPTH_ATTACHMENT };
  356. GL_ASSERT( glDiscardFramebufferEXT(GL_READ_FRAMEBUFFER_APPLE, 2, discards) );
  357. }
  358. }
  359. else
  360. {
  361. if (oglDiscardSupported)
  362. {
  363. // Performance hint to the GL driver that the depth buffer is no longer required.
  364. const GLenum discards[] = { GL_DEPTH_ATTACHMENT };
  365. GL_ASSERT( glBindFramebuffer(GL_FRAMEBUFFER, defaultFramebuffer) );
  366. GL_ASSERT( glDiscardFramebufferEXT(GL_FRAMEBUFFER, 1, discards) );
  367. }
  368. }
  369. // Present the color buffer
  370. GL_ASSERT( glBindRenderbuffer(GL_RENDERBUFFER, colorRenderbuffer) );
  371. [context presentRenderbuffer:GL_RENDERBUFFER];
  372. }
  373. }
  374. - (void)startGame
  375. {
  376. if (game == nil)
  377. {
  378. game = Game::getInstance();
  379. __timeStart = getMachTimeInMilliseconds();
  380. game->run();
  381. }
  382. }
  383. - (void)startUpdating
  384. {
  385. if (!updating)
  386. {
  387. displayLink = [CADisplayLink displayLinkWithTarget:self selector:@selector(update:)];
  388. [displayLink setFrameInterval:swapInterval];
  389. [displayLink addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
  390. if (game)
  391. game->resume();
  392. updating = TRUE;
  393. }
  394. }
  395. - (void)stopUpdating
  396. {
  397. if (updating)
  398. {
  399. if (game)
  400. game->pause();
  401. [displayLink invalidate];
  402. displayLink = nil;
  403. updating = FALSE;
  404. }
  405. }
  406. - (void)update:(id)sender
  407. {
  408. if (context != nil)
  409. {
  410. // Ensure our context is current
  411. [EAGLContext setCurrentContext:context];
  412. // If the framebuffer needs (re)creating, do so
  413. if (updateFramebuffer)
  414. {
  415. updateFramebuffer = NO;
  416. [self deleteFramebuffer];
  417. [self createFramebuffer];
  418. // Start the game after our framebuffer is created for the first time.
  419. if (game == nil)
  420. {
  421. [self startGame];
  422. // HACK: Skip the first display update after creating buffers and initializing the game.
  423. // If we don't do this, the first frame (which includes any drawing during initialization)
  424. // does not make it to the display for some reason.
  425. return;
  426. }
  427. }
  428. // Bind our framebuffer for rendering.
  429. // If multisampling is enabled, bind the multisample buffer - otherwise bind the default buffer
  430. GL_ASSERT( glBindFramebuffer(GL_FRAMEBUFFER, multisampleFramebuffer ? multisampleFramebuffer : defaultFramebuffer) );
  431. GL_ASSERT( glViewport(0, 0, framebufferWidth, framebufferHeight) );
  432. // Execute a single game frame
  433. if (game)
  434. game->frame();
  435. // Present the contents of the color buffer
  436. [self swapBuffers];
  437. }
  438. }
  439. - (BOOL)showKeyboard
  440. {
  441. return [self becomeFirstResponder];
  442. }
  443. - (BOOL)dismissKeyboard
  444. {
  445. return [self resignFirstResponder];
  446. }
  447. - (void)insertText:(NSString*)text
  448. {
  449. if([text length] == 0) return;
  450. assert([text length] == 1);
  451. unichar c = [text characterAtIndex:0];
  452. int key = getKey(c);
  453. Platform::keyEventInternal(Keyboard::KEY_PRESS, key);
  454. int character = getUnicode(key);
  455. if (character)
  456. {
  457. Platform::keyEventInternal(Keyboard::KEY_CHAR, /*character*/c);
  458. }
  459. Platform::keyEventInternal(Keyboard::KEY_RELEASE, key);
  460. }
  461. - (void)deleteBackward
  462. {
  463. Platform::keyEventInternal(Keyboard::KEY_PRESS, Keyboard::KEY_BACKSPACE);
  464. Platform::keyEventInternal(Keyboard::KEY_CHAR, getUnicode(Keyboard::KEY_BACKSPACE));
  465. Platform::keyEventInternal(Keyboard::KEY_RELEASE, Keyboard::KEY_BACKSPACE);
  466. }
  467. - (BOOL)hasText
  468. {
  469. return YES;
  470. }
  471. - (void)touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event
  472. {
  473. unsigned int touchID = 0;
  474. for(UITouch* touch in touches)
  475. {
  476. CGPoint touchPoint = [touch locationInView:self];
  477. if(self.multipleTouchEnabled == YES)
  478. {
  479. touchID = [touch hash];
  480. }
  481. // Nested loop efficiency shouldn't be a concern since both loop sizes are small (<= 10)
  482. int i = 0;
  483. while (i < TOUCH_POINTS_MAX && __touchPoints[i].down)
  484. {
  485. i++;
  486. }
  487. if (i < TOUCH_POINTS_MAX)
  488. {
  489. __touchPoints[i].hashId = touchID;
  490. __touchPoints[i].x = touchPoint.x * WINDOW_SCALE;
  491. __touchPoints[i].y = touchPoint.y * WINDOW_SCALE;
  492. __touchPoints[i].down = true;
  493. Platform::touchEventInternal(Touch::TOUCH_PRESS, __touchPoints[i].x, __touchPoints[i].y, i);
  494. }
  495. else
  496. {
  497. print("touchesBegan: unable to find free element in __touchPoints");
  498. }
  499. }
  500. }
  501. - (void)touchesEnded:(NSSet*)touches withEvent:(UIEvent*)event
  502. {
  503. unsigned int touchID = 0;
  504. for(UITouch* touch in touches)
  505. {
  506. CGPoint touchPoint = [touch locationInView:self];
  507. if(self.multipleTouchEnabled == YES)
  508. touchID = [touch hash];
  509. // Nested loop efficiency shouldn't be a concern since both loop sizes are small (<= 10)
  510. bool found = false;
  511. for (int i = 0; !found && i < TOUCH_POINTS_MAX; i++)
  512. {
  513. if (__touchPoints[i].down && __touchPoints[i].hashId == touchID)
  514. {
  515. __touchPoints[i].down = false;
  516. Platform::touchEventInternal(Touch::TOUCH_RELEASE, touchPoint.x * WINDOW_SCALE, touchPoint.y * WINDOW_SCALE, i);
  517. found = true;
  518. }
  519. }
  520. if (!found)
  521. {
  522. // It seems possible to receive an ID not in the array.
  523. // The best we can do is clear the whole array.
  524. for (int i = 0; i < TOUCH_POINTS_MAX; i++)
  525. {
  526. if (__touchPoints[i].down)
  527. {
  528. __touchPoints[i].down = false;
  529. Platform::touchEventInternal(Touch::TOUCH_RELEASE, __touchPoints[i].x, __touchPoints[i].y, i);
  530. }
  531. }
  532. }
  533. }
  534. }
  535. - (void)touchesCancelled:(NSSet*)touches withEvent:(UIEvent*)event
  536. {
  537. // No equivalent for this in GamePlay -- treat as touch end
  538. [self touchesEnded:touches withEvent:event];
  539. }
  540. - (void)touchesMoved:(NSSet*)touches withEvent:(UIEvent*)event
  541. {
  542. unsigned int touchID = 0;
  543. for(UITouch* touch in touches)
  544. {
  545. CGPoint touchPoint = [touch locationInView:self];
  546. if(self.multipleTouchEnabled == YES)
  547. touchID = [touch hash];
  548. // Nested loop efficiency shouldn't be a concern since both loop sizes are small (<= 10)
  549. for (int i = 0; i < TOUCH_POINTS_MAX; i++)
  550. {
  551. if (__touchPoints[i].down && __touchPoints[i].hashId == touchID)
  552. {
  553. __touchPoints[i].x = touchPoint.x * WINDOW_SCALE;
  554. __touchPoints[i].y = touchPoint.y * WINDOW_SCALE;
  555. Platform::touchEventInternal(Touch::TOUCH_MOVE, __touchPoints[i].x, __touchPoints[i].y, i);
  556. break;
  557. }
  558. }
  559. }
  560. }
  561. // Gesture support for Mac OS X Trackpads
  562. - (bool)isGestureRegistered: (Gesture::GestureEvent) evt
  563. {
  564. switch(evt) {
  565. case Gesture::GESTURE_SWIPE:
  566. return (_swipeRecognizer != NULL);
  567. case Gesture::GESTURE_PINCH:
  568. return (_pinchRecognizer != NULL);
  569. case Gesture::GESTURE_TAP:
  570. return (_tapRecognizer != NULL);
  571. case Gesture::GESTURE_LONG_TAP:
  572. return (_longTapRecognizer != NULL);
  573. case Gesture::GESTURE_DRAG:
  574. case Gesture::GESTURE_DROP:
  575. return (_dragAndDropRecognizer != NULL);
  576. default:
  577. break;
  578. }
  579. return false;
  580. }
  581. - (void)registerGesture: (Gesture::GestureEvent) evt
  582. {
  583. if((evt & Gesture::GESTURE_SWIPE) == Gesture::GESTURE_SWIPE && _swipeRecognizer == NULL)
  584. {
  585. // right swipe (default)
  586. _swipeRecognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleSwipeGesture:)];
  587. [self addGestureRecognizer:_swipeRecognizer];
  588. // left swipe
  589. UISwipeGestureRecognizer *swipeGesture = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleSwipeGesture:)];
  590. swipeGesture.direction = UISwipeGestureRecognizerDirectionLeft;
  591. [self addGestureRecognizer:swipeGesture];
  592. [swipeGesture release];
  593. // up swipe
  594. UISwipeGestureRecognizer *swipeGesture2 = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleSwipeGesture:)];
  595. swipeGesture2.direction = UISwipeGestureRecognizerDirectionUp;
  596. [self addGestureRecognizer:swipeGesture2];
  597. [swipeGesture2 release];
  598. // down swipe
  599. UISwipeGestureRecognizer *swipeGesture3 = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleSwipeGesture:)];
  600. swipeGesture3.direction = UISwipeGestureRecognizerDirectionDown;
  601. [self addGestureRecognizer:swipeGesture3];
  602. [swipeGesture3 release];
  603. }
  604. if((evt & Gesture::GESTURE_PINCH) == Gesture::GESTURE_PINCH && _pinchRecognizer == NULL)
  605. {
  606. _pinchRecognizer = [[UIPinchGestureRecognizer alloc] initWithTarget:self action:@selector(handlePinchGesture:)];
  607. [self addGestureRecognizer:_pinchRecognizer];
  608. }
  609. if((evt & Gesture::GESTURE_TAP) == Gesture::GESTURE_TAP && _tapRecognizer == NULL)
  610. {
  611. _tapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTapGesture:)];
  612. [self addGestureRecognizer:_tapRecognizer];
  613. }
  614. if ((evt & Gesture::GESTURE_LONG_TAP) == Gesture::GESTURE_LONG_TAP && _longTapRecognizer == NULL)
  615. {
  616. if (_longPressRecognizer == NULL)
  617. {
  618. _longPressRecognizer =[[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handleLongPressGestures:)];
  619. _longPressRecognizer.minimumPressDuration = GESTURE_LONG_PRESS_DURATION_MIN;
  620. _longPressRecognizer.allowableMovement = CGFLOAT_MAX;
  621. [self addGestureRecognizer:_longPressRecognizer];
  622. }
  623. _longTapRecognizer = _longPressRecognizer;
  624. }
  625. if (((evt & Gesture::GESTURE_DRAG) == Gesture::GESTURE_DRAG || (evt & Gesture::GESTURE_DROP) == Gesture::GESTURE_DROP) && _dragAndDropRecognizer == NULL)
  626. {
  627. if (_longPressRecognizer == NULL)
  628. {
  629. _longPressRecognizer =[[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handleLongPressGestures:)];
  630. _longPressRecognizer.minimumPressDuration = GESTURE_LONG_PRESS_DURATION_MIN;
  631. _longPressRecognizer.allowableMovement = CGFLOAT_MAX;
  632. [self addGestureRecognizer:_longPressRecognizer];
  633. }
  634. _dragAndDropRecognizer = _longPressRecognizer;
  635. }
  636. }
  637. - (void)unregisterGesture: (Gesture::GestureEvent) evt
  638. {
  639. if((evt & Gesture::GESTURE_SWIPE) == Gesture::GESTURE_SWIPE && _swipeRecognizer != NULL)
  640. {
  641. [self removeGestureRecognizer:_swipeRecognizer];
  642. [_swipeRecognizer release];
  643. _swipeRecognizer = NULL;
  644. }
  645. if((evt & Gesture::GESTURE_PINCH) == Gesture::GESTURE_PINCH && _pinchRecognizer != NULL)
  646. {
  647. [self removeGestureRecognizer:_pinchRecognizer];
  648. [_pinchRecognizer release];
  649. _pinchRecognizer = NULL;
  650. }
  651. if((evt & Gesture::GESTURE_TAP) == Gesture::GESTURE_TAP && _tapRecognizer != NULL)
  652. {
  653. [self removeGestureRecognizer:_tapRecognizer];
  654. [_tapRecognizer release];
  655. _tapRecognizer = NULL;
  656. }
  657. if((evt & Gesture::GESTURE_LONG_TAP) == Gesture::GESTURE_LONG_TAP && _longTapRecognizer != NULL)
  658. {
  659. if (_longTapRecognizer == NULL)
  660. {
  661. [self removeGestureRecognizer:_longTapRecognizer];
  662. [_longTapRecognizer release];
  663. }
  664. _longTapRecognizer = NULL;
  665. }
  666. if (((evt & Gesture::GESTURE_DRAG) == Gesture::GESTURE_DRAG || (evt & Gesture::GESTURE_DROP) == Gesture::GESTURE_DROP) && _dragAndDropRecognizer != NULL)
  667. {
  668. if (_dragAndDropRecognizer == NULL)
  669. {
  670. [self removeGestureRecognizer:_dragAndDropRecognizer];
  671. [_dragAndDropRecognizer release];
  672. }
  673. _dragAndDropRecognizer = NULL;
  674. }
  675. }
  676. - (void)handleTapGesture:(UITapGestureRecognizer*)sender
  677. {
  678. CGPoint location = [sender locationInView:self];
  679. gameplay::Platform::gestureTapEventInternal(location.x * WINDOW_SCALE, location.y * WINDOW_SCALE);
  680. }
  681. - (void)handleLongTapGesture:(UILongPressGestureRecognizer*)sender
  682. {
  683. if (sender.state == UIGestureRecognizerStateBegan)
  684. {
  685. struct timeval time;
  686. gettimeofday(&time, NULL);
  687. __gestureLongTapStartTimestamp = (time.tv_sec * 1000) + (time.tv_usec / 1000);
  688. }
  689. else if (sender.state == UIGestureRecognizerStateEnded)
  690. {
  691. CGPoint location = [sender locationInView:self];
  692. struct timeval time;
  693. long currentTimeStamp;
  694. gettimeofday(&time, NULL);
  695. currentTimeStamp = (time.tv_sec * 1000) + (time.tv_usec / 1000);
  696. gameplay::Platform::gestureLongTapEventInternal(location.x * WINDOW_SCALE, location.y * WINDOW_SCALE, currentTimeStamp - __gestureLongTapStartTimestamp);
  697. }
  698. }
  699. - (void)handlePinchGesture:(UIPinchGestureRecognizer*)sender
  700. {
  701. CGFloat factor = [sender scale];
  702. CGPoint location = [sender locationInView:self];
  703. gameplay::Platform::gesturePinchEventInternal(location.x * WINDOW_SCALE, location.y * WINDOW_SCALE, factor);
  704. }
  705. - (void)handleSwipeGesture:(UISwipeGestureRecognizer*)sender
  706. {
  707. UISwipeGestureRecognizerDirection direction = [sender direction];
  708. CGPoint location = [sender locationInView:self];
  709. int gameplayDirection = 0;
  710. switch(direction) {
  711. case UISwipeGestureRecognizerDirectionRight:
  712. gameplayDirection = Gesture::SWIPE_DIRECTION_RIGHT;
  713. break;
  714. case UISwipeGestureRecognizerDirectionLeft:
  715. gameplayDirection = Gesture::SWIPE_DIRECTION_LEFT;
  716. break;
  717. case UISwipeGestureRecognizerDirectionUp:
  718. gameplayDirection = Gesture::SWIPE_DIRECTION_UP;
  719. break;
  720. case UISwipeGestureRecognizerDirectionDown:
  721. gameplayDirection = Gesture::SWIPE_DIRECTION_DOWN;
  722. break;
  723. }
  724. gameplay::Platform::gestureSwipeEventInternal(location.x * WINDOW_SCALE, location.y * WINDOW_SCALE, gameplayDirection);
  725. }
  726. - (void)handleLongPressGestures:(UILongPressGestureRecognizer*)sender
  727. {
  728. CGPoint location = [sender locationInView:self];
  729. if (sender.state == UIGestureRecognizerStateBegan)
  730. {
  731. struct timeval time;
  732. gettimeofday(&time, NULL);
  733. __gestureLongTapStartTimestamp = (time.tv_sec * 1000) + (time.tv_usec / 1000);
  734. __gestureLongPressStartPosition = location;
  735. }
  736. if (sender.state == UIGestureRecognizerStateChanged)
  737. {
  738. if (__gestureDraging)
  739. gameplay::Platform::gestureDragEventInternal(location.x * WINDOW_SCALE, location.y * WINDOW_SCALE);
  740. else
  741. {
  742. float delta = sqrt(pow(__gestureLongPressStartPosition.x - location.x, 2) + pow(__gestureLongPressStartPosition.y - location.y, 2));
  743. if (delta >= GESTURE_LONG_PRESS_DISTANCE_MIN)
  744. {
  745. __gestureDraging = true;
  746. gameplay::Platform::gestureDragEventInternal(__gestureLongPressStartPosition.x * WINDOW_SCALE, __gestureLongPressStartPosition.y * WINDOW_SCALE);
  747. }
  748. }
  749. }
  750. if (sender.state == UIGestureRecognizerStateEnded)
  751. {
  752. if (__gestureDraging)
  753. {
  754. gameplay::Platform::gestureDropEventInternal(location.x * WINDOW_SCALE, location.y * WINDOW_SCALE);
  755. __gestureDraging = false;
  756. }
  757. else
  758. {
  759. struct timeval time;
  760. long currentTimeStamp;
  761. gettimeofday(&time, NULL);
  762. currentTimeStamp = (time.tv_sec * 1000) + (time.tv_usec / 1000);
  763. gameplay::Platform::gestureLongTapEventInternal(location.x * WINDOW_SCALE, location.y * WINDOW_SCALE, currentTimeStamp - __gestureLongTapStartTimestamp);
  764. }
  765. }
  766. if ((sender.state == UIGestureRecognizerStateCancelled || sender.state == UIGestureRecognizerStateFailed) && __gestureDraging)
  767. {
  768. gameplay::Platform::gestureDropEventInternal(location.x * WINDOW_SCALE, location.y * WINDOW_SCALE);
  769. __gestureDraging = false;
  770. }
  771. }
  772. @end
  773. @interface ViewController : UIViewController
  774. - (void)startUpdating;
  775. - (void)stopUpdating;
  776. - (void)gameCenterViewControllerDidFinish:(GKGameCenterViewController *)gameCenterViewController;
  777. @end
  778. @implementation ViewController
  779. - (id)init
  780. {
  781. if((self = [super init]))
  782. {
  783. }
  784. return self;
  785. }
  786. - (void)dealloc
  787. {
  788. __view = nil;
  789. [super dealloc];
  790. }
  791. - (void)didReceiveMemoryWarning
  792. {
  793. [super didReceiveMemoryWarning];
  794. }
  795. #pragma mark - View lifecycle
  796. - (void)loadView
  797. {
  798. self.view = [[[View alloc] init] autorelease];
  799. if(__view == nil)
  800. {
  801. __view = (View*)self.view;
  802. }
  803. }
  804. - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
  805. {
  806. // Fetch the supported orientations array
  807. NSArray *supportedOrientations = NULL;
  808. if([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad)
  809. {
  810. supportedOrientations = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"UISupportedInterfaceOrientations~ipad"];
  811. }
  812. else if([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone)
  813. {
  814. supportedOrientations = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"UISupportedInterfaceOrientations~iphone"];
  815. }
  816. if(supportedOrientations == NULL)
  817. {
  818. supportedOrientations = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"UISupportedInterfaceOrientations"];
  819. }
  820. // If no supported orientations default to v1.0 handling (landscape only)
  821. if(supportedOrientations == nil) {
  822. return UIInterfaceOrientationIsLandscape(interfaceOrientation);
  823. }
  824. for(NSString *s in supportedOrientations) {
  825. if(interfaceOrientation == UIInterfaceOrientationEnum(s)) return YES;
  826. }
  827. return NO;
  828. }
  829. - (void)startUpdating
  830. {
  831. [(View*)self.view startUpdating];
  832. }
  833. - (void)stopUpdating
  834. {
  835. [(View*)self.view stopUpdating];
  836. }
  837. - (void)gameCenterViewControllerDidFinish:(GKGameCenterViewController *)gameCenterViewController
  838. {
  839. [self dismissViewControllerAnimated:YES completion:nil];
  840. }
  841. @end
  842. @interface AppDelegate : UIApplication <UIApplicationDelegate>
  843. {
  844. UIWindow* window;
  845. ViewController* viewController;
  846. CMMotionManager *motionManager;
  847. }
  848. @property (nonatomic, retain) ViewController *viewController;
  849. @end
  850. @implementation AppDelegate
  851. @synthesize viewController;
  852. - (BOOL)application:(UIApplication*)application didFinishLaunchingWithOptions:(NSDictionary*)launchOptions
  853. {
  854. __appDelegate = self;
  855. [UIApplication sharedApplication].statusBarHidden = YES;
  856. [[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];
  857. motionManager = [[CMMotionManager alloc] init];
  858. if([motionManager isAccelerometerAvailable] == YES)
  859. {
  860. motionManager.accelerometerUpdateInterval = 1 / 40.0; // 40Hz
  861. [motionManager startAccelerometerUpdates];
  862. }
  863. if([motionManager isGyroAvailable] == YES)
  864. {
  865. motionManager.gyroUpdateInterval = 1 / 40.0; // 40Hz
  866. [motionManager startGyroUpdates];
  867. }
  868. window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
  869. viewController = [[ViewController alloc] init];
  870. [window setRootViewController:viewController];
  871. [window makeKeyAndVisible];
  872. return YES;
  873. }
  874. - (BOOL)prefersStatusBarHidden
  875. {
  876. return YES;
  877. }
  878. - (void)getAccelerometerPitch:(float*)pitch roll:(float*)roll
  879. {
  880. float p = 0.0f;
  881. float r = 0.0f;
  882. CMAccelerometerData* accelerometerData = motionManager.accelerometerData;
  883. if(accelerometerData != nil)
  884. {
  885. float tx, ty, tz;
  886. switch ([[UIApplication sharedApplication] statusBarOrientation])
  887. {
  888. case UIInterfaceOrientationLandscapeRight:
  889. tx = -accelerometerData.acceleration.y;
  890. ty = accelerometerData.acceleration.x;
  891. break;
  892. case UIInterfaceOrientationLandscapeLeft:
  893. tx = accelerometerData.acceleration.y;
  894. ty = -accelerometerData.acceleration.x;
  895. break;
  896. case UIInterfaceOrientationPortraitUpsideDown:
  897. tx = -accelerometerData.acceleration.y;
  898. ty = -accelerometerData.acceleration.x;
  899. break;
  900. case UIInterfaceOrientationPortrait:
  901. tx = accelerometerData.acceleration.x;
  902. ty = accelerometerData.acceleration.y;
  903. break;
  904. }
  905. tz = accelerometerData.acceleration.z;
  906. p = atan(ty / sqrt(tx * tx + tz * tz)) * 180.0f * M_1_PI;
  907. r = atan(tx / sqrt(ty * ty + tz * tz)) * 180.0f * M_1_PI;
  908. }
  909. if(pitch != NULL)
  910. *pitch = p;
  911. if(roll != NULL)
  912. *roll = r;
  913. }
  914. - (void)getRawAccelX:(float*)x Y:(float*)y Z:(float*)z
  915. {
  916. CMAccelerometerData* accelerometerData = motionManager.accelerometerData;
  917. if(accelerometerData != nil)
  918. {
  919. *x = -9.81f * accelerometerData.acceleration.x;
  920. *y = -9.81f * accelerometerData.acceleration.y;
  921. *z = -9.81f * accelerometerData.acceleration.z;
  922. }
  923. }
  924. - (void)getRawGyroX:(float*)x Y:(float*)y Z:(float*)z
  925. {
  926. CMGyroData* gyroData = motionManager.gyroData;
  927. if(gyroData != nil)
  928. {
  929. *x = gyroData.rotationRate.x;
  930. *y = gyroData.rotationRate.y;
  931. *z = gyroData.rotationRate.z;
  932. }
  933. }
  934. - (void)applicationWillResignActive:(UIApplication*)application
  935. {
  936. [viewController stopUpdating];
  937. }
  938. - (void)applicationDidEnterBackground:(UIApplication*)application
  939. {
  940. [viewController stopUpdating];
  941. }
  942. - (void)applicationWillEnterForeground:(UIApplication*)application
  943. {
  944. [viewController startUpdating];
  945. }
  946. - (void)applicationDidBecomeActive:(UIApplication*)application
  947. {
  948. [viewController startUpdating];
  949. }
  950. - (void)applicationWillTerminate:(UIApplication*)application
  951. {
  952. [viewController stopUpdating];
  953. }
  954. - (void)dealloc
  955. {
  956. [window setRootViewController:nil];
  957. [viewController release];
  958. [window release];
  959. [motionManager release];
  960. [super dealloc];
  961. }
  962. @end
  963. double getMachTimeInMilliseconds()
  964. {
  965. static const double kOneMillion = 1000 * 1000;
  966. static mach_timebase_info_data_t s_timebase_info;
  967. if (s_timebase_info.denom == 0)
  968. (void) mach_timebase_info(&s_timebase_info);
  969. // mach_absolute_time() returns billionth of seconds, so divide by one million to get milliseconds
  970. GP_ASSERT(s_timebase_info.denom);
  971. return ((double)mach_absolute_time() * (double)s_timebase_info.numer) / (kOneMillion * (double)s_timebase_info.denom);
  972. }
  973. int getKey(unichar keyCode)
  974. {
  975. switch(keyCode)
  976. {
  977. case 0x0A:
  978. return Keyboard::KEY_RETURN;
  979. case 0x20:
  980. return Keyboard::KEY_SPACE;
  981. case 0x30:
  982. return Keyboard::KEY_ZERO;
  983. case 0x31:
  984. return Keyboard::KEY_ONE;
  985. case 0x32:
  986. return Keyboard::KEY_TWO;
  987. case 0x33:
  988. return Keyboard::KEY_THREE;
  989. case 0x34:
  990. return Keyboard::KEY_FOUR;
  991. case 0x35:
  992. return Keyboard::KEY_FIVE;
  993. case 0x36:
  994. return Keyboard::KEY_SIX;
  995. case 0x37:
  996. return Keyboard::KEY_SEVEN;
  997. case 0x38:
  998. return Keyboard::KEY_EIGHT;
  999. case 0x39:
  1000. return Keyboard::KEY_NINE;
  1001. case 0x41:
  1002. return Keyboard::KEY_CAPITAL_A;
  1003. case 0x42:
  1004. return Keyboard::KEY_CAPITAL_B;
  1005. case 0x43:
  1006. return Keyboard::KEY_CAPITAL_C;
  1007. case 0x44:
  1008. return Keyboard::KEY_CAPITAL_D;
  1009. case 0x45:
  1010. return Keyboard::KEY_CAPITAL_E;
  1011. case 0x46:
  1012. return Keyboard::KEY_CAPITAL_F;
  1013. case 0x47:
  1014. return Keyboard::KEY_CAPITAL_G;
  1015. case 0x48:
  1016. return Keyboard::KEY_CAPITAL_H;
  1017. case 0x49:
  1018. return Keyboard::KEY_CAPITAL_I;
  1019. case 0x4A:
  1020. return Keyboard::KEY_CAPITAL_J;
  1021. case 0x4B:
  1022. return Keyboard::KEY_CAPITAL_K;
  1023. case 0x4C:
  1024. return Keyboard::KEY_CAPITAL_L;
  1025. case 0x4D:
  1026. return Keyboard::KEY_CAPITAL_M;
  1027. case 0x4E:
  1028. return Keyboard::KEY_CAPITAL_N;
  1029. case 0x4F:
  1030. return Keyboard::KEY_CAPITAL_O;
  1031. case 0x50:
  1032. return Keyboard::KEY_CAPITAL_P;
  1033. case 0x51:
  1034. return Keyboard::KEY_CAPITAL_Q;
  1035. case 0x52:
  1036. return Keyboard::KEY_CAPITAL_R;
  1037. case 0x53:
  1038. return Keyboard::KEY_CAPITAL_S;
  1039. case 0x54:
  1040. return Keyboard::KEY_CAPITAL_T;
  1041. case 0x55:
  1042. return Keyboard::KEY_CAPITAL_U;
  1043. case 0x56:
  1044. return Keyboard::KEY_CAPITAL_V;
  1045. case 0x57:
  1046. return Keyboard::KEY_CAPITAL_W;
  1047. case 0x58:
  1048. return Keyboard::KEY_CAPITAL_X;
  1049. case 0x59:
  1050. return Keyboard::KEY_CAPITAL_Y;
  1051. case 0x5A:
  1052. return Keyboard::KEY_CAPITAL_Z;
  1053. case 0x61:
  1054. return Keyboard::KEY_A;
  1055. case 0x62:
  1056. return Keyboard::KEY_B;
  1057. case 0x63:
  1058. return Keyboard::KEY_C;
  1059. case 0x64:
  1060. return Keyboard::KEY_D;
  1061. case 0x65:
  1062. return Keyboard::KEY_E;
  1063. case 0x66:
  1064. return Keyboard::KEY_F;
  1065. case 0x67:
  1066. return Keyboard::KEY_G;
  1067. case 0x68:
  1068. return Keyboard::KEY_H;
  1069. case 0x69:
  1070. return Keyboard::KEY_I;
  1071. case 0x6A:
  1072. return Keyboard::KEY_J;
  1073. case 0x6B:
  1074. return Keyboard::KEY_K;
  1075. case 0x6C:
  1076. return Keyboard::KEY_L;
  1077. case 0x6D:
  1078. return Keyboard::KEY_M;
  1079. case 0x6E:
  1080. return Keyboard::KEY_N;
  1081. case 0x6F:
  1082. return Keyboard::KEY_O;
  1083. case 0x70:
  1084. return Keyboard::KEY_P;
  1085. case 0x71:
  1086. return Keyboard::KEY_Q;
  1087. case 0x72:
  1088. return Keyboard::KEY_R;
  1089. case 0x73:
  1090. return Keyboard::KEY_S;
  1091. case 0x74:
  1092. return Keyboard::KEY_T;
  1093. case 0x75:
  1094. return Keyboard::KEY_U;
  1095. case 0x76:
  1096. return Keyboard::KEY_V;
  1097. case 0x77:
  1098. return Keyboard::KEY_W;
  1099. case 0x78:
  1100. return Keyboard::KEY_X;
  1101. case 0x79:
  1102. return Keyboard::KEY_Y;
  1103. case 0x7A:
  1104. return Keyboard::KEY_Z;
  1105. default:
  1106. break;
  1107. // Symbol Row 3
  1108. case 0x2E:
  1109. return Keyboard::KEY_PERIOD;
  1110. case 0x2C:
  1111. return Keyboard::KEY_COMMA;
  1112. case 0x3F:
  1113. return Keyboard::KEY_QUESTION;
  1114. case 0x21:
  1115. return Keyboard::KEY_EXCLAM;
  1116. case 0x27:
  1117. return Keyboard::KEY_APOSTROPHE;
  1118. // Symbols Row 2
  1119. case 0x2D:
  1120. return Keyboard::KEY_MINUS;
  1121. case 0x2F:
  1122. return Keyboard::KEY_SLASH;
  1123. case 0x3A:
  1124. return Keyboard::KEY_COLON;
  1125. case 0x3B:
  1126. return Keyboard::KEY_SEMICOLON;
  1127. case 0x28:
  1128. return Keyboard::KEY_LEFT_PARENTHESIS;
  1129. case 0x29:
  1130. return Keyboard::KEY_RIGHT_PARENTHESIS;
  1131. case 0x24:
  1132. return Keyboard::KEY_DOLLAR;
  1133. case 0x26:
  1134. return Keyboard::KEY_AMPERSAND;
  1135. case 0x40:
  1136. return Keyboard::KEY_AT;
  1137. case 0x22:
  1138. return Keyboard::KEY_QUOTE;
  1139. // Numeric Symbols Row 1
  1140. case 0x5B:
  1141. return Keyboard::KEY_LEFT_BRACKET;
  1142. case 0x5D:
  1143. return Keyboard::KEY_RIGHT_BRACKET;
  1144. case 0x7B:
  1145. return Keyboard::KEY_LEFT_BRACE;
  1146. case 0x7D:
  1147. return Keyboard::KEY_RIGHT_BRACE;
  1148. case 0x23:
  1149. return Keyboard::KEY_NUMBER;
  1150. case 0x25:
  1151. return Keyboard::KEY_PERCENT;
  1152. case 0x5E:
  1153. return Keyboard::KEY_CIRCUMFLEX;
  1154. case 0x2A:
  1155. return Keyboard::KEY_ASTERISK;
  1156. case 0x2B:
  1157. return Keyboard::KEY_PLUS;
  1158. case 0x3D:
  1159. return Keyboard::KEY_EQUAL;
  1160. // Numeric Symbols Row 2
  1161. case 0x5F:
  1162. return Keyboard::KEY_UNDERSCORE;
  1163. case 0x5C:
  1164. return Keyboard::KEY_BACK_SLASH;
  1165. case 0x7C:
  1166. return Keyboard::KEY_BAR;
  1167. case 0x7E:
  1168. return Keyboard::KEY_TILDE;
  1169. case 0x3C:
  1170. return Keyboard::KEY_LESS_THAN;
  1171. case 0x3E:
  1172. return Keyboard::KEY_GREATER_THAN;
  1173. case 0x80:
  1174. return Keyboard::KEY_EURO;
  1175. case 0xA3:
  1176. return Keyboard::KEY_POUND;
  1177. case 0xA5:
  1178. return Keyboard::KEY_YEN;
  1179. case 0xB7:
  1180. return Keyboard::KEY_MIDDLE_DOT;
  1181. }
  1182. return Keyboard::KEY_NONE;
  1183. }
  1184. /**
  1185. * Returns the unicode value for the given keycode or zero if the key is not a valid printable character.
  1186. */
  1187. int getUnicode(int key)
  1188. {
  1189. switch (key)
  1190. {
  1191. case Keyboard::KEY_BACKSPACE:
  1192. return 0x0008;
  1193. case Keyboard::KEY_TAB:
  1194. return 0x0009;
  1195. case Keyboard::KEY_RETURN:
  1196. case Keyboard::KEY_KP_ENTER:
  1197. return 0x000A;
  1198. case Keyboard::KEY_ESCAPE:
  1199. return 0x001B;
  1200. case Keyboard::KEY_SPACE:
  1201. case Keyboard::KEY_EXCLAM:
  1202. case Keyboard::KEY_QUOTE:
  1203. case Keyboard::KEY_NUMBER:
  1204. case Keyboard::KEY_DOLLAR:
  1205. case Keyboard::KEY_PERCENT:
  1206. case Keyboard::KEY_CIRCUMFLEX:
  1207. case Keyboard::KEY_AMPERSAND:
  1208. case Keyboard::KEY_APOSTROPHE:
  1209. case Keyboard::KEY_LEFT_PARENTHESIS:
  1210. case Keyboard::KEY_RIGHT_PARENTHESIS:
  1211. case Keyboard::KEY_ASTERISK:
  1212. case Keyboard::KEY_PLUS:
  1213. case Keyboard::KEY_COMMA:
  1214. case Keyboard::KEY_MINUS:
  1215. case Keyboard::KEY_PERIOD:
  1216. case Keyboard::KEY_SLASH:
  1217. case Keyboard::KEY_ZERO:
  1218. case Keyboard::KEY_ONE:
  1219. case Keyboard::KEY_TWO:
  1220. case Keyboard::KEY_THREE:
  1221. case Keyboard::KEY_FOUR:
  1222. case Keyboard::KEY_FIVE:
  1223. case Keyboard::KEY_SIX:
  1224. case Keyboard::KEY_SEVEN:
  1225. case Keyboard::KEY_EIGHT:
  1226. case Keyboard::KEY_NINE:
  1227. case Keyboard::KEY_COLON:
  1228. case Keyboard::KEY_SEMICOLON:
  1229. case Keyboard::KEY_LESS_THAN:
  1230. case Keyboard::KEY_EQUAL:
  1231. case Keyboard::KEY_GREATER_THAN:
  1232. case Keyboard::KEY_QUESTION:
  1233. case Keyboard::KEY_AT:
  1234. case Keyboard::KEY_CAPITAL_A:
  1235. case Keyboard::KEY_CAPITAL_B:
  1236. case Keyboard::KEY_CAPITAL_C:
  1237. case Keyboard::KEY_CAPITAL_D:
  1238. case Keyboard::KEY_CAPITAL_E:
  1239. case Keyboard::KEY_CAPITAL_F:
  1240. case Keyboard::KEY_CAPITAL_G:
  1241. case Keyboard::KEY_CAPITAL_H:
  1242. case Keyboard::KEY_CAPITAL_I:
  1243. case Keyboard::KEY_CAPITAL_J:
  1244. case Keyboard::KEY_CAPITAL_K:
  1245. case Keyboard::KEY_CAPITAL_L:
  1246. case Keyboard::KEY_CAPITAL_M:
  1247. case Keyboard::KEY_CAPITAL_N:
  1248. case Keyboard::KEY_CAPITAL_O:
  1249. case Keyboard::KEY_CAPITAL_P:
  1250. case Keyboard::KEY_CAPITAL_Q:
  1251. case Keyboard::KEY_CAPITAL_R:
  1252. case Keyboard::KEY_CAPITAL_S:
  1253. case Keyboard::KEY_CAPITAL_T:
  1254. case Keyboard::KEY_CAPITAL_U:
  1255. case Keyboard::KEY_CAPITAL_V:
  1256. case Keyboard::KEY_CAPITAL_W:
  1257. case Keyboard::KEY_CAPITAL_X:
  1258. case Keyboard::KEY_CAPITAL_Y:
  1259. case Keyboard::KEY_CAPITAL_Z:
  1260. case Keyboard::KEY_LEFT_BRACKET:
  1261. case Keyboard::KEY_BACK_SLASH:
  1262. case Keyboard::KEY_RIGHT_BRACKET:
  1263. case Keyboard::KEY_UNDERSCORE:
  1264. case Keyboard::KEY_GRAVE:
  1265. case Keyboard::KEY_A:
  1266. case Keyboard::KEY_B:
  1267. case Keyboard::KEY_C:
  1268. case Keyboard::KEY_D:
  1269. case Keyboard::KEY_E:
  1270. case Keyboard::KEY_F:
  1271. case Keyboard::KEY_G:
  1272. case Keyboard::KEY_H:
  1273. case Keyboard::KEY_I:
  1274. case Keyboard::KEY_J:
  1275. case Keyboard::KEY_K:
  1276. case Keyboard::KEY_L:
  1277. case Keyboard::KEY_M:
  1278. case Keyboard::KEY_N:
  1279. case Keyboard::KEY_O:
  1280. case Keyboard::KEY_P:
  1281. case Keyboard::KEY_Q:
  1282. case Keyboard::KEY_R:
  1283. case Keyboard::KEY_S:
  1284. case Keyboard::KEY_T:
  1285. case Keyboard::KEY_U:
  1286. case Keyboard::KEY_V:
  1287. case Keyboard::KEY_W:
  1288. case Keyboard::KEY_X:
  1289. case Keyboard::KEY_Y:
  1290. case Keyboard::KEY_Z:
  1291. case Keyboard::KEY_LEFT_BRACE:
  1292. case Keyboard::KEY_BAR:
  1293. case Keyboard::KEY_RIGHT_BRACE:
  1294. case Keyboard::KEY_TILDE:
  1295. return key;
  1296. default:
  1297. return 0;
  1298. }
  1299. }
  1300. namespace gameplay
  1301. {
  1302. extern void print(const char* format, ...)
  1303. {
  1304. GP_ASSERT(format);
  1305. va_list argptr;
  1306. va_start(argptr, format);
  1307. vfprintf(stderr, format, argptr);
  1308. va_end(argptr);
  1309. }
  1310. extern int strcmpnocase(const char* s1, const char* s2)
  1311. {
  1312. return strcasecmp(s1, s2);
  1313. }
  1314. Platform::Platform(Game* game) : _game(game)
  1315. {
  1316. }
  1317. Platform::~Platform()
  1318. {
  1319. }
  1320. Platform* Platform::create(Game* game)
  1321. {
  1322. Platform* platform = new Platform(game);
  1323. return platform;
  1324. }
  1325. int Platform::enterMessagePump()
  1326. {
  1327. NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
  1328. [AppDelegate load];
  1329. UIApplicationMain(0, nil, NSStringFromClass([AppDelegate class]), NSStringFromClass([AppDelegate class]));
  1330. [pool release];
  1331. return EXIT_SUCCESS;
  1332. }
  1333. void Platform::signalShutdown()
  1334. {
  1335. // Cannot 'exit' an iOS Application
  1336. assert(false);
  1337. [__view stopUpdating];
  1338. exit(0);
  1339. }
  1340. bool Platform::canExit()
  1341. {
  1342. return false;
  1343. }
  1344. unsigned int Platform::getDisplayWidth()
  1345. {
  1346. #ifdef NSFoundationVersionNumber_iOS_7_1
  1347. if (NSFoundationVersionNumber > NSFoundationVersionNumber_iOS_7_1)
  1348. {
  1349. //iOS 8+
  1350. return [[UIScreen mainScreen] bounds].size.width * [[UIScreen mainScreen] scale];
  1351. }
  1352. else
  1353. #endif
  1354. {
  1355. CGSize size = DeviceOrientedSize([__appDelegate.viewController interfaceOrientation]);
  1356. return size.width;
  1357. }
  1358. }
  1359. unsigned int Platform::getDisplayHeight()
  1360. {
  1361. #ifdef NSFoundationVersionNumber_iOS_7_1
  1362. if (NSFoundationVersionNumber > NSFoundationVersionNumber_iOS_7_1)
  1363. {
  1364. //iOS 8+
  1365. return [[UIScreen mainScreen] bounds].size.height * [[UIScreen mainScreen] scale];
  1366. }
  1367. else
  1368. #endif
  1369. {
  1370. CGSize size = DeviceOrientedSize([__appDelegate.viewController interfaceOrientation]);
  1371. return size.height;
  1372. }
  1373. }
  1374. double Platform::getAbsoluteTime()
  1375. {
  1376. __timeAbsolute = getMachTimeInMilliseconds();
  1377. return __timeAbsolute;
  1378. }
  1379. void Platform::setAbsoluteTime(double time)
  1380. {
  1381. __timeAbsolute = time;
  1382. }
  1383. bool Platform::isVsync()
  1384. {
  1385. return __vsync;
  1386. }
  1387. void Platform::setVsync(bool enable)
  1388. {
  1389. __vsync = enable;
  1390. }
  1391. void Platform::swapBuffers()
  1392. {
  1393. if (__view)
  1394. [__view swapBuffers];
  1395. }
  1396. void Platform::sleep(long ms)
  1397. {
  1398. usleep(ms * 1000);
  1399. }
  1400. bool Platform::hasAccelerometer()
  1401. {
  1402. return true;
  1403. }
  1404. void Platform::getAccelerometerValues(float* pitch, float* roll)
  1405. {
  1406. [__appDelegate getAccelerometerPitch:pitch roll:roll];
  1407. }
  1408. void Platform::getSensorValues(float* accelX, float* accelY, float* accelZ, float* gyroX, float* gyroY, float* gyroZ)
  1409. {
  1410. float x, y, z;
  1411. [__appDelegate getRawAccelX:&x Y:&y Z:&z];
  1412. if (accelX)
  1413. {
  1414. *accelX = x;
  1415. }
  1416. if (accelY)
  1417. {
  1418. *accelY = y;
  1419. }
  1420. if (accelZ)
  1421. {
  1422. *accelZ = z;
  1423. }
  1424. [__appDelegate getRawGyroX:&x Y:&y Z:&z];
  1425. if (gyroX)
  1426. {
  1427. *gyroX = x;
  1428. }
  1429. if (gyroY)
  1430. {
  1431. *gyroY = y;
  1432. }
  1433. if (gyroZ)
  1434. {
  1435. *gyroZ = z;
  1436. }
  1437. }
  1438. void Platform::getArguments(int* argc, char*** argv)
  1439. {
  1440. if (argc)
  1441. *argc = __argc;
  1442. if (argv)
  1443. *argv = __argv;
  1444. }
  1445. bool Platform::hasMouse()
  1446. {
  1447. // not supported
  1448. return false;
  1449. }
  1450. void Platform::setMouseCaptured(bool captured)
  1451. {
  1452. // not supported
  1453. }
  1454. bool Platform::isMouseCaptured()
  1455. {
  1456. // not supported
  1457. return false;
  1458. }
  1459. void Platform::setCursorVisible(bool visible)
  1460. {
  1461. // not supported
  1462. }
  1463. bool Platform::isCursorVisible()
  1464. {
  1465. // not supported
  1466. return false;
  1467. }
  1468. void Platform::setMultiSampling(bool enabled)
  1469. {
  1470. //todo
  1471. }
  1472. bool Platform::isMultiSampling()
  1473. {
  1474. return false; //todo
  1475. }
  1476. void Platform::setMultiTouch(bool enabled)
  1477. {
  1478. __view.multipleTouchEnabled = enabled;
  1479. }
  1480. bool Platform::isMultiTouch()
  1481. {
  1482. return __view.multipleTouchEnabled;
  1483. }
  1484. void Platform::displayKeyboard(bool display)
  1485. {
  1486. if(__view)
  1487. {
  1488. if(display)
  1489. {
  1490. [__view showKeyboard];
  1491. }
  1492. else
  1493. {
  1494. [__view dismissKeyboard];
  1495. }
  1496. }
  1497. }
  1498. void Platform::shutdownInternal()
  1499. {
  1500. Game::getInstance()->shutdown();
  1501. }
  1502. bool Platform::isGestureSupported(Gesture::GestureEvent evt)
  1503. {
  1504. return true;
  1505. }
  1506. void Platform::registerGesture(Gesture::GestureEvent evt)
  1507. {
  1508. [__view registerGesture:evt];
  1509. }
  1510. void Platform::unregisterGesture(Gesture::GestureEvent evt)
  1511. {
  1512. [__view unregisterGesture:evt];
  1513. }
  1514. bool Platform::isGestureRegistered(Gesture::GestureEvent evt)
  1515. {
  1516. return [__view isGestureRegistered:evt];
  1517. }
  1518. void Platform::pollGamepadState(Gamepad* gamepad)
  1519. {
  1520. }
  1521. bool Platform::launchURL(const char *url)
  1522. {
  1523. if (url == NULL || *url == '\0')
  1524. return false;
  1525. return [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithUTF8String: url]]];
  1526. }
  1527. std::string Platform::displayFileDialog(size_t mode, const char* title, const char* filterDescription, const char* filterExtensions, const char* initialDirectory)
  1528. {
  1529. return "";
  1530. }
  1531. }
  1532. #endif
  1533. #endif