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