PlatformAndroid.cpp 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999
  1. #ifdef __ANDROID__
  2. #include "Base.h"
  3. #include "Platform.h"
  4. #include "FileSystem.h"
  5. #include "Game.h"
  6. #include "Form.h"
  7. #include <unistd.h>
  8. #include <android/sensor.h>
  9. #include <android_native_app_glue.h>
  10. #include <android/log.h>
  11. // Externally referenced global variables.
  12. struct android_app* __state;
  13. AAssetManager* __assetManager;
  14. static bool __initialized;
  15. static bool __suspended;
  16. static EGLDisplay __eglDisplay = EGL_NO_DISPLAY;
  17. static EGLContext __eglContext = EGL_NO_CONTEXT;
  18. static EGLSurface __eglSurface = EGL_NO_SURFACE;
  19. static EGLConfig __eglConfig = 0;
  20. static int __width;
  21. static int __height;
  22. static struct timespec __timespec;
  23. static double __timeStart;
  24. static double __timeAbsolute;
  25. static bool __vsync = WINDOW_VSYNC;
  26. static ASensorManager* __sensorManager;
  27. static ASensorEventQueue* __sensorEventQueue;
  28. static ASensorEvent __sensorEvent;
  29. static const ASensor* __accelerometerSensor;
  30. static int __orientationAngle = 90;
  31. static bool __multiTouch = false;
  32. static int __primaryTouchId = -1;
  33. static bool __displayKeyboard = false;
  34. // OpenGL VAO functions.
  35. static const char* __glExtensions;
  36. PFNGLBINDVERTEXARRAYOESPROC glBindVertexArray = NULL;
  37. PFNGLDELETEVERTEXARRAYSOESPROC glDeleteVertexArrays = NULL;
  38. PFNGLGENVERTEXARRAYSOESPROC glGenVertexArrays = NULL;
  39. PFNGLISVERTEXARRAYOESPROC glIsVertexArray = NULL;
  40. namespace gameplay
  41. {
  42. static double timespec2millis(struct timespec *a)
  43. {
  44. GP_ASSERT(a);
  45. return (1000.0 * a->tv_sec) + (0.000001 * a->tv_nsec);
  46. }
  47. extern void printError(const char* format, ...)
  48. {
  49. GP_ASSERT(format);
  50. va_list argptr;
  51. va_start(argptr, format);
  52. __android_log_vprint(ANDROID_LOG_INFO, "gameplay-native-activity", format, argptr);
  53. va_end(argptr);
  54. }
  55. static EGLenum checkErrorEGL(const char* msg)
  56. {
  57. GP_ASSERT(msg);
  58. static const char* errmsg[] =
  59. {
  60. "EGL function succeeded",
  61. "EGL is not initialized, or could not be initialized, for the specified display",
  62. "EGL cannot access a requested resource",
  63. "EGL failed to allocate resources for the requested operation",
  64. "EGL fail to access an unrecognized attribute or attribute value was passed in an attribute list",
  65. "EGLConfig argument does not name a valid EGLConfig",
  66. "EGLContext argument does not name a valid EGLContext",
  67. "EGL current surface of the calling thread is no longer valid",
  68. "EGLDisplay argument does not name a valid EGLDisplay",
  69. "EGL arguments are inconsistent",
  70. "EGLNativePixmapType argument does not refer to a valid native pixmap",
  71. "EGLNativeWindowType argument does not refer to a valid native window",
  72. "EGL one or more argument values are invalid",
  73. "EGLSurface argument does not name a valid surface configured for rendering",
  74. "EGL power management event has occurred",
  75. };
  76. EGLenum error = eglGetError();
  77. printError("%s: %s.", msg, errmsg[error - EGL_SUCCESS]);
  78. return error;
  79. }
  80. // Initialized EGL resources.
  81. static bool initEGL()
  82. {
  83. // Hard-coded to 32-bit/OpenGL ES 2.0.
  84. const EGLint eglConfigAttrs[] =
  85. {
  86. EGL_RED_SIZE, 8,
  87. EGL_GREEN_SIZE, 8,
  88. EGL_BLUE_SIZE, 8,
  89. EGL_ALPHA_SIZE, 8,
  90. EGL_DEPTH_SIZE, 24,
  91. EGL_STENCIL_SIZE, 8,
  92. EGL_SURFACE_TYPE, EGL_WINDOW_BIT,
  93. EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT,
  94. EGL_NONE
  95. };
  96. EGLint eglConfigCount;
  97. const EGLint eglContextAttrs[] =
  98. {
  99. EGL_CONTEXT_CLIENT_VERSION, 2,
  100. EGL_NONE
  101. };
  102. const EGLint eglSurfaceAttrs[] =
  103. {
  104. EGL_RENDER_BUFFER, EGL_BACK_BUFFER,
  105. EGL_NONE
  106. };
  107. if (__eglDisplay == EGL_NO_DISPLAY && __eglContext == EGL_NO_CONTEXT)
  108. {
  109. // Get the EGL display and initialize.
  110. __eglDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY);
  111. if (__eglDisplay == EGL_NO_DISPLAY)
  112. {
  113. checkErrorEGL("eglGetDisplay");
  114. goto error;
  115. }
  116. if (eglInitialize(__eglDisplay, NULL, NULL) != EGL_TRUE)
  117. {
  118. checkErrorEGL("eglInitialize");
  119. goto error;
  120. }
  121. if (eglChooseConfig(__eglDisplay, eglConfigAttrs, &__eglConfig, 1, &eglConfigCount) != EGL_TRUE || eglConfigCount == 0)
  122. {
  123. checkErrorEGL("eglChooseConfig");
  124. goto error;
  125. }
  126. __eglContext = eglCreateContext(__eglDisplay, __eglConfig, EGL_NO_CONTEXT, eglContextAttrs);
  127. if (__eglContext == EGL_NO_CONTEXT)
  128. {
  129. checkErrorEGL("eglCreateContext");
  130. goto error;
  131. }
  132. }
  133. // EGL_NATIVE_VISUAL_ID is an attribute of the EGLConfig that is
  134. // guaranteed to be accepted by ANativeWindow_setBuffersGeometry().
  135. // As soon as we picked a EGLConfig, we can safely reconfigure the
  136. // ANativeWindow buffers to match, using EGL_NATIVE_VISUAL_ID.
  137. EGLint format;
  138. eglGetConfigAttrib(__eglDisplay, __eglConfig, EGL_NATIVE_VISUAL_ID, &format);
  139. ANativeWindow_setBuffersGeometry(__state->window, 0, 0, format);
  140. __eglSurface = eglCreateWindowSurface(__eglDisplay, __eglConfig, __state->window, eglSurfaceAttrs);
  141. if (__eglSurface == EGL_NO_SURFACE)
  142. {
  143. checkErrorEGL("eglCreateWindowSurface");
  144. goto error;
  145. }
  146. if (eglMakeCurrent(__eglDisplay, __eglSurface, __eglSurface, __eglContext) != EGL_TRUE)
  147. {
  148. checkErrorEGL("eglMakeCurrent");
  149. goto error;
  150. }
  151. eglQuerySurface(__eglDisplay, __eglSurface, EGL_WIDTH, &__width);
  152. eglQuerySurface(__eglDisplay, __eglSurface, EGL_HEIGHT, &__height);
  153. if (__width < __height)
  154. __orientationAngle = 0;
  155. // Set vsync.
  156. eglSwapInterval(__eglDisplay, WINDOW_VSYNC ? 1 : 0);
  157. // Initialize OpenGL ES extensions.
  158. __glExtensions = (const char*)glGetString(GL_EXTENSIONS);
  159. if (strstr(__glExtensions, "GL_OES_vertex_array_object") || strstr(__glExtensions, "GL_ARB_vertex_array_object"))
  160. {
  161. // Disable VAO extension for now.
  162. glBindVertexArray = (PFNGLBINDVERTEXARRAYOESPROC)eglGetProcAddress("glBindVertexArrayOES");
  163. glDeleteVertexArrays = (PFNGLDELETEVERTEXARRAYSOESPROC)eglGetProcAddress("glDeleteVertexArrays");
  164. glGenVertexArrays = (PFNGLGENVERTEXARRAYSOESPROC)eglGetProcAddress("glGenVertexArraysOES");
  165. glIsVertexArray = (PFNGLISVERTEXARRAYOESPROC)eglGetProcAddress("glIsVertexArrayOES");
  166. }
  167. return true;
  168. error:
  169. return false;
  170. }
  171. static void destroyEGLSurface()
  172. {
  173. if (__eglDisplay != EGL_NO_DISPLAY)
  174. {
  175. eglMakeCurrent(__eglDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
  176. }
  177. if (__eglSurface != EGL_NO_SURFACE)
  178. {
  179. eglDestroySurface(__eglDisplay, __eglSurface);
  180. __eglSurface = EGL_NO_SURFACE;
  181. }
  182. }
  183. static void destroyEGLMain()
  184. {
  185. destroyEGLSurface();
  186. if (__eglContext != EGL_NO_CONTEXT)
  187. {
  188. eglDestroyContext(__eglDisplay, __eglContext);
  189. __eglContext = EGL_NO_CONTEXT;
  190. }
  191. if (__eglDisplay != EGL_NO_DISPLAY)
  192. {
  193. eglTerminate(__eglDisplay);
  194. __eglDisplay = EGL_NO_DISPLAY;
  195. }
  196. }
  197. // Display the android virtual keyboard.
  198. static void displayKeyboard(android_app* state, bool show)
  199. {
  200. // The following functions is supposed to show / hide functins from a native activity.. but currently do not work.
  201. // ANativeActivity_showSoftInput(state->activity, ANATIVEACTIVITY_SHOW_SOFT_INPUT_IMPLICIT);
  202. // ANativeActivity_hideSoftInput(state->activity, ANATIVEACTIVITY_HIDE_SOFT_INPUT_IMPLICIT_ONLY);
  203. GP_ASSERT(state && state->activity && state->activity->vm);
  204. // Show or hide the keyboard by calling the appropriate Java method through JNI instead.
  205. jint flags = 0;
  206. JavaVM* jvm = state->activity->vm;
  207. JNIEnv* env = NULL;
  208. jvm->GetEnv((void **)&env, JNI_VERSION_1_6);
  209. jint result = jvm->AttachCurrentThread(&env, NULL);
  210. if (result == JNI_ERR)
  211. {
  212. GP_ERROR("Failed to retrieve JVM environment to display keyboard.");
  213. return;
  214. }
  215. GP_ASSERT(env);
  216. // Retrieves NativeActivity.
  217. jobject lNativeActivity = state->activity->clazz;
  218. jclass ClassNativeActivity = env->GetObjectClass(lNativeActivity);
  219. // Retrieves Context.INPUT_METHOD_SERVICE.
  220. jclass ClassContext = env->FindClass("android/content/Context");
  221. jfieldID FieldINPUT_METHOD_SERVICE = env->GetStaticFieldID(ClassContext, "INPUT_METHOD_SERVICE", "Ljava/lang/String;");
  222. jobject INPUT_METHOD_SERVICE = env->GetStaticObjectField(ClassContext, FieldINPUT_METHOD_SERVICE);
  223. // Runs getSystemService(Context.INPUT_METHOD_SERVICE).
  224. jclass ClassInputMethodManager = env->FindClass("android/view/inputmethod/InputMethodManager");
  225. jmethodID MethodGetSystemService = env->GetMethodID(ClassNativeActivity, "getSystemService", "(Ljava/lang/String;)Ljava/lang/Object;");
  226. jobject lInputMethodManager = env->CallObjectMethod(lNativeActivity, MethodGetSystemService, INPUT_METHOD_SERVICE);
  227. // Runs getWindow().getDecorView().
  228. jmethodID MethodGetWindow = env->GetMethodID(ClassNativeActivity, "getWindow", "()Landroid/view/Window;");
  229. jobject lWindow = env->CallObjectMethod(lNativeActivity, MethodGetWindow);
  230. jclass ClassWindow = env->FindClass("android/view/Window");
  231. jmethodID MethodGetDecorView = env->GetMethodID(ClassWindow, "getDecorView", "()Landroid/view/View;");
  232. jobject lDecorView = env->CallObjectMethod(lWindow, MethodGetDecorView);
  233. if (show)
  234. {
  235. // Runs lInputMethodManager.showSoftInput(...).
  236. jmethodID MethodShowSoftInput = env->GetMethodID( ClassInputMethodManager, "showSoftInput", "(Landroid/view/View;I)Z");
  237. jboolean result = env->CallBooleanMethod(lInputMethodManager, MethodShowSoftInput, lDecorView, flags);
  238. }
  239. else
  240. {
  241. // Runs lWindow.getViewToken()
  242. jclass ClassView = env->FindClass("android/view/View");
  243. jmethodID MethodGetWindowToken = env->GetMethodID(ClassView, "getWindowToken", "()Landroid/os/IBinder;");
  244. jobject lBinder = env->CallObjectMethod(lDecorView, MethodGetWindowToken);
  245. // lInputMethodManager.hideSoftInput(...).
  246. jmethodID MethodHideSoftInput = env->GetMethodID(ClassInputMethodManager, "hideSoftInputFromWindow", "(Landroid/os/IBinder;I)Z");
  247. jboolean lRes = env->CallBooleanMethod( lInputMethodManager, MethodHideSoftInput, lBinder, flags);
  248. }
  249. // Finished with the JVM.
  250. jvm->DetachCurrentThread();
  251. }
  252. // Gets the Keyboard::Key enumeration constant that corresponds to the given Android key code.
  253. static Keyboard::Key getKey(int keycode, int metastate)
  254. {
  255. bool shiftOn = (metastate == AMETA_SHIFT_ON);
  256. switch(keycode)
  257. {
  258. case AKEYCODE_HOME:
  259. return Keyboard::KEY_HOME;
  260. case AKEYCODE_0:
  261. return Keyboard::KEY_ZERO;
  262. case AKEYCODE_1:
  263. return Keyboard::KEY_ONE;
  264. case AKEYCODE_2:
  265. return Keyboard::KEY_TWO;
  266. case AKEYCODE_3:
  267. return Keyboard::KEY_THREE;
  268. case AKEYCODE_4:
  269. return Keyboard::KEY_FOUR;
  270. case AKEYCODE_5:
  271. return Keyboard::KEY_FIVE;
  272. case AKEYCODE_6:
  273. return Keyboard::KEY_SIX;
  274. case AKEYCODE_7:
  275. return Keyboard::KEY_SEVEN;
  276. case AKEYCODE_8:
  277. return Keyboard::KEY_EIGHT;
  278. case AKEYCODE_9:
  279. return Keyboard::KEY_NINE;
  280. case AKEYCODE_STAR:
  281. return Keyboard::KEY_ASTERISK;
  282. case AKEYCODE_POUND:
  283. return Keyboard::KEY_NUMBER;
  284. case AKEYCODE_DPAD_UP:
  285. return Keyboard::KEY_UP_ARROW;
  286. case AKEYCODE_DPAD_DOWN:
  287. return Keyboard::KEY_DOWN_ARROW;
  288. case AKEYCODE_DPAD_LEFT:
  289. return Keyboard::KEY_LEFT_ARROW;
  290. case AKEYCODE_DPAD_RIGHT:
  291. return Keyboard::KEY_RIGHT_ARROW;
  292. case AKEYCODE_A:
  293. return (shiftOn) ? Keyboard::KEY_CAPITAL_A : Keyboard::KEY_A;
  294. case AKEYCODE_B:
  295. return (shiftOn) ? Keyboard::KEY_CAPITAL_B : Keyboard::KEY_B;
  296. case AKEYCODE_C:
  297. return (shiftOn) ? Keyboard::KEY_CAPITAL_C : Keyboard::KEY_C;
  298. case AKEYCODE_D:
  299. return (shiftOn) ? Keyboard::KEY_CAPITAL_D : Keyboard::KEY_D;
  300. case AKEYCODE_E:
  301. return (shiftOn) ? Keyboard::KEY_CAPITAL_E : Keyboard::KEY_E;
  302. case AKEYCODE_F:
  303. return (shiftOn) ? Keyboard::KEY_CAPITAL_F : Keyboard::KEY_F;
  304. case AKEYCODE_G:
  305. return (shiftOn) ? Keyboard::KEY_CAPITAL_G : Keyboard::KEY_G;
  306. case AKEYCODE_H:
  307. return (shiftOn) ? Keyboard::KEY_CAPITAL_H : Keyboard::KEY_H;
  308. case AKEYCODE_I:
  309. return (shiftOn) ? Keyboard::KEY_CAPITAL_I : Keyboard::KEY_I;
  310. case AKEYCODE_J:
  311. return (shiftOn) ? Keyboard::KEY_CAPITAL_J : Keyboard::KEY_J;
  312. case AKEYCODE_K:
  313. return (shiftOn) ? Keyboard::KEY_CAPITAL_K : Keyboard::KEY_K;
  314. case AKEYCODE_L:
  315. return (shiftOn) ? Keyboard::KEY_CAPITAL_L : Keyboard::KEY_L;
  316. case AKEYCODE_M:
  317. return (shiftOn) ? Keyboard::KEY_CAPITAL_M : Keyboard::KEY_M;
  318. case AKEYCODE_N:
  319. return (shiftOn) ? Keyboard::KEY_CAPITAL_N : Keyboard::KEY_N;
  320. case AKEYCODE_O:
  321. return (shiftOn) ? Keyboard::KEY_CAPITAL_O : Keyboard::KEY_O;
  322. case AKEYCODE_P:
  323. return (shiftOn) ? Keyboard::KEY_CAPITAL_P : Keyboard::KEY_P;
  324. case AKEYCODE_Q:
  325. return (shiftOn) ? Keyboard::KEY_CAPITAL_Q : Keyboard::KEY_Q;
  326. case AKEYCODE_R:
  327. return (shiftOn) ? Keyboard::KEY_CAPITAL_R : Keyboard::KEY_R;
  328. case AKEYCODE_S:
  329. return (shiftOn) ? Keyboard::KEY_CAPITAL_S : Keyboard::KEY_S;
  330. case AKEYCODE_T:
  331. return (shiftOn) ? Keyboard::KEY_CAPITAL_T : Keyboard::KEY_T;
  332. case AKEYCODE_U:
  333. return (shiftOn) ? Keyboard::KEY_CAPITAL_U : Keyboard::KEY_U;
  334. case AKEYCODE_V:
  335. return (shiftOn) ? Keyboard::KEY_CAPITAL_V : Keyboard::KEY_V;
  336. case AKEYCODE_W:
  337. return (shiftOn) ? Keyboard::KEY_CAPITAL_W : Keyboard::KEY_W;
  338. case AKEYCODE_X:
  339. return (shiftOn) ? Keyboard::KEY_CAPITAL_X : Keyboard::KEY_X;
  340. case AKEYCODE_Y:
  341. return (shiftOn) ? Keyboard::KEY_CAPITAL_Y : Keyboard::KEY_Y;
  342. case AKEYCODE_Z:
  343. return (shiftOn) ? Keyboard::KEY_CAPITAL_Y : Keyboard::KEY_Y;
  344. case AKEYCODE_COMMA:
  345. return Keyboard::KEY_COMMA;
  346. case AKEYCODE_PERIOD:
  347. return Keyboard::KEY_PERIOD;
  348. case AKEYCODE_ALT_LEFT:
  349. case AKEYCODE_ALT_RIGHT:
  350. return Keyboard::KEY_ALT;
  351. case AKEYCODE_SHIFT_LEFT:
  352. case AKEYCODE_SHIFT_RIGHT:
  353. return Keyboard::KEY_SHIFT;
  354. case AKEYCODE_TAB:
  355. return Keyboard::KEY_TAB;
  356. case AKEYCODE_SPACE:
  357. return Keyboard::KEY_SPACE;
  358. case AKEYCODE_ENTER:
  359. return Keyboard::KEY_RETURN;
  360. case AKEYCODE_DEL:
  361. return Keyboard::KEY_DELETE;
  362. case AKEYCODE_GRAVE:
  363. return Keyboard::KEY_GRAVE;
  364. case AKEYCODE_MINUS:
  365. return Keyboard::KEY_MINUS;
  366. case AKEYCODE_EQUALS:
  367. return Keyboard::KEY_EQUAL;
  368. case AKEYCODE_LEFT_BRACKET:
  369. return Keyboard::KEY_LEFT_BRACKET;
  370. case AKEYCODE_RIGHT_BRACKET:
  371. return Keyboard::KEY_RIGHT_BRACKET;
  372. case AKEYCODE_BACKSLASH:
  373. return Keyboard::KEY_BACK_SLASH;
  374. case AKEYCODE_SEMICOLON:
  375. return Keyboard::KEY_SEMICOLON;
  376. case AKEYCODE_APOSTROPHE:
  377. return Keyboard::KEY_APOSTROPHE;
  378. case AKEYCODE_SLASH:
  379. return Keyboard::KEY_SLASH;
  380. case AKEYCODE_AT:
  381. return Keyboard::KEY_AT;
  382. case AKEYCODE_PLUS:
  383. return Keyboard::KEY_PLUS;
  384. case AKEYCODE_PAGE_UP:
  385. return Keyboard::KEY_PG_UP;
  386. case AKEYCODE_PAGE_DOWN:
  387. return Keyboard::KEY_PG_DOWN;
  388. case AKEYCODE_MENU:
  389. return Keyboard::KEY_MENU;
  390. case AKEYCODE_SEARCH:
  391. return Keyboard::KEY_SEARCH;
  392. default:
  393. return Keyboard::KEY_NONE;
  394. }
  395. }
  396. /**
  397. * Returns the unicode value for the given keycode or zero if the key is not a valid printable character.
  398. */
  399. static int getUnicode(int keycode, int metastate)
  400. {
  401. if (keycode == AKEYCODE_DEL)
  402. return 0x0008;
  403. // TODO: Doesn't support unicode currently.
  404. Keyboard::Key key = getKey(keycode, metastate);
  405. switch (key)
  406. {
  407. case Keyboard::KEY_BACKSPACE:
  408. return 0x0008;
  409. case Keyboard::KEY_TAB:
  410. return 0x0009;
  411. case Keyboard::KEY_RETURN:
  412. case Keyboard::KEY_KP_ENTER:
  413. return 0x000A;
  414. case Keyboard::KEY_ESCAPE:
  415. return 0x001B;
  416. case Keyboard::KEY_SPACE:
  417. case Keyboard::KEY_EXCLAM:
  418. case Keyboard::KEY_QUOTE:
  419. case Keyboard::KEY_NUMBER:
  420. case Keyboard::KEY_DOLLAR:
  421. case Keyboard::KEY_PERCENT:
  422. case Keyboard::KEY_CIRCUMFLEX:
  423. case Keyboard::KEY_AMPERSAND:
  424. case Keyboard::KEY_APOSTROPHE:
  425. case Keyboard::KEY_LEFT_PARENTHESIS:
  426. case Keyboard::KEY_RIGHT_PARENTHESIS:
  427. case Keyboard::KEY_ASTERISK:
  428. case Keyboard::KEY_PLUS:
  429. case Keyboard::KEY_COMMA:
  430. case Keyboard::KEY_MINUS:
  431. case Keyboard::KEY_PERIOD:
  432. case Keyboard::KEY_SLASH:
  433. case Keyboard::KEY_ZERO:
  434. case Keyboard::KEY_ONE:
  435. case Keyboard::KEY_TWO:
  436. case Keyboard::KEY_THREE:
  437. case Keyboard::KEY_FOUR:
  438. case Keyboard::KEY_FIVE:
  439. case Keyboard::KEY_SIX:
  440. case Keyboard::KEY_SEVEN:
  441. case Keyboard::KEY_EIGHT:
  442. case Keyboard::KEY_NINE:
  443. case Keyboard::KEY_COLON:
  444. case Keyboard::KEY_SEMICOLON:
  445. case Keyboard::KEY_LESS_THAN:
  446. case Keyboard::KEY_EQUAL:
  447. case Keyboard::KEY_GREATER_THAN:
  448. case Keyboard::KEY_QUESTION:
  449. case Keyboard::KEY_AT:
  450. case Keyboard::KEY_CAPITAL_A:
  451. case Keyboard::KEY_CAPITAL_B:
  452. case Keyboard::KEY_CAPITAL_C:
  453. case Keyboard::KEY_CAPITAL_D:
  454. case Keyboard::KEY_CAPITAL_E:
  455. case Keyboard::KEY_CAPITAL_F:
  456. case Keyboard::KEY_CAPITAL_G:
  457. case Keyboard::KEY_CAPITAL_H:
  458. case Keyboard::KEY_CAPITAL_I:
  459. case Keyboard::KEY_CAPITAL_J:
  460. case Keyboard::KEY_CAPITAL_K:
  461. case Keyboard::KEY_CAPITAL_L:
  462. case Keyboard::KEY_CAPITAL_M:
  463. case Keyboard::KEY_CAPITAL_N:
  464. case Keyboard::KEY_CAPITAL_O:
  465. case Keyboard::KEY_CAPITAL_P:
  466. case Keyboard::KEY_CAPITAL_Q:
  467. case Keyboard::KEY_CAPITAL_R:
  468. case Keyboard::KEY_CAPITAL_S:
  469. case Keyboard::KEY_CAPITAL_T:
  470. case Keyboard::KEY_CAPITAL_U:
  471. case Keyboard::KEY_CAPITAL_V:
  472. case Keyboard::KEY_CAPITAL_W:
  473. case Keyboard::KEY_CAPITAL_X:
  474. case Keyboard::KEY_CAPITAL_Y:
  475. case Keyboard::KEY_CAPITAL_Z:
  476. case Keyboard::KEY_LEFT_BRACKET:
  477. case Keyboard::KEY_BACK_SLASH:
  478. case Keyboard::KEY_RIGHT_BRACKET:
  479. case Keyboard::KEY_UNDERSCORE:
  480. case Keyboard::KEY_GRAVE:
  481. case Keyboard::KEY_A:
  482. case Keyboard::KEY_B:
  483. case Keyboard::KEY_C:
  484. case Keyboard::KEY_D:
  485. case Keyboard::KEY_E:
  486. case Keyboard::KEY_F:
  487. case Keyboard::KEY_G:
  488. case Keyboard::KEY_H:
  489. case Keyboard::KEY_I:
  490. case Keyboard::KEY_J:
  491. case Keyboard::KEY_K:
  492. case Keyboard::KEY_L:
  493. case Keyboard::KEY_M:
  494. case Keyboard::KEY_N:
  495. case Keyboard::KEY_O:
  496. case Keyboard::KEY_P:
  497. case Keyboard::KEY_Q:
  498. case Keyboard::KEY_R:
  499. case Keyboard::KEY_S:
  500. case Keyboard::KEY_T:
  501. case Keyboard::KEY_U:
  502. case Keyboard::KEY_V:
  503. case Keyboard::KEY_W:
  504. case Keyboard::KEY_X:
  505. case Keyboard::KEY_Y:
  506. case Keyboard::KEY_Z:
  507. case Keyboard::KEY_LEFT_BRACE:
  508. case Keyboard::KEY_BAR:
  509. case Keyboard::KEY_RIGHT_BRACE:
  510. case Keyboard::KEY_TILDE:
  511. return key;
  512. default:
  513. return 0;
  514. }
  515. }
  516. // Process the next input event.
  517. static int32_t engine_handle_input(struct android_app* app, AInputEvent* event)
  518. {
  519. if (AInputEvent_getType(event) == AINPUT_EVENT_TYPE_MOTION)
  520. {
  521. int32_t action = AMotionEvent_getAction(event);
  522. size_t pointerIndex;
  523. size_t pointerId;
  524. size_t pointerCount;
  525. switch (action & AMOTION_EVENT_ACTION_MASK)
  526. {
  527. case AMOTION_EVENT_ACTION_DOWN:
  528. // Primary pointer down.
  529. pointerId = AMotionEvent_getPointerId(event, 0);
  530. gameplay::Platform::touchEventInternal(Touch::TOUCH_PRESS, AMotionEvent_getX(event, 0), AMotionEvent_getY(event, 0), pointerId);
  531. __primaryTouchId = pointerId;
  532. break;
  533. case AMOTION_EVENT_ACTION_UP:
  534. pointerId = AMotionEvent_getPointerId(event, 0);
  535. if (__multiTouch || __primaryTouchId == pointerId)
  536. {
  537. gameplay::Platform::touchEventInternal(Touch::TOUCH_RELEASE, AMotionEvent_getX(event, 0), AMotionEvent_getY(event, 0), pointerId);
  538. }
  539. __primaryTouchId = -1;
  540. break;
  541. case AMOTION_EVENT_ACTION_POINTER_DOWN:
  542. // Non-primary pointer down.
  543. if (__multiTouch)
  544. {
  545. pointerIndex = (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK) >> AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
  546. pointerId = AMotionEvent_getPointerId(event, pointerIndex);
  547. gameplay::Platform::touchEventInternal(Touch::TOUCH_PRESS, AMotionEvent_getX(event, pointerIndex), AMotionEvent_getY(event, pointerIndex), pointerId);
  548. }
  549. break;
  550. case AMOTION_EVENT_ACTION_POINTER_UP:
  551. pointerIndex = (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK) >> AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
  552. pointerId = AMotionEvent_getPointerId(event, pointerIndex);
  553. if (__multiTouch || __primaryTouchId == pointerId)
  554. {
  555. gameplay::Platform::touchEventInternal(Touch::TOUCH_RELEASE, AMotionEvent_getX(event, pointerIndex), AMotionEvent_getY(event, pointerIndex), pointerId);
  556. }
  557. if (__primaryTouchId == pointerId)
  558. __primaryTouchId = -1;
  559. break;
  560. case AMOTION_EVENT_ACTION_MOVE:
  561. // ACTION_MOVE events are batched, unlike the other events.
  562. pointerCount = AMotionEvent_getPointerCount(event);
  563. for (size_t i = 0; i < pointerCount; ++i)
  564. {
  565. pointerId = AMotionEvent_getPointerId(event, i);
  566. if (__multiTouch || __primaryTouchId == pointerId)
  567. {
  568. gameplay::Platform::touchEventInternal(Touch::TOUCH_MOVE, AMotionEvent_getX(event, i), AMotionEvent_getY(event, i), pointerId);
  569. }
  570. }
  571. break;
  572. }
  573. return 1;
  574. }
  575. else if (AInputEvent_getType(event) == AINPUT_EVENT_TYPE_KEY)
  576. {
  577. int32_t action = AKeyEvent_getAction(event);
  578. int32_t keycode = AKeyEvent_getKeyCode(event);
  579. int32_t metastate = AKeyEvent_getMetaState(event);
  580. switch(action)
  581. {
  582. case AKEY_EVENT_ACTION_DOWN:
  583. Game::getInstance()->keyEvent(Keyboard::KEY_PRESS, getKey(keycode, metastate));
  584. if (int character = getUnicode(keycode, metastate))
  585. gameplay::Platform::keyEventInternal(Keyboard::KEY_CHAR, character);
  586. break;
  587. case AKEY_EVENT_ACTION_UP:
  588. gameplay::Platform::keyEventInternal(Keyboard::KEY_RELEASE, getKey(keycode, metastate));
  589. break;
  590. }
  591. }
  592. return 0;
  593. }
  594. // Process the next main command.
  595. static void engine_handle_cmd(struct android_app* app, int32_t cmd)
  596. {
  597. switch (cmd)
  598. {
  599. case APP_CMD_INIT_WINDOW:
  600. // The window is being shown, get it ready.
  601. if (app->window != NULL)
  602. {
  603. initEGL();
  604. __initialized = true;
  605. }
  606. break;
  607. case APP_CMD_TERM_WINDOW:
  608. destroyEGLSurface();
  609. __initialized = false;
  610. break;
  611. case APP_CMD_DESTROY:
  612. Game::getInstance()->exit();
  613. destroyEGLMain();
  614. __initialized = false;
  615. break;
  616. case APP_CMD_GAINED_FOCUS:
  617. // When our app gains focus, we start monitoring the accelerometer.
  618. if (__accelerometerSensor != NULL)
  619. {
  620. ASensorEventQueue_enableSensor(__sensorEventQueue, __accelerometerSensor);
  621. // We'd like to get 60 events per second (in microseconds).
  622. ASensorEventQueue_setEventRate(__sensorEventQueue, __accelerometerSensor, (1000L/60)*1000);
  623. }
  624. if (Game::getInstance()->getState() == Game::UNINITIALIZED)
  625. {
  626. Game::getInstance()->run();
  627. }
  628. else
  629. {
  630. Game::getInstance()->resume();
  631. }
  632. break;
  633. case APP_CMD_RESUME:
  634. if (__initialized)
  635. {
  636. Game::getInstance()->resume();
  637. }
  638. __suspended = false;
  639. break;
  640. case APP_CMD_PAUSE:
  641. Game::getInstance()->pause();
  642. __suspended = true;
  643. break;
  644. case APP_CMD_LOST_FOCUS:
  645. // When our app loses focus, we stop monitoring the accelerometer.
  646. // This is to avoid consuming battery while not being used.
  647. if (__accelerometerSensor != NULL)
  648. {
  649. ASensorEventQueue_disableSensor(__sensorEventQueue, __accelerometerSensor);
  650. }
  651. break;
  652. }
  653. }
  654. Platform::Platform(Game* game)
  655. : _game(game)
  656. {
  657. }
  658. Platform::Platform(const Platform& copy)
  659. {
  660. // hidden
  661. }
  662. Platform::~Platform()
  663. {
  664. }
  665. Platform* Platform::create(Game* game, void* attachToWindow)
  666. {
  667. Platform* platform = new Platform(game);
  668. return platform;
  669. }
  670. int Platform::enterMessagePump()
  671. {
  672. GP_ASSERT(__state && __state->activity && __state->activity->vm);
  673. __initialized = false;
  674. __suspended = false;
  675. // Get the android application's activity.
  676. ANativeActivity* activity = __state->activity;
  677. JavaVM* jvm = __state->activity->vm;
  678. JNIEnv* env = NULL;
  679. jvm->GetEnv((void **)&env, JNI_VERSION_1_6);
  680. jint res = jvm->AttachCurrentThread(&env, NULL);
  681. if (res == JNI_ERR)
  682. {
  683. GP_ERROR("Failed to retrieve JVM environment when entering message pump.");
  684. return -1;
  685. }
  686. GP_ASSERT(env);
  687. // Get the package name for this app from Java.
  688. jclass clazz = env->GetObjectClass(activity->clazz);
  689. jmethodID methodID = env->GetMethodID(clazz, "getPackageName", "()Ljava/lang/String;");
  690. jobject result = env->CallObjectMethod(activity->clazz, methodID);
  691. const char* packageName;
  692. jboolean isCopy;
  693. packageName = env->GetStringUTFChars((jstring)result, &isCopy);
  694. jvm->DetachCurrentThread();
  695. // Set the default path to store the resources.
  696. std::string assetsPath = "/mnt/sdcard/android/data/";
  697. assetsPath += packageName;
  698. assetsPath += "/";
  699. FileSystem::setResourcePath(assetsPath.c_str());
  700. // Get the asset manager to get the resources from the .apk file.
  701. __assetManager = activity->assetManager;
  702. // Set the event call back functions.
  703. __state->onAppCmd = engine_handle_cmd;
  704. __state->onInputEvent = engine_handle_input;
  705. // Prepare to monitor accelerometer.
  706. __sensorManager = ASensorManager_getInstance();
  707. __accelerometerSensor = ASensorManager_getDefaultSensor(__sensorManager, ASENSOR_TYPE_ACCELEROMETER);
  708. __sensorEventQueue = ASensorManager_createEventQueue(__sensorManager, __state->looper, LOOPER_ID_USER, NULL, NULL);
  709. // Get the initial time.
  710. clock_gettime(CLOCK_REALTIME, &__timespec);
  711. __timeStart = timespec2millis(&__timespec);
  712. __timeAbsolute = 0L;
  713. while (true)
  714. {
  715. // Read all pending events.
  716. int ident;
  717. int events;
  718. struct android_poll_source* source;
  719. while ((ident=ALooper_pollAll(!__suspended ? 0 : -1, NULL, &events, (void**)&source)) >= 0)
  720. {
  721. // Process this event.
  722. if (source != NULL)
  723. source->process(__state, source);
  724. // If a sensor has data, process it now.
  725. if (ident == LOOPER_ID_USER && __accelerometerSensor != NULL)
  726. ASensorEventQueue_getEvents(__sensorEventQueue, &__sensorEvent, 1);
  727. if (__state->destroyRequested != 0)
  728. {
  729. return 0;
  730. }
  731. }
  732. // Idle time (no events left to process) is spent rendering.
  733. // We skip rendering when the app is paused.
  734. if (__initialized && !__suspended)
  735. {
  736. _game->frame();
  737. // Post the new frame to the display.
  738. // Note that there are a couple cases where eglSwapBuffers could fail
  739. // with an error code that requires a certain level of re-initialization:
  740. //
  741. // 1) EGL_BAD_NATIVE_WINDOW - Called when the surface we're currently using
  742. // is invalidated. This would require us to destroy our EGL surface,
  743. // close our OpenKODE window, and start again.
  744. //
  745. // 2) EGL_CONTEXT_LOST - Power management event that led to our EGL context
  746. // being lost. Requires us to re-create and re-initalize our EGL context
  747. // and all OpenGL ES state.
  748. //
  749. // For now, if we get these, we'll simply exit.
  750. int rc = eglSwapBuffers(__eglDisplay, __eglSurface);
  751. if (rc != EGL_TRUE)
  752. {
  753. EGLint error = eglGetError();
  754. if (error == EGL_BAD_NATIVE_WINDOW)
  755. {
  756. if (__state->window != NULL)
  757. {
  758. destroyEGLSurface();
  759. initEGL();
  760. }
  761. __initialized = true;
  762. }
  763. else
  764. {
  765. perror("eglSwapBuffers");
  766. break;
  767. }
  768. }
  769. }
  770. // Display the keyboard.
  771. gameplay::displayKeyboard(__state, __displayKeyboard);
  772. }
  773. }
  774. void Platform::signalShutdown()
  775. {
  776. // nothing to do
  777. }
  778. unsigned int Platform::getDisplayWidth()
  779. {
  780. return __width;
  781. }
  782. unsigned int Platform::getDisplayHeight()
  783. {
  784. return __height;
  785. }
  786. double Platform::getAbsoluteTime()
  787. {
  788. clock_gettime(CLOCK_REALTIME, &__timespec);
  789. double now = timespec2millis(&__timespec);
  790. __timeAbsolute = now - __timeStart;
  791. return __timeAbsolute;
  792. }
  793. void Platform::setAbsoluteTime(double time)
  794. {
  795. __timeAbsolute = time;
  796. }
  797. bool Platform::isVsync()
  798. {
  799. return __vsync;
  800. }
  801. void Platform::setVsync(bool enable)
  802. {
  803. eglSwapInterval(__eglDisplay, enable ? 1 : 0);
  804. __vsync = enable;
  805. }
  806. void Platform::setMultiTouch(bool enabled)
  807. {
  808. __multiTouch = enabled;
  809. }
  810. bool Platform::isMultiTouch()
  811. {
  812. return __multiTouch;
  813. }
  814. void Platform::getAccelerometerValues(float* pitch, float* roll)
  815. {
  816. double tx, ty, tz;
  817. ASensorEvent event;
  818. // By default, android accelerometer values are oriented to the portrait mode.
  819. // flipping the x and y to get the desired landscape mode values.
  820. if (__orientationAngle == 90)
  821. {
  822. tx = -__sensorEvent.acceleration.y;
  823. ty = __sensorEvent.acceleration.x;
  824. }
  825. else
  826. {
  827. tx = __sensorEvent.acceleration.x;
  828. ty = __sensorEvent.acceleration.y;
  829. }
  830. tz = __sensorEvent.acceleration.z;
  831. if (pitch != NULL)
  832. {
  833. GP_ASSERT(tx * tx + tz * tz);
  834. *pitch = -atan(ty / sqrt(tx * tx + tz * tz)) * 180.0f * M_1_PI;
  835. }
  836. if (roll != NULL)
  837. {
  838. GP_ASSERT(ty * ty + tz * tz);
  839. *roll = -atan(tx / sqrt(ty * ty + tz * tz)) * 180.0f * M_1_PI;
  840. }
  841. }
  842. bool Platform::hasMouse()
  843. {
  844. // not supported
  845. return false;
  846. }
  847. void Platform::setMouseCaptured(bool captured)
  848. {
  849. // not supported
  850. }
  851. bool Platform::isMouseCaptured()
  852. {
  853. // not supported
  854. return false;
  855. }
  856. void Platform::setCursorVisible(bool visible)
  857. {
  858. // not supported
  859. }
  860. bool Platform::isCursorVisible()
  861. {
  862. // not supported
  863. return false;
  864. }
  865. void Platform::swapBuffers()
  866. {
  867. if (__eglDisplay && __eglSurface)
  868. eglSwapBuffers(__eglDisplay, __eglSurface);
  869. }
  870. void Platform::displayKeyboard(bool display)
  871. {
  872. if (display)
  873. __displayKeyboard = true;
  874. else
  875. __displayKeyboard = false;
  876. }
  877. void Platform::touchEventInternal(Touch::TouchEvent evt, int x, int y, unsigned int contactIndex)
  878. {
  879. if (!Form::touchEventInternal(evt, x, y, contactIndex))
  880. Game::getInstance()->touchEvent(evt, x, y, contactIndex);
  881. }
  882. void Platform::keyEventInternal(Keyboard::KeyEvent evt, int key)
  883. {
  884. if (!Form::keyEventInternal(evt, key))
  885. Game::getInstance()->keyEvent(evt, key);
  886. }
  887. bool Platform::mouseEventInternal(Mouse::MouseEvent evt, int x, int y, int wheelDelta)
  888. {
  889. if (Form::mouseEventInternal(evt, x, y, wheelDelta))
  890. {
  891. return true;
  892. }
  893. else
  894. {
  895. return Game::getInstance()->mouseEvent(evt, x, y, wheelDelta);
  896. }
  897. }
  898. void Platform::sleep(long ms)
  899. {
  900. usleep(ms * 1000);
  901. }
  902. }
  903. #endif