main.mm 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273
  1. // Dear ImGui: standalone example application for OSX + OpenGL2, using legacy fixed pipeline
  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. #import <Cocoa/Cocoa.h>
  8. #import <OpenGL/gl.h>
  9. #import <OpenGL/glu.h>
  10. #include "imgui.h"
  11. #include "imgui_impl_opengl2.h"
  12. #include "imgui_impl_osx.h"
  13. //-----------------------------------------------------------------------------------
  14. // AppView
  15. //-----------------------------------------------------------------------------------
  16. @interface AppView : NSOpenGLView
  17. {
  18. NSTimer* animationTimer;
  19. }
  20. @end
  21. @implementation AppView
  22. -(void)prepareOpenGL
  23. {
  24. [super prepareOpenGL];
  25. #ifndef DEBUG
  26. GLint swapInterval = 1;
  27. [[self openGLContext] setValues:&swapInterval forParameter:NSOpenGLCPSwapInterval];
  28. if (swapInterval == 0)
  29. NSLog(@"Error: Cannot set swap interval.");
  30. #endif
  31. }
  32. -(void)initialize
  33. {
  34. // Setup Dear ImGui context
  35. // FIXME: This example doesn't have proper cleanup...
  36. IMGUI_CHECKVERSION();
  37. ImGui::CreateContext();
  38. ImGuiIO& io = ImGui::GetIO(); (void)io;
  39. io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls
  40. io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls
  41. io.ConfigFlags |= ImGuiConfigFlags_DockingEnable; // Enable Docking
  42. io.ConfigFlags |= ImGuiConfigFlags_ViewportsEnable; // Enable Multi-Viewport / Platform Windows
  43. // Setup Dear ImGui style
  44. ImGui::StyleColorsDark();
  45. //ImGui::StyleColorsLight();
  46. // When viewports are enabled we tweak WindowRounding/WindowBg so platform windows can look identical to regular ones.
  47. ImGuiStyle& style = ImGui::GetStyle();
  48. if (io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable)
  49. {
  50. style.WindowRounding = 0.0f;
  51. style.Colors[ImGuiCol_WindowBg].w = 1.0f;
  52. }
  53. // Setup Platform/Renderer backends
  54. ImGui_ImplOSX_Init(self);
  55. ImGui_ImplOpenGL2_Init();
  56. // Load Fonts
  57. // - 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.
  58. // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple.
  59. // - If the file cannot be loaded, the function will return a nullptr. Please handle those errors in your application (e.g. use an assertion, or display an error and quit).
  60. // - 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.
  61. // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use Freetype for higher quality font rendering.
  62. // - Read 'docs/FONTS.md' for more instructions and details.
  63. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ !
  64. //io.Fonts->AddFontDefault();
  65. //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf", 18.0f);
  66. //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf", 16.0f);
  67. //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf", 16.0f);
  68. //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Cousine-Regular.ttf", 15.0f);
  69. //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f, nullptr, io.Fonts->GetGlyphRangesJapanese());
  70. //IM_ASSERT(font != nullptr);
  71. }
  72. -(void)updateAndDrawDemoView
  73. {
  74. // Start the Dear ImGui frame
  75. ImGuiIO& io = ImGui::GetIO();
  76. ImGui_ImplOpenGL2_NewFrame();
  77. ImGui_ImplOSX_NewFrame(self);
  78. ImGui::NewFrame();
  79. // Our state (make them static = more or less global) as a convenience to keep the example terse.
  80. static bool show_demo_window = true;
  81. static bool show_another_window = false;
  82. static ImVec4 clear_color = ImVec4(0.45f, 0.55f, 0.60f, 1.00f);
  83. // 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!).
  84. if (show_demo_window)
  85. ImGui::ShowDemoWindow(&show_demo_window);
  86. // 2. Show a simple window that we create ourselves. We use a Begin/End pair to create a named window.
  87. {
  88. static float f = 0.0f;
  89. static int counter = 0;
  90. ImGui::Begin("Hello, world!"); // Create a window called "Hello, world!" and append into it.
  91. ImGui::Text("This is some useful text."); // Display some text (you can use a format strings too)
  92. ImGui::Checkbox("Demo Window", &show_demo_window); // Edit bools storing our window open/close state
  93. ImGui::Checkbox("Another Window", &show_another_window);
  94. ImGui::SliderFloat("float", &f, 0.0f, 1.0f); // Edit 1 float using a slider from 0.0f to 1.0f
  95. ImGui::ColorEdit3("clear color", (float*)&clear_color); // Edit 3 floats representing a color
  96. if (ImGui::Button("Button")) // Buttons return true when clicked (most widgets return true when edited/activated)
  97. counter++;
  98. ImGui::SameLine();
  99. ImGui::Text("counter = %d", counter);
  100. ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / io.Framerate, io.Framerate);
  101. ImGui::End();
  102. }
  103. // 3. Show another simple window.
  104. if (show_another_window)
  105. {
  106. 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)
  107. ImGui::Text("Hello from another window!");
  108. if (ImGui::Button("Close Me"))
  109. show_another_window = false;
  110. ImGui::End();
  111. }
  112. // Rendering
  113. ImGui::Render();
  114. ImDrawData* draw_data = ImGui::GetDrawData();
  115. [[self openGLContext] makeCurrentContext];
  116. GLsizei width = (GLsizei)(draw_data->DisplaySize.x * draw_data->FramebufferScale.x);
  117. GLsizei height = (GLsizei)(draw_data->DisplaySize.y * draw_data->FramebufferScale.y);
  118. glViewport(0, 0, width, height);
  119. glClearColor(clear_color.x * clear_color.w, clear_color.y * clear_color.w, clear_color.z * clear_color.w, clear_color.w);
  120. glClear(GL_COLOR_BUFFER_BIT);
  121. ImGui_ImplOpenGL2_RenderDrawData(draw_data);
  122. // Update and Render additional Platform Windows
  123. if (io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable)
  124. {
  125. ImGui::UpdatePlatformWindows();
  126. ImGui::RenderPlatformWindowsDefault();
  127. }
  128. // Present
  129. [[self openGLContext] flushBuffer];
  130. if (!animationTimer)
  131. animationTimer = [NSTimer scheduledTimerWithTimeInterval:0.017 target:self selector:@selector(animationTimerFired:) userInfo:nil repeats:YES];
  132. }
  133. -(void)reshape { [super reshape]; [[self openGLContext] update]; [self updateAndDrawDemoView]; }
  134. -(void)drawRect:(NSRect)bounds { [self updateAndDrawDemoView]; }
  135. -(void)animationTimerFired:(NSTimer*)timer { [self setNeedsDisplay:YES]; }
  136. -(void)dealloc { animationTimer = nil; }
  137. @end
  138. //-----------------------------------------------------------------------------------
  139. // AppDelegate
  140. //-----------------------------------------------------------------------------------
  141. @interface AppDelegate : NSObject <NSApplicationDelegate>
  142. @property (nonatomic, readonly) NSWindow* window;
  143. @end
  144. @implementation AppDelegate
  145. @synthesize window = _window;
  146. -(BOOL)applicationShouldTerminateAfterLastWindowClosed:(NSApplication *)theApplication
  147. {
  148. return YES;
  149. }
  150. -(NSWindow*)window
  151. {
  152. if (_window != nil)
  153. return (_window);
  154. NSRect viewRect = NSMakeRect(100.0, 100.0, 100.0 + 1280.0, 100 + 720.0);
  155. _window = [[NSWindow alloc] initWithContentRect:viewRect styleMask:NSWindowStyleMaskTitled|NSWindowStyleMaskMiniaturizable|NSWindowStyleMaskResizable|NSWindowStyleMaskClosable backing:NSBackingStoreBuffered defer:YES];
  156. [_window setTitle:@"Dear ImGui OSX+OpenGL2 Example"];
  157. [_window setAcceptsMouseMovedEvents:YES];
  158. [_window setOpaque:YES];
  159. [_window makeKeyAndOrderFront:NSApp];
  160. return (_window);
  161. }
  162. -(void)setupMenu
  163. {
  164. NSMenu* mainMenuBar = [[NSMenu alloc] init];
  165. NSMenu* appMenu;
  166. NSMenuItem* menuItem;
  167. appMenu = [[NSMenu alloc] initWithTitle:@"Dear ImGui OSX+OpenGL2 Example"];
  168. menuItem = [appMenu addItemWithTitle:@"Quit Dear ImGui OSX+OpenGL2 Example" action:@selector(terminate:) keyEquivalent:@"q"];
  169. [menuItem setKeyEquivalentModifierMask:NSEventModifierFlagCommand];
  170. menuItem = [[NSMenuItem alloc] init];
  171. [menuItem setSubmenu:appMenu];
  172. [mainMenuBar addItem:menuItem];
  173. appMenu = nil;
  174. [NSApp setMainMenu:mainMenuBar];
  175. }
  176. -(void)dealloc
  177. {
  178. _window = nil;
  179. }
  180. -(void)applicationDidFinishLaunching:(NSNotification *)aNotification
  181. {
  182. // Make the application a foreground application (else it won't receive keyboard events)
  183. ProcessSerialNumber psn = {0, kCurrentProcess};
  184. TransformProcessType(&psn, kProcessTransformToForegroundApplication);
  185. // Menu
  186. [self setupMenu];
  187. NSOpenGLPixelFormatAttribute attrs[] =
  188. {
  189. NSOpenGLPFADoubleBuffer,
  190. NSOpenGLPFADepthSize, 32,
  191. 0
  192. };
  193. NSOpenGLPixelFormat* format = [[NSOpenGLPixelFormat alloc] initWithAttributes:attrs];
  194. AppView* view = [[AppView alloc] initWithFrame:self.window.frame pixelFormat:format];
  195. format = nil;
  196. #if MAC_OS_X_VERSION_MAX_ALLOWED >= 1070
  197. if (floor(NSAppKitVersionNumber) > NSAppKitVersionNumber10_6)
  198. [view setWantsBestResolutionOpenGLSurface:YES];
  199. #endif // MAC_OS_X_VERSION_MAX_ALLOWED >= 1070
  200. [self.window setContentView:view];
  201. if ([view openGLContext] == nil)
  202. NSLog(@"No OpenGL Context!");
  203. [view initialize];
  204. }
  205. @end
  206. //-----------------------------------------------------------------------------------
  207. // Application main() function
  208. //-----------------------------------------------------------------------------------
  209. int main(int argc, const char* argv[])
  210. {
  211. @autoreleasepool
  212. {
  213. NSApp = [NSApplication sharedApplication];
  214. AppDelegate* delegate = [[AppDelegate alloc] init];
  215. [[NSApplication sharedApplication] setDelegate:delegate];
  216. [NSApp run];
  217. }
  218. return NSApplicationMain(argc, argv);
  219. }