2020-10-12 23:34:22 +08:00
// dear imgui: Renderer Backend for Metal
// This needs to be used along with a Platform Backend (e.g. OSX)
2018-07-05 17:41:21 +08:00
// Implemented features:
2019-10-16 17:23:15 +08:00
// [X] Renderer: User texture binding. Use 'MTLTexture' as ImTextureID. Read the FAQ about ImTextureID!
2019-11-20 18:58:25 +08:00
// [X] Renderer: Support for large meshes (64k+ vertices) with 16-bit indices.
2018-07-05 17:41:21 +08:00
2021-05-27 19:59:35 +08:00
// You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
// Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
2020-10-14 18:22:53 +08:00
// If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp.
// Read online: https://github.com/ocornut/imgui/tree/master/docs
2018-07-05 17:41:21 +08:00
// CHANGELOG
// (minor and older changes stripped away, please see git history for details)
2021-02-07 19:36:54 +08:00
// 2021-05-19: Metal: Replaced direct access to ImDrawCmd::TextureId with a call to ImDrawCmd::GetTexID(). (will become a requirement)
2021-02-18 02:29:07 +08:00
// 2021-02-18: Metal: Change blending equation to preserve alpha in output buffer.
2021-01-23 00:04:54 +08:00
// 2021-01-25: Metal: Fixed texture storage mode when building on Mac Catalyst.
2019-05-30 01:35:41 +08:00
// 2019-05-29: Metal: Added support for large mesh (64K+ vertices), enable ImGuiBackendFlags_RendererHasVtxOffset flag.
2019-05-01 04:28:29 +08:00
// 2019-04-30: Metal: Added support for special ImDrawCallback_ResetRenderState callback to reset render state.
2019-02-12 01:38:07 +08:00
// 2019-02-11: Metal: Projecting clipping rectangles correctly using draw_data->FramebufferScale to allow multi-viewports for retina display.
2018-12-01 01:18:15 +08:00
// 2018-11-30: Misc: Setting up io.BackendRendererName so it can be displayed in the About Window.
2018-07-08 16:47:31 +08:00
// 2018-07-05: Metal: Added new Metal backend implementation.
2018-07-05 17:41:21 +08:00
#include "imgui.h"
#include "imgui_impl_metal.h"
#import <Metal/Metal.h>
2019-04-03 23:23:31 +08:00
// #import <QuartzCore/CAMetalLayer.h> // Not supported in XCode 9.2. Maybe a macro to detect the SDK version can be used (something like #if MACOS_SDK >= 10.13 ...)
2018-07-05 17:41:21 +08:00
#import <simd/simd.h>
#pragma mark - Support classes
// A wrapper around a MTLBuffer object that knows the last time it was reused
@interface MetalBuffer : NSObject
@property (nonatomic, strong) id<MTLBuffer> buffer;
@property (nonatomic, assign) NSTimeInterval lastReuseTime;
- (instancetype)initWithBuffer:(id<MTLBuffer>)buffer;
@end
// An object that encapsulates the data necessary to uniquely identify a
// render pipeline state. These are used as cache keys.
@interface FramebufferDescriptor : NSObject<NSCopying>
@property (nonatomic, assign) unsigned long sampleCount;
@property (nonatomic, assign) MTLPixelFormat colorPixelFormat;
@property (nonatomic, assign) MTLPixelFormat depthPixelFormat;
@property (nonatomic, assign) MTLPixelFormat stencilPixelFormat;
- (instancetype)initWithRenderPassDescriptor:(MTLRenderPassDescriptor *)renderPassDescriptor;
@end
// A singleton that stores long-lived objects that are needed by the Metal
// renderer backend. Stores the render pipeline state cache and the default
// font texture, and manages the reusable buffer cache.
@interface MetalContext : NSObject
@property (nonatomic, strong) id<MTLDepthStencilState> depthStencilState;
@property (nonatomic, strong) FramebufferDescriptor *framebufferDescriptor; // framebuffer descriptor for current frame; transient
@property (nonatomic, strong) NSMutableDictionary *renderPipelineStateCache; // pipeline cache; keyed on framebuffer descriptors
@property (nonatomic, strong, nullable) id<MTLTexture> fontTexture;
@property (nonatomic, strong) NSMutableArray<MetalBuffer *> *bufferCache;
@property (nonatomic, assign) NSTimeInterval lastBufferCachePurge;
- (void)makeDeviceObjectsWithDevice:(id<MTLDevice>)device;
- (void)makeFontTextureWithDevice:(id<MTLDevice>)device;
- (MetalBuffer *)dequeueReusableBufferOfLength:(NSUInteger)length device:(id<MTLDevice>)device;
- (void)enqueueReusableBuffer:(MetalBuffer *)buffer;
- (id<MTLRenderPipelineState>)renderPipelineStateForFrameAndDevice:(id<MTLDevice>)device;
- (void)emptyRenderPipelineStateCache;
2019-03-30 02:11:55 +08:00
- (void)setupRenderState:(ImDrawData *)drawData
commandBuffer:(id<MTLCommandBuffer>)commandBuffer
commandEncoder:(id<MTLRenderCommandEncoder>)commandEncoder
renderPipelineState:(id<MTLRenderPipelineState>)renderPipelineState
vertexBuffer:(MetalBuffer *)vertexBuffer
vertexBufferOffset:(size_t)vertexBufferOffset;
2018-07-05 17:41:21 +08:00
- (void)renderDrawData:(ImDrawData *)drawData
commandBuffer:(id<MTLCommandBuffer>)commandBuffer
commandEncoder:(id<MTLRenderCommandEncoder>)commandEncoder;
@end
static MetalContext *g_sharedMetalContext = nil;
#pragma mark - ImGui API implementation
bool ImGui_ImplMetal_Init(id<MTLDevice> device)
{
2018-12-01 01:18:15 +08:00
ImGuiIO& io = ImGui::GetIO();
io.BackendRendererName = "imgui_impl_metal";
2019-05-30 01:35:41 +08:00
io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset; // We can honor the ImDrawCmd::VtxOffset field, allowing for large meshes.
2018-12-01 01:18:15 +08:00
2018-07-05 17:41:21 +08:00
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
g_sharedMetalContext = [[MetalContext alloc] init];
});
2019-01-21 00:56:17 +08:00
2018-07-05 17:41:21 +08:00
ImGui_ImplMetal_CreateDeviceObjects(device);
return true;
}
void ImGui_ImplMetal_Shutdown()
{
ImGui_ImplMetal_DestroyDeviceObjects();
}
void ImGui_ImplMetal_NewFrame(MTLRenderPassDescriptor *renderPassDescriptor)
{
2019-04-17 15:59:03 +08:00
IM_ASSERT(g_sharedMetalContext != nil && "No Metal context. Did you call ImGui_ImplMetal_Init() ?");
2018-07-05 17:41:21 +08:00
g_sharedMetalContext.framebufferDescriptor = [[FramebufferDescriptor alloc] initWithRenderPassDescriptor:renderPassDescriptor];
}
// Metal Render function.
void ImGui_ImplMetal_RenderDrawData(ImDrawData* draw_data, id<MTLCommandBuffer> commandBuffer, id<MTLRenderCommandEncoder> commandEncoder)
{
[g_sharedMetalContext renderDrawData:draw_data commandBuffer:commandBuffer commandEncoder:commandEncoder];
}
bool ImGui_ImplMetal_CreateFontsTexture(id<MTLDevice> device)
{
[g_sharedMetalContext makeFontTextureWithDevice:device];
2019-01-21 00:56:17 +08:00
2018-07-05 17:41:21 +08:00
ImGuiIO& io = ImGui::GetIO();
2021-02-04 01:30:26 +08:00
io.Fonts->SetTexID((__bridge void *)g_sharedMetalContext.fontTexture); // ImTextureID == void*
2018-07-05 17:41:21 +08:00
return (g_sharedMetalContext.fontTexture != nil);
}
void ImGui_ImplMetal_DestroyFontsTexture()
{
ImGuiIO& io = ImGui::GetIO();
g_sharedMetalContext.fontTexture = nil;
2021-02-04 01:30:26 +08:00
io.Fonts->SetTexID(nullptr);
2018-07-05 17:41:21 +08:00
}
bool ImGui_ImplMetal_CreateDeviceObjects(id<MTLDevice> device)
{
[g_sharedMetalContext makeDeviceObjectsWithDevice:device];
ImGui_ImplMetal_CreateFontsTexture(device);
return true;
}
void ImGui_ImplMetal_DestroyDeviceObjects()
{
ImGui_ImplMetal_DestroyFontsTexture();
[g_sharedMetalContext emptyRenderPipelineStateCache];
}
#pragma mark - MetalBuffer implementation
@implementation MetalBuffer
2019-01-21 00:56:17 +08:00
- (instancetype)initWithBuffer:(id<MTLBuffer>)buffer
2018-07-08 17:16:11 +08:00
{
2019-01-21 00:56:17 +08:00
if ((self = [super init]))
2018-07-08 17:16:11 +08:00
{
2018-07-05 17:41:21 +08:00
_buffer = buffer;
_lastReuseTime = [NSDate date].timeIntervalSince1970;
}
return self;
}
@end
#pragma mark - FramebufferDescriptor implementation
@implementation FramebufferDescriptor
2019-01-21 00:56:17 +08:00
- (instancetype)initWithRenderPassDescriptor:(MTLRenderPassDescriptor *)renderPassDescriptor
2018-07-08 17:16:11 +08:00
{
2019-01-21 00:56:17 +08:00
if ((self = [super init]))
2018-07-08 17:16:11 +08:00
{
2018-07-05 17:41:21 +08:00
_sampleCount = renderPassDescriptor.colorAttachments[0].texture.sampleCount;
_colorPixelFormat = renderPassDescriptor.colorAttachments[0].texture.pixelFormat;
_depthPixelFormat = renderPassDescriptor.depthAttachment.texture.pixelFormat;
_stencilPixelFormat = renderPassDescriptor.stencilAttachment.texture.pixelFormat;
}
return self;
}
2019-01-21 00:56:17 +08:00
- (nonnull id)copyWithZone:(nullable NSZone *)zone
2018-07-08 17:16:11 +08:00
{
2018-07-05 17:41:21 +08:00
FramebufferDescriptor *copy = [[FramebufferDescriptor allocWithZone:zone] init];
copy.sampleCount = self.sampleCount;
copy.colorPixelFormat = self.colorPixelFormat;
copy.depthPixelFormat = self.depthPixelFormat;
copy.stencilPixelFormat = self.stencilPixelFormat;
return copy;
}
2019-01-21 00:56:17 +08:00
- (NSUInteger)hash
2018-07-08 17:16:11 +08:00
{
2018-07-05 17:41:21 +08:00
NSUInteger sc = _sampleCount & 0x3;
NSUInteger cf = _colorPixelFormat & 0x3FF;
NSUInteger df = _depthPixelFormat & 0x3FF;
NSUInteger sf = _stencilPixelFormat & 0x3FF;
NSUInteger hash = (sf << 22) | (df << 12) | (cf << 2) | sc;
return hash;
}
2019-01-21 00:56:17 +08:00
- (BOOL)isEqual:(id)object
2018-07-08 17:16:11 +08:00
{
2018-07-05 17:41:21 +08:00
FramebufferDescriptor *other = object;
2018-07-08 17:16:11 +08:00
if (![other isKindOfClass:[FramebufferDescriptor class]])
2018-07-05 17:41:21 +08:00
return NO;
2018-07-08 17:16:11 +08:00
return other.sampleCount == self.sampleCount &&
2018-07-05 17:41:21 +08:00
other.colorPixelFormat == self.colorPixelFormat &&
other.depthPixelFormat == self.depthPixelFormat &&
other.stencilPixelFormat == self.stencilPixelFormat;
}
@end
#pragma mark - MetalContext implementation
@implementation MetalContext
- (instancetype)init {
2019-01-21 00:56:17 +08:00
if ((self = [super init]))
2018-07-08 17:16:11 +08:00
{
2018-07-05 17:41:21 +08:00
_renderPipelineStateCache = [NSMutableDictionary dictionary];
_bufferCache = [NSMutableArray array];
_lastBufferCachePurge = [NSDate date].timeIntervalSince1970;
}
return self;
}
2019-01-21 00:56:17 +08:00
- (void)makeDeviceObjectsWithDevice:(id<MTLDevice>)device
2018-07-08 17:16:11 +08:00
{
2018-07-05 17:41:21 +08:00
MTLDepthStencilDescriptor *depthStencilDescriptor = [[MTLDepthStencilDescriptor alloc] init];
depthStencilDescriptor.depthWriteEnabled = NO;
depthStencilDescriptor.depthCompareFunction = MTLCompareFunctionAlways;
self.depthStencilState = [device newDepthStencilStateWithDescriptor:depthStencilDescriptor];
}
2018-07-08 17:16:11 +08:00
// We are retrieving and uploading the font atlas as a 4-channels RGBA texture here.
// In theory we could call GetTexDataAsAlpha8() and upload a 1-channel texture to save on memory access bandwidth.
// However, using a shader designed for 1-channel texture would make it less obvious to use the ImTextureID facility to render users own textures.
// You can make that change in your implementation.
2019-01-21 00:56:17 +08:00
- (void)makeFontTextureWithDevice:(id<MTLDevice>)device
2018-07-08 17:16:11 +08:00
{
2018-07-05 17:41:21 +08:00
ImGuiIO &io = ImGui::GetIO();
unsigned char* pixels;
int width, height;
io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height);
MTLTextureDescriptor *textureDescriptor = [MTLTextureDescriptor texture2DDescriptorWithPixelFormat:MTLPixelFormatRGBA8Unorm
2020-10-24 00:57:35 +08:00
width:(NSUInteger)width
height:(NSUInteger)height
2018-07-05 17:41:21 +08:00
mipmapped:NO];
textureDescriptor.usage = MTLTextureUsageShaderRead;
2021-01-23 00:04:54 +08:00
#if TARGET_OS_OSX || TARGET_OS_MACCATALYST
2018-07-05 17:41:21 +08:00
textureDescriptor.storageMode = MTLStorageModeManaged;
#else
textureDescriptor.storageMode = MTLStorageModeShared;
#endif
id <MTLTexture> texture = [device newTextureWithDescriptor:textureDescriptor];
2020-10-24 00:57:35 +08:00
[texture replaceRegion:MTLRegionMake2D(0, 0, (NSUInteger)width, (NSUInteger)height) mipmapLevel:0 withBytes:pixels bytesPerRow:(NSUInteger)width * 4];
2018-07-05 17:41:21 +08:00
self.fontTexture = texture;
}
2019-01-21 00:56:17 +08:00
- (MetalBuffer *)dequeueReusableBufferOfLength:(NSUInteger)length device:(id<MTLDevice>)device
2018-07-08 17:16:11 +08:00
{
2018-07-05 17:41:21 +08:00
NSTimeInterval now = [NSDate date].timeIntervalSince1970;
2019-01-21 00:56:17 +08:00
2018-07-05 17:41:21 +08:00
// Purge old buffers that haven't been useful for a while
2019-01-21 00:56:17 +08:00
if (now - self.lastBufferCachePurge > 1.0)
2018-07-08 17:16:11 +08:00
{
2018-07-05 17:41:21 +08:00
NSMutableArray *survivors = [NSMutableArray array];
2019-01-21 00:56:17 +08:00
for (MetalBuffer *candidate in self.bufferCache)
2018-07-08 17:16:11 +08:00
{
2019-01-21 00:56:17 +08:00
if (candidate.lastReuseTime > self.lastBufferCachePurge)
2018-07-08 17:16:11 +08:00
{
2018-07-05 17:41:21 +08:00
[survivors addObject:candidate];
}
}
self.bufferCache = [survivors mutableCopy];
self.lastBufferCachePurge = now;
}
2019-01-21 00:56:17 +08:00
2018-07-05 17:41:21 +08:00
// See if we have a buffer we can reuse
MetalBuffer *bestCandidate = nil;
2019-01-21 00:56:17 +08:00
for (MetalBuffer *candidate in self.bufferCache)
2018-07-08 17:16:11 +08:00
if (candidate.buffer.length >= length && (bestCandidate == nil || bestCandidate.lastReuseTime > candidate.lastReuseTime))
2018-07-05 17:41:21 +08:00
bestCandidate = candidate;
2019-01-21 00:56:17 +08:00
if (bestCandidate != nil)
2018-07-08 17:16:11 +08:00
{
2018-07-05 17:41:21 +08:00
[self.bufferCache removeObject:bestCandidate];
bestCandidate.lastReuseTime = now;
return bestCandidate;
}
2019-01-21 00:56:17 +08:00
2018-07-05 17:41:21 +08:00
// No luck; make a new buffer
id<MTLBuffer> backing = [device newBufferWithLength:length options:MTLResourceStorageModeShared];
return [[MetalBuffer alloc] initWithBuffer:backing];
}
2019-01-21 00:56:17 +08:00
- (void)enqueueReusableBuffer:(MetalBuffer *)buffer
2018-07-08 17:16:11 +08:00
{
2018-07-05 17:41:21 +08:00
[self.bufferCache addObject:buffer];
}
2019-01-21 00:56:17 +08:00
- (_Nullable id<MTLRenderPipelineState>)renderPipelineStateForFrameAndDevice:(id<MTLDevice>)device
2018-07-08 17:16:11 +08:00
{
2018-07-05 17:41:21 +08:00
// Try to retrieve a render pipeline state that is compatible with the framebuffer config for this frame
2019-03-09 17:10:17 +08:00
// The hit rate for this cache should be very near 100%.
2018-07-05 17:41:21 +08:00
id<MTLRenderPipelineState> renderPipelineState = self.renderPipelineStateCache[self.framebufferDescriptor];
2019-01-21 00:56:17 +08:00
if (renderPipelineState == nil)
2018-07-08 17:16:11 +08:00
{
2018-07-05 17:41:21 +08:00
// No luck; make a new render pipeline state
renderPipelineState = [self _renderPipelineStateForFramebufferDescriptor:self.framebufferDescriptor device:device];
// Cache render pipeline state for later reuse
self.renderPipelineStateCache[self.framebufferDescriptor] = renderPipelineState;
}
2019-01-21 00:56:17 +08:00
2018-07-05 17:41:21 +08:00
return renderPipelineState;
}
- (id<MTLRenderPipelineState>)_renderPipelineStateForFramebufferDescriptor:(FramebufferDescriptor *)descriptor device:(id<MTLDevice>)device
{
NSError *error = nil;
2019-01-21 00:56:17 +08:00
2018-07-05 17:41:21 +08:00
NSString *shaderSource = @""
"#include <metal_stdlib>\n"
"using namespace metal;\n"
"\n"
"struct Uniforms {\n"
" float4x4 projectionMatrix;\n"
"};\n"
"\n"
"struct VertexIn {\n"
" float2 position [[attribute(0)]];\n"
" float2 texCoords [[attribute(1)]];\n"
" uchar4 color [[attribute(2)]];\n"
"};\n"
"\n"
"struct VertexOut {\n"
" float4 position [[position]];\n"
" float2 texCoords;\n"
" float4 color;\n"
"};\n"
"\n"
"vertex VertexOut vertex_main(VertexIn in [[stage_in]],\n"
" constant Uniforms &uniforms [[buffer(1)]]) {\n"
" VertexOut out;\n"
" out.position = uniforms.projectionMatrix * float4(in.position, 0, 1);\n"
" out.texCoords = in.texCoords;\n"
" out.color = float4(in.color) / float4(255.0);\n"
" return out;\n"
"}\n"
"\n"
"fragment half4 fragment_main(VertexOut in [[stage_in]],\n"
" texture2d<half, access::sample> texture [[texture(0)]]) {\n"
" constexpr sampler linearSampler(coord::normalized, min_filter::linear, mag_filter::linear, mip_filter::linear);\n"
" half4 texColor = texture.sample(linearSampler, in.texCoords);\n"
" return half4(in.color) * texColor;\n"
"}\n";
2019-01-21 00:56:17 +08:00
2018-07-05 17:41:21 +08:00
id<MTLLibrary> library = [device newLibraryWithSource:shaderSource options:nil error:&error];
2019-01-21 00:56:17 +08:00
if (library == nil)
2018-07-08 17:16:11 +08:00
{
2018-07-05 17:41:21 +08:00
NSLog(@"Error: failed to create Metal library: %@", error);
return nil;
}
2019-01-21 00:56:17 +08:00
2018-07-05 17:41:21 +08:00
id<MTLFunction> vertexFunction = [library newFunctionWithName:@"vertex_main"];
id<MTLFunction> fragmentFunction = [library newFunctionWithName:@"fragment_main"];
2019-01-21 00:56:17 +08:00
if (vertexFunction == nil || fragmentFunction == nil)
2018-07-08 17:16:11 +08:00
{
2018-07-05 17:41:21 +08:00
NSLog(@"Error: failed to find Metal shader functions in library: %@", error);
return nil;
}
2019-01-21 00:56:17 +08:00
2018-07-05 17:41:21 +08:00
MTLVertexDescriptor *vertexDescriptor = [MTLVertexDescriptor vertexDescriptor];
vertexDescriptor.attributes[0].offset = IM_OFFSETOF(ImDrawVert, pos);
vertexDescriptor.attributes[0].format = MTLVertexFormatFloat2; // position
vertexDescriptor.attributes[0].bufferIndex = 0;
vertexDescriptor.attributes[1].offset = IM_OFFSETOF(ImDrawVert, uv);
vertexDescriptor.attributes[1].format = MTLVertexFormatFloat2; // texCoords
vertexDescriptor.attributes[1].bufferIndex = 0;
vertexDescriptor.attributes[2].offset = IM_OFFSETOF(ImDrawVert, col);
vertexDescriptor.attributes[2].format = MTLVertexFormatUChar4; // color
vertexDescriptor.attributes[2].bufferIndex = 0;
vertexDescriptor.layouts[0].stepRate = 1;
vertexDescriptor.layouts[0].stepFunction = MTLVertexStepFunctionPerVertex;
vertexDescriptor.layouts[0].stride = sizeof(ImDrawVert);
2019-01-21 00:56:17 +08:00
2018-07-05 17:41:21 +08:00
MTLRenderPipelineDescriptor *pipelineDescriptor = [[MTLRenderPipelineDescriptor alloc] init];
pipelineDescriptor.vertexFunction = vertexFunction;
pipelineDescriptor.fragmentFunction = fragmentFunction;
pipelineDescriptor.vertexDescriptor = vertexDescriptor;
pipelineDescriptor.sampleCount = self.framebufferDescriptor.sampleCount;
pipelineDescriptor.colorAttachments[0].pixelFormat = self.framebufferDescriptor.colorPixelFormat;
pipelineDescriptor.colorAttachments[0].blendingEnabled = YES;
pipelineDescriptor.colorAttachments[0].rgbBlendOperation = MTLBlendOperationAdd;
pipelineDescriptor.colorAttachments[0].sourceRGBBlendFactor = MTLBlendFactorSourceAlpha;
pipelineDescriptor.colorAttachments[0].destinationRGBBlendFactor = MTLBlendFactorOneMinusSourceAlpha;
2021-02-18 02:29:07 +08:00
pipelineDescriptor.colorAttachments[0].alphaBlendOperation = MTLBlendOperationAdd;
pipelineDescriptor.colorAttachments[0].sourceAlphaBlendFactor = MTLBlendFactorOne;
2018-07-05 17:41:21 +08:00
pipelineDescriptor.colorAttachments[0].destinationAlphaBlendFactor = MTLBlendFactorOneMinusSourceAlpha;
pipelineDescriptor.depthAttachmentPixelFormat = self.framebufferDescriptor.depthPixelFormat;
pipelineDescriptor.stencilAttachmentPixelFormat = self.framebufferDescriptor.stencilPixelFormat;
2019-01-21 00:56:17 +08:00
2018-07-05 17:41:21 +08:00
id<MTLRenderPipelineState> renderPipelineState = [device newRenderPipelineStateWithDescriptor:pipelineDescriptor error:&error];
2019-01-21 00:56:17 +08:00
if (error != nil)
2018-07-08 17:16:11 +08:00
{
2018-07-05 17:41:21 +08:00
NSLog(@"Error: failed to create Metal pipeline state: %@", error);
}
2019-01-21 00:56:17 +08:00
2018-07-05 17:41:21 +08:00
return renderPipelineState;
}
2019-01-21 00:56:17 +08:00
- (void)emptyRenderPipelineStateCache
2018-07-08 17:16:11 +08:00
{
2018-07-05 17:41:21 +08:00
[self.renderPipelineStateCache removeAllObjects];
}
2019-03-30 02:11:55 +08:00
- (void)setupRenderState:(ImDrawData *)drawData
commandBuffer:(id<MTLCommandBuffer>)commandBuffer
commandEncoder:(id<MTLRenderCommandEncoder>)commandEncoder
renderPipelineState:(id<MTLRenderPipelineState>)renderPipelineState
vertexBuffer:(MetalBuffer *)vertexBuffer
vertexBufferOffset:(size_t)vertexBufferOffset
2018-07-05 17:41:21 +08:00
{
[commandEncoder setCullMode:MTLCullModeNone];
[commandEncoder setDepthStencilState:g_sharedMetalContext.depthStencilState];
2019-01-21 00:56:17 +08:00
2018-07-05 17:41:21 +08:00
// Setup viewport, orthographic projection matrix
2018-09-13 22:44:08 +08:00
// Our visible imgui space lies from draw_data->DisplayPos (top left) to
2018-07-05 17:41:21 +08:00
// draw_data->DisplayPos+data_data->DisplaySize (bottom right). DisplayMin is typically (0,0) for single viewport apps.
2019-01-21 00:56:17 +08:00
MTLViewport viewport =
{
2018-07-08 17:16:11 +08:00
.originX = 0.0,
2018-07-05 17:41:21 +08:00
.originY = 0.0,
2019-03-30 02:11:55 +08:00
.width = (double)(drawData->DisplaySize.x * drawData->FramebufferScale.x),
.height = (double)(drawData->DisplaySize.y * drawData->FramebufferScale.y),
2018-07-05 17:41:21 +08:00
.znear = 0.0,
2019-01-21 00:56:17 +08:00
.zfar = 1.0
2018-07-08 17:16:11 +08:00
};
2018-07-05 17:41:21 +08:00
[commandEncoder setViewport:viewport];
2019-03-30 02:11:55 +08:00
2018-07-05 17:41:21 +08:00
float L = drawData->DisplayPos.x;
float R = drawData->DisplayPos.x + drawData->DisplaySize.x;
float T = drawData->DisplayPos.y;
float B = drawData->DisplayPos.y + drawData->DisplaySize.y;
2020-10-24 00:57:35 +08:00
float N = (float)viewport.znear;
float F = (float)viewport.zfar;
2018-07-05 17:41:21 +08:00
const float ortho_projection[4][4] =
{
{ 2.0f/(R-L), 0.0f, 0.0f, 0.0f },
{ 0.0f, 2.0f/(T-B), 0.0f, 0.0f },
{ 0.0f, 0.0f, 1/(F-N), 0.0f },
{ (R+L)/(L-R), (T+B)/(B-T), N/(F-N), 1.0f },
};
[commandEncoder setVertexBytes:&ortho_projection length:sizeof(ortho_projection) atIndex:1];
2019-01-21 00:56:17 +08:00
2019-03-30 02:11:55 +08:00
[commandEncoder setRenderPipelineState:renderPipelineState];
[commandEncoder setVertexBuffer:vertexBuffer.buffer offset:0 atIndex:0];
[commandEncoder setVertexBufferOffset:vertexBufferOffset atIndex:0];
}
- (void)renderDrawData:(ImDrawData *)drawData
commandBuffer:(id<MTLCommandBuffer>)commandBuffer
commandEncoder:(id<MTLRenderCommandEncoder>)commandEncoder
{
// Avoid rendering when minimized, scale coordinates for retina displays (screen coordinates != framebuffer coordinates)
int fb_width = (int)(drawData->DisplaySize.x * drawData->FramebufferScale.x);
int fb_height = (int)(drawData->DisplaySize.y * drawData->FramebufferScale.y);
if (fb_width <= 0 || fb_height <= 0 || drawData->CmdListsCount == 0)
return;
id<MTLRenderPipelineState> renderPipelineState = [self renderPipelineStateForFrameAndDevice:commandBuffer.device];
2020-10-24 00:57:35 +08:00
size_t vertexBufferLength = (size_t)drawData->TotalVtxCount * sizeof(ImDrawVert);
size_t indexBufferLength = (size_t)drawData->TotalIdxCount * sizeof(ImDrawIdx);
2019-02-12 00:38:34 +08:00
MetalBuffer* vertexBuffer = [self dequeueReusableBufferOfLength:vertexBufferLength device:commandBuffer.device];
MetalBuffer* indexBuffer = [self dequeueReusableBufferOfLength:indexBufferLength device:commandBuffer.device];
2019-01-21 00:56:17 +08:00
2019-03-30 02:11:55 +08:00
[self setupRenderState:drawData commandBuffer:commandBuffer commandEncoder:commandEncoder renderPipelineState:renderPipelineState vertexBuffer:vertexBuffer vertexBufferOffset:0];
2019-01-21 00:56:17 +08:00
2019-02-12 01:38:07 +08:00
// Will project scissor/clipping rectangles into framebuffer space
2019-02-12 17:30:09 +08:00
ImVec2 clip_off = drawData->DisplayPos; // (0,0) unless using multi-viewports
ImVec2 clip_scale = drawData->FramebufferScale; // (1,1) unless using retina display which are often (2,2)
2019-02-12 01:38:07 +08:00
// Render command lists
2018-07-05 17:41:21 +08:00
size_t vertexBufferOffset = 0;
size_t indexBufferOffset = 0;
for (int n = 0; n < drawData->CmdListsCount; n++)
{
const ImDrawList* cmd_list = drawData->CmdLists[n];
2019-01-21 00:56:17 +08:00
2020-10-24 00:57:35 +08:00
memcpy((char *)vertexBuffer.buffer.contents + vertexBufferOffset, cmd_list->VtxBuffer.Data, (size_t)cmd_list->VtxBuffer.Size * sizeof(ImDrawVert));
memcpy((char *)indexBuffer.buffer.contents + indexBufferOffset, cmd_list->IdxBuffer.Data, (size_t)cmd_list->IdxBuffer.Size * sizeof(ImDrawIdx));
2019-01-21 00:56:17 +08:00
2018-07-05 17:41:21 +08:00
for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++)
{
const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i];
if (pcmd->UserCallback)
{
2019-03-30 02:11:55 +08:00
// User callback, registered via ImDrawList::AddCallback()
// (ImDrawCallback_ResetRenderState is a special callback value used by the user to request the renderer to reset render state.)
if (pcmd->UserCallback == ImDrawCallback_ResetRenderState)
[self setupRenderState:drawData commandBuffer:commandBuffer commandEncoder:commandEncoder renderPipelineState:renderPipelineState vertexBuffer:vertexBuffer vertexBufferOffset:vertexBufferOffset];
else
pcmd->UserCallback(cmd_list, pcmd);
2018-07-05 17:41:21 +08:00
}
else
{
2019-02-12 01:38:07 +08:00
// Project scissor/clipping rectangles into framebuffer space
ImVec4 clip_rect;
clip_rect.x = (pcmd->ClipRect.x - clip_off.x) * clip_scale.x;
clip_rect.y = (pcmd->ClipRect.y - clip_off.y) * clip_scale.y;
clip_rect.z = (pcmd->ClipRect.z - clip_off.x) * clip_scale.x;
clip_rect.w = (pcmd->ClipRect.w - clip_off.y) * clip_scale.y;
2018-07-05 17:41:21 +08:00
if (clip_rect.x < fb_width && clip_rect.y < fb_height && clip_rect.z >= 0.0f && clip_rect.w >= 0.0f)
{
// Apply scissor/clipping rectangle
2019-02-12 00:38:34 +08:00
MTLScissorRect scissorRect =
{
.x = NSUInteger(clip_rect.x),
2018-07-05 17:41:21 +08:00
.y = NSUInteger(clip_rect.y),
.width = NSUInteger(clip_rect.z - clip_rect.x),
2019-02-12 00:38:34 +08:00
.height = NSUInteger(clip_rect.w - clip_rect.y)
};
2018-07-05 17:41:21 +08:00
[commandEncoder setScissorRect:scissorRect];
2019-01-21 00:56:17 +08:00
2018-07-05 17:41:21 +08:00
// Bind texture, Draw
2021-02-07 19:36:54 +08:00
if (ImTextureID tex_id = pcmd->GetTexID())
[commandEncoder setFragmentTexture:(__bridge id<MTLTexture>)(tex_id) atIndex:0];
2019-05-30 01:35:41 +08:00
[commandEncoder setVertexBufferOffset:(vertexBufferOffset + pcmd->VtxOffset * sizeof(ImDrawVert)) atIndex:0];
2018-07-05 17:41:21 +08:00
[commandEncoder drawIndexedPrimitives:MTLPrimitiveTypeTriangle
indexCount:pcmd->ElemCount
indexType:sizeof(ImDrawIdx) == 2 ? MTLIndexTypeUInt16 : MTLIndexTypeUInt32
indexBuffer:indexBuffer.buffer
2019-05-30 01:35:41 +08:00
indexBufferOffset:indexBufferOffset + pcmd->IdxOffset * sizeof(ImDrawIdx)];
2018-07-05 17:41:21 +08:00
}
}
}
2019-01-21 00:56:17 +08:00
2020-10-24 00:57:35 +08:00
vertexBufferOffset += (size_t)cmd_list->VtxBuffer.Size * sizeof(ImDrawVert);
indexBufferOffset += (size_t)cmd_list->IdxBuffer.Size * sizeof(ImDrawIdx);
2018-07-05 17:41:21 +08:00
}
2019-01-21 00:56:17 +08:00
2018-07-05 17:41:21 +08:00
__weak id weakSelf = self;
2019-01-21 00:56:17 +08:00
[commandBuffer addCompletedHandler:^(id<MTLCommandBuffer>)
2018-07-08 17:16:11 +08:00
{
2018-07-05 17:41:21 +08:00
dispatch_async(dispatch_get_main_queue(), ^{
[weakSelf enqueueReusableBuffer:vertexBuffer];
[weakSelf enqueueReusableBuffer:indexBuffer];
});
}];
}
@end