imgui_impl_metal.mm 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597
  1. // dear imgui: Renderer Backend for Metal
  2. // This needs to be used along with a Platform Backend (e.g. OSX)
  3. // Implemented features:
  4. // [X] Renderer: User texture binding. Use 'MTLTexture' as ImTextureID. Read the FAQ about ImTextureID!
  5. // [X] Renderer: Large meshes support (64k+ vertices) even with 16-bit indices (ImGuiBackendFlags_RendererHasVtxOffset).
  6. // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
  7. // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
  8. // Learn about Dear ImGui:
  9. // - FAQ https://dearimgui.com/faq
  10. // - Getting Started https://dearimgui.com/getting-started
  11. // - Documentation https://dearimgui.com/docs (same as your local docs/ folder).
  12. // - Introduction, links and more at the top of imgui.cpp
  13. // CHANGELOG
  14. // (minor and older changes stripped away, please see git history for details)
  15. // 2025-02-03: Metal: Crash fix. (#8367)
  16. // 2024-01-08: Metal: Fixed memory leaks when using metal-cpp (#8276, #8166) or when using multiple contexts (#7419).
  17. // 2022-08-23: Metal: Update deprecated property 'sampleCount'->'rasterSampleCount'.
  18. // 2022-07-05: Metal: Add dispatch synchronization.
  19. // 2022-06-30: Metal: Use __bridge for ARC based systems.
  20. // 2022-06-01: Metal: Fixed null dereference on exit inside command buffer completion handler.
  21. // 2022-04-27: Misc: Store backend data in a per-context struct, allowing to use this backend with multiple contexts.
  22. // 2022-01-03: Metal: Ignore ImDrawCmd where ElemCount == 0 (very rare but can technically be manufactured by user code).
  23. // 2021-12-30: Metal: Added Metal C++ support. Enable with '#define IMGUI_IMPL_METAL_CPP' in your imconfig.h file.
  24. // 2021-08-24: Metal: Fixed a crash when clipping rect larger than framebuffer is submitted. (#4464)
  25. // 2021-05-19: Metal: Replaced direct access to ImDrawCmd::TextureId with a call to ImDrawCmd::GetTexID(). (will become a requirement)
  26. // 2021-02-18: Metal: Change blending equation to preserve alpha in output buffer.
  27. // 2021-01-25: Metal: Fixed texture storage mode when building on Mac Catalyst.
  28. // 2019-05-29: Metal: Added support for large mesh (64K+ vertices), enable ImGuiBackendFlags_RendererHasVtxOffset flag.
  29. // 2019-04-30: Metal: Added support for special ImDrawCallback_ResetRenderState callback to reset render state.
  30. // 2019-02-11: Metal: Projecting clipping rectangles correctly using draw_data->FramebufferScale to allow multi-viewports for retina display.
  31. // 2018-11-30: Misc: Setting up io.BackendRendererName so it can be displayed in the About Window.
  32. // 2018-07-05: Metal: Added new Metal backend implementation.
  33. #include "imgui.h"
  34. #ifndef IMGUI_DISABLE
  35. #include "imgui_impl_metal.h"
  36. #import <time.h>
  37. #import <Metal/Metal.h>
  38. #pragma mark - Support classes
  39. // A wrapper around a MTLBuffer object that knows the last time it was reused
  40. @interface MetalBuffer : NSObject
  41. @property (nonatomic, strong) id<MTLBuffer> buffer;
  42. @property (nonatomic, assign) double lastReuseTime;
  43. - (instancetype)initWithBuffer:(id<MTLBuffer>)buffer;
  44. @end
  45. // An object that encapsulates the data necessary to uniquely identify a
  46. // render pipeline state. These are used as cache keys.
  47. @interface FramebufferDescriptor : NSObject<NSCopying>
  48. @property (nonatomic, assign) unsigned long sampleCount;
  49. @property (nonatomic, assign) MTLPixelFormat colorPixelFormat;
  50. @property (nonatomic, assign) MTLPixelFormat depthPixelFormat;
  51. @property (nonatomic, assign) MTLPixelFormat stencilPixelFormat;
  52. - (instancetype)initWithRenderPassDescriptor:(MTLRenderPassDescriptor*)renderPassDescriptor;
  53. @end
  54. // A singleton that stores long-lived objects that are needed by the Metal
  55. // renderer backend. Stores the render pipeline state cache and the default
  56. // font texture, and manages the reusable buffer cache.
  57. @interface MetalContext : NSObject
  58. @property (nonatomic, strong) id<MTLDevice> device;
  59. @property (nonatomic, strong) id<MTLDepthStencilState> depthStencilState;
  60. @property (nonatomic, strong) FramebufferDescriptor* framebufferDescriptor; // framebuffer descriptor for current frame; transient
  61. @property (nonatomic, strong) NSMutableDictionary* renderPipelineStateCache; // pipeline cache; keyed on framebuffer descriptors
  62. @property (nonatomic, strong, nullable) id<MTLTexture> fontTexture;
  63. @property (nonatomic, strong) NSMutableArray<MetalBuffer*>* bufferCache;
  64. @property (nonatomic, assign) double lastBufferCachePurge;
  65. - (MetalBuffer*)dequeueReusableBufferOfLength:(NSUInteger)length device:(id<MTLDevice>)device;
  66. - (id<MTLRenderPipelineState>)renderPipelineStateForFramebufferDescriptor:(FramebufferDescriptor*)descriptor device:(id<MTLDevice>)device;
  67. @end
  68. struct ImGui_ImplMetal_Data
  69. {
  70. MetalContext* SharedMetalContext;
  71. ImGui_ImplMetal_Data() { memset((void*)this, 0, sizeof(*this)); }
  72. };
  73. static ImGui_ImplMetal_Data* ImGui_ImplMetal_GetBackendData() { return ImGui::GetCurrentContext() ? (ImGui_ImplMetal_Data*)ImGui::GetIO().BackendRendererUserData : nullptr; }
  74. static void ImGui_ImplMetal_DestroyBackendData(){ IM_DELETE(ImGui_ImplMetal_GetBackendData()); }
  75. static inline CFTimeInterval GetMachAbsoluteTimeInSeconds() { return (CFTimeInterval)(double)(clock_gettime_nsec_np(CLOCK_UPTIME_RAW) / 1e9); }
  76. #ifdef IMGUI_IMPL_METAL_CPP
  77. #pragma mark - Dear ImGui Metal C++ Backend API
  78. bool ImGui_ImplMetal_Init(MTL::Device* device)
  79. {
  80. return ImGui_ImplMetal_Init((__bridge id<MTLDevice>)(device));
  81. }
  82. void ImGui_ImplMetal_NewFrame(MTL::RenderPassDescriptor* renderPassDescriptor)
  83. {
  84. ImGui_ImplMetal_NewFrame((__bridge MTLRenderPassDescriptor*)(renderPassDescriptor));
  85. }
  86. void ImGui_ImplMetal_RenderDrawData(ImDrawData* draw_data,
  87. MTL::CommandBuffer* commandBuffer,
  88. MTL::RenderCommandEncoder* commandEncoder)
  89. {
  90. ImGui_ImplMetal_RenderDrawData(draw_data,
  91. (__bridge id<MTLCommandBuffer>)(commandBuffer),
  92. (__bridge id<MTLRenderCommandEncoder>)(commandEncoder));
  93. }
  94. bool ImGui_ImplMetal_CreateFontsTexture(MTL::Device* device)
  95. {
  96. return ImGui_ImplMetal_CreateFontsTexture((__bridge id<MTLDevice>)(device));
  97. }
  98. bool ImGui_ImplMetal_CreateDeviceObjects(MTL::Device* device)
  99. {
  100. return ImGui_ImplMetal_CreateDeviceObjects((__bridge id<MTLDevice>)(device));
  101. }
  102. #endif // #ifdef IMGUI_IMPL_METAL_CPP
  103. #pragma mark - Dear ImGui Metal Backend API
  104. bool ImGui_ImplMetal_Init(id<MTLDevice> device)
  105. {
  106. ImGuiIO& io = ImGui::GetIO();
  107. IMGUI_CHECKVERSION();
  108. IM_ASSERT(io.BackendRendererUserData == nullptr && "Already initialized a renderer backend!");
  109. ImGui_ImplMetal_Data* bd = IM_NEW(ImGui_ImplMetal_Data)();
  110. io.BackendRendererUserData = (void*)bd;
  111. io.BackendRendererName = "imgui_impl_metal";
  112. io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset; // We can honor the ImDrawCmd::VtxOffset field, allowing for large meshes.
  113. bd->SharedMetalContext = [[MetalContext alloc] init];
  114. bd->SharedMetalContext.device = device;
  115. return true;
  116. }
  117. void ImGui_ImplMetal_Shutdown()
  118. {
  119. ImGui_ImplMetal_Data* bd = ImGui_ImplMetal_GetBackendData();
  120. IM_UNUSED(bd);
  121. IM_ASSERT(bd != nullptr && "No renderer backend to shutdown, or already shutdown?");
  122. ImGui_ImplMetal_DestroyDeviceObjects();
  123. ImGui_ImplMetal_DestroyBackendData();
  124. ImGuiIO& io = ImGui::GetIO();
  125. io.BackendRendererName = nullptr;
  126. io.BackendRendererUserData = nullptr;
  127. io.BackendFlags &= ~ImGuiBackendFlags_RendererHasVtxOffset;
  128. }
  129. void ImGui_ImplMetal_NewFrame(MTLRenderPassDescriptor* renderPassDescriptor)
  130. {
  131. ImGui_ImplMetal_Data* bd = ImGui_ImplMetal_GetBackendData();
  132. IM_ASSERT(bd != nil && "Context or backend not initialized! Did you call ImGui_ImplMetal_Init()?");
  133. #ifdef IMGUI_IMPL_METAL_CPP
  134. bd->SharedMetalContext.framebufferDescriptor = [[[FramebufferDescriptor alloc] initWithRenderPassDescriptor:renderPassDescriptor]autorelease];
  135. #else
  136. bd->SharedMetalContext.framebufferDescriptor = [[FramebufferDescriptor alloc] initWithRenderPassDescriptor:renderPassDescriptor];
  137. #endif
  138. if (bd->SharedMetalContext.depthStencilState == nil)
  139. ImGui_ImplMetal_CreateDeviceObjects(bd->SharedMetalContext.device);
  140. }
  141. static void ImGui_ImplMetal_SetupRenderState(ImDrawData* drawData, id<MTLCommandBuffer> commandBuffer,
  142. id<MTLRenderCommandEncoder> commandEncoder, id<MTLRenderPipelineState> renderPipelineState,
  143. MetalBuffer* vertexBuffer, size_t vertexBufferOffset)
  144. {
  145. IM_UNUSED(commandBuffer);
  146. ImGui_ImplMetal_Data* bd = ImGui_ImplMetal_GetBackendData();
  147. [commandEncoder setCullMode:MTLCullModeNone];
  148. [commandEncoder setDepthStencilState:bd->SharedMetalContext.depthStencilState];
  149. // Setup viewport, orthographic projection matrix
  150. // Our visible imgui space lies from draw_data->DisplayPos (top left) to
  151. // draw_data->DisplayPos+data_data->DisplaySize (bottom right). DisplayMin is typically (0,0) for single viewport apps.
  152. MTLViewport viewport =
  153. {
  154. .originX = 0.0,
  155. .originY = 0.0,
  156. .width = (double)(drawData->DisplaySize.x * drawData->FramebufferScale.x),
  157. .height = (double)(drawData->DisplaySize.y * drawData->FramebufferScale.y),
  158. .znear = 0.0,
  159. .zfar = 1.0
  160. };
  161. [commandEncoder setViewport:viewport];
  162. float L = drawData->DisplayPos.x;
  163. float R = drawData->DisplayPos.x + drawData->DisplaySize.x;
  164. float T = drawData->DisplayPos.y;
  165. float B = drawData->DisplayPos.y + drawData->DisplaySize.y;
  166. float N = (float)viewport.znear;
  167. float F = (float)viewport.zfar;
  168. const float ortho_projection[4][4] =
  169. {
  170. { 2.0f/(R-L), 0.0f, 0.0f, 0.0f },
  171. { 0.0f, 2.0f/(T-B), 0.0f, 0.0f },
  172. { 0.0f, 0.0f, 1/(F-N), 0.0f },
  173. { (R+L)/(L-R), (T+B)/(B-T), N/(F-N), 1.0f },
  174. };
  175. [commandEncoder setVertexBytes:&ortho_projection length:sizeof(ortho_projection) atIndex:1];
  176. [commandEncoder setRenderPipelineState:renderPipelineState];
  177. [commandEncoder setVertexBuffer:vertexBuffer.buffer offset:0 atIndex:0];
  178. [commandEncoder setVertexBufferOffset:vertexBufferOffset atIndex:0];
  179. }
  180. // Metal Render function.
  181. void ImGui_ImplMetal_RenderDrawData(ImDrawData* drawData, id<MTLCommandBuffer> commandBuffer, id<MTLRenderCommandEncoder> commandEncoder)
  182. {
  183. ImGui_ImplMetal_Data* bd = ImGui_ImplMetal_GetBackendData();
  184. MetalContext* ctx = bd->SharedMetalContext;
  185. // Avoid rendering when minimized, scale coordinates for retina displays (screen coordinates != framebuffer coordinates)
  186. int fb_width = (int)(drawData->DisplaySize.x * drawData->FramebufferScale.x);
  187. int fb_height = (int)(drawData->DisplaySize.y * drawData->FramebufferScale.y);
  188. if (fb_width <= 0 || fb_height <= 0 || drawData->CmdListsCount == 0)
  189. return;
  190. // Try to retrieve a render pipeline state that is compatible with the framebuffer config for this frame
  191. // The hit rate for this cache should be very near 100%.
  192. id<MTLRenderPipelineState> renderPipelineState = ctx.renderPipelineStateCache[ctx.framebufferDescriptor];
  193. if (renderPipelineState == nil)
  194. {
  195. // No luck; make a new render pipeline state
  196. renderPipelineState = [ctx renderPipelineStateForFramebufferDescriptor:ctx.framebufferDescriptor device:commandBuffer.device];
  197. // Cache render pipeline state for later reuse
  198. ctx.renderPipelineStateCache[ctx.framebufferDescriptor] = renderPipelineState;
  199. }
  200. size_t vertexBufferLength = (size_t)drawData->TotalVtxCount * sizeof(ImDrawVert);
  201. size_t indexBufferLength = (size_t)drawData->TotalIdxCount * sizeof(ImDrawIdx);
  202. MetalBuffer* vertexBuffer = [ctx dequeueReusableBufferOfLength:vertexBufferLength device:commandBuffer.device];
  203. MetalBuffer* indexBuffer = [ctx dequeueReusableBufferOfLength:indexBufferLength device:commandBuffer.device];
  204. ImGui_ImplMetal_SetupRenderState(drawData, commandBuffer, commandEncoder, renderPipelineState, vertexBuffer, 0);
  205. // Will project scissor/clipping rectangles into framebuffer space
  206. ImVec2 clip_off = drawData->DisplayPos; // (0,0) unless using multi-viewports
  207. ImVec2 clip_scale = drawData->FramebufferScale; // (1,1) unless using retina display which are often (2,2)
  208. // Render command lists
  209. size_t vertexBufferOffset = 0;
  210. size_t indexBufferOffset = 0;
  211. for (int n = 0; n < drawData->CmdListsCount; n++)
  212. {
  213. const ImDrawList* draw_list = drawData->CmdLists[n];
  214. memcpy((char*)vertexBuffer.buffer.contents + vertexBufferOffset, draw_list->VtxBuffer.Data, (size_t)draw_list->VtxBuffer.Size * sizeof(ImDrawVert));
  215. memcpy((char*)indexBuffer.buffer.contents + indexBufferOffset, draw_list->IdxBuffer.Data, (size_t)draw_list->IdxBuffer.Size * sizeof(ImDrawIdx));
  216. for (int cmd_i = 0; cmd_i < draw_list->CmdBuffer.Size; cmd_i++)
  217. {
  218. const ImDrawCmd* pcmd = &draw_list->CmdBuffer[cmd_i];
  219. if (pcmd->UserCallback)
  220. {
  221. // User callback, registered via ImDrawList::AddCallback()
  222. // (ImDrawCallback_ResetRenderState is a special callback value used by the user to request the renderer to reset render state.)
  223. if (pcmd->UserCallback == ImDrawCallback_ResetRenderState)
  224. ImGui_ImplMetal_SetupRenderState(drawData, commandBuffer, commandEncoder, renderPipelineState, vertexBuffer, vertexBufferOffset);
  225. else
  226. pcmd->UserCallback(draw_list, pcmd);
  227. }
  228. else
  229. {
  230. // Project scissor/clipping rectangles into framebuffer space
  231. ImVec2 clip_min((pcmd->ClipRect.x - clip_off.x) * clip_scale.x, (pcmd->ClipRect.y - clip_off.y) * clip_scale.y);
  232. ImVec2 clip_max((pcmd->ClipRect.z - clip_off.x) * clip_scale.x, (pcmd->ClipRect.w - clip_off.y) * clip_scale.y);
  233. // Clamp to viewport as setScissorRect() won't accept values that are off bounds
  234. if (clip_min.x < 0.0f) { clip_min.x = 0.0f; }
  235. if (clip_min.y < 0.0f) { clip_min.y = 0.0f; }
  236. if (clip_max.x > fb_width) { clip_max.x = (float)fb_width; }
  237. if (clip_max.y > fb_height) { clip_max.y = (float)fb_height; }
  238. if (clip_max.x <= clip_min.x || clip_max.y <= clip_min.y)
  239. continue;
  240. if (pcmd->ElemCount == 0) // drawIndexedPrimitives() validation doesn't accept this
  241. continue;
  242. // Apply scissor/clipping rectangle
  243. MTLScissorRect scissorRect =
  244. {
  245. .x = NSUInteger(clip_min.x),
  246. .y = NSUInteger(clip_min.y),
  247. .width = NSUInteger(clip_max.x - clip_min.x),
  248. .height = NSUInteger(clip_max.y - clip_min.y)
  249. };
  250. [commandEncoder setScissorRect:scissorRect];
  251. // Bind texture, Draw
  252. if (ImTextureID tex_id = pcmd->GetTexID())
  253. [commandEncoder setFragmentTexture:(__bridge id<MTLTexture>)(void*)(intptr_t)(tex_id) atIndex:0];
  254. [commandEncoder setVertexBufferOffset:(vertexBufferOffset + pcmd->VtxOffset * sizeof(ImDrawVert)) atIndex:0];
  255. [commandEncoder drawIndexedPrimitives:MTLPrimitiveTypeTriangle
  256. indexCount:pcmd->ElemCount
  257. indexType:sizeof(ImDrawIdx) == 2 ? MTLIndexTypeUInt16 : MTLIndexTypeUInt32
  258. indexBuffer:indexBuffer.buffer
  259. indexBufferOffset:indexBufferOffset + pcmd->IdxOffset * sizeof(ImDrawIdx)];
  260. }
  261. }
  262. vertexBufferOffset += (size_t)draw_list->VtxBuffer.Size * sizeof(ImDrawVert);
  263. indexBufferOffset += (size_t)draw_list->IdxBuffer.Size * sizeof(ImDrawIdx);
  264. }
  265. MetalContext* sharedMetalContext = bd->SharedMetalContext;
  266. [commandBuffer addCompletedHandler:^(id<MTLCommandBuffer>)
  267. {
  268. dispatch_async(dispatch_get_main_queue(), ^{
  269. @synchronized(sharedMetalContext.bufferCache)
  270. {
  271. [sharedMetalContext.bufferCache addObject:vertexBuffer];
  272. [sharedMetalContext.bufferCache addObject:indexBuffer];
  273. }
  274. });
  275. }];
  276. }
  277. bool ImGui_ImplMetal_CreateFontsTexture(id<MTLDevice> device)
  278. {
  279. ImGui_ImplMetal_Data* bd = ImGui_ImplMetal_GetBackendData();
  280. ImGuiIO& io = ImGui::GetIO();
  281. // We are retrieving and uploading the font atlas as a 4-channels RGBA texture here.
  282. // In theory we could call GetTexDataAsAlpha8() and upload a 1-channel texture to save on memory access bandwidth.
  283. // However, using a shader designed for 1-channel texture would make it less obvious to use the ImTextureID facility to render users own textures.
  284. // You can make that change in your implementation.
  285. unsigned char* pixels;
  286. int width, height;
  287. io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height);
  288. MTLTextureDescriptor* textureDescriptor = [MTLTextureDescriptor texture2DDescriptorWithPixelFormat:MTLPixelFormatRGBA8Unorm
  289. width:(NSUInteger)width
  290. height:(NSUInteger)height
  291. mipmapped:NO];
  292. textureDescriptor.usage = MTLTextureUsageShaderRead;
  293. #if TARGET_OS_OSX || TARGET_OS_MACCATALYST
  294. textureDescriptor.storageMode = MTLStorageModeManaged;
  295. #else
  296. textureDescriptor.storageMode = MTLStorageModeShared;
  297. #endif
  298. id <MTLTexture> texture = [device newTextureWithDescriptor:textureDescriptor];
  299. [texture replaceRegion:MTLRegionMake2D(0, 0, (NSUInteger)width, (NSUInteger)height) mipmapLevel:0 withBytes:pixels bytesPerRow:(NSUInteger)width * 4];
  300. bd->SharedMetalContext.fontTexture = texture;
  301. io.Fonts->SetTexID((ImTextureID)(intptr_t)(__bridge void*)bd->SharedMetalContext.fontTexture); // ImTextureID == ImU64
  302. return (bd->SharedMetalContext.fontTexture != nil);
  303. }
  304. void ImGui_ImplMetal_DestroyFontsTexture()
  305. {
  306. ImGui_ImplMetal_Data* bd = ImGui_ImplMetal_GetBackendData();
  307. ImGuiIO& io = ImGui::GetIO();
  308. bd->SharedMetalContext.fontTexture = nil;
  309. io.Fonts->SetTexID(0);
  310. }
  311. bool ImGui_ImplMetal_CreateDeviceObjects(id<MTLDevice> device)
  312. {
  313. ImGui_ImplMetal_Data* bd = ImGui_ImplMetal_GetBackendData();
  314. MTLDepthStencilDescriptor* depthStencilDescriptor = [[MTLDepthStencilDescriptor alloc] init];
  315. depthStencilDescriptor.depthWriteEnabled = NO;
  316. depthStencilDescriptor.depthCompareFunction = MTLCompareFunctionAlways;
  317. bd->SharedMetalContext.depthStencilState = [device newDepthStencilStateWithDescriptor:depthStencilDescriptor];
  318. #ifdef IMGUI_IMPL_METAL_CPP
  319. [depthStencilDescriptor release];
  320. #endif
  321. ImGui_ImplMetal_CreateFontsTexture(device);
  322. return true;
  323. }
  324. void ImGui_ImplMetal_DestroyDeviceObjects()
  325. {
  326. ImGui_ImplMetal_Data* bd = ImGui_ImplMetal_GetBackendData();
  327. ImGui_ImplMetal_DestroyFontsTexture();
  328. [bd->SharedMetalContext.renderPipelineStateCache removeAllObjects];
  329. }
  330. #pragma mark - MetalBuffer implementation
  331. @implementation MetalBuffer
  332. - (instancetype)initWithBuffer:(id<MTLBuffer>)buffer
  333. {
  334. if ((self = [super init]))
  335. {
  336. _buffer = buffer;
  337. _lastReuseTime = GetMachAbsoluteTimeInSeconds();
  338. }
  339. return self;
  340. }
  341. @end
  342. #pragma mark - FramebufferDescriptor implementation
  343. @implementation FramebufferDescriptor
  344. - (instancetype)initWithRenderPassDescriptor:(MTLRenderPassDescriptor*)renderPassDescriptor
  345. {
  346. if ((self = [super init]))
  347. {
  348. _sampleCount = renderPassDescriptor.colorAttachments[0].texture.sampleCount;
  349. _colorPixelFormat = renderPassDescriptor.colorAttachments[0].texture.pixelFormat;
  350. _depthPixelFormat = renderPassDescriptor.depthAttachment.texture.pixelFormat;
  351. _stencilPixelFormat = renderPassDescriptor.stencilAttachment.texture.pixelFormat;
  352. }
  353. return self;
  354. }
  355. - (nonnull id)copyWithZone:(nullable NSZone*)zone
  356. {
  357. FramebufferDescriptor* copy = [[FramebufferDescriptor allocWithZone:zone] init];
  358. copy.sampleCount = self.sampleCount;
  359. copy.colorPixelFormat = self.colorPixelFormat;
  360. copy.depthPixelFormat = self.depthPixelFormat;
  361. copy.stencilPixelFormat = self.stencilPixelFormat;
  362. return copy;
  363. }
  364. - (NSUInteger)hash
  365. {
  366. NSUInteger sc = _sampleCount & 0x3;
  367. NSUInteger cf = _colorPixelFormat & 0x3FF;
  368. NSUInteger df = _depthPixelFormat & 0x3FF;
  369. NSUInteger sf = _stencilPixelFormat & 0x3FF;
  370. NSUInteger hash = (sf << 22) | (df << 12) | (cf << 2) | sc;
  371. return hash;
  372. }
  373. - (BOOL)isEqual:(id)object
  374. {
  375. FramebufferDescriptor* other = object;
  376. if (![other isKindOfClass:[FramebufferDescriptor class]])
  377. return NO;
  378. return other.sampleCount == self.sampleCount &&
  379. other.colorPixelFormat == self.colorPixelFormat &&
  380. other.depthPixelFormat == self.depthPixelFormat &&
  381. other.stencilPixelFormat == self.stencilPixelFormat;
  382. }
  383. @end
  384. #pragma mark - MetalContext implementation
  385. @implementation MetalContext
  386. - (instancetype)init
  387. {
  388. if ((self = [super init]))
  389. {
  390. self.renderPipelineStateCache = [NSMutableDictionary dictionary];
  391. self.bufferCache = [NSMutableArray array];
  392. _lastBufferCachePurge = GetMachAbsoluteTimeInSeconds();
  393. }
  394. return self;
  395. }
  396. - (MetalBuffer*)dequeueReusableBufferOfLength:(NSUInteger)length device:(id<MTLDevice>)device
  397. {
  398. uint64_t now = GetMachAbsoluteTimeInSeconds();
  399. @synchronized(self.bufferCache)
  400. {
  401. // Purge old buffers that haven't been useful for a while
  402. if (now - self.lastBufferCachePurge > 1.0)
  403. {
  404. NSMutableArray* survivors = [NSMutableArray array];
  405. for (MetalBuffer* candidate in self.bufferCache)
  406. if (candidate.lastReuseTime > self.lastBufferCachePurge)
  407. [survivors addObject:candidate];
  408. self.bufferCache = [survivors mutableCopy];
  409. self.lastBufferCachePurge = now;
  410. }
  411. // See if we have a buffer we can reuse
  412. MetalBuffer* bestCandidate = nil;
  413. for (MetalBuffer* candidate in self.bufferCache)
  414. if (candidate.buffer.length >= length && (bestCandidate == nil || bestCandidate.lastReuseTime > candidate.lastReuseTime))
  415. bestCandidate = candidate;
  416. if (bestCandidate != nil)
  417. {
  418. [self.bufferCache removeObject:bestCandidate];
  419. bestCandidate.lastReuseTime = now;
  420. return bestCandidate;
  421. }
  422. }
  423. // No luck; make a new buffer
  424. id<MTLBuffer> backing = [device newBufferWithLength:length options:MTLResourceStorageModeShared];
  425. return [[MetalBuffer alloc] initWithBuffer:backing];
  426. }
  427. // Bilinear sampling is required by default. Set 'io.Fonts->Flags |= ImFontAtlasFlags_NoBakedLines' or 'style.AntiAliasedLinesUseTex = false' to allow point/nearest sampling.
  428. - (id<MTLRenderPipelineState>)renderPipelineStateForFramebufferDescriptor:(FramebufferDescriptor*)descriptor device:(id<MTLDevice>)device
  429. {
  430. NSError* error = nil;
  431. NSString* shaderSource = @""
  432. "#include <metal_stdlib>\n"
  433. "using namespace metal;\n"
  434. "\n"
  435. "struct Uniforms {\n"
  436. " float4x4 projectionMatrix;\n"
  437. "};\n"
  438. "\n"
  439. "struct VertexIn {\n"
  440. " float2 position [[attribute(0)]];\n"
  441. " float2 texCoords [[attribute(1)]];\n"
  442. " uchar4 color [[attribute(2)]];\n"
  443. "};\n"
  444. "\n"
  445. "struct VertexOut {\n"
  446. " float4 position [[position]];\n"
  447. " float2 texCoords;\n"
  448. " float4 color;\n"
  449. "};\n"
  450. "\n"
  451. "vertex VertexOut vertex_main(VertexIn in [[stage_in]],\n"
  452. " constant Uniforms &uniforms [[buffer(1)]]) {\n"
  453. " VertexOut out;\n"
  454. " out.position = uniforms.projectionMatrix * float4(in.position, 0, 1);\n"
  455. " out.texCoords = in.texCoords;\n"
  456. " out.color = float4(in.color) / float4(255.0);\n"
  457. " return out;\n"
  458. "}\n"
  459. "\n"
  460. "fragment half4 fragment_main(VertexOut in [[stage_in]],\n"
  461. " texture2d<half, access::sample> texture [[texture(0)]]) {\n"
  462. " constexpr sampler linearSampler(coord::normalized, min_filter::linear, mag_filter::linear, mip_filter::linear);\n"
  463. " half4 texColor = texture.sample(linearSampler, in.texCoords);\n"
  464. " return half4(in.color) * texColor;\n"
  465. "}\n";
  466. id<MTLLibrary> library = [device newLibraryWithSource:shaderSource options:nil error:&error];
  467. if (library == nil)
  468. {
  469. NSLog(@"Error: failed to create Metal library: %@", error);
  470. return nil;
  471. }
  472. id<MTLFunction> vertexFunction = [library newFunctionWithName:@"vertex_main"];
  473. id<MTLFunction> fragmentFunction = [library newFunctionWithName:@"fragment_main"];
  474. if (vertexFunction == nil || fragmentFunction == nil)
  475. {
  476. NSLog(@"Error: failed to find Metal shader functions in library: %@", error);
  477. return nil;
  478. }
  479. MTLVertexDescriptor* vertexDescriptor = [MTLVertexDescriptor vertexDescriptor];
  480. vertexDescriptor.attributes[0].offset = offsetof(ImDrawVert, pos);
  481. vertexDescriptor.attributes[0].format = MTLVertexFormatFloat2; // position
  482. vertexDescriptor.attributes[0].bufferIndex = 0;
  483. vertexDescriptor.attributes[1].offset = offsetof(ImDrawVert, uv);
  484. vertexDescriptor.attributes[1].format = MTLVertexFormatFloat2; // texCoords
  485. vertexDescriptor.attributes[1].bufferIndex = 0;
  486. vertexDescriptor.attributes[2].offset = offsetof(ImDrawVert, col);
  487. vertexDescriptor.attributes[2].format = MTLVertexFormatUChar4; // color
  488. vertexDescriptor.attributes[2].bufferIndex = 0;
  489. vertexDescriptor.layouts[0].stepRate = 1;
  490. vertexDescriptor.layouts[0].stepFunction = MTLVertexStepFunctionPerVertex;
  491. vertexDescriptor.layouts[0].stride = sizeof(ImDrawVert);
  492. MTLRenderPipelineDescriptor* pipelineDescriptor = [[MTLRenderPipelineDescriptor alloc] init];
  493. pipelineDescriptor.vertexFunction = vertexFunction;
  494. pipelineDescriptor.fragmentFunction = fragmentFunction;
  495. pipelineDescriptor.vertexDescriptor = vertexDescriptor;
  496. pipelineDescriptor.rasterSampleCount = self.framebufferDescriptor.sampleCount;
  497. pipelineDescriptor.colorAttachments[0].pixelFormat = self.framebufferDescriptor.colorPixelFormat;
  498. pipelineDescriptor.colorAttachments[0].blendingEnabled = YES;
  499. pipelineDescriptor.colorAttachments[0].rgbBlendOperation = MTLBlendOperationAdd;
  500. pipelineDescriptor.colorAttachments[0].sourceRGBBlendFactor = MTLBlendFactorSourceAlpha;
  501. pipelineDescriptor.colorAttachments[0].destinationRGBBlendFactor = MTLBlendFactorOneMinusSourceAlpha;
  502. pipelineDescriptor.colorAttachments[0].alphaBlendOperation = MTLBlendOperationAdd;
  503. pipelineDescriptor.colorAttachments[0].sourceAlphaBlendFactor = MTLBlendFactorOne;
  504. pipelineDescriptor.colorAttachments[0].destinationAlphaBlendFactor = MTLBlendFactorOneMinusSourceAlpha;
  505. pipelineDescriptor.depthAttachmentPixelFormat = self.framebufferDescriptor.depthPixelFormat;
  506. pipelineDescriptor.stencilAttachmentPixelFormat = self.framebufferDescriptor.stencilPixelFormat;
  507. id<MTLRenderPipelineState> renderPipelineState = [device newRenderPipelineStateWithDescriptor:pipelineDescriptor error:&error];
  508. if (error != nil)
  509. NSLog(@"Error: failed to create Metal pipeline state: %@", error);
  510. return renderPipelineState;
  511. }
  512. @end
  513. //-----------------------------------------------------------------------------
  514. #endif // #ifndef IMGUI_DISABLE