imgui

FORK: Dear ImGui: Bloat-free Graphical User interface for C++ with minimal dependencies
git clone https://git.neptards.moe/neptards/imgui.git
Log | Files | Refs

main.mm (10952B)


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