imgui_impl_metal.mm 30 KB

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