1// Dear ImGui: standalone example application for OSX + OpenGL2, using legacy fixed pipeline 2// If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp. 3// Read online: https://github.com/ocornut/imgui/tree/master/docs 4 5#import <Cocoa/Cocoa.h> 6#import <OpenGL/gl.h> 7#import <OpenGL/glu.h> 8 9#include "imgui.h" 10#include "imgui_impl_opengl2.h" 11#include "imgui_impl_osx.h" 12 13//----------------------------------------------------------------------------------- 14// AppView 15//----------------------------------------------------------------------------------- 16 17@interface AppView : NSOpenGLView 18{ 19 NSTimer* animationTimer; 20} 21@end 22 23@implementation AppView 24 25-(void)prepareOpenGL 26{ 27 [super prepareOpenGL]; 28 29#ifndef DEBUG 30 GLint swapInterval = 1; 31 [[self openGLContext] setValues:&swapInterval forParameter:NSOpenGLCPSwapInterval]; 32 if (swapInterval == 0) 33 NSLog(@"Error: Cannot set swap interval."); 34#endif 35} 36 37-(void)initialize 38{ 39 // Some events do not raise callbacks of AppView in some circumstances (for example when CMD key is held down). 40 // This monitor taps into global event stream and captures these events. 41 NSEventMask eventMask = NSEventMaskKeyDown | NSEventMaskKeyUp | NSEventMaskFlagsChanged; 42 [NSEvent addLocalMonitorForEventsMatchingMask:eventMask handler:^NSEvent * _Nullable(NSEvent *event) 43 { 44 ImGui_ImplOSX_HandleEvent(event, self); 45 return event; 46 }]; 47 48 // Setup Dear ImGui context 49 // FIXME: This example doesn't have proper cleanup... 50 IMGUI_CHECKVERSION(); 51 ImGui::CreateContext(); 52 ImGuiIO& io = ImGui::GetIO(); (void)io; 53 //io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls 54 //io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls 55 56 // Setup Dear ImGui style 57 ImGui::StyleColorsDark(); 58 //ImGui::StyleColorsClassic(); 59 60 // Setup Platform/Renderer backends 61 ImGui_ImplOSX_Init(); 62 ImGui_ImplOpenGL2_Init(); 63 64 // Load Fonts 65 // - 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. 66 // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple. 67 // - 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). 68 // - 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. 69 // - Read 'docs/FONTS.txt' for more instructions and details. 70 // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! 71 //io.Fonts->AddFontDefault(); 72 //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf", 16.0f); 73 //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Cousine-Regular.ttf", 15.0f); 74 //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf", 16.0f); 75 //io.Fonts->AddFontFromFileTTF("../../misc/fonts/ProggyTiny.ttf", 10.0f); 76 //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f, NULL, io.Fonts->GetGlyphRangesJapanese()); 77 //IM_ASSERT(font != NULL); 78} 79 80-(void)updateAndDrawDemoView 81{ 82 // Start the Dear ImGui frame 83 ImGui_ImplOpenGL2_NewFrame(); 84 ImGui_ImplOSX_NewFrame(self); 85 ImGui::NewFrame(); 86 87 // Our state (make them static = more or less global) as a convenience to keep the example terse. 88 static bool show_demo_window = true; 89 static bool show_another_window = false; 90 static ImVec4 clear_color = ImVec4(0.45f, 0.55f, 0.60f, 1.00f); 91 92 // 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!). 93 if (show_demo_window) 94 ImGui::ShowDemoWindow(&show_demo_window); 95 96 // 2. Show a simple window that we create ourselves. We use a Begin/End pair to created a named window. 97 { 98 static float f = 0.0f; 99 static int counter = 0; 100 101 ImGui::Begin("Hello, world!"); // Create a window called "Hello, world!" and append into it. 102 103 ImGui::Text("This is some useful text."); // Display some text (you can use a format strings too) 104 ImGui::Checkbox("Demo Window", &show_demo_window); // Edit bools storing our window open/close state 105 ImGui::Checkbox("Another Window", &show_another_window); 106 107 ImGui::SliderFloat("float", &f, 0.0f, 1.0f); // Edit 1 float using a slider from 0.0f to 1.0f 108 ImGui::ColorEdit3("clear color", (float*)&clear_color); // Edit 3 floats representing a color 109 110 if (ImGui::Button("Button")) // Buttons return true when clicked (most widgets return true when edited/activated) 111 counter++; 112 ImGui::SameLine(); 113 ImGui::Text("counter = %d", counter); 114 115 ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate); 116 ImGui::End(); 117 } 118 119 // 3. Show another simple window. 120 if (show_another_window) 121 { 122 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) 123 ImGui::Text("Hello from another window!"); 124 if (ImGui::Button("Close Me")) 125 show_another_window = false; 126 ImGui::End(); 127 } 128 129 // Rendering 130 ImGui::Render(); 131 ImDrawData* draw_data = ImGui::GetDrawData(); 132 133 [[self openGLContext] makeCurrentContext]; 134 GLsizei width = (GLsizei)(draw_data->DisplaySize.x * draw_data->FramebufferScale.x); 135 GLsizei height = (GLsizei)(draw_data->DisplaySize.y * draw_data->FramebufferScale.y); 136 glViewport(0, 0, width, height); 137 glClearColor(clear_color.x * clear_color.w, clear_color.y * clear_color.w, clear_color.z * clear_color.w, clear_color.w); 138 glClear(GL_COLOR_BUFFER_BIT); 139 140 ImGui_ImplOpenGL2_RenderDrawData(draw_data); 141 142 // Present 143 [[self openGLContext] flushBuffer]; 144 145 if (!animationTimer) 146 animationTimer = [NSTimer scheduledTimerWithTimeInterval:0.017 target:self selector:@selector(animationTimerFired:) userInfo:nil repeats:YES]; 147} 148 149-(void)reshape { [[self openGLContext] update]; [self updateAndDrawDemoView]; } 150-(void)drawRect:(NSRect)bounds { [self updateAndDrawDemoView]; } 151-(void)animationTimerFired:(NSTimer*)timer { [self setNeedsDisplay:YES]; } 152-(BOOL)acceptsFirstResponder { return (YES); } 153-(BOOL)becomeFirstResponder { return (YES); } 154-(BOOL)resignFirstResponder { return (YES); } 155-(void)dealloc { animationTimer = nil; } 156 157//----------------------------------------------------------------------------------- 158// Input processing 159//----------------------------------------------------------------------------------- 160 161// Forward Mouse/Keyboard events to Dear ImGui OSX backend. 162// Other events are registered via addLocalMonitorForEventsMatchingMask() 163-(void)mouseDown:(NSEvent *)event { ImGui_ImplOSX_HandleEvent(event, self); } 164-(void)rightMouseDown:(NSEvent *)event { ImGui_ImplOSX_HandleEvent(event, self); } 165-(void)otherMouseDown:(NSEvent *)event { ImGui_ImplOSX_HandleEvent(event, self); } 166-(void)mouseUp:(NSEvent *)event { ImGui_ImplOSX_HandleEvent(event, self); } 167-(void)rightMouseUp:(NSEvent *)event { ImGui_ImplOSX_HandleEvent(event, self); } 168-(void)otherMouseUp:(NSEvent *)event { ImGui_ImplOSX_HandleEvent(event, self); } 169-(void)mouseMoved:(NSEvent *)event { ImGui_ImplOSX_HandleEvent(event, self); } 170-(void)mouseDragged:(NSEvent *)event { ImGui_ImplOSX_HandleEvent(event, self); } 171-(void)rightMouseMoved:(NSEvent *)event { ImGui_ImplOSX_HandleEvent(event, self); } 172-(void)rightMouseDragged:(NSEvent *)event { ImGui_ImplOSX_HandleEvent(event, self); } 173-(void)otherMouseMoved:(NSEvent *)event { ImGui_ImplOSX_HandleEvent(event, self); } 174-(void)otherMouseDragged:(NSEvent *)event { ImGui_ImplOSX_HandleEvent(event, self); } 175-(void)scrollWheel:(NSEvent *)event { ImGui_ImplOSX_HandleEvent(event, self); } 176 177@end 178 179//----------------------------------------------------------------------------------- 180// AppDelegate 181//----------------------------------------------------------------------------------- 182 183@interface AppDelegate : NSObject <NSApplicationDelegate> 184@property (nonatomic, readonly) NSWindow* window; 185@end 186 187@implementation AppDelegate 188@synthesize window = _window; 189 190-(BOOL)applicationShouldTerminateAfterLastWindowClosed:(NSApplication *)theApplication 191{ 192 return YES; 193} 194 195-(NSWindow*)window 196{ 197 if (_window != nil) 198 return (_window); 199 200 NSRect viewRect = NSMakeRect(100.0, 100.0, 100.0 + 1280.0, 100 + 720.0); 201 202 _window = [[NSWindow alloc] initWithContentRect:viewRect styleMask:NSWindowStyleMaskTitled|NSWindowStyleMaskMiniaturizable|NSWindowStyleMaskResizable|NSWindowStyleMaskClosable backing:NSBackingStoreBuffered defer:YES]; 203 [_window setTitle:@"Dear ImGui OSX+OpenGL2 Example"]; 204 [_window setAcceptsMouseMovedEvents:YES]; 205 [_window setOpaque:YES]; 206 [_window makeKeyAndOrderFront:NSApp]; 207 208 return (_window); 209} 210 211-(void)setupMenu 212{ 213 NSMenu* mainMenuBar = [[NSMenu alloc] init]; 214 NSMenu* appMenu; 215 NSMenuItem* menuItem; 216 217 appMenu = [[NSMenu alloc] initWithTitle:@"Dear ImGui OSX+OpenGL2 Example"]; 218 menuItem = [appMenu addItemWithTitle:@"Quit Dear ImGui OSX+OpenGL2 Example" action:@selector(terminate:) keyEquivalent:@"q"]; 219 [menuItem setKeyEquivalentModifierMask:NSEventModifierFlagCommand]; 220 221 menuItem = [[NSMenuItem alloc] init]; 222 [menuItem setSubmenu:appMenu]; 223 224 [mainMenuBar addItem:menuItem]; 225 226 appMenu = nil; 227 [NSApp setMainMenu:mainMenuBar]; 228} 229 230-(void)dealloc 231{ 232 _window = nil; 233} 234 235-(void)applicationDidFinishLaunching:(NSNotification *)aNotification 236{ 237 // Make the application a foreground application (else it won't receive keyboard events) 238 ProcessSerialNumber psn = {0, kCurrentProcess}; 239 TransformProcessType(&psn, kProcessTransformToForegroundApplication); 240 241 // Menu 242 [self setupMenu]; 243 244 NSOpenGLPixelFormatAttribute attrs[] = 245 { 246 NSOpenGLPFADoubleBuffer, 247 NSOpenGLPFADepthSize, 32, 248 0 249 }; 250 251 NSOpenGLPixelFormat* format = [[NSOpenGLPixelFormat alloc] initWithAttributes:attrs]; 252 AppView* view = [[AppView alloc] initWithFrame:self.window.frame pixelFormat:format]; 253 format = nil; 254#if MAC_OS_X_VERSION_MAX_ALLOWED >= 1070 255 if (floor(NSAppKitVersionNumber) > NSAppKitVersionNumber10_6) 256 [view setWantsBestResolutionOpenGLSurface:YES]; 257#endif // MAC_OS_X_VERSION_MAX_ALLOWED >= 1070 258 [self.window setContentView:view]; 259 260 if ([view openGLContext] == nil) 261 NSLog(@"No OpenGL Context!"); 262 263 [view initialize]; 264} 265 266@end 267 268//----------------------------------------------------------------------------------- 269// Application main() function 270//----------------------------------------------------------------------------------- 271 272int main(int argc, const char* argv[]) 273{ 274 @autoreleasepool 275 { 276 NSApp = [NSApplication sharedApplication]; 277 AppDelegate* delegate = [[AppDelegate alloc] init]; 278 [[NSApplication sharedApplication] setDelegate:delegate]; 279 [NSApp run]; 280 } 281 return NSApplicationMain(argc, argv); 282} 283