2
0

main.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385
  1. // dear imgui: standalone example application for Android + OpenGL ES 3
  2. // Learn about Dear ImGui:
  3. // - FAQ https://dearimgui.com/faq
  4. // - Getting Started https://dearimgui.com/getting-started
  5. // - Documentation https://dearimgui.com/docs (same as your local docs/ folder).
  6. // - Introduction, links and more at the top of imgui.cpp
  7. #include "imgui.h"
  8. #include "imgui_impl_android.h"
  9. #include "imgui_impl_opengl3.h"
  10. #include <android/log.h>
  11. #include <android_native_app_glue.h>
  12. #include <android/asset_manager.h>
  13. #include <EGL/egl.h>
  14. #include <GLES3/gl3.h>
  15. #include <string>
  16. // Data
  17. static EGLDisplay g_EglDisplay = EGL_NO_DISPLAY;
  18. static EGLSurface g_EglSurface = EGL_NO_SURFACE;
  19. static EGLContext g_EglContext = EGL_NO_CONTEXT;
  20. static struct android_app* g_App = nullptr;
  21. static bool g_Initialized = false;
  22. static char g_LogTag[] = "ImGuiExample";
  23. static std::string g_IniFilename = "";
  24. // Forward declarations of helper functions
  25. static void Init(struct android_app* app);
  26. static void Shutdown();
  27. static void MainLoopStep();
  28. static int ShowSoftKeyboardInput();
  29. static int PollUnicodeChars();
  30. static int GetAssetData(const char* filename, void** out_data);
  31. // Main code
  32. static void handleAppCmd(struct android_app* app, int32_t appCmd)
  33. {
  34. switch (appCmd)
  35. {
  36. case APP_CMD_SAVE_STATE:
  37. break;
  38. case APP_CMD_INIT_WINDOW:
  39. Init(app);
  40. break;
  41. case APP_CMD_TERM_WINDOW:
  42. Shutdown();
  43. break;
  44. case APP_CMD_GAINED_FOCUS:
  45. case APP_CMD_LOST_FOCUS:
  46. break;
  47. }
  48. }
  49. static int32_t handleInputEvent(struct android_app* app, AInputEvent* inputEvent)
  50. {
  51. return ImGui_ImplAndroid_HandleInputEvent(inputEvent);
  52. }
  53. void android_main(struct android_app* app)
  54. {
  55. app->onAppCmd = handleAppCmd;
  56. app->onInputEvent = handleInputEvent;
  57. while (true)
  58. {
  59. int out_events;
  60. struct android_poll_source* out_data;
  61. // Poll all events. If the app is not visible, this loop blocks until g_Initialized == true.
  62. while (ALooper_pollOnce(g_Initialized ? 0 : -1, nullptr, &out_events, (void**)&out_data) >= 0)
  63. {
  64. // Process one event
  65. if (out_data != nullptr)
  66. out_data->process(app, out_data);
  67. // Exit the app by returning from within the infinite loop
  68. if (app->destroyRequested != 0)
  69. {
  70. // shutdown() should have been called already while processing the
  71. // app command APP_CMD_TERM_WINDOW. But we play save here
  72. if (!g_Initialized)
  73. Shutdown();
  74. return;
  75. }
  76. }
  77. // Initiate a new frame
  78. MainLoopStep();
  79. }
  80. }
  81. void Init(struct android_app* app)
  82. {
  83. if (g_Initialized)
  84. return;
  85. g_App = app;
  86. ANativeWindow_acquire(g_App->window);
  87. // Initialize EGL
  88. // This is mostly boilerplate code for EGL...
  89. {
  90. g_EglDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY);
  91. if (g_EglDisplay == EGL_NO_DISPLAY)
  92. __android_log_print(ANDROID_LOG_ERROR, g_LogTag, "%s", "eglGetDisplay(EGL_DEFAULT_DISPLAY) returned EGL_NO_DISPLAY");
  93. if (eglInitialize(g_EglDisplay, 0, 0) != EGL_TRUE)
  94. __android_log_print(ANDROID_LOG_ERROR, g_LogTag, "%s", "eglInitialize() returned with an error");
  95. const EGLint egl_attributes[] = { EGL_BLUE_SIZE, 8, EGL_GREEN_SIZE, 8, EGL_RED_SIZE, 8, EGL_DEPTH_SIZE, 24, EGL_SURFACE_TYPE, EGL_WINDOW_BIT, EGL_NONE };
  96. EGLint num_configs = 0;
  97. if (eglChooseConfig(g_EglDisplay, egl_attributes, nullptr, 0, &num_configs) != EGL_TRUE)
  98. __android_log_print(ANDROID_LOG_ERROR, g_LogTag, "%s", "eglChooseConfig() returned with an error");
  99. if (num_configs == 0)
  100. __android_log_print(ANDROID_LOG_ERROR, g_LogTag, "%s", "eglChooseConfig() returned 0 matching config");
  101. // Get the first matching config
  102. EGLConfig egl_config;
  103. eglChooseConfig(g_EglDisplay, egl_attributes, &egl_config, 1, &num_configs);
  104. EGLint egl_format;
  105. eglGetConfigAttrib(g_EglDisplay, egl_config, EGL_NATIVE_VISUAL_ID, &egl_format);
  106. ANativeWindow_setBuffersGeometry(g_App->window, 0, 0, egl_format);
  107. const EGLint egl_context_attributes[] = { EGL_CONTEXT_CLIENT_VERSION, 3, EGL_NONE };
  108. g_EglContext = eglCreateContext(g_EglDisplay, egl_config, EGL_NO_CONTEXT, egl_context_attributes);
  109. if (g_EglContext == EGL_NO_CONTEXT)
  110. __android_log_print(ANDROID_LOG_ERROR, g_LogTag, "%s", "eglCreateContext() returned EGL_NO_CONTEXT");
  111. g_EglSurface = eglCreateWindowSurface(g_EglDisplay, egl_config, g_App->window, nullptr);
  112. eglMakeCurrent(g_EglDisplay, g_EglSurface, g_EglSurface, g_EglContext);
  113. }
  114. // Setup Dear ImGui context
  115. IMGUI_CHECKVERSION();
  116. ImGui::CreateContext();
  117. ImGuiIO& io = ImGui::GetIO();
  118. // Redirect loading/saving of .ini file to our location.
  119. // Make sure 'g_IniFilename' persists while we use Dear ImGui.
  120. g_IniFilename = std::string(app->activity->internalDataPath) + "/imgui.ini";
  121. io.IniFilename = g_IniFilename.c_str();;
  122. // Setup Dear ImGui style
  123. ImGui::StyleColorsDark();
  124. //ImGui::StyleColorsLight();
  125. // Setup Platform/Renderer backends
  126. ImGui_ImplAndroid_Init(g_App->window);
  127. ImGui_ImplOpenGL3_Init("#version 300 es");
  128. // Setup scaling
  129. float main_scale = 2.0f;
  130. ImGuiStyle& style = ImGui::GetStyle();
  131. style.ScaleAllSizes(main_scale); // Bake a fixed style scale. (until we have a solution for dynamic style scaling, changing this requires resetting Style + calling this again)
  132. style.FontScaleDpi = main_scale; // Set initial font scale.
  133. // Load Fonts
  134. // - If fonts are not explicitly loaded, Dear ImGui will select an embedded font: either AddFontDefaultVector() or AddFontDefaultBitmap().
  135. // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a small threshold.
  136. // - You can load multiple fonts and use ImGui::PushFont()/PopFont() to select them.
  137. // - If a file cannot be loaded, AddFont functions will return a nullptr. Please handle those errors in your code (e.g. use an assertion, display an error and quit).
  138. // - Read 'docs/FONTS.md' for more instructions and details.
  139. // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use FreeType for higher quality font rendering.
  140. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ !
  141. // - Android: The TTF files have to be placed into the assets/ directory (android/app/src/main/assets), we use our GetAssetData() helper to retrieve them.
  142. //style.FontSizeBase = 20.0f;
  143. //io.Fonts->AddFontDefaultVector();
  144. //io.Fonts->AddFontDefaultBitmap();
  145. // Important: when calling AddFontFromMemoryTTF(), ownership of font_data is transferred by Dear ImGui by default (deleted is handled by Dear ImGui), unless we set FontDataOwnedByAtlas=false in ImFontConfig
  146. //void* font_data;
  147. //int font_data_size;
  148. //ImFont* font;
  149. //font_data_size = GetAssetData("segoeui.ttf", &font_data);
  150. //font = io.Fonts->AddFontFromMemoryTTF(font_data, font_data_size);
  151. //IM_ASSERT(font != nullptr);
  152. //font_data_size = GetAssetData("DroidSans.ttf", &font_data);
  153. //font = io.Fonts->AddFontFromMemoryTTF(font_data, font_data_size);
  154. //IM_ASSERT(font != nullptr);
  155. //font_data_size = GetAssetData("Roboto-Medium.ttf", &font_data);
  156. //font = io.Fonts->AddFontFromMemoryTTF(font_data, font_data_size);
  157. //IM_ASSERT(font != nullptr);
  158. //font_data_size = GetAssetData("Cousine-Regular.ttf", &font_data);
  159. //font = io.Fonts->AddFontFromMemoryTTF(font_data, font_data_size);
  160. //IM_ASSERT(font != nullptr);
  161. //font_data_size = GetAssetData("ArialUni.ttf", &font_data);
  162. //font = io.Fonts->AddFontFromMemoryTTF(font_data, font_data_size);
  163. //IM_ASSERT(font != nullptr);
  164. g_Initialized = true;
  165. }
  166. void MainLoopStep()
  167. {
  168. ImGuiIO& io = ImGui::GetIO();
  169. if (g_EglDisplay == EGL_NO_DISPLAY)
  170. return;
  171. // Our state
  172. // (we use static, which essentially makes the variable globals, as a convenience to keep the example code easy to follow)
  173. static bool show_demo_window = true;
  174. static bool show_another_window = false;
  175. static ImVec4 clear_color = ImVec4(0.45f, 0.55f, 0.60f, 1.00f);
  176. // Poll Unicode characters via JNI
  177. // FIXME: do not call this every frame because of JNI overhead
  178. PollUnicodeChars();
  179. // Open on-screen (soft) input if requested by Dear ImGui
  180. static bool WantTextInputLast = false;
  181. if (io.WantTextInput && !WantTextInputLast)
  182. ShowSoftKeyboardInput();
  183. WantTextInputLast = io.WantTextInput;
  184. // Start the Dear ImGui frame
  185. ImGui_ImplOpenGL3_NewFrame();
  186. ImGui_ImplAndroid_NewFrame();
  187. ImGui::NewFrame();
  188. // 1. Show the big demo window (Most of the sample code is in ImGui::ShowDemoWindow()! You can browse its code to learn more about Dear ImGui!).
  189. if (show_demo_window)
  190. ImGui::ShowDemoWindow(&show_demo_window);
  191. // 2. Show a simple window that we create ourselves. We use a Begin/End pair to create a named window.
  192. {
  193. static float f = 0.0f;
  194. static int counter = 0;
  195. ImGui::Begin("Hello, world!"); // Create a window called "Hello, world!" and append into it.
  196. ImGui::Text("This is some useful text."); // Display some text (you can use a format strings too)
  197. ImGui::Checkbox("Demo Window", &show_demo_window); // Edit bools storing our window open/close state
  198. ImGui::Checkbox("Another Window", &show_another_window);
  199. ImGui::SliderFloat("float", &f, 0.0f, 1.0f); // Edit 1 float using a slider from 0.0f to 1.0f
  200. ImGui::ColorEdit3("clear color", (float*)&clear_color); // Edit 3 floats representing a color
  201. if (ImGui::Button("Button")) // Buttons return true when clicked (most widgets return true when edited/activated)
  202. counter++;
  203. ImGui::SameLine();
  204. ImGui::Text("counter = %d", counter);
  205. ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / io.Framerate, io.Framerate);
  206. ImGui::End();
  207. }
  208. // 3. Show another simple window.
  209. if (show_another_window)
  210. {
  211. ImGui::Begin("Another Window", &show_another_window); // Pass a pointer to our bool variable (the window will have a closing button that will clear the bool when clicked)
  212. ImGui::Text("Hello from another window!");
  213. if (ImGui::Button("Close Me"))
  214. show_another_window = false;
  215. ImGui::End();
  216. }
  217. // Rendering
  218. ImGui::Render();
  219. glViewport(0, 0, (int)io.DisplaySize.x, (int)io.DisplaySize.y);
  220. glClearColor(clear_color.x * clear_color.w, clear_color.y * clear_color.w, clear_color.z * clear_color.w, clear_color.w);
  221. glClear(GL_COLOR_BUFFER_BIT);
  222. ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData());
  223. eglSwapBuffers(g_EglDisplay, g_EglSurface);
  224. }
  225. void Shutdown()
  226. {
  227. if (!g_Initialized)
  228. return;
  229. // Cleanup
  230. ImGui_ImplOpenGL3_Shutdown();
  231. ImGui_ImplAndroid_Shutdown();
  232. ImGui::DestroyContext();
  233. if (g_EglDisplay != EGL_NO_DISPLAY)
  234. {
  235. eglMakeCurrent(g_EglDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
  236. if (g_EglContext != EGL_NO_CONTEXT)
  237. eglDestroyContext(g_EglDisplay, g_EglContext);
  238. if (g_EglSurface != EGL_NO_SURFACE)
  239. eglDestroySurface(g_EglDisplay, g_EglSurface);
  240. eglTerminate(g_EglDisplay);
  241. }
  242. g_EglDisplay = EGL_NO_DISPLAY;
  243. g_EglContext = EGL_NO_CONTEXT;
  244. g_EglSurface = EGL_NO_SURFACE;
  245. ANativeWindow_release(g_App->window);
  246. g_Initialized = false;
  247. }
  248. // Helper functions
  249. // Unfortunately, there is no way to show the on-screen input from native code.
  250. // Therefore, we call ShowSoftKeyboardInput() of the main activity implemented in MainActivity.kt via JNI.
  251. static int ShowSoftKeyboardInput()
  252. {
  253. JavaVM* java_vm = g_App->activity->vm;
  254. JNIEnv* java_env = nullptr;
  255. jint jni_return = java_vm->GetEnv((void**)&java_env, JNI_VERSION_1_6);
  256. if (jni_return == JNI_ERR)
  257. return -1;
  258. jni_return = java_vm->AttachCurrentThread(&java_env, nullptr);
  259. if (jni_return != JNI_OK)
  260. return -2;
  261. jclass native_activity_clazz = java_env->GetObjectClass(g_App->activity->clazz);
  262. if (native_activity_clazz == nullptr)
  263. return -3;
  264. jmethodID method_id = java_env->GetMethodID(native_activity_clazz, "showSoftInput", "()V");
  265. if (method_id == nullptr)
  266. return -4;
  267. java_env->CallVoidMethod(g_App->activity->clazz, method_id);
  268. jni_return = java_vm->DetachCurrentThread();
  269. if (jni_return != JNI_OK)
  270. return -5;
  271. return 0;
  272. }
  273. // Unfortunately, the native KeyEvent implementation has no getUnicodeChar() function.
  274. // Therefore, we implement the processing of KeyEvents in MainActivity.kt and poll
  275. // the resulting Unicode characters here via JNI and send them to Dear ImGui.
  276. static int PollUnicodeChars()
  277. {
  278. JavaVM* java_vm = g_App->activity->vm;
  279. JNIEnv* java_env = nullptr;
  280. jint jni_return = java_vm->GetEnv((void**)&java_env, JNI_VERSION_1_6);
  281. if (jni_return == JNI_ERR)
  282. return -1;
  283. jni_return = java_vm->AttachCurrentThread(&java_env, nullptr);
  284. if (jni_return != JNI_OK)
  285. return -2;
  286. jclass native_activity_clazz = java_env->GetObjectClass(g_App->activity->clazz);
  287. if (native_activity_clazz == nullptr)
  288. return -3;
  289. jmethodID method_id = java_env->GetMethodID(native_activity_clazz, "pollUnicodeChar", "()I");
  290. if (method_id == nullptr)
  291. return -4;
  292. // Send the actual characters to Dear ImGui
  293. ImGuiIO& io = ImGui::GetIO();
  294. jint unicode_character;
  295. while ((unicode_character = java_env->CallIntMethod(g_App->activity->clazz, method_id)) != 0)
  296. io.AddInputCharacter(unicode_character);
  297. jni_return = java_vm->DetachCurrentThread();
  298. if (jni_return != JNI_OK)
  299. return -5;
  300. return 0;
  301. }
  302. // Helper to retrieve data placed into the assets/ directory (android/app/src/main/assets)
  303. static int GetAssetData(const char* filename, void** outData)
  304. {
  305. int num_bytes = 0;
  306. AAsset* asset_descriptor = AAssetManager_open(g_App->activity->assetManager, filename, AASSET_MODE_BUFFER);
  307. if (asset_descriptor)
  308. {
  309. num_bytes = AAsset_getLength(asset_descriptor);
  310. *outData = IM_ALLOC(num_bytes);
  311. int64_t num_bytes_read = AAsset_read(asset_descriptor, *outData, num_bytes);
  312. AAsset_close(asset_descriptor);
  313. IM_ASSERT(num_bytes_read == num_bytes);
  314. }
  315. return num_bytes;
  316. }