main.mm 12 KB

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