main.mm 10 KB

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