main.mm 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256
  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. // Setup Dear ImGui style
  42. ImGui::StyleColorsDark();
  43. //ImGui::StyleColorsLight();
  44. // Setup Platform/Renderer backends
  45. ImGui_ImplOSX_Init(self);
  46. ImGui_ImplOpenGL2_Init();
  47. // Load Fonts
  48. // - 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.
  49. // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple.
  50. // - 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).
  51. // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use Freetype for higher quality font rendering.
  52. // - Read 'docs/FONTS.md' for more instructions and details.
  53. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ !
  54. //style.FontSizeBase = 20.0f;
  55. //io.Fonts->AddFontDefault();
  56. //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf");
  57. //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf");
  58. //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf");
  59. //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Cousine-Regular.ttf");
  60. //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf");
  61. //IM_ASSERT(font != nullptr);
  62. }
  63. -(void)updateAndDrawDemoView
  64. {
  65. // Start the Dear ImGui frame
  66. ImGuiIO& io = ImGui::GetIO();
  67. ImGui_ImplOpenGL2_NewFrame();
  68. ImGui_ImplOSX_NewFrame(self);
  69. ImGui::NewFrame();
  70. // Our state (make them static = more or less global) as a convenience to keep the example terse.
  71. static bool show_demo_window = true;
  72. static bool show_another_window = false;
  73. static ImVec4 clear_color = ImVec4(0.45f, 0.55f, 0.60f, 1.00f);
  74. // 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!).
  75. if (show_demo_window)
  76. ImGui::ShowDemoWindow(&show_demo_window);
  77. // 2. Show a simple window that we create ourselves. We use a Begin/End pair to create a named window.
  78. {
  79. static float f = 0.0f;
  80. static int counter = 0;
  81. ImGui::Begin("Hello, world!"); // Create a window called "Hello, world!" and append into it.
  82. ImGui::Text("This is some useful text."); // Display some text (you can use a format strings too)
  83. ImGui::Checkbox("Demo Window", &show_demo_window); // Edit bools storing our window open/close state
  84. ImGui::Checkbox("Another Window", &show_another_window);
  85. ImGui::SliderFloat("float", &f, 0.0f, 1.0f); // Edit 1 float using a slider from 0.0f to 1.0f
  86. ImGui::ColorEdit3("clear color", (float*)&clear_color); // Edit 3 floats representing a color
  87. if (ImGui::Button("Button")) // Buttons return true when clicked (most widgets return true when edited/activated)
  88. counter++;
  89. ImGui::SameLine();
  90. ImGui::Text("counter = %d", counter);
  91. ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / io.Framerate, io.Framerate);
  92. ImGui::End();
  93. }
  94. // 3. Show another simple window.
  95. if (show_another_window)
  96. {
  97. 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)
  98. ImGui::Text("Hello from another window!");
  99. if (ImGui::Button("Close Me"))
  100. show_another_window = false;
  101. ImGui::End();
  102. }
  103. // Rendering
  104. ImGui::Render();
  105. ImDrawData* draw_data = ImGui::GetDrawData();
  106. [[self openGLContext] makeCurrentContext];
  107. GLsizei width = (GLsizei)(draw_data->DisplaySize.x * draw_data->FramebufferScale.x);
  108. GLsizei height = (GLsizei)(draw_data->DisplaySize.y * draw_data->FramebufferScale.y);
  109. glViewport(0, 0, width, height);
  110. glClearColor(clear_color.x * clear_color.w, clear_color.y * clear_color.w, clear_color.z * clear_color.w, clear_color.w);
  111. glClear(GL_COLOR_BUFFER_BIT);
  112. ImGui_ImplOpenGL2_RenderDrawData(draw_data);
  113. // Present
  114. [[self openGLContext] flushBuffer];
  115. if (!animationTimer)
  116. animationTimer = [NSTimer scheduledTimerWithTimeInterval:0.017 target:self selector:@selector(animationTimerFired:) userInfo:nil repeats:YES];
  117. }
  118. -(void)reshape { [super reshape]; [[self openGLContext] update]; [self updateAndDrawDemoView]; }
  119. -(void)drawRect:(NSRect)bounds { [self updateAndDrawDemoView]; }
  120. -(void)animationTimerFired:(NSTimer*)timer { [self setNeedsDisplay:YES]; }
  121. -(void)dealloc { animationTimer = nil; }
  122. @end
  123. //-----------------------------------------------------------------------------------
  124. // AppDelegate
  125. //-----------------------------------------------------------------------------------
  126. @interface AppDelegate : NSObject <NSApplicationDelegate>
  127. @property (nonatomic, readonly) NSWindow* window;
  128. @end
  129. @implementation AppDelegate
  130. @synthesize window = _window;
  131. -(BOOL)applicationShouldTerminateAfterLastWindowClosed:(NSApplication *)theApplication
  132. {
  133. return YES;
  134. }
  135. -(NSWindow*)window
  136. {
  137. if (_window != nil)
  138. return (_window);
  139. NSRect viewRect = NSMakeRect(100.0, 100.0, 100.0 + 1280.0, 100 + 720.0);
  140. _window = [[NSWindow alloc] initWithContentRect:viewRect styleMask:NSWindowStyleMaskTitled|NSWindowStyleMaskMiniaturizable|NSWindowStyleMaskResizable|NSWindowStyleMaskClosable backing:NSBackingStoreBuffered defer:YES];
  141. [_window setTitle:@"Dear ImGui OSX+OpenGL2 Example"];
  142. [_window setAcceptsMouseMovedEvents:YES];
  143. [_window setOpaque:YES];
  144. [_window makeKeyAndOrderFront:NSApp];
  145. return (_window);
  146. }
  147. -(void)setupMenu
  148. {
  149. NSMenu* mainMenuBar = [[NSMenu alloc] init];
  150. NSMenu* appMenu;
  151. NSMenuItem* menuItem;
  152. appMenu = [[NSMenu alloc] initWithTitle:@"Dear ImGui OSX+OpenGL2 Example"];
  153. menuItem = [appMenu addItemWithTitle:@"Quit Dear ImGui OSX+OpenGL2 Example" action:@selector(terminate:) keyEquivalent:@"q"];
  154. [menuItem setKeyEquivalentModifierMask:NSEventModifierFlagCommand];
  155. menuItem = [[NSMenuItem alloc] init];
  156. [menuItem setSubmenu:appMenu];
  157. [mainMenuBar addItem:menuItem];
  158. appMenu = nil;
  159. [NSApp setMainMenu:mainMenuBar];
  160. }
  161. -(void)dealloc
  162. {
  163. _window = nil;
  164. }
  165. -(void)applicationDidFinishLaunching:(NSNotification *)aNotification
  166. {
  167. // Make the application a foreground application (else it won't receive keyboard events)
  168. ProcessSerialNumber psn = {0, kCurrentProcess};
  169. TransformProcessType(&psn, kProcessTransformToForegroundApplication);
  170. // Menu
  171. [self setupMenu];
  172. NSOpenGLPixelFormatAttribute attrs[] =
  173. {
  174. NSOpenGLPFADoubleBuffer,
  175. NSOpenGLPFADepthSize, 32,
  176. 0
  177. };
  178. NSOpenGLPixelFormat* format = [[NSOpenGLPixelFormat alloc] initWithAttributes:attrs];
  179. AppView* view = [[AppView alloc] initWithFrame:self.window.frame pixelFormat:format];
  180. format = nil;
  181. #if MAC_OS_X_VERSION_MAX_ALLOWED >= 1070
  182. if (floor(NSAppKitVersionNumber) > NSAppKitVersionNumber10_6)
  183. [view setWantsBestResolutionOpenGLSurface:YES];
  184. #endif // MAC_OS_X_VERSION_MAX_ALLOWED >= 1070
  185. [self.window setContentView:view];
  186. if ([view openGLContext] == nil)
  187. NSLog(@"No OpenGL Context!");
  188. [view initialize];
  189. }
  190. @end
  191. //-----------------------------------------------------------------------------------
  192. // Application main() function
  193. //-----------------------------------------------------------------------------------
  194. int main(int argc, const char* argv[])
  195. {
  196. @autoreleasepool
  197. {
  198. NSApp = [NSApplication sharedApplication];
  199. AppDelegate* delegate = [[AppDelegate alloc] init];
  200. [[NSApplication sharedApplication] setDelegate:delegate];
  201. [NSApp run];
  202. }
  203. return NSApplicationMain(argc, argv);
  204. }