2
0

main.mm 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354
  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. io.ConfigFlags |= ImGuiConfigFlags_DockingEnable; // Enable Docking
  52. io.ConfigFlags |= ImGuiConfigFlags_ViewportsEnable; // Enable Multi-Viewport / Platform Windows
  53. // Setup Dear ImGui style
  54. ImGui::StyleColorsDark();
  55. //ImGui::StyleColorsLight();
  56. // When viewports are enabled we tweak WindowRounding/WindowBg so platform windows can look identical to regular ones.
  57. ImGuiStyle& style = ImGui::GetStyle();
  58. if (io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable)
  59. {
  60. style.WindowRounding = 0.0f;
  61. style.Colors[ImGuiCol_WindowBg].w = 1.0f;
  62. }
  63. // Setup Renderer backend
  64. ImGui_ImplMetal_Init(_device);
  65. // Load Fonts
  66. // - 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.
  67. // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple.
  68. // - If the file cannot be loaded, the function will return a nullptr. Please handle those errors in your application (e.g. use an assertion, or display an error and quit).
  69. // - 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.
  70. // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use Freetype for higher quality font rendering.
  71. // - Read 'docs/FONTS.md' for more instructions and details.
  72. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ !
  73. //io.Fonts->AddFontDefault();
  74. //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf", 18.0f);
  75. //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf", 16.0f);
  76. //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf", 16.0f);
  77. //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Cousine-Regular.ttf", 15.0f);
  78. //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f, nullptr, io.Fonts->GetGlyphRangesJapanese());
  79. //IM_ASSERT(font != nullptr);
  80. return self;
  81. }
  82. -(MTKView *)mtkView
  83. {
  84. return (MTKView *)self.view;
  85. }
  86. -(void)loadView
  87. {
  88. self.view = [[MTKView alloc] initWithFrame:CGRectMake(0, 0, 1200, 720)];
  89. }
  90. -(void)viewDidLoad
  91. {
  92. [super viewDidLoad];
  93. self.mtkView.device = self.device;
  94. self.mtkView.delegate = self;
  95. #if TARGET_OS_OSX
  96. ImGui_ImplOSX_Init(self.view);
  97. [NSApp activateIgnoringOtherApps:YES];
  98. #endif
  99. }
  100. -(void)drawInMTKView:(MTKView*)view
  101. {
  102. ImGuiIO& io = ImGui::GetIO();
  103. io.DisplaySize.x = view.bounds.size.width;
  104. io.DisplaySize.y = view.bounds.size.height;
  105. #if TARGET_OS_OSX
  106. CGFloat framebufferScale = view.window.screen.backingScaleFactor ?: NSScreen.mainScreen.backingScaleFactor;
  107. #else
  108. CGFloat framebufferScale = view.window.screen.scale ?: UIScreen.mainScreen.scale;
  109. #endif
  110. io.DisplayFramebufferScale = ImVec2(framebufferScale, framebufferScale);
  111. id<MTLCommandBuffer> commandBuffer = [self.commandQueue commandBuffer];
  112. MTLRenderPassDescriptor* renderPassDescriptor = view.currentRenderPassDescriptor;
  113. if (renderPassDescriptor == nil)
  114. {
  115. [commandBuffer commit];
  116. return;
  117. }
  118. // Start the Dear ImGui frame
  119. ImGui_ImplMetal_NewFrame(renderPassDescriptor);
  120. #if TARGET_OS_OSX
  121. ImGui_ImplOSX_NewFrame(view);
  122. #endif
  123. ImGui::NewFrame();
  124. // Our state (make them static = more or less global) as a convenience to keep the example terse.
  125. static bool show_demo_window = true;
  126. static bool show_another_window = false;
  127. static ImVec4 clear_color = ImVec4(0.45f, 0.55f, 0.60f, 1.00f);
  128. // 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!).
  129. if (show_demo_window)
  130. ImGui::ShowDemoWindow(&show_demo_window);
  131. // 2. Show a simple window that we create ourselves. We use a Begin/End pair to create a named window.
  132. {
  133. static float f = 0.0f;
  134. static int counter = 0;
  135. ImGui::Begin("Hello, world!"); // Create a window called "Hello, world!" and append into it.
  136. ImGui::Text("This is some useful text."); // Display some text (you can use a format strings too)
  137. ImGui::Checkbox("Demo Window", &show_demo_window); // Edit bools storing our window open/close state
  138. ImGui::Checkbox("Another Window", &show_another_window);
  139. ImGui::SliderFloat("float", &f, 0.0f, 1.0f); // Edit 1 float using a slider from 0.0f to 1.0f
  140. ImGui::ColorEdit3("clear color", (float*)&clear_color); // Edit 3 floats representing a color
  141. if (ImGui::Button("Button")) // Buttons return true when clicked (most widgets return true when edited/activated)
  142. counter++;
  143. ImGui::SameLine();
  144. ImGui::Text("counter = %d", counter);
  145. ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / io.Framerate, io.Framerate);
  146. ImGui::End();
  147. }
  148. // 3. Show another simple window.
  149. if (show_another_window)
  150. {
  151. 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)
  152. ImGui::Text("Hello from another window!");
  153. if (ImGui::Button("Close Me"))
  154. show_another_window = false;
  155. ImGui::End();
  156. }
  157. // Rendering
  158. ImGui::Render();
  159. ImDrawData* draw_data = ImGui::GetDrawData();
  160. 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);
  161. id <MTLRenderCommandEncoder> renderEncoder = [commandBuffer renderCommandEncoderWithDescriptor:renderPassDescriptor];
  162. [renderEncoder pushDebugGroup:@"Dear ImGui rendering"];
  163. ImGui_ImplMetal_RenderDrawData(draw_data, commandBuffer, renderEncoder);
  164. [renderEncoder popDebugGroup];
  165. [renderEncoder endEncoding];
  166. // Present
  167. [commandBuffer presentDrawable:view.currentDrawable];
  168. [commandBuffer commit];
  169. // Update and Render additional Platform Windows
  170. if (io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable)
  171. {
  172. ImGui::UpdatePlatformWindows();
  173. ImGui::RenderPlatformWindowsDefault();
  174. }
  175. }
  176. -(void)mtkView:(MTKView*)view drawableSizeWillChange:(CGSize)size
  177. {
  178. }
  179. //-----------------------------------------------------------------------------------
  180. // Input processing
  181. //-----------------------------------------------------------------------------------
  182. #if TARGET_OS_OSX
  183. - (void)viewWillAppear
  184. {
  185. [super viewWillAppear];
  186. self.view.window.delegate = self;
  187. }
  188. - (void)windowWillClose:(NSNotification *)notification
  189. {
  190. ImGui_ImplMetal_Shutdown();
  191. ImGui_ImplOSX_Shutdown();
  192. ImGui::DestroyContext();
  193. }
  194. #else
  195. // This touch mapping is super cheesy/hacky. We treat any touch on the screen
  196. // as if it were a depressed left mouse button, and we don't bother handling
  197. // multitouch correctly at all. This causes the "cursor" to behave very erratically
  198. // when there are multiple active touches. But for demo purposes, single-touch
  199. // interaction actually works surprisingly well.
  200. -(void)updateIOWithTouchEvent:(UIEvent *)event
  201. {
  202. UITouch *anyTouch = event.allTouches.anyObject;
  203. CGPoint touchLocation = [anyTouch locationInView:self.view];
  204. ImGuiIO &io = ImGui::GetIO();
  205. io.AddMouseSourceEvent(ImGuiMouseSource_TouchScreen);
  206. io.AddMousePosEvent(touchLocation.x, touchLocation.y);
  207. BOOL hasActiveTouch = NO;
  208. for (UITouch *touch in event.allTouches)
  209. {
  210. if (touch.phase != UITouchPhaseEnded && touch.phase != UITouchPhaseCancelled)
  211. {
  212. hasActiveTouch = YES;
  213. break;
  214. }
  215. }
  216. io.AddMouseButtonEvent(0, hasActiveTouch);
  217. }
  218. -(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event { [self updateIOWithTouchEvent:event]; }
  219. -(void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event { [self updateIOWithTouchEvent:event]; }
  220. -(void)touchesCancelled:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event { [self updateIOWithTouchEvent:event]; }
  221. -(void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event { [self updateIOWithTouchEvent:event]; }
  222. #endif
  223. @end
  224. //-----------------------------------------------------------------------------------
  225. // AppDelegate
  226. //-----------------------------------------------------------------------------------
  227. #if TARGET_OS_OSX
  228. @interface AppDelegate : NSObject <NSApplicationDelegate>
  229. @property (nonatomic, strong) NSWindow *window;
  230. @end
  231. @implementation AppDelegate
  232. -(BOOL)applicationShouldTerminateAfterLastWindowClosed:(NSApplication *)sender
  233. {
  234. return YES;
  235. }
  236. -(instancetype)init
  237. {
  238. if (self = [super init])
  239. {
  240. NSViewController *rootViewController = [[AppViewController alloc] initWithNibName:nil bundle:nil];
  241. self.window = [[NSWindow alloc] initWithContentRect:NSZeroRect
  242. styleMask:NSWindowStyleMaskTitled | NSWindowStyleMaskClosable | NSWindowStyleMaskResizable | NSWindowStyleMaskMiniaturizable
  243. backing:NSBackingStoreBuffered
  244. defer:NO];
  245. self.window.contentViewController = rootViewController;
  246. [self.window center];
  247. [self.window makeKeyAndOrderFront:self];
  248. }
  249. return self;
  250. }
  251. @end
  252. #else
  253. @interface AppDelegate : UIResponder <UIApplicationDelegate>
  254. @property (strong, nonatomic) UIWindow *window;
  255. @end
  256. @implementation AppDelegate
  257. -(BOOL)application:(UIApplication *)application
  258. didFinishLaunchingWithOptions:(NSDictionary<UIApplicationLaunchOptionsKey,id> *)launchOptions
  259. {
  260. UIViewController *rootViewController = [[AppViewController alloc] init];
  261. self.window = [[UIWindow alloc] initWithFrame:UIScreen.mainScreen.bounds];
  262. self.window.rootViewController = rootViewController;
  263. [self.window makeKeyAndVisible];
  264. return YES;
  265. }
  266. @end
  267. #endif
  268. //-----------------------------------------------------------------------------------
  269. // Application main() function
  270. //-----------------------------------------------------------------------------------
  271. #if TARGET_OS_OSX
  272. int main(int argc, const char * argv[])
  273. {
  274. return NSApplicationMain(argc, argv);
  275. }
  276. #else
  277. int main(int argc, char * argv[])
  278. {
  279. @autoreleasepool
  280. {
  281. return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));
  282. }
  283. }
  284. #endif