main.cpp (14164B)
1 // dear imgui: standalone example application for Android + OpenGL ES 3 2 // If you are new to dear imgui, see examples/README.txt and documentation at the top of imgui.cpp. 3 4 #include "imgui.h" 5 #include "imgui_impl_android.h" 6 #include "imgui_impl_opengl3.h" 7 #include <android/log.h> 8 #include <android_native_app_glue.h> 9 #include <android/asset_manager.h> 10 #include <EGL/egl.h> 11 #include <GLES3/gl3.h> 12 13 // Data 14 static EGLDisplay g_EglDisplay = EGL_NO_DISPLAY; 15 static EGLSurface g_EglSurface = EGL_NO_SURFACE; 16 static EGLContext g_EglContext = EGL_NO_CONTEXT; 17 static struct android_app* g_App = NULL; 18 static bool g_Initialized = false; 19 static char g_LogTag[] = "ImGuiExample"; 20 21 // Forward declarations of helper functions 22 static int ShowSoftKeyboardInput(); 23 static int PollUnicodeChars(); 24 static int GetAssetData(const char* filename, void** out_data); 25 26 void init(struct android_app* app) 27 { 28 if (g_Initialized) 29 return; 30 31 g_App = app; 32 ANativeWindow_acquire(g_App->window); 33 34 // Initialize EGL 35 // This is mostly boilerplate code for EGL... 36 { 37 g_EglDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY); 38 if (g_EglDisplay == EGL_NO_DISPLAY) 39 __android_log_print(ANDROID_LOG_ERROR, g_LogTag, "%s", "eglGetDisplay(EGL_DEFAULT_DISPLAY) returned EGL_NO_DISPLAY"); 40 41 if (eglInitialize(g_EglDisplay, 0, 0) != EGL_TRUE) 42 __android_log_print(ANDROID_LOG_ERROR, g_LogTag, "%s", "eglInitialize() returned with an error"); 43 44 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 }; 45 EGLint num_configs = 0; 46 if (eglChooseConfig(g_EglDisplay, egl_attributes, nullptr, 0, &num_configs) != EGL_TRUE) 47 __android_log_print(ANDROID_LOG_ERROR, g_LogTag, "%s", "eglChooseConfig() returned with an error"); 48 if (num_configs == 0) 49 __android_log_print(ANDROID_LOG_ERROR, g_LogTag, "%s", "eglChooseConfig() returned 0 matching config"); 50 51 // Get the first matching config 52 EGLConfig egl_config; 53 eglChooseConfig(g_EglDisplay, egl_attributes, &egl_config, 1, &num_configs); 54 EGLint egl_format; 55 eglGetConfigAttrib(g_EglDisplay, egl_config, EGL_NATIVE_VISUAL_ID, &egl_format); 56 ANativeWindow_setBuffersGeometry(g_App->window, 0, 0, egl_format); 57 58 const EGLint egl_context_attributes[] = { EGL_CONTEXT_CLIENT_VERSION, 3, EGL_NONE }; 59 g_EglContext = eglCreateContext(g_EglDisplay, egl_config, EGL_NO_CONTEXT, egl_context_attributes); 60 61 if (g_EglContext == EGL_NO_CONTEXT) 62 __android_log_print(ANDROID_LOG_ERROR, g_LogTag, "%s", "eglCreateContext() returned EGL_NO_CONTEXT"); 63 64 g_EglSurface = eglCreateWindowSurface(g_EglDisplay, egl_config, g_App->window, NULL); 65 eglMakeCurrent(g_EglDisplay, g_EglSurface, g_EglSurface, g_EglContext); 66 } 67 68 // Setup Dear ImGui context 69 IMGUI_CHECKVERSION(); 70 ImGui::CreateContext(); 71 ImGuiIO& io = ImGui::GetIO(); 72 73 // Disable loading/saving of .ini file from disk. 74 // FIXME: Consider using LoadIniSettingsFromMemory() / SaveIniSettingsToMemory() to save in appropriate location for Android. 75 io.IniFilename = NULL; 76 77 // Setup Dear ImGui style 78 ImGui::StyleColorsDark(); 79 //ImGui::StyleColorsClassic(); 80 81 // Setup Platform/Renderer backends 82 ImGui_ImplAndroid_Init(g_App->window); 83 ImGui_ImplOpenGL3_Init("#version 300 es"); 84 85 // Load Fonts 86 // - If no fonts are loaded, dear imgui will use the default font. You can also load multiple fonts and use ImGui::PushFont()/PopFont() to select them. 87 // - If the file cannot be loaded, the function will return NULL. Please handle those errors in your application (e.g. use an assertion, or display an error and quit). 88 // - The fonts will be rasterized at a given size (w/ oversampling) and stored into a texture when calling ImFontAtlas::Build()/GetTexDataAsXXXX(), which ImGui_ImplXXXX_NewFrame below will call. 89 // - Read 'docs/FONTS.md' for more instructions and details. 90 // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! 91 // - 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. 92 93 // We load the default font with increased size to improve readability on many devices with "high" DPI. 94 // FIXME: Put some effort into DPI awareness. 95 // Important: when calling AddFontFromMemoryTTF(), ownership of font_data is transfered by Dear ImGui by default (deleted is handled by Dear ImGui), unless we set FontDataOwnedByAtlas=false in ImFontConfig 96 ImFontConfig font_cfg; 97 font_cfg.SizePixels = 22.0f; 98 io.Fonts->AddFontDefault(&font_cfg); 99 //void* font_data; 100 //int font_data_size; 101 //ImFont* font; 102 //font_data_size = GetAssetData("Roboto-Medium.ttf", &font_data); 103 //font = io.Fonts->AddFontFromMemoryTTF(font_data, font_data_size, 16.0f); 104 //IM_ASSERT(font != NULL); 105 //font_data_size = GetAssetData("Cousine-Regular.ttf", &font_data); 106 //font = io.Fonts->AddFontFromMemoryTTF(font_data, font_data_size, 15.0f); 107 //IM_ASSERT(font != NULL); 108 //font_data_size = GetAssetData("DroidSans.ttf", &font_data); 109 //font = io.Fonts->AddFontFromMemoryTTF(font_data, font_data_size, 16.0f); 110 //IM_ASSERT(font != NULL); 111 //font_data_size = GetAssetData("ProggyTiny.ttf", &font_data); 112 //font = io.Fonts->AddFontFromMemoryTTF(font_data, font_data_size, 10.0f); 113 //IM_ASSERT(font != NULL); 114 //font_data_size = GetAssetData("ArialUni.ttf", &font_data); 115 //font = io.Fonts->AddFontFromMemoryTTF(font_data, font_data_size, 18.0f, NULL, io.Fonts->GetGlyphRangesJapanese()); 116 //IM_ASSERT(font != NULL); 117 118 // Arbitrary scale-up 119 // FIXME: Put some effort into DPI awareness 120 ImGui::GetStyle().ScaleAllSizes(3.0f); 121 122 g_Initialized = true; 123 } 124 125 void tick() 126 { 127 ImGuiIO& io = ImGui::GetIO(); 128 if (g_EglDisplay == EGL_NO_DISPLAY) 129 return; 130 131 // Our state 132 static bool show_demo_window = true; 133 static bool show_another_window = false; 134 static ImVec4 clear_color = ImVec4(0.45f, 0.55f, 0.60f, 1.00f); 135 136 // Poll Unicode characters via JNI 137 // FIXME: do not call this every frame because of JNI overhead 138 PollUnicodeChars(); 139 140 // Open on-screen (soft) input if requested by Dear ImGui 141 static bool WantTextInputLast = false; 142 if (io.WantTextInput && !WantTextInputLast) 143 ShowSoftKeyboardInput(); 144 WantTextInputLast = io.WantTextInput; 145 146 // Start the Dear ImGui frame 147 ImGui_ImplOpenGL3_NewFrame(); 148 ImGui_ImplAndroid_NewFrame(); 149 ImGui::NewFrame(); 150 151 // 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!). 152 if (show_demo_window) 153 ImGui::ShowDemoWindow(&show_demo_window); 154 155 // 2. Show a simple window that we create ourselves. We use a Begin/End pair to created a named window. 156 { 157 static float f = 0.0f; 158 static int counter = 0; 159 160 ImGui::Begin("Hello, world!"); // Create a window called "Hello, world!" and append into it. 161 162 ImGui::Text("This is some useful text."); // Display some text (you can use a format strings too) 163 ImGui::Checkbox("Demo Window", &show_demo_window); // Edit bools storing our window open/close state 164 ImGui::Checkbox("Another Window", &show_another_window); 165 166 ImGui::SliderFloat("float", &f, 0.0f, 1.0f); // Edit 1 float using a slider from 0.0f to 1.0f 167 ImGui::ColorEdit3("clear color", (float*)&clear_color); // Edit 3 floats representing a color 168 169 if (ImGui::Button("Button")) // Buttons return true when clicked (most widgets return true when edited/activated) 170 counter++; 171 ImGui::SameLine(); 172 ImGui::Text("counter = %d", counter); 173 174 ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate); 175 ImGui::End(); 176 } 177 178 // 3. Show another simple window. 179 if (show_another_window) 180 { 181 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) 182 ImGui::Text("Hello from another window!"); 183 if (ImGui::Button("Close Me")) 184 show_another_window = false; 185 ImGui::End(); 186 } 187 188 // Rendering 189 ImGui::Render(); 190 glViewport(0, 0, (int)io.DisplaySize.x, (int)io.DisplaySize.y); 191 glClearColor(clear_color.x * clear_color.w, clear_color.y * clear_color.w, clear_color.z * clear_color.w, clear_color.w); 192 glClear(GL_COLOR_BUFFER_BIT); 193 ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData()); 194 eglSwapBuffers(g_EglDisplay, g_EglSurface); 195 } 196 197 void shutdown() 198 { 199 if (!g_Initialized) 200 return; 201 202 // Cleanup 203 ImGui_ImplOpenGL3_Shutdown(); 204 ImGui_ImplAndroid_Shutdown(); 205 ImGui::DestroyContext(); 206 207 if (g_EglDisplay != EGL_NO_DISPLAY) 208 { 209 eglMakeCurrent(g_EglDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT); 210 211 if (g_EglContext != EGL_NO_CONTEXT) 212 eglDestroyContext(g_EglDisplay, g_EglContext); 213 214 if (g_EglSurface != EGL_NO_SURFACE) 215 eglDestroySurface(g_EglDisplay, g_EglSurface); 216 217 eglTerminate(g_EglDisplay); 218 } 219 220 g_EglDisplay = EGL_NO_DISPLAY; 221 g_EglContext = EGL_NO_CONTEXT; 222 g_EglSurface = EGL_NO_SURFACE; 223 ANativeWindow_release(g_App->window); 224 225 g_Initialized = false; 226 } 227 228 static void handleAppCmd(struct android_app* app, int32_t appCmd) 229 { 230 switch (appCmd) 231 { 232 case APP_CMD_SAVE_STATE: 233 break; 234 case APP_CMD_INIT_WINDOW: 235 init(app); 236 break; 237 case APP_CMD_TERM_WINDOW: 238 shutdown(); 239 break; 240 case APP_CMD_GAINED_FOCUS: 241 break; 242 case APP_CMD_LOST_FOCUS: 243 break; 244 } 245 } 246 247 static int32_t handleInputEvent(struct android_app* app, AInputEvent* inputEvent) 248 { 249 return ImGui_ImplAndroid_HandleInputEvent(inputEvent); 250 } 251 252 void android_main(struct android_app* app) 253 { 254 app->onAppCmd = handleAppCmd; 255 app->onInputEvent = handleInputEvent; 256 257 while (true) 258 { 259 int out_events; 260 struct android_poll_source* out_data; 261 262 // Poll all events. If the app is not visible, this loop blocks until g_Initialized == true. 263 while (ALooper_pollAll(g_Initialized ? 0 : -1, NULL, &out_events, (void**)&out_data) >= 0) 264 { 265 // Process one event 266 if (out_data != NULL) 267 out_data->process(app, out_data); 268 269 // Exit the app by returning from within the infinite loop 270 if (app->destroyRequested != 0) 271 { 272 // shutdown() should have been called already while processing the 273 // app command APP_CMD_TERM_WINDOW. But we play save here 274 if (!g_Initialized) 275 shutdown(); 276 277 return; 278 } 279 } 280 281 // Initiate a new frame 282 tick(); 283 } 284 } 285 286 // Unfortunately, there is no way to show the on-screen input from native code. 287 // Therefore, we call ShowSoftKeyboardInput() of the main activity implemented in MainActivity.kt via JNI. 288 static int ShowSoftKeyboardInput() 289 { 290 JavaVM* java_vm = g_App->activity->vm; 291 JNIEnv* java_env = NULL; 292 293 jint jni_return = java_vm->GetEnv((void**)&java_env, JNI_VERSION_1_6); 294 if (jni_return == JNI_ERR) 295 return -1; 296 297 jni_return = java_vm->AttachCurrentThread(&java_env, NULL); 298 if (jni_return != JNI_OK) 299 return -2; 300 301 jclass native_activity_clazz = java_env->GetObjectClass(g_App->activity->clazz); 302 if (native_activity_clazz == NULL) 303 return -3; 304 305 jmethodID method_id = java_env->GetMethodID(native_activity_clazz, "showSoftInput", "()V"); 306 if (method_id == NULL) 307 return -4; 308 309 java_env->CallVoidMethod(g_App->activity->clazz, method_id); 310 311 jni_return = java_vm->DetachCurrentThread(); 312 if (jni_return != JNI_OK) 313 return -5; 314 315 return 0; 316 } 317 318 // Unfortunately, the native KeyEvent implementation has no getUnicodeChar() function. 319 // Therefore, we implement the processing of KeyEvents in MainActivity.kt and poll 320 // the resulting Unicode characters here via JNI and send them to Dear ImGui. 321 static int PollUnicodeChars() 322 { 323 JavaVM* java_vm = g_App->activity->vm; 324 JNIEnv* java_env = NULL; 325 326 jint jni_return = java_vm->GetEnv((void**)&java_env, JNI_VERSION_1_6); 327 if (jni_return == JNI_ERR) 328 return -1; 329 330 jni_return = java_vm->AttachCurrentThread(&java_env, NULL); 331 if (jni_return != JNI_OK) 332 return -2; 333 334 jclass native_activity_clazz = java_env->GetObjectClass(g_App->activity->clazz); 335 if (native_activity_clazz == NULL) 336 return -3; 337 338 jmethodID method_id = java_env->GetMethodID(native_activity_clazz, "pollUnicodeChar", "()I"); 339 if (method_id == NULL) 340 return -4; 341 342 // Send the actual characters to Dear ImGui 343 ImGuiIO& io = ImGui::GetIO(); 344 jint unicode_character; 345 while ((unicode_character = java_env->CallIntMethod(g_App->activity->clazz, method_id)) != 0) 346 io.AddInputCharacter(unicode_character); 347 348 jni_return = java_vm->DetachCurrentThread(); 349 if (jni_return != JNI_OK) 350 return -5; 351 352 return 0; 353 } 354 355 // Helper to retrieve data placed into the assets/ directory (android/app/src/main/assets) 356 static int GetAssetData(const char* filename, void** outData) 357 { 358 int num_bytes = 0; 359 AAsset* asset_descriptor = AAssetManager_open(g_App->activity->assetManager, filename, AASSET_MODE_BUFFER); 360 if (asset_descriptor) 361 { 362 num_bytes = AAsset_getLength(asset_descriptor); 363 *outData = IM_ALLOC(num_bytes); 364 int64_t num_bytes_read = AAsset_read(asset_descriptor, *outData, num_bytes); 365 AAsset_close(asset_descriptor); 366 IM_ASSERT(num_bytes_read == num_bytes); 367 } 368 return num_bytes; 369 }