imgui_impl_metal.mm 27 KB

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