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