12.6 KB、367行 生 Blame 履歴
1// Dear ImGui: standalone example application for OSX + Metal.
2
3// Learn about Dear ImGui:
4// - FAQ https://dearimgui.com/faq
5// - Getting Started https://dearimgui.com/getting-started
6// - Documentation https://dearimgui.com/docs (same as your local docs/ folder).
7// - Introduction, links and more at the top of imgui.cpp
8
9#import <Foundation/Foundation.h>
10
11#if TARGET_OS_OSX
12#import <Cocoa/Cocoa.h>
13#else
14#import <UIKit/UIKit.h>
15#endif
16
17#import <Metal/Metal.h>
18#import <MetalKit/MetalKit.h>
19
20#include "imgui.h"
21#include "imgui_impl_metal.h"
22#if TARGET_OS_OSX
23#include "imgui_impl_osx.h"
24@interface AppViewController : NSViewController<NSWindowDelegate>
25@end
26#else
27@interface AppViewController : UIViewController
28@end
29#endif
30
31@interface AppViewController () <MTKViewDelegate>
32@property (nonatomic, readonly) MTKView *mtkView;
33@property (nonatomic, strong) id <MTLDevice> device;
34@property (nonatomic, strong) id <MTLCommandQueue> commandQueue;
35@end
36
37//-----------------------------------------------------------------------------------
38// AppViewController
39//-----------------------------------------------------------------------------------
40
41@implementation AppViewController
42
43-(instancetype)initWithNibName:(nullable NSString *)nibNameOrNil bundle:(nullable NSBundle *)nibBundleOrNil
44{
45 self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
46
47 _device = MTLCreateSystemDefaultDevice();
48 _commandQueue = [_device newCommandQueue];
49
50 if (!self.device)
51 {
52 NSLog(@"Metal is not supported");
53 abort();
54 }
55
56 // Setup Dear ImGui context
57 // FIXME: This example doesn't have proper cleanup...
58 IMGUI_CHECKVERSION();
59 ImGui::CreateContext();
60 ImGuiIO& io = ImGui::GetIO(); (void)io;
61 io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls
62 io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls
63 io.ConfigFlags |= ImGuiConfigFlags_DockingEnable; // Enable Docking
64 io.ConfigFlags |= ImGuiConfigFlags_ViewportsEnable; // Enable Multi-Viewport / Platform Windows
65
66 // Setup Dear ImGui style
67 ImGui::StyleColorsDark();
68 //ImGui::StyleColorsLight();
69
70 // When viewports are enabled we tweak WindowRounding/WindowBg so platform windows can look identical to regular ones.
71 ImGuiStyle& style = ImGui::GetStyle();
72 if (io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable)
73 {
74 style.WindowRounding = 0.0f;
75 style.Colors[ImGuiCol_WindowBg].w = 1.0f;
76 }
77
78 // Setup Renderer backend
79 ImGui_ImplMetal_Init(_device);
80
81 // Load Fonts
82 // - If fonts are not explicitly loaded, Dear ImGui will select an embedded font: either AddFontDefaultVector() or AddFontDefaultBitmap().
83 // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a small threshold.
84 // - You can load multiple fonts and use ImGui::PushFont()/PopFont() to select them.
85 // - If a file cannot be loaded, AddFont functions will return a nullptr. Please handle those errors in your code (e.g. use an assertion, display an error and quit).
86 // - Read 'docs/FONTS.md' for more instructions and details.
87 // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use FreeType for higher quality font rendering.
88 // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ !
89 //style.FontSizeBase = 20.0f;
90 //io.Fonts->AddFontDefaultVector();
91 //io.Fonts->AddFontDefaultBitmap();
92 //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf");
93 //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf");
94 //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf");
95 //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Cousine-Regular.ttf");
96 //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf");
97 //IM_ASSERT(font != nullptr);
98
99 return self;
100}
101
102-(MTKView *)mtkView
103{
104 return (MTKView *)self.view;
105}
106
107-(void)loadView
108{
109 self.view = [[MTKView alloc] initWithFrame:CGRectMake(0, 0, 1200, 800)];
110}
111
112-(void)viewDidLoad
113{
114 [super viewDidLoad];
115
116 self.mtkView.device = self.device;
117 self.mtkView.delegate = self;
118
119#if TARGET_OS_OSX
120 ImGui_ImplOSX_Init(self.view);
121 [NSApp activateIgnoringOtherApps:YES];
122#endif
123}
124
125-(void)drawInMTKView:(MTKView*)view
126{
127 ImGuiIO& io = ImGui::GetIO();
128 io.DisplaySize.x = view.bounds.size.width;
129 io.DisplaySize.y = view.bounds.size.height;
130
131#if TARGET_OS_OSX
132 CGFloat framebufferScale = view.window.screen.backingScaleFactor ?: NSScreen.mainScreen.backingScaleFactor;
133#else
134 CGFloat framebufferScale = view.window.screen.scale ?: UIScreen.mainScreen.scale;
135#endif
136 io.DisplayFramebufferScale = ImVec2(framebufferScale, framebufferScale);
137
138 id<MTLCommandBuffer> commandBuffer = [self.commandQueue commandBuffer];
139
140 MTLRenderPassDescriptor* renderPassDescriptor = view.currentRenderPassDescriptor;
141 if (renderPassDescriptor == nil)
142 {
143 [commandBuffer commit];
144 return;
145 }
146
147 // Start the Dear ImGui frame
148 ImGui_ImplMetal_NewFrame(renderPassDescriptor);
149#if TARGET_OS_OSX
150 ImGui_ImplOSX_NewFrame(view);
151#endif
152 ImGui::NewFrame();
153
154 // Our state (make them static = more or less global) as a convenience to keep the example terse.
155 static bool show_demo_window = true;
156 static bool show_another_window = false;
157 static ImVec4 clear_color = ImVec4(0.45f, 0.55f, 0.60f, 1.00f);
158
159 // 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!).
160 if (show_demo_window)
161 ImGui::ShowDemoWindow(&show_demo_window);
162
163 // 2. Show a simple window that we create ourselves. We use a Begin/End pair to create a named window.
164 {
165 static float f = 0.0f;
166 static int counter = 0;
167
168 ImGui::Begin("Hello, world!"); // Create a window called "Hello, world!" and append into it.
169
170 ImGui::Text("This is some useful text."); // Display some text (you can use a format strings too)
171 ImGui::Checkbox("Demo Window", &show_demo_window); // Edit bools storing our window open/close state
172 ImGui::Checkbox("Another Window", &show_another_window);
173
174 ImGui::SliderFloat("float", &f, 0.0f, 1.0f); // Edit 1 float using a slider from 0.0f to 1.0f
175 ImGui::ColorEdit3("clear color", (float*)&clear_color); // Edit 3 floats representing a color
176
177 if (ImGui::Button("Button")) // Buttons return true when clicked (most widgets return true when edited/activated)
178 counter++;
179 ImGui::SameLine();
180 ImGui::Text("counter = %d", counter);
181
182 ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / io.Framerate, io.Framerate);
183 ImGui::End();
184 }
185
186 // 3. Show another simple window.
187 if (show_another_window)
188 {
189 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)
190 ImGui::Text("Hello from another window!");
191 if (ImGui::Button("Close Me"))
192 show_another_window = false;
193 ImGui::End();
194 }
195
196 // Rendering
197 ImGui::Render();
198 ImDrawData* draw_data = ImGui::GetDrawData();
199
200 renderPassDescriptor.colorAttachments[0].clearColor = MTLClearColorMake(clear_color.x * clear_color.w, clear_color.y * clear_color.w, clear_color.z * clear_color.w, clear_color.w);
201 id <MTLRenderCommandEncoder> renderEncoder = [commandBuffer renderCommandEncoderWithDescriptor:renderPassDescriptor];
202 [renderEncoder pushDebugGroup:@"Dear ImGui rendering"];
203 ImGui_ImplMetal_RenderDrawData(draw_data, commandBuffer, renderEncoder);
204 [renderEncoder popDebugGroup];
205 [renderEncoder endEncoding];
206
207 // Present
208 [commandBuffer presentDrawable:view.currentDrawable];
209 [commandBuffer commit];
210
211 // Update and Render additional Platform Windows
212 if (io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable)
213 {
214 ImGui::UpdatePlatformWindows();
215 ImGui::RenderPlatformWindowsDefault();
216 }
217}
218
219-(void)mtkView:(MTKView*)view drawableSizeWillChange:(CGSize)size
220{
221}
222
223//-----------------------------------------------------------------------------------
224// Input processing
225//-----------------------------------------------------------------------------------
226
227#if TARGET_OS_OSX
228
229- (void)viewWillAppear
230{
231 [super viewWillAppear];
232 self.view.window.delegate = self;
233}
234
235- (void)windowWillClose:(NSNotification *)notification
236{
237 ImGui_ImplMetal_Shutdown();
238 ImGui_ImplOSX_Shutdown();
239 ImGui::DestroyContext();
240}
241
242#else
243
244// This touch mapping is super cheesy/hacky. We treat any touch on the screen
245// as if it were a depressed left mouse button, and we don't bother handling
246// multitouch correctly at all. This causes the "cursor" to behave very erratically
247// when there are multiple active touches. But for demo purposes, single-touch
248// interaction actually works surprisingly well.
249-(void)updateIOWithTouchEvent:(UIEvent *)event
250{
251 UITouch *anyTouch = event.allTouches.anyObject;
252 CGPoint touchLocation = [anyTouch locationInView:self.view];
253 ImGuiIO &io = ImGui::GetIO();
254 io.AddMouseSourceEvent(ImGuiMouseSource_TouchScreen);
255 io.AddMousePosEvent(touchLocation.x, touchLocation.y);
256
257 BOOL hasActiveTouch = NO;
258 for (UITouch *touch in event.allTouches)
259 {
260 if (touch.phase != UITouchPhaseEnded && touch.phase != UITouchPhaseCancelled)
261 {
262 hasActiveTouch = YES;
263 break;
264 }
265 }
266 io.AddMouseButtonEvent(0, hasActiveTouch);
267}
268
269-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event { [self updateIOWithTouchEvent:event]; }
270-(void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event { [self updateIOWithTouchEvent:event]; }
271-(void)touchesCancelled:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event { [self updateIOWithTouchEvent:event]; }
272-(void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event { [self updateIOWithTouchEvent:event]; }
273
274#endif
275
276@end
277
278//-----------------------------------------------------------------------------------
279// AppDelegate
280//-----------------------------------------------------------------------------------
281
282#if TARGET_OS_OSX
283
284@interface AppDelegate : NSObject <NSApplicationDelegate>
285@property (nonatomic, strong) NSWindow *window;
286@end
287
288@implementation AppDelegate
289
290-(BOOL)applicationShouldTerminateAfterLastWindowClosed:(NSApplication *)sender
291{
292 return YES;
293}
294
295-(instancetype)init
296{
297 if (self = [super init])
298 {
299 NSViewController *rootViewController = [[AppViewController alloc] initWithNibName:nil bundle:nil];
300 self.window = [[NSWindow alloc] initWithContentRect:NSZeroRect
301 styleMask:NSWindowStyleMaskTitled | NSWindowStyleMaskClosable | NSWindowStyleMaskResizable | NSWindowStyleMaskMiniaturizable
302 backing:NSBackingStoreBuffered
303 defer:NO];
304 self.window.contentViewController = rootViewController;
305 [self.window center];
306 [self.window makeKeyAndOrderFront:self];
307 }
308 return self;
309}
310
311@end
312
313#else
314
315@interface AppDelegate : UIResponder <UIApplicationDelegate>
316@property (strong, nonatomic) UIWindow *window;
317@end
318
319@implementation AppDelegate
320
321-(BOOL)application:(UIApplication *)application
322 didFinishLaunchingWithOptions:(NSDictionary<UIApplicationLaunchOptionsKey,id> *)launchOptions
323{
324 UIViewController *rootViewController = [[AppViewController alloc] init];
325 self.window = [[UIWindow alloc] initWithFrame:UIScreen.mainScreen.bounds];
326 self.window.rootViewController = rootViewController;
327 [self.window makeKeyAndVisible];
328 return YES;
329}
330
331@end
332
333#endif
334
335//-----------------------------------------------------------------------------------
336// Application main() function
337//-----------------------------------------------------------------------------------
338
339#if TARGET_OS_OSX
340
341int main(int, const char**)
342{
343 @autoreleasepool
344 {
345 [NSApplication sharedApplication];
346 [NSApp setActivationPolicy:NSApplicationActivationPolicyRegular];
347
348 AppDelegate *appDelegate = [[AppDelegate alloc] init]; // creates window
349 [NSApp setDelegate:appDelegate];
350
351 [NSApp activateIgnoringOtherApps:YES];
352 [NSApp run];
353 }
354 return 0;
355}
356
357#else
358
359int main(int argc, char * argv[])
360{
361 @autoreleasepool
362 {
363 return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));
364 }
365}
366
367#endif