diff --git a/CMakeLists.txt b/CMakeLists.txt index eb63eaaffc..0b982c582c 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -38,7 +38,11 @@ if(APPLE) set(CMAKE_OSX_DEPLOYMENT_TARGET "10.15" CACHE STRING "Minimum macOS deployment version") set(CMAKE_OSX_ARCHITECTURES "x86_64;arm64" CACHE STRING "") endif() - set(ZLIB_LIBRARY "-lz" CACHE STRING "Use generic linker flag for Xcode to support multiple SDKs") + if(CMAKE_GENERATOR STREQUAL "Xcode") + # Ninja/Makefiles treat this as a file dependency of the final link and fail + # with "no known rule to make -lz"; only the Xcode generator needs it. + set(ZLIB_LIBRARY "-lz" CACHE STRING "Use generic linker flag for Xcode to support multiple SDKs") + endif() endif() if(LIBRETRO) @@ -90,6 +94,7 @@ option(USE_HOST_LIBCHDR "Use host libchdr" OFF) option(USE_HOST_LIBJUICE "Use host libjuice" OFF) option(USE_OPENMP "Use OpenMP if available" ON) option(USE_VULKAN "Build with Vulkan support" ON) +option(USE_METAL "Build with Metal support (macOS only)" ON) set(MOLTENVK_DYLIB "" CACHE FILEPATH "Path to macOS MoltenVK dylib for macOS Vulkan builds") option(USE_DX9 "Build with Direct3D 9 support" ON) option(USE_DX11 "Build with Direct3D 11 support" ON) @@ -113,6 +118,10 @@ if(IOS AND NOT LIBRETRO) set(USE_VULKAN OFF CACHE BOOL "Force vulkan off" FORCE) endif() +if(NOT APPLE OR IOS OR LIBRETRO) + set(USE_METAL OFF CACHE BOOL "Force metal off" FORCE) +endif() + if(WEBOS) if(CMAKE_CXX_COMPILER MATCHES "aarch64") set(USE_GLES ON CACHE BOOL "Use GLES[3] API" FORCE) @@ -1426,6 +1435,9 @@ if(NOT LIBRETRO) # gets its main() from gtest_main and stubs the rest (tests/src/test_stubs.cpp). if(NOT BUILD_TESTING) add_subdirectory(core/deps/Syphon) + # Syphon's prefix header is meant for its own sources. Don't let it propagate: + # flycast would get a C++-only PCH that can't be used for .mm files. + set_target_properties(Syphon PROPERTIES INTERFACE_PRECOMPILE_HEADERS "") target_link_libraries(${PROJECT_NAME} PRIVATE Syphon) add_custom_command(TARGET ${PROJECT_NAME} POST_BUILD COMMAND ${CMAKE_COMMAND} -E copy ${SYPHON_METALLIB} diff --git a/core/deps/imgui/backends/imgui_impl_metal.h b/core/deps/imgui/backends/imgui_impl_metal.h new file mode 100644 index 0000000000..8af2c8b6bf --- /dev/null +++ b/core/deps/imgui/backends/imgui_impl_metal.h @@ -0,0 +1,78 @@ +// dear imgui: Renderer Backend for Metal +// This needs to be used along with a Platform Backend (e.g. OSX) + +// Implemented features: +// [X] Renderer: User texture binding. Use 'MTLTexture' as texture identifier. Read the FAQ about ImTextureID/ImTextureRef! +// [X] Renderer: Large meshes support (64k+ vertices) even with 16-bit indices (ImGuiBackendFlags_RendererHasVtxOffset). +// [X] Renderer: Texture updates support for dynamic font atlas (ImGuiBackendFlags_RendererHasTextures). + +// 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. +// Learn about Dear ImGui: +// - FAQ https://dearimgui.com/faq +// - Getting Started https://dearimgui.com/getting-started +// - Documentation https://dearimgui.com/docs (same as your local docs/ folder). +// - Introduction, links and more at the top of imgui.cpp + +#pragma once +#include "imgui.h" // IMGUI_IMPL_API +#ifndef IMGUI_DISABLE + +//----------------------------------------------------------------------------- +// ObjC API +//----------------------------------------------------------------------------- + +#ifdef __OBJC__ + +@class MTLRenderPassDescriptor; +@protocol MTLDevice, MTLCommandBuffer, MTLRenderCommandEncoder; + +// Follow "Getting Started" link and check examples/ folder to learn about using backends! +IMGUI_IMPL_API bool ImGui_ImplMetal_Init(id device); +IMGUI_IMPL_API void ImGui_ImplMetal_Shutdown(); +IMGUI_IMPL_API void ImGui_ImplMetal_NewFrame(MTLRenderPassDescriptor* renderPassDescriptor); +IMGUI_IMPL_API void ImGui_ImplMetal_RenderDrawData(ImDrawData* drawData, + id commandBuffer, + id commandEncoder); + +// Called by Init/NewFrame/Shutdown +IMGUI_IMPL_API bool ImGui_ImplMetal_CreateDeviceObjects(id device); +IMGUI_IMPL_API void ImGui_ImplMetal_DestroyDeviceObjects(); + +// (Advanced) Use e.g. if you need to precisely control the timing of texture updates (e.g. for staged rendering), by setting ImDrawData::Textures = nullptr to handle this manually. +IMGUI_IMPL_API void ImGui_ImplMetal_UpdateTexture(ImTextureData* tex); + +#endif + +//----------------------------------------------------------------------------- +// C++ API +//----------------------------------------------------------------------------- + +// Enable Metal C++ binding support with '#define IMGUI_IMPL_METAL_CPP' in your imconfig.h file +// More info about using Metal from C++: https://developer.apple.com/metal/cpp/ + +#ifdef IMGUI_IMPL_METAL_CPP +#include +#ifndef __OBJC__ + +// Follow "Getting Started" link and check examples/ folder to learn about using backends! +IMGUI_IMPL_API bool ImGui_ImplMetal_Init(MTL::Device* device); +IMGUI_IMPL_API void ImGui_ImplMetal_Shutdown(); +IMGUI_IMPL_API void ImGui_ImplMetal_NewFrame(MTL::RenderPassDescriptor* renderPassDescriptor); +IMGUI_IMPL_API void ImGui_ImplMetal_RenderDrawData(ImDrawData* draw_data, + MTL::CommandBuffer* commandBuffer, + MTL::RenderCommandEncoder* commandEncoder); + +// Called by Init/NewFrame/Shutdown +IMGUI_IMPL_API bool ImGui_ImplMetal_CreateDeviceObjects(MTL::Device* device); +IMGUI_IMPL_API void ImGui_ImplMetal_DestroyDeviceObjects(); + +// (Advanced) Use e.g. if you need to precisely control the timing of texture updates (e.g. for staged rendering), by setting ImDrawData::Textures = nullptr to handle this manually. +IMGUI_IMPL_API void ImGui_ImplMetal_UpdateTexture(ImTextureData* tex); + +#endif +#endif + +//----------------------------------------------------------------------------- + +#endif // #ifndef IMGUI_DISABLE diff --git a/core/deps/imgui/backends/imgui_impl_metal.mm b/core/deps/imgui/backends/imgui_impl_metal.mm new file mode 100644 index 0000000000..9088fff229 --- /dev/null +++ b/core/deps/imgui/backends/imgui_impl_metal.mm @@ -0,0 +1,676 @@ +// dear imgui: Renderer Backend for Metal +// This needs to be used along with a Platform Backend (e.g. OSX) + +// Implemented features: +// [X] Renderer: User texture binding. Use 'MTLTexture' as texture identifier. Read the FAQ about ImTextureID/ImTextureRef! +// [X] Renderer: Large meshes support (64k+ vertices) even with 16-bit indices (ImGuiBackendFlags_RendererHasVtxOffset). +// [X] Renderer: Texture updates support for dynamic font atlas (ImGuiBackendFlags_RendererHasTextures). + +// 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. +// Learn about Dear ImGui: +// - FAQ https://dearimgui.com/faq +// - Getting Started https://dearimgui.com/getting-started +// - Documentation https://dearimgui.com/docs (same as your local docs/ folder). +// - Introduction, links and more at the top of imgui.cpp + +// CHANGELOG +// (minor and older changes stripped away, please see git history for details) +// 2026-04-28: Added support for standard draw callbacks (in platform_io): DrawCallback_SetSamplerLinear and DrawCallback_SetSamplerNearest. (#9378, #9381) +// 2026-04-23: Added support for standard draw callbacks (in platform_io): DrawCallback_ResetRenderState (others are not yet supported). (#9378) +// 2026-04-14: Metal: use a dedicated bufferCacheLock to avoid crashing when bufferCache is replaced by a new object while being used for @synchronize(). (#9367) +// 2026-04-03: Metal: avoid redundant vertex buffer bind in SetupRenderState. (#9343) +// 2026-03-19: Fixed issue in ImGui_ImplMetal_RenderDrawData() if ImTextureID_Invalid is defined to be != 0, which became the default since 2026-03-12. (#9295, #9310) +// 2025-09-18: Call platform_io.ClearRendererHandlers() on shutdown. +// 2025-06-11: Added support for ImGuiBackendFlags_RendererHasTextures, for dynamic font atlas. Removed ImGui_ImplMetal_CreateFontsTexture() and ImGui_ImplMetal_DestroyFontsTexture(). +// 2025-02-03: Metal: Crash fix. (#8367) +// 2025-01-08: Metal: Fixed memory leaks when using metal-cpp (#8276, #8166) or when using multiple contexts (#7419). +// 2022-08-23: Metal: Update deprecated property 'sampleCount'->'rasterSampleCount'. +// 2022-07-05: Metal: Add dispatch synchronization. +// 2022-06-30: Metal: Use __bridge for ARC based systems. +// 2022-06-01: Metal: Fixed null dereference on exit inside command buffer completion handler. +// 2022-04-27: Misc: Store backend data in a per-context struct, allowing to use this backend with multiple contexts. +// 2022-01-03: Metal: Ignore ImDrawCmd where ElemCount == 0 (very rare but can technically be manufactured by user code). +// 2021-12-30: Metal: Added Metal C++ support. Enable with '#define IMGUI_IMPL_METAL_CPP' in your imconfig.h file. +// 2021-08-24: Metal: Fixed a crash when clipping rect larger than framebuffer is submitted. (#4464) +// 2021-05-19: Metal: Replaced direct access to ImDrawCmd::TextureId with a call to ImDrawCmd::GetTexID(). (will become a requirement) +// 2021-02-18: Metal: Change blending equation to preserve alpha in output buffer. +// 2021-01-25: Metal: Fixed texture storage mode when building on Mac Catalyst. +// 2019-05-29: Metal: Added support for large mesh (64K+ vertices), enable ImGuiBackendFlags_RendererHasVtxOffset flag. +// 2019-04-30: Metal: Added support for special ImDrawCallback_ResetRenderState callback to reset render state. +// 2019-02-11: Metal: Projecting clipping rectangles correctly using draw_data->FramebufferScale to allow multi-viewports for retina display. +// 2018-11-30: Misc: Setting up io.BackendRendererName so it can be displayed in the About Window. +// 2018-07-05: Metal: Added new Metal backend implementation. + +#include "imgui.h" +#ifndef IMGUI_DISABLE +#include "imgui_impl_metal.h" +#import +#import + +#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 buffer; +@property (nonatomic, assign) double lastReuseTime; +- (instancetype)initWithBuffer:(id)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 +@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 + +@interface MetalTexture : NSObject +@property (nonatomic, strong) id metalTexture; +- (instancetype)initWithTexture:(id)metalTexture; +@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 device; +@property (nonatomic, strong) id depthStencilState; +@property (nonatomic, strong) id samplerStateLinear; +@property (nonatomic, strong) id samplerStateNearest; +@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) NSMutableArray* bufferCache; +@property (nonatomic, strong) NSObject* bufferCacheLock; +@property (nonatomic, assign) double lastBufferCachePurge; +- (MetalBuffer*)dequeueReusableBufferOfLength:(NSUInteger)length device:(id)device; +- (id)renderPipelineStateForFramebufferDescriptor:(FramebufferDescriptor*)descriptor device:(id)device; +@end + +struct ImGui_ImplMetal_Data +{ + MetalContext* SharedMetalContext; + id RenderCommandEncoder; + + ImGui_ImplMetal_Data() { memset((void*)this, 0, sizeof(*this)); } +}; + +static ImGui_ImplMetal_Data* ImGui_ImplMetal_GetBackendData() { return ImGui::GetCurrentContext() ? (ImGui_ImplMetal_Data*)ImGui::GetIO().BackendRendererUserData : nullptr; } +static void ImGui_ImplMetal_DestroyBackendData(){ IM_DELETE(ImGui_ImplMetal_GetBackendData()); } + +static inline CFTimeInterval GetMachAbsoluteTimeInSeconds() { return (CFTimeInterval)(double)(clock_gettime_nsec_np(CLOCK_UPTIME_RAW) / 1e9); } + +#ifdef IMGUI_IMPL_METAL_CPP + +#pragma mark - Dear ImGui Metal C++ Backend API + +bool ImGui_ImplMetal_Init(MTL::Device* device) +{ + return ImGui_ImplMetal_Init((__bridge id)(device)); +} + +void ImGui_ImplMetal_NewFrame(MTL::RenderPassDescriptor* renderPassDescriptor) +{ + ImGui_ImplMetal_NewFrame((__bridge MTLRenderPassDescriptor*)(renderPassDescriptor)); +} + +void ImGui_ImplMetal_RenderDrawData(ImDrawData* draw_data, + MTL::CommandBuffer* commandBuffer, + MTL::RenderCommandEncoder* commandEncoder) +{ + ImGui_ImplMetal_RenderDrawData(draw_data, + (__bridge id)(commandBuffer), + (__bridge id)(commandEncoder)); + +} + +bool ImGui_ImplMetal_CreateDeviceObjects(MTL::Device* device) +{ + return ImGui_ImplMetal_CreateDeviceObjects((__bridge id)(device)); +} + +#endif // #ifdef IMGUI_IMPL_METAL_CPP + +#pragma mark - Dear ImGui Metal Backend API + +void ImGui_ImplMetal_NewFrame(MTLRenderPassDescriptor* renderPassDescriptor) +{ + ImGui_ImplMetal_Data* bd = ImGui_ImplMetal_GetBackendData(); + IM_ASSERT(bd != nil && "Context or backend not initialized! Did you call ImGui_ImplMetal_Init()?"); +#ifdef IMGUI_IMPL_METAL_CPP + bd->SharedMetalContext.framebufferDescriptor = [[[FramebufferDescriptor alloc] initWithRenderPassDescriptor:renderPassDescriptor]autorelease]; +#else + bd->SharedMetalContext.framebufferDescriptor = [[FramebufferDescriptor alloc] initWithRenderPassDescriptor:renderPassDescriptor]; +#endif + if (bd->SharedMetalContext.depthStencilState == nil) + ImGui_ImplMetal_CreateDeviceObjects(bd->SharedMetalContext.device); +} + +static void ImGui_ImplMetal_SetupRenderState(ImDrawData* draw_data, id commandBuffer, + id commandEncoder, id renderPipelineState, + MetalBuffer* vertexBuffer, size_t vertexBufferOffset) +{ + IM_UNUSED(commandBuffer); + ImGui_ImplMetal_Data* bd = ImGui_ImplMetal_GetBackendData(); + [commandEncoder setCullMode:MTLCullModeNone]; + [commandEncoder setDepthStencilState:bd->SharedMetalContext.depthStencilState]; + + // Setup viewport, orthographic projection matrix + // Our visible imgui space lies from draw_data->DisplayPos (top left) to + // draw_data->DisplayPos+data_data->DisplaySize (bottom right). DisplayMin is typically (0,0) for single viewport apps. + MTLViewport viewport = + { + .originX = 0.0, + .originY = 0.0, + .width = (double)(draw_data->DisplaySize.x * draw_data->FramebufferScale.x), + .height = (double)(draw_data->DisplaySize.y * draw_data->FramebufferScale.y), + .znear = 0.0, + .zfar = 1.0 + }; + [commandEncoder setViewport:viewport]; + + float L = draw_data->DisplayPos.x; + float R = draw_data->DisplayPos.x + draw_data->DisplaySize.x; + float T = draw_data->DisplayPos.y; + float B = draw_data->DisplayPos.y + draw_data->DisplaySize.y; + float N = (float)viewport.znear; + float F = (float)viewport.zfar; + 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]; + + [commandEncoder setRenderPipelineState:renderPipelineState]; + [commandEncoder setFragmentSamplerState:bd->SharedMetalContext.samplerStateLinear atIndex:0]; + + [commandEncoder setVertexBuffer:vertexBuffer.buffer offset:vertexBufferOffset atIndex:0]; +} + +// Metal Render function. +void ImGui_ImplMetal_RenderDrawData(ImDrawData* draw_data, id commandBuffer, id commandEncoder) +{ + ImGui_ImplMetal_Data* bd = ImGui_ImplMetal_GetBackendData(); + MetalContext* ctx = bd->SharedMetalContext; + + // Avoid rendering when minimized, scale coordinates for retina displays (screen coordinates != framebuffer coordinates) + int fb_width = (int)(draw_data->DisplaySize.x * draw_data->FramebufferScale.x); + int fb_height = (int)(draw_data->DisplaySize.y * draw_data->FramebufferScale.y); + if (fb_width <= 0 || fb_height <= 0 || draw_data->CmdLists.Size == 0) + return; + + // Catch up with texture updates. Most of the times, the list will have 1 element with an OK status, aka nothing to do. + // (This almost always points to ImGui::GetPlatformIO().Textures[] but is part of ImDrawData to allow overriding or disabling texture updates). + if (draw_data->Textures != nullptr) + for (ImTextureData* tex : *draw_data->Textures) + if (tex->Status != ImTextureStatus_OK) + ImGui_ImplMetal_UpdateTexture(tex); + + // Try to retrieve a render pipeline state that is compatible with the framebuffer config for this frame + // The hit rate for this cache should be very near 100%. + id renderPipelineState = ctx.renderPipelineStateCache[ctx.framebufferDescriptor]; + if (renderPipelineState == nil) + { + // No luck; make a new render pipeline state + renderPipelineState = [ctx renderPipelineStateForFramebufferDescriptor:ctx.framebufferDescriptor device:commandBuffer.device]; + + // Cache render pipeline state for later reuse + ctx.renderPipelineStateCache[ctx.framebufferDescriptor] = renderPipelineState; + } + + size_t vertexBufferLength = (size_t)draw_data->TotalVtxCount * sizeof(ImDrawVert); + size_t indexBufferLength = (size_t)draw_data->TotalIdxCount * sizeof(ImDrawIdx); + MetalBuffer* vertexBuffer = [ctx dequeueReusableBufferOfLength:vertexBufferLength device:commandBuffer.device]; + MetalBuffer* indexBuffer = [ctx dequeueReusableBufferOfLength:indexBufferLength device:commandBuffer.device]; + + bd->RenderCommandEncoder = commandEncoder; + ImGui_ImplMetal_SetupRenderState(draw_data, commandBuffer, commandEncoder, renderPipelineState, vertexBuffer, 0); + + // Will project scissor/clipping rectangles into framebuffer space + ImVec2 clip_off = draw_data->DisplayPos; // (0,0) unless using multi-viewports + ImVec2 clip_scale = draw_data->FramebufferScale; // (1,1) unless using retina display which are often (2,2) + + // Render command lists + size_t vertexBufferOffset = 0; + size_t indexBufferOffset = 0; + for (const ImDrawList* draw_list : draw_data->CmdLists) + { + memcpy((char*)vertexBuffer.buffer.contents + vertexBufferOffset, draw_list->VtxBuffer.Data, (size_t)draw_list->VtxBuffer.Size * sizeof(ImDrawVert)); + memcpy((char*)indexBuffer.buffer.contents + indexBufferOffset, draw_list->IdxBuffer.Data, (size_t)draw_list->IdxBuffer.Size * sizeof(ImDrawIdx)); + + for (int cmd_i = 0; cmd_i < draw_list->CmdBuffer.Size; cmd_i++) + { + const ImDrawCmd* pcmd = &draw_list->CmdBuffer[cmd_i]; + if (pcmd->UserCallback) + { + // User callback, registered via ImDrawList::AddCallback() + if (pcmd->UserCallback == ImDrawCallback_ResetRenderState) + ImGui_ImplMetal_SetupRenderState(draw_data, commandBuffer, commandEncoder, renderPipelineState, vertexBuffer, vertexBufferOffset); + else + pcmd->UserCallback(draw_list, pcmd); + } + else + { + // Project scissor/clipping rectangles into framebuffer space + ImVec2 clip_min((pcmd->ClipRect.x - clip_off.x) * clip_scale.x, (pcmd->ClipRect.y - clip_off.y) * clip_scale.y); + ImVec2 clip_max((pcmd->ClipRect.z - clip_off.x) * clip_scale.x, (pcmd->ClipRect.w - clip_off.y) * clip_scale.y); + + // Clamp to viewport as setScissorRect() won't accept values that are off bounds + if (clip_min.x < 0.0f) { clip_min.x = 0.0f; } + if (clip_min.y < 0.0f) { clip_min.y = 0.0f; } + if (clip_max.x > (float)fb_width) { clip_max.x = (float)fb_width; } + if (clip_max.y > (float)fb_height) { clip_max.y = (float)fb_height; } + if (clip_max.x <= clip_min.x || clip_max.y <= clip_min.y) + continue; + if (pcmd->ElemCount == 0) // drawIndexedPrimitives() validation doesn't accept this + continue; + + // Apply scissor/clipping rectangle + MTLScissorRect scissorRect = + { + .x = NSUInteger(clip_min.x), + .y = NSUInteger(clip_min.y), + .width = NSUInteger(clip_max.x - clip_min.x), + .height = NSUInteger(clip_max.y - clip_min.y) + }; + [commandEncoder setScissorRect:scissorRect]; + + // Bind texture, Draw + ImTextureID tex_id = pcmd->GetTexID(); + if (tex_id != ImTextureID_Invalid) + [commandEncoder setFragmentTexture:(__bridge id)(void*)(intptr_t)(tex_id) atIndex:0]; + + [commandEncoder setVertexBufferOffset:(vertexBufferOffset + pcmd->VtxOffset * sizeof(ImDrawVert)) atIndex:0]; + [commandEncoder drawIndexedPrimitives:MTLPrimitiveTypeTriangle + indexCount:pcmd->ElemCount + indexType:sizeof(ImDrawIdx) == 2 ? MTLIndexTypeUInt16 : MTLIndexTypeUInt32 + indexBuffer:indexBuffer.buffer + indexBufferOffset:indexBufferOffset + pcmd->IdxOffset * sizeof(ImDrawIdx)]; + } + } + + vertexBufferOffset += (size_t)draw_list->VtxBuffer.Size * sizeof(ImDrawVert); + indexBufferOffset += (size_t)draw_list->IdxBuffer.Size * sizeof(ImDrawIdx); + } + + MetalContext* sharedMetalContext = bd->SharedMetalContext; + [commandBuffer addCompletedHandler:^(id) + { + @synchronized(sharedMetalContext.bufferCacheLock) + { + [sharedMetalContext.bufferCache addObject:vertexBuffer]; + [sharedMetalContext.bufferCache addObject:indexBuffer]; + } + }]; + bd->RenderCommandEncoder = nil; +} + +static void ImGui_ImplMetal_DestroyTexture(ImTextureData* tex) +{ + if (MetalTexture* backend_tex = (__bridge_transfer MetalTexture*)(tex->BackendUserData)) + { + IM_ASSERT(backend_tex.metalTexture == (__bridge id)(void*)(intptr_t)tex->TexID); + backend_tex.metalTexture = nil; + + // Clear identifiers and mark as destroyed (in order to allow e.g. calling InvalidateDeviceObjects while running) + tex->SetTexID(ImTextureID_Invalid); + tex->BackendUserData = nullptr; + } + tex->SetStatus(ImTextureStatus_Destroyed); +} + +void ImGui_ImplMetal_UpdateTexture(ImTextureData* tex) +{ + ImGui_ImplMetal_Data* bd = ImGui_ImplMetal_GetBackendData(); + if (tex->Status == ImTextureStatus_WantCreate) + { + // Create and upload new texture to graphics system + //IMGUI_DEBUG_LOG("UpdateTexture #%03d: WantCreate %dx%d\n", tex->UniqueID, tex->Width, tex->Height); + IM_ASSERT(tex->TexID == ImTextureID_Invalid && tex->BackendUserData == nullptr); + IM_ASSERT(tex->Format == ImTextureFormat_RGBA32); + + // 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. + MTLTextureDescriptor* textureDescriptor = [MTLTextureDescriptor texture2DDescriptorWithPixelFormat:MTLPixelFormatRGBA8Unorm + width:(NSUInteger)tex->Width + height:(NSUInteger)tex->Height + mipmapped:NO]; + textureDescriptor.usage = MTLTextureUsageShaderRead; + #if TARGET_OS_OSX || TARGET_OS_MACCATALYST + textureDescriptor.storageMode = MTLStorageModeManaged; + #else + textureDescriptor.storageMode = MTLStorageModeShared; + #endif + id texture = [bd->SharedMetalContext.device newTextureWithDescriptor:textureDescriptor]; + [texture replaceRegion:MTLRegionMake2D(0, 0, (NSUInteger)tex->Width, (NSUInteger)tex->Height) mipmapLevel:0 withBytes:tex->Pixels bytesPerRow:(NSUInteger)tex->Width * 4]; + MetalTexture* backend_tex = [[MetalTexture alloc] initWithTexture:texture]; + + // Store identifiers + tex->SetTexID((ImTextureID)(intptr_t)texture); + tex->SetStatus(ImTextureStatus_OK); + tex->BackendUserData = (__bridge_retained void*)(backend_tex); + } + else if (tex->Status == ImTextureStatus_WantUpdates) + { + // Update selected blocks. We only ever write to textures regions which have never been used before! + // This backend choose to use tex->Updates[] but you can use tex->UpdateRect to upload a single region. + MetalTexture* backend_tex = (__bridge MetalTexture*)(tex->BackendUserData); + for (ImTextureRect& r : tex->Updates) + { + [backend_tex.metalTexture replaceRegion:MTLRegionMake2D((NSUInteger)r.x, (NSUInteger)r.y, (NSUInteger)r.w, (NSUInteger)r.h) + mipmapLevel:0 + withBytes:tex->GetPixelsAt(r.x, r.y) + bytesPerRow:(NSUInteger)tex->Width * 4]; + } + tex->SetStatus(ImTextureStatus_OK); + } + else if (tex->Status == ImTextureStatus_WantDestroy && tex->UnusedFrames > 0) + { + ImGui_ImplMetal_DestroyTexture(tex); + } +} + +bool ImGui_ImplMetal_CreateDeviceObjects(id device) +{ + ImGui_ImplMetal_Data* bd = ImGui_ImplMetal_GetBackendData(); + MTLDepthStencilDescriptor* depthStencilDescriptor = [[MTLDepthStencilDescriptor alloc] init]; + depthStencilDescriptor.depthWriteEnabled = NO; + depthStencilDescriptor.depthCompareFunction = MTLCompareFunctionAlways; + bd->SharedMetalContext.depthStencilState = [device newDepthStencilStateWithDescriptor:depthStencilDescriptor]; + MTLSamplerDescriptor* samplerDescriptor = [[MTLSamplerDescriptor alloc] init]; + samplerDescriptor.minFilter = MTLSamplerMinMagFilterLinear; + samplerDescriptor.magFilter = MTLSamplerMinMagFilterLinear; + samplerDescriptor.mipFilter = MTLSamplerMipFilterLinear; + bd->SharedMetalContext.samplerStateLinear = [device newSamplerStateWithDescriptor:samplerDescriptor]; + samplerDescriptor.minFilter = MTLSamplerMinMagFilterNearest; + samplerDescriptor.magFilter = MTLSamplerMinMagFilterNearest; + samplerDescriptor.mipFilter = MTLSamplerMipFilterNearest; + bd->SharedMetalContext.samplerStateNearest = [device newSamplerStateWithDescriptor:samplerDescriptor]; +#ifdef IMGUI_IMPL_METAL_CPP + [samplerDescriptor release]; + [depthStencilDescriptor release]; +#endif + + return true; +} + +void ImGui_ImplMetal_DestroyDeviceObjects() +{ + ImGui_ImplMetal_Data* bd = ImGui_ImplMetal_GetBackendData(); + + // Destroy all textures + for (ImTextureData* tex : ImGui::GetPlatformIO().Textures) + if (tex->RefCount == 1) + ImGui_ImplMetal_DestroyTexture(tex); + + [bd->SharedMetalContext.renderPipelineStateCache removeAllObjects]; + bd->SharedMetalContext.samplerStateLinear = nil; + bd->SharedMetalContext.samplerStateNearest = nil; +} + +bool ImGui_ImplMetal_Init(id device) +{ + ImGuiIO& io = ImGui::GetIO(); + IMGUI_CHECKVERSION(); + IM_ASSERT(io.BackendRendererUserData == nullptr && "Already initialized a renderer backend!"); + + ImGui_ImplMetal_Data* bd = IM_NEW(ImGui_ImplMetal_Data)(); + io.BackendRendererUserData = (void*)bd; + io.BackendRendererName = "imgui_impl_metal"; + io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset; // We can honor the ImDrawCmd::VtxOffset field, allowing for large meshes. + io.BackendFlags |= ImGuiBackendFlags_RendererHasTextures; // We can honor ImGuiPlatformIO::Textures[] requests during render. + + bd->SharedMetalContext = [[MetalContext alloc] init]; + bd->SharedMetalContext.device = device; + + return true; +} + +void ImGui_ImplMetal_Shutdown() +{ + ImGui_ImplMetal_Data* bd = ImGui_ImplMetal_GetBackendData(); + IM_UNUSED(bd); + IM_ASSERT(bd != nullptr && "No renderer backend to shutdown, or already shutdown?"); + ImGuiIO& io = ImGui::GetIO(); + ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO(); + + ImGui_ImplMetal_DestroyDeviceObjects(); + ImGui_ImplMetal_DestroyBackendData(); + + io.BackendRendererName = nullptr; + io.BackendRendererUserData = nullptr; + io.BackendFlags &= ~(ImGuiBackendFlags_RendererHasVtxOffset | ImGuiBackendFlags_RendererHasTextures); + platform_io.ClearRendererHandlers(); +} + +#pragma mark - MetalBuffer implementation + +@implementation MetalBuffer +- (instancetype)initWithBuffer:(id)buffer +{ + if ((self = [super init])) + { + _buffer = buffer; + _lastReuseTime = GetMachAbsoluteTimeInSeconds(); + } + return self; +} +@end + +#pragma mark - FramebufferDescriptor implementation + +@implementation FramebufferDescriptor +- (instancetype)initWithRenderPassDescriptor:(MTLRenderPassDescriptor*)renderPassDescriptor +{ + if ((self = [super init])) + { + _sampleCount = renderPassDescriptor.colorAttachments[0].texture.sampleCount; + _colorPixelFormat = renderPassDescriptor.colorAttachments[0].texture.pixelFormat; + _depthPixelFormat = renderPassDescriptor.depthAttachment.texture.pixelFormat; + _stencilPixelFormat = renderPassDescriptor.stencilAttachment.texture.pixelFormat; + } + return self; +} + +- (nonnull id)copyWithZone:(nullable NSZone*)zone +{ + FramebufferDescriptor* copy = [[FramebufferDescriptor allocWithZone:zone] init]; + copy.sampleCount = self.sampleCount; + copy.colorPixelFormat = self.colorPixelFormat; + copy.depthPixelFormat = self.depthPixelFormat; + copy.stencilPixelFormat = self.stencilPixelFormat; + return copy; +} + +- (NSUInteger)hash +{ + 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; +} + +- (BOOL)isEqual:(id)object +{ + FramebufferDescriptor* other = object; + if (![other isKindOfClass:[FramebufferDescriptor class]]) + return NO; + return other.sampleCount == self.sampleCount && + other.colorPixelFormat == self.colorPixelFormat && + other.depthPixelFormat == self.depthPixelFormat && + other.stencilPixelFormat == self.stencilPixelFormat; +} + +@end + +#pragma mark - MetalTexture implementation + +@implementation MetalTexture +- (instancetype)initWithTexture:(id)metalTexture +{ + if ((self = [super init])) + self.metalTexture = metalTexture; + return self; +} + +@end + +#pragma mark - MetalContext implementation + +@implementation MetalContext +- (instancetype)init +{ + if ((self = [super init])) + { + self.renderPipelineStateCache = [NSMutableDictionary dictionary]; + self.bufferCache = [NSMutableArray array]; + self.bufferCacheLock = [[NSObject alloc] init]; + _lastBufferCachePurge = GetMachAbsoluteTimeInSeconds(); + } + return self; +} + +- (MetalBuffer*)dequeueReusableBufferOfLength:(NSUInteger)length device:(id)device +{ + double now = GetMachAbsoluteTimeInSeconds(); + + @synchronized(self.bufferCacheLock) + { + // Purge old buffers that haven't been useful for a while + if (now - self.lastBufferCachePurge > 1.0) + { + NSMutableArray* survivors = [NSMutableArray array]; + for (MetalBuffer* candidate in self.bufferCache) + if (candidate.lastReuseTime > self.lastBufferCachePurge) + [survivors addObject:candidate]; + self.bufferCache = [survivors mutableCopy]; + self.lastBufferCachePurge = now; + } + + // See if we have a buffer we can reuse + MetalBuffer* bestCandidate = nil; + for (MetalBuffer* candidate in self.bufferCache) + if (candidate.buffer.length >= length && (bestCandidate == nil || bestCandidate.lastReuseTime > candidate.lastReuseTime)) + bestCandidate = candidate; + + if (bestCandidate != nil) + { + [self.bufferCache removeObject:bestCandidate]; + bestCandidate.lastReuseTime = now; + return bestCandidate; + } + } + + // No luck; make a new buffer + id backing = [device newBufferWithLength:length options:MTLResourceStorageModeShared]; + return [[MetalBuffer alloc] initWithBuffer:backing]; +} + +// Bilinear sampling is required by default. Set 'io.Fonts->Flags |= ImFontAtlasFlags_NoBakedLines' or 'style.AntiAliasedLinesUseTex = false' to allow point/nearest sampling. +- (id)renderPipelineStateForFramebufferDescriptor:(FramebufferDescriptor*)descriptor device:(id)device +{ + NSError* error = nil; + + NSString* shaderSource = @"" + "#include \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 texture [[texture(0)]],\n" + " sampler textureSampler [[sampler(0)]]) {\n" + " half4 texColor = texture.sample(textureSampler, in.texCoords);\n" + " return half4(in.color) * texColor;\n" + "}\n"; + + id library = [device newLibraryWithSource:shaderSource options:nil error:&error]; + if (library == nil) + { + NSLog(@"Error: failed to create Metal library: %@", error); + return nil; + } + + id vertexFunction = [library newFunctionWithName:@"vertex_main"]; + id fragmentFunction = [library newFunctionWithName:@"fragment_main"]; + + if (vertexFunction == nil || fragmentFunction == nil) + { + NSLog(@"Error: failed to find Metal shader functions in library: %@", error); + return nil; + } + + MTLVertexDescriptor* vertexDescriptor = [MTLVertexDescriptor vertexDescriptor]; + vertexDescriptor.attributes[0].offset = offsetof(ImDrawVert, pos); + vertexDescriptor.attributes[0].format = MTLVertexFormatFloat2; // position + vertexDescriptor.attributes[0].bufferIndex = 0; + vertexDescriptor.attributes[1].offset = offsetof(ImDrawVert, uv); + vertexDescriptor.attributes[1].format = MTLVertexFormatFloat2; // texCoords + vertexDescriptor.attributes[1].bufferIndex = 0; + vertexDescriptor.attributes[2].offset = 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); + + MTLRenderPipelineDescriptor* pipelineDescriptor = [[MTLRenderPipelineDescriptor alloc] init]; + pipelineDescriptor.vertexFunction = vertexFunction; + pipelineDescriptor.fragmentFunction = fragmentFunction; + pipelineDescriptor.vertexDescriptor = vertexDescriptor; + pipelineDescriptor.rasterSampleCount = 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; + pipelineDescriptor.colorAttachments[0].alphaBlendOperation = MTLBlendOperationAdd; + pipelineDescriptor.colorAttachments[0].sourceAlphaBlendFactor = MTLBlendFactorOne; + pipelineDescriptor.colorAttachments[0].destinationAlphaBlendFactor = MTLBlendFactorOneMinusSourceAlpha; + pipelineDescriptor.depthAttachmentPixelFormat = self.framebufferDescriptor.depthPixelFormat; + pipelineDescriptor.stencilAttachmentPixelFormat = self.framebufferDescriptor.stencilPixelFormat; + + id renderPipelineState = [device newRenderPipelineStateWithDescriptor:pipelineDescriptor error:&error]; + if (error != nil) + NSLog(@"Error: failed to create Metal pipeline state: %@", error); + + return renderPipelineState; +} + +@end + +//----------------------------------------------------------------------------- + +#endif // #ifndef IMGUI_DISABLE diff --git a/core/hw/pvr/Renderer_if.cpp b/core/hw/pvr/Renderer_if.cpp index 69660e3465..1d3a3185ac 100644 --- a/core/hw/pvr/Renderer_if.cpp +++ b/core/hw/pvr/Renderer_if.cpp @@ -417,6 +417,8 @@ Renderer* rend_OITVulkan(); Renderer* rend_DirectX9(); Renderer* rend_DirectX11(); Renderer* rend_OITDirectX11(); +Renderer* rend_Metal(); +Renderer* rend_OITMetal(); static void rend_create_renderer() { @@ -456,6 +458,14 @@ static void rend_create_renderer() case RenderType::DirectX11_OIT: renderer = rend_OITDirectX11(); break; +#endif +#ifdef USE_METAL + case RenderType::Metal: + renderer = rend_Metal(); + break; + case RenderType::Metal_OIT: + renderer = rend_OITMetal(); + break; #endif } #endif diff --git a/core/hw/pvr/ta_vtx.cpp b/core/hw/pvr/ta_vtx.cpp index de08e0a440..b5140214b6 100644 --- a/core/hw/pvr/ta_vtx.cpp +++ b/core/hw/pvr/ta_vtx.cpp @@ -1195,7 +1195,8 @@ static void parseRenderPass(RenderPass& pass, const RenderPass& previousPass, re { const bool perPixel = config::RendererType == RenderType::OpenGL_OIT || config::RendererType == RenderType::DirectX11_OIT - || config::RendererType == RenderType::Vulkan_OIT; + || config::RendererType == RenderType::Vulkan_OIT + || config::RendererType == RenderType::Metal_OIT; const bool mergeTranslucent = config::PerStripSorting || perPixel; if (config::RenderResolution > 480 && !config::EmulateFramebuffer && config::FixUpscaleBleedingEdge) diff --git a/core/rend/CMakeLists.txt b/core/rend/CMakeLists.txt index 122b06704c..6a810f5cc2 100644 --- a/core/rend/CMakeLists.txt +++ b/core/rend/CMakeLists.txt @@ -33,6 +33,10 @@ if(USE_VULKAN) add_subdirectory(vulkan) endif() +if(USE_METAL) + add_subdirectory(metal) +endif() + if(WIN32 AND USE_DX9 AND NOT LIBRETRO AND NOT WINDOWS_STORE AND ("x86" IN_LIST ARCHITECTURE OR "x86_64" IN_LIST ARCHITECTURE)) add_subdirectory(dx9) endif() diff --git a/core/rend/custom_texture/CustomTextureTypes.h b/core/rend/custom_texture/CustomTextureTypes.h index a0f1f8a76e..2754aa46c5 100644 --- a/core/rend/custom_texture/CustomTextureTypes.h +++ b/core/rend/custom_texture/CustomTextureTypes.h @@ -78,6 +78,7 @@ enum class CustomTextureBackend : uint8_t Direct3D9, OpenGL, OpenGLES, + Metal, }; struct CustomTextureCandidate diff --git a/core/rend/metal/CMakeLists.txt b/core/rend/metal/CMakeLists.txt new file mode 100644 index 0000000000..901b0142a2 --- /dev/null +++ b/core/rend/metal/CMakeLists.txt @@ -0,0 +1,41 @@ +target_compile_definitions(${PROJECT_NAME} PRIVATE USE_METAL) + +set(METAL_SOURCES + metal.h + metal_buffer.h + metal_buffer.mm + metal_commandpool.h + metal_commandpool.mm + metal_context.h + metal_context.mm + metal_drawer.h + metal_drawer.mm + metal_driver.h + metal_overlay.h + metal_overlay.mm + metal_pipeline.h + metal_pipeline.mm + metal_quad.h + metal_quad.mm + metal_renderer.h + metal_renderer.mm + metal_shaders.h + metal_shaders.mm + metal_texture.h + metal_texture.mm + oit/metal_oit_buffer.h + oit/metal_oit_drawer.h + oit/metal_oit_drawer.mm + oit/metal_oit_pipeline.h + oit/metal_oit_shaders.h + "${IMGUI_BACKENDS_DIR}/imgui_impl_metal.h" + "${IMGUI_BACKENDS_DIR}/imgui_impl_metal.mm") +target_sources(${PROJECT_NAME} PRIVATE ${METAL_SOURCES}) + +# The Metal renderer and the imgui Metal backend rely on ARC +set_source_files_properties(${METAL_SOURCES} TARGET_DIRECTORY ${PROJECT_NAME} + PROPERTIES COMPILE_OPTIONS "-fobjc-arc") + +find_library(METAL_FRAMEWORK Metal REQUIRED) +find_library(QUARTZCORE_FRAMEWORK QuartzCore REQUIRED) +target_link_libraries(${PROJECT_NAME} PRIVATE ${METAL_FRAMEWORK} ${QUARTZCORE_FRAMEWORK}) diff --git a/core/rend/metal/metal.h b/core/rend/metal/metal.h new file mode 100644 index 0000000000..bf3e74bc4d --- /dev/null +++ b/core/rend/metal/metal.h @@ -0,0 +1,53 @@ +/* + Copyright 2025 flyinghead + + This file is part of Flycast. + + Flycast is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 2 of the License, or + (at your option) any later version. + + Flycast is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with Flycast. If not, see . +*/ + +#pragma once +#include "metal_apple.h" + +#include "types.h" + +class MetalDeletable +{ +public: + virtual ~MetalDeletable() = default; +}; + +class MetalFlightManager +{ +public: + virtual void addToFlight(MetalDeletable *object) = 0; + + virtual ~MetalFlightManager() = default; +}; + +template +class MetalDeleter : public MetalDeletable +{ +public: + MetalDeleter() = delete; + explicit MetalDeleter(T& o) : o(o) {} + MetalDeleter(T&& o) : o(std::move(o)) {} + ~MetalDeleter() override { + if constexpr (std::is_pointer_v) + delete o; + } + +private: + T o; +}; \ No newline at end of file diff --git a/core/rend/metal/metal_apple.h b/core/rend/metal/metal_apple.h new file mode 100644 index 0000000000..0b7cb9ac34 --- /dev/null +++ b/core/rend/metal/metal_apple.h @@ -0,0 +1,29 @@ +/* + This file is part of Flycast. + + Flycast is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 2 of the License, or + (at your option) any later version. + + Flycast is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with Flycast. If not, see . +*/ +#pragma once + +// Apple's MacTypes.h and QuickDraw headers declare global Rect and RGBColor types, +// which clash with flycast's own Rect (hw/pvr/ta_ctx.h) and RGBColor (hw/pvr/pvr_regs.h). +// Import the Apple frameworks with these names renamed. This header must be included +// before any other Apple framework header. +#define Rect AppleRect +#define RGBColor AppleRGBColor +#import +#import +#import +#undef Rect +#undef RGBColor diff --git a/core/rend/metal/metal_buffer.h b/core/rend/metal/metal_buffer.h new file mode 100644 index 0000000000..5fd8f806b4 --- /dev/null +++ b/core/rend/metal/metal_buffer.h @@ -0,0 +1,132 @@ +/* + Copyright 2025 flyinghead + + This file is part of Flycast. + + Flycast is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 2 of the License, or + (at your option) any later version. + + Flycast is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with Flycast. If not, see . +*/ + +#pragma once +#include "metal_apple.h" +#include "types.h" +#include +#include +#include + +// Minimum alignment for an offset bound to a `constant` buffer argument. Mac-family +// GPUs require 256-byte alignment; Apple-family GPUs only need 16. Binding a constant +// buffer at a misaligned offset is a Metal validation error and silently reads the +// wrong uniforms without validation. macOS (including Apple silicon) uses the Mac rule. +#if TARGET_OS_OSX || TARGET_OS_SIMULATOR +static constexpr u32 kConstantBufferAlign = 256; +#else +static constexpr u32 kConstantBufferAlign = 16; +#endif + +struct MetalBufferData +{ + MetalBufferData(u64 size); + ~MetalBufferData() + { + buffer = nil; + } + + void upload(u32 size, const void *data, u32 bufOffset = 0) const + { + verify(bufOffset + size <= bufferSize); + + void* dataPtr = (u8 *)[buffer contents] + bufOffset; + memcpy(dataPtr, data, size); + } + + void upload(size_t count, const u32 *sizes, const void * const *data, u32 bufOffset = 0) const + { + u32 totalSize = 0; + for (size_t i = 0; i < count; ++i) + totalSize += sizes[i]; + verify(bufOffset + totalSize <= bufferSize); + void* dataPtr = (u8 *)[buffer contents] + bufOffset; + for (size_t i = 0; i < count; ++i) + { + if (data[i] != nullptr) + memcpy(dataPtr, data[i], sizes[i]); + dataPtr = (u8 *)dataPtr + sizes[i]; + } + } + + void download(u32 size, void *data, u32 bufOffset = 0) const + { + verify(bufOffset + size <= bufferSize); + + void* dataPtr = (u8 *)[buffer contents] + bufOffset; + memcpy(data, dataPtr, size); + } + + id buffer; + u64 bufferSize; +}; + +class MetalBufferPacker +{ +public: + MetalBufferPacker(); + + u64 addUniform(const void *p, size_t size) { + // Constant buffers need 256-byte offset alignment on the Simulator. + return add(p, size, kConstantBufferAlign); + } + + u64 addStorage(const void *p, size_t size) { + return add(p, size, kConstantBufferAlign); + } + + u64 add(const void *p, size_t size, u32 alignment = 16) + { + u32 padding = align(offset, alignment); + if (padding != 0) + { + chunks.push_back(nullptr); + chunkSizes.push_back(padding); + offset += padding; + } + u64 start = offset; + chunks.push_back(p); + verify(size <= (size_t)std::numeric_limits::max()); + chunkSizes.push_back((u32)size); + offset += size; + + return start; + } + + void upload(MetalBufferData& bufferData, u32 bufOffset = 0) + { + if (!chunks.empty()) + bufferData.upload(chunks.size(), &chunkSizes[0], &chunks[0], bufOffset); + } + + u64 size() const { + return offset; + } + + static inline u32 align(u64 offset, u32 alignment) + { + u32 pad = (u32)(offset & (alignment - 1)); + return pad == 0 ? 0 : alignment - pad; + } + +private: + std::vector chunks; + std::vector chunkSizes; + u64 offset = 0; +}; diff --git a/core/rend/metal/metal_buffer.mm b/core/rend/metal/metal_buffer.mm new file mode 100644 index 0000000000..fc5a17de42 --- /dev/null +++ b/core/rend/metal/metal_buffer.mm @@ -0,0 +1,34 @@ +/* + Copyright 2025 flyinghead + + This file is part of Flycast. + + Flycast is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 2 of the License, or + (at your option) any later version. + + Flycast is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with Flycast. If not, see . +*/ + +#include "metal_buffer.h" +#include "metal_context.h" + +MetalBufferData::MetalBufferData(u64 size) : bufferSize(size) { + auto device = MetalContext::Instance()->GetDevice(); + MTLResourceOptions opts = MTLResourceStorageModeShared; +#if TARGET_OS_IPHONE || TARGET_OS_TV + // Prefer write-combined for CPU->GPU streams + opts |= MTLResourceCPUCacheModeWriteCombined; +#endif + buffer = [device newBufferWithLength:size options:opts]; + [buffer setLabel:@"Flycast Shared Buffer"]; +} + +MetalBufferPacker::MetalBufferPacker() {} diff --git a/core/rend/metal/metal_commandpool.h b/core/rend/metal/metal_commandpool.h new file mode 100644 index 0000000000..ffcb36c380 --- /dev/null +++ b/core/rend/metal/metal_commandpool.h @@ -0,0 +1,77 @@ +/* + Copyright 2025 flyinghead + + This file is part of Flycast. + + Flycast is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 2 of the License, or + (at your option) any later version. + + Flycast is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with Flycast. If not, see . +*/ + +#pragma once +#include "metal_apple.h" +#include "metal.h" + +#include + +class MetalCommandPool : public MetalFlightManager +{ +public: + void Init(size_t chainSize = 3); + void Term(); + void BeginFrame(); + void EndFrame(); + void EndFrameAndWait(); + // Block until the GPU has finished the command buffer committed by the + // most recent EndFrame() (i.e. the one signalled into events[index]). + // Unlike EndFrameAndWait() this does NOT call EndFrame() itself — the + // caller must have already ended the frame. Used by the threaded-render + // screen path to guarantee GPU completion before signalling RENDER_DONE. + void WaitForLastFrame(); + id Allocate(); + + int GetIndex() const { + return index; + } + + void addToFlight(MetalDeletable *object) override { + inFlightObjects[index].emplace_back(object); + } + +private: + // A frame slot whose bounded GPU-completion wait timed out. Its deletables + // must NOT be destroyed yet: their destructors recycle host buffers the + // still-executing command buffer may read — GPU-side undefined behaviour + // on top of the stall that caused the timeout. They are held here, keyed + // on the command buffer, and freed once MTLCommandBuffer.status reports + // Completed/Error. + struct QuarantinedFrame + { + id buffer; + std::vector> objects; + }; + static bool gpuDone(id buffer); + void quarantineSlot(int slot, const char *where); + void sweepQuarantine(); + // Poll `buffer` until gpuDone() or timeoutMs elapsed; true if done. + static bool waitGpuDone(id buffer, uint32_t timeoutMs); + + int index = 0; + std::vector> inFlightBuffers; + std::vector> events; + size_t chainSize; + std::vector>> inFlightObjects; + std::vector quarantine; + bool frameStarted = false; + id queue = nil; + id device = nil; +}; diff --git a/core/rend/metal/metal_commandpool.mm b/core/rend/metal/metal_commandpool.mm new file mode 100644 index 0000000000..90b1721741 --- /dev/null +++ b/core/rend/metal/metal_commandpool.mm @@ -0,0 +1,276 @@ +/* + Copyright 2025 flyinghead + + This file is part of Flycast. + + Flycast is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 2 of the License, or + (at your option) any later version. + + Flycast is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with Flycast. If not, see . +*/ + +#include "metal_commandpool.h" +#include "metal_context.h" +#include "log/Log.h" +#include +#include +#include + +namespace { +std::atomic s_gpuWaitTimeouts{0}; +std::atomic s_phantomEvents{0}; +// Frame slots parked in the quarantine (see QuarantinedFrame) because their +// GPU work had not finished when the slot was recycled; and the objects that +// had to be leaked at Term() because the GPU never finished with them. +std::atomic s_quarantinedFrames{0}; +std::atomic s_leakedAtTerm{0}; + +void logGpuWaitTimeout(const char *where) +{ + const uint64_t n = ++s_gpuWaitTimeouts; + if (n == 1 || (n % 60) == 0) + WARN_LOG(RENDERER, "GPU-completion wait timed out (200ms) at %s, count=%llu", + where, (unsigned long long)n); +} + +// The Metal context doesn't start before macOS 12 (see MetalContext::init) +bool waitForEvent(id event, uint64_t timeoutMs) +{ + if (@available(macOS 12.0, iOS 15.0, tvOS 15.0, *)) + return [event waitUntilSignaledValue:1 timeoutMS:timeoutMs]; + return true; +} + +void logPhantomEvent() +{ + const uint64_t n = ++s_phantomEvents; + if (n == 1 || (n % 60) == 0) + DEBUG_LOG(RENDERER, "EndFrame: no command buffer this frame, count=%llu", + (unsigned long long)n); +} +} + +void MetalCommandPool::Init(size_t chainSize) +{ + this->chainSize = chainSize; + device = MetalContext::Instance()->GetDevice(); + + // Commit rendering and presentation on one queue, including after bounded waits. + queue = MetalContext::Instance()->GetQueue(); + + DEBUG_LOG(RENDERER, "MetalCommandPool::Init chainSize=%zu", chainSize); + if (events.size() > chainSize) + { + events.resize(chainSize); + } + else + { + while (events.size() < chainSize) + { + events.push_back(nil); + } + } + + inFlightBuffers.resize(chainSize); + inFlightObjects.resize(chainSize); +} + +bool MetalCommandPool::gpuDone(id buffer) +{ + // Completed OR Error: either way the GPU is finished with the resources. + // An errored buffer never signals its shared event, which is why the + // event alone is not a safe completion test (Term() used to hang on it). + return buffer == nil || buffer.status >= MTLCommandBufferStatusCompleted; +} + +bool MetalCommandPool::waitGpuDone(id buffer, uint32_t timeoutMs) +{ + const auto deadline = std::chrono::steady_clock::now() + std::chrono::milliseconds(timeoutMs); + while (!gpuDone(buffer)) + { + if (std::chrono::steady_clock::now() >= deadline) + return false; + std::this_thread::sleep_for(std::chrono::microseconds(500)); + } + return true; +} + +void MetalCommandPool::quarantineSlot(int slot, const char *where) +{ + if (inFlightBuffers[slot] == nil || inFlightObjects[slot].empty()) + { + // Nothing on the GPU, or nothing whose destruction could hurt it. + inFlightObjects[slot].clear(); + return; + } + const uint64_t n = ++s_quarantinedFrames; + if (n == 1 || (n % 60) == 0) + NOTICE_LOG(RENDERER, "GPU still busy at %s — %zu deletables quarantined until the command buffer completes (count=%llu, held=%zu)", + where, inFlightObjects[slot].size(), (unsigned long long)n, quarantine.size() + 1); + quarantine.push_back({inFlightBuffers[slot], std::move(inFlightObjects[slot])}); + inFlightObjects[slot].clear(); +} + +void MetalCommandPool::sweepQuarantine() +{ + // Non-blocking: free whatever the GPU has finished with since last frame. + // Runs on the render thread (the pool's owner), so the deletables' + // destructors (BufferHolder pushes back into the drawer's pool) stay on + // the thread they expect. + for (size_t i = 0; i < quarantine.size();) + { + if (gpuDone(quarantine[i].buffer)) + quarantine.erase(quarantine.begin() + i); + else + ++i; + } +} + +void MetalCommandPool::Term() +{ + // Bounded, and keyed on the command buffers rather than the events: an + // errored buffer never signals, and the old UINT64_MAX event wait ran on + // the frontend's main thread from unload. If the GPU still hasn't finished + // after the bound, the deletables are LEAKED on purpose — a few textures + // per wedged GPU is better than recycling buffers it may still read. + constexpr uint32_t kTermWaitMs = 2000; + for (size_t i = 0; i < inFlightBuffers.size(); i++) + { + if (!waitGpuDone(inFlightBuffers[i], kTermWaitMs)) + quarantineSlot((int)i, "Term"); + } + inFlightObjects.clear(); + inFlightBuffers.clear(); + events.clear(); + for (QuarantinedFrame& q : quarantine) + { + if (waitGpuDone(q.buffer, kTermWaitMs)) + continue; + s_leakedAtTerm += q.objects.size(); + WARN_LOG(RENDERER, "MetalCommandPool::Term: GPU never finished a command buffer (status=%ld) — leaking %zu deletables (total leaked=%llu)", + (long)q.buffer.status, q.objects.size(), (unsigned long long)s_leakedAtTerm.load()); + for (auto& obj : q.objects) + (void)obj.release(); + } + quarantine.clear(); + index = 0; + frameStarted = false; + queue = nil; + device = nil; +} + +void MetalCommandPool::BeginFrame() +{ + if (frameStarted) + return; + frameStarted = true; + index = (index + 1) % chainSize; + // Bounded wait (same latent deadlock class as WaitForLastFrame): a missed + // GPU-completion signal on the buffer we're about to recycle must not hang + // the render+SH4 threads forever. Healthy frames complete in <17ms so the + // 200ms timeout never fires; worst case is a dropped frame, not a hang. + sweepQuarantine(); + if (events[index] != nil) + if (!waitForEvent(events[index], 200)) + logGpuWaitTimeout("BeginFrame"); + // The timeout is only a stall if the buffer is genuinely still running; + // an errored buffer never signals but IS finished (gpuDone). Only a + // still-running buffer's deletables go to quarantine. + if (!gpuDone(inFlightBuffers[index])) + quarantineSlot(index, "BeginFrame"); + inFlightBuffers[index] = nil; + inFlightObjects[index].clear(); +} + +void MetalCommandPool::EndFrame() +{ + if (!frameStarted) + return; + frameStarted = false; + // No command buffer allocated this frame: nothing could ever signal the + // event we'd create below, so the next WaitForLastFrame/BeginFrame on this + // index would sit out the full 200ms bound. There is also nothing for a + // later wait to depend on: no GPU work was submitted for this slot. + // Leave the slot's event nil so the bounded waits skip it. + if (inFlightBuffers[index] == nil) + { + logPhantomEvent(); + events[index] = nil; + return; + } + events[index] = [device newSharedEvent]; + [inFlightBuffers[index] encodeSignalEvent:events[index] value:1]; + [inFlightBuffers[index] commit]; +} + +id MetalCommandPool::Allocate() +{ + verify(frameStarted); + if (inFlightBuffers[index] == nil) + inFlightBuffers[index] = [queue commandBuffer]; + return inFlightBuffers[index]; +} + +void MetalCommandPool::EndFrameAndWait() +{ + EndFrame(); + // Same bound as WaitForLastFrame/BeginFrame. This was the last UINT64_MAX + // wait on the frame path (render-to-texture, metal_drawer EndFrameAndWait + // callers): a missed signal here hung the render thread — and through + // renderEnd.Wait(), the SH4 thread — permanently, with no log. Healthy + // frames signal in <17ms; on a miss we log, drop the wait and continue. + // Term() keeps its unbounded wait — at teardown a hang is preferable to + // freeing objects the GPU may still touch. + bool signaled = true; + for (size_t i = 0; i < events.size(); i++) + { + if (events[i] != nil && !waitForEvent(events[i], 200)) + { + logGpuWaitTimeout("EndFrameAndWait"); + if ((int)i == index) + signaled = false; + } + } + // Callers read the frame back (getBytes) right after this; on a timeout + // that readback is torn — a dropped frame, unchanged. What must not + // happen is freeing this slot's deletables under a running buffer. + // The event is signaled once the GPU has executed every command encoded + // before it, so a signaled slot is safe to free even though the command + // buffer status only switches to Completed a little later. + if (!signaled && !gpuDone(inFlightBuffers[index])) + quarantineSlot(index, "EndFrameAndWait"); + else + inFlightObjects[index].clear(); +} + +void MetalCommandPool::WaitForLastFrame() +{ + // EndFrame() assigns events[index] and encodeSignalEvent:value:1 on the + // just-committed command buffer, then BeginFrame() bumps index on the + // next frame. So between EndFrame() and the next BeginFrame(), + // events[index] is exactly the event the most recent frame's GPU work + // signals on completion. Wait on that single event only. + // + // Deadlock-free: the signal is encoded by the GPU on a committed command + // buffer (no CPU-thread dependency), the event is non-nil here because + // EndFrame() just created it. + // + // Bounded wait: a never-arriving GPU-completion signal must not wedge the + // render thread (and through renderEnd.Wait(), the SH4 thread) forever. + // Healthy frames complete in <17ms, so the 200ms timeout never fires in + // normal operation; worst case on a missed signal is a dropped frame + // instead of a permanent hang. + if (events[index] != nil) + { + if (!waitForEvent(events[index], 200)) + logGpuWaitTimeout("WaitForLastFrame"); + } +} \ No newline at end of file diff --git a/core/rend/metal/metal_context.h b/core/rend/metal/metal_context.h new file mode 100644 index 0000000000..cfe2a3bd43 --- /dev/null +++ b/core/rend/metal/metal_context.h @@ -0,0 +1,129 @@ +/* + Copyright 2025 flyinghead + + This file is part of Flycast. + + Flycast is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 2 of the License, or + (at your option) any later version. + + Flycast is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with Flycast. If not, see . +*/ + +#pragma once +#include "metal_apple.h" +#include "metal_texture_utils.h" + +#include "types.h" +#include "rend/transform_matrix.h" +#include "wsi/context.h" +#include "metal_quad.h" +#include "metal_overlay.h" + +#ifdef VIDEO_ROUTING +// Syphon, implemented by the macOS shell +void os_VideoRoutingPublishFrameTexture(id texture, id commandBuffer, float x, float y, float w, float h); +void os_VideoRoutingTermMetal(); +#endif + +class MetalContext : public GraphicsContext +{ +public: + ~MetalContext() override; + // Throws FlycastException if Metal initialization fails. + static void Create(void *window, void *display); + + void resize() override { resized = true; } + bool IsValid() { return width != 0 && height != 0; } + void NewFrame(); + void BeginRenderPass(); + void EndFrame(); + void Present(); + void PresentFrame(id texture, MTLViewport viewport, float aspectRatio); + void PresentLastFrame(); + bool GetLastFrame(std::vector& data, int& width, int& height); + + id GetDevice() const { return device; } + CAMetalLayer* GetLayer() const { return layer; } + id GetQueue() const { return queue; } + MTLRenderPassDescriptor* GetDescriptor() const { return renderPassDescriptor; } + id GetEncoder() const { return commandEncoder; } + id GetCommandBuffer() const { return commandBuffers[currentImage]; } + bool IsRendering() const { return rendering; } + + std::string getDriverName() override; + + std::string getDriverVersion() override; + + bool isAMD() override { + return false; + } + + bool hasPerPixel() override { + return true; + } + bool recreateSwapChainIfNeeded(); + + // True if the device supports the packed 16-bit pixel formats (A1BGR5, B5G6R5, ABGR4). + // Only Apple GPUs do. + bool SupportsPacked16BitFormats() const { return metalSupportsPacked16BitFormats(device); } + + static MetalContext* Instance() { return contextInstance; } +private: + MetalContext(void *window, void *display); + bool init(); + void term(); + void CreateSwapChain(); + id currentCommandBuffer(); + void getFrameRect(float aspectRatio, float& x, float& y, float& w, float& h) const; + void DrawFrame(id texture, MTLViewport viewport, float aspectRatio); + void RenderVideoRouting(); + + bool HasSurfaceDimensionChanged() const; + void SetWindowSize(u32 width, u32 height); + + bool rendering = false; + bool renderDone = false; + u32 width = 0; + u32 height = 0; + bool resized = false; + bool swapOnVSync = true; + int swapInterval = 1; + + u32 currentImage = 0; + + id currentDrawable = nil; + MTLRenderPassDescriptor *renderPassDescriptor = nil; + + std::vector> commandBuffers; + id commandEncoder; + + std::unique_ptr quadPipelineWithAlpha; + std::unique_ptr quadPipeline; + std::unique_ptr quadRotatePipeline; + std::unique_ptr quadDrawer; + std::unique_ptr quadRotateDrawer; + std::unique_ptr overlay; + std::unique_ptr shaderManager; + + id lastFrameTexture = nil; + MTLViewport lastFrameViewport; + float lastFrameAR = 0.f; + + // Scaled copy of the frame sent by video routing + id videoRoutingTexture = nil; + + id device = nil; + id queue = nil; + CAMetalLayer* layer = nil; + void *metalView = nullptr; + + static MetalContext* contextInstance; +}; diff --git a/core/rend/metal/metal_context.mm b/core/rend/metal/metal_context.mm new file mode 100644 index 0000000000..89a2fa71fa --- /dev/null +++ b/core/rend/metal/metal_context.mm @@ -0,0 +1,663 @@ +/* + Copyright 2025 flyinghead + + This file is part of Flycast. + + Flycast is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 2 of the License, or + (at your option) any later version. + + Flycast is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with Flycast. If not, see . +*/ + +#include "metal_context.h" +#include "metal_driver.h" +#include "cfg/option.h" +#include "ui/gui.h" +#include "ui/imgui_driver.h" +#include "oslib/i18n.h" +#ifdef USE_SDL +#include "sdl/sdl.h" +#include +#endif + +#include +#include + +MetalContext *MetalContext::contextInstance; + +void MetalContext::CreateSwapChain() +{ + commandBuffers.clear(); + + [layer setPixelFormat:MTLPixelFormatBGRA8Unorm]; + CGColorSpaceRef colorSpace = CGColorSpaceCreateWithName(kCGColorSpaceSRGB); + [layer setColorspace:colorSpace]; + CGColorSpaceRelease(colorSpace); + [layer setFramebufferOnly:FALSE]; + [layer setMaximumDrawableCount:3]; + [layer setDisplaySyncEnabled:swapOnVSync]; + + auto size = [layer drawableSize]; + // Validate up front, then let SetWindowSize() do the assignment and propagation. + if (size.width <= 0 || size.height <= 0) + { + WARN_LOG(RENDERER, "Metal layer reported invalid drawable size %.0fx%.0f; skipping swap chain creation", + size.width, size.height); + return; + } + SetWindowSize((u32)size.width, (u32)size.height); + resized = false; + + if (swapOnVSync && config::DupeFrames && settings.display.refreshRate > 60.f) + swapInterval = settings.display.refreshRate / 60.f; + else + swapInterval = 1; + + commandBuffers.resize(3); + + quadPipeline->Init(shaderManager.get()); + quadPipelineWithAlpha->Init(shaderManager.get()); + quadDrawer->Init(quadPipeline.get()); + quadRotatePipeline->Init(shaderManager.get()); + quadRotateDrawer->Init(quadRotatePipeline.get()); + overlay->Init(quadPipelineWithAlpha.get()); + + currentImage = 2; + + INFO_LOG(RENDERER, "Metal swap chain created: %d x %d, swap chain size %d", width, height, 3); +} + +bool MetalContext::init() +{ + // MTLSharedEvent waitUntilSignaledValue:timeoutMS: (MetalCommandPool) requires macOS 12 + if (@available(macOS 12.0, *)) { + } else { + gui_error(i18n::T("The Metal renderer requires macOS 12 or later. Falling back to OpenGL.")); + return false; + } +#ifdef USE_SDL + if (!sdl_recreate_window(SDL_WINDOW_METAL)) + return false; + + metalView = SDL_Metal_CreateView((SDL_Window *)window); + if (metalView == nullptr) { + ERROR_LOG(RENDERER, "Failed to create SDL Metal View: %s", SDL_GetError()); + term(); + return false; + } + layer = (__bridge CAMetalLayer *)SDL_Metal_GetLayer(metalView); +#endif + if (layer == nil) { + ERROR_LOG(RENDERER, "No CAMetalLayer available"); + term(); + return false; + } + + device = MTLCreateSystemDefaultDevice(); + if (!device) { + ERROR_LOG(RENDERER, "Metal device is null."); + term(); + return false; + } + + [layer setDevice:device]; + queue = [device newCommandQueue]; + + shaderManager = std::make_unique(); + quadPipeline = std::make_unique(true, false); + quadPipelineWithAlpha = std::make_unique(false, false); + quadDrawer = std::make_unique(); + quadRotatePipeline = std::make_unique(true, true); + quadRotateDrawer = std::make_unique(); + overlay = std::make_unique(); + +#ifdef USE_SDL + sdl_update_display_metrics((SDL_Window *)window, SDL_WINDOW_METAL); +#endif + NOTICE_LOG(RENDERER, "Metal device: %s", [[device name] UTF8String]); + + imguiDriver = std::unique_ptr(new MetalDriver()); + + CreateSwapChain(); + + return true; +} + +std::string MetalContext::getDriverName() { + return [[device name] UTF8String]; +} + +bool MetalContext::recreateSwapChainIfNeeded() +{ + if (resized || HasSurfaceDimensionChanged()) + { + CreateSwapChain(); + lastFrameTexture = nil; + return true; + } + else + return false; +} + +void MetalContext::BeginRenderPass() +{ + recreateSwapChainIfNeeded(); + if (!IsValid()) + return; + + // Reuse the drawable PresentFrame already acquired for this frame. + if (currentDrawable == nil) + currentDrawable = [layer nextDrawable]; + + // nextDrawable can return nil when the pool is exhausted or it times out. + // Skip this frame's pass. EndFrame and the encoder users below are nil-encoder safe. + if (currentDrawable == nil) { + DEBUG_LOG(RENDERER, "Skipping render pass: no drawable available"); + commandEncoder = nil; + return; + } + + if (!renderPassDescriptor) + renderPassDescriptor = [[MTLRenderPassDescriptor alloc] init]; + + auto colorAttachment = renderPassDescriptor.colorAttachments[0]; + [colorAttachment setTexture:currentDrawable.texture]; + [colorAttachment setLoadAction:MTLLoadActionClear]; + [colorAttachment setStoreAction:MTLStoreActionStore]; + [colorAttachment setClearColor:MTLClearColorMake(VO_BORDER_COL.red(), VO_BORDER_COL.green(), VO_BORDER_COL.blue(), 1.0f)]; + + commandEncoder = [currentCommandBuffer() renderCommandEncoderWithDescriptor:renderPassDescriptor]; +} + +id MetalContext::currentCommandBuffer() +{ + if (currentImage >= commandBuffers.size()) + commandBuffers.resize(currentImage + 1); + + if (!commandBuffers[currentImage]) { + commandBuffers[currentImage] = [queue commandBuffer]; + [commandBuffers[currentImage] setLabel:@"Render Frame"]; + } + return commandBuffers[currentImage]; +} + +void MetalContext::NewFrame() +{ + if (!IsValid()) + return; + + currentImage = (currentImage + 1) % 3; + currentDrawable = nil; + verify(!rendering); + rendering = true; +} + +void MetalContext::EndFrame() +{ + if (!IsValid()) + return; + + [commandEncoder endEncoding]; + commandEncoder = nil; + + if (currentDrawable != nil) + { + RenderVideoRouting(); + [commandBuffers[currentImage] presentDrawable:currentDrawable]; + } + + // Don't wait for completion. Triple buffering (currentImage % 3) keeps in-flight frames apart. + [commandBuffers[currentImage] commit]; + commandBuffers[currentImage] = nil; + + verify(rendering); + rendering = false; + renderDone = true; +} + +void MetalContext::Present() +{ + if (renderDone) + { + if (lastFrameTexture != nil && IsValid() && !gui_is_open()) + { + for (int i = 1; i < swapInterval; i++) + PresentFrame(lastFrameTexture, lastFrameViewport, lastFrameAR); + } + renderDone = false; + } + if (swapOnVSync == (settings.input.fastForwardMode || !config::VSync)) + { + swapOnVSync = (!settings.input.fastForwardMode && config::VSync); + resized = true; + } + if (resized) { + CreateSwapChain(); + lastFrameTexture = nil; + } +} + +// Fit the content aspect ratio into the drawable +void MetalContext::getFrameRect(float aspectRatio, float& viewportX, float& viewportY, float& viewportWidth, float& viewportHeight) const +{ + int dx = 0, dy = 0; + getWindowboxDimensions(width, height, aspectRatio, dx, dy, config::Rotate90); + viewportX = dx; + viewportY = dy; + viewportWidth = width - 2 * dx; + viewportHeight = height - 2 * dy; +} + + +void MetalContext::DrawFrame(id texture, MTLViewport viewport, float aspectRatio) +{ + float viewportWidth, viewportHeight, viewportX, viewportY; + getFrameRect(aspectRatio, viewportX, viewportY, viewportWidth, viewportHeight); + + const float sourceWidth = texture.width; + const float sourceHeight = texture.height; + + MetalQuadVertex vtx[4] { + { -1, -1, 0, 0, 1 }, // bottom-left + { 1, -1, 0, 1, 1 }, // bottom-right + { -1, 1, 0, 0, 0 }, // top-left + { 1, 1, 0, 1, 0 }, // top-right + }; + + float shiftX, shiftY; + getVideoShift(shiftX, shiftY); + for (auto& vertex : vtx) { + vertex.x += shiftX * 2.f / sourceWidth; + vertex.y -= shiftY * 2.f / sourceHeight; + } + [commandEncoder pushDebugGroup:@"DrawFrame"]; + + const bool bound = config::Rotate90 + ? quadRotatePipeline->BindPipeline(commandEncoder) + : quadPipeline->BindPipeline(commandEncoder); + if (!bound) { + // The present pipeline failed to compile + [commandEncoder popDebugGroup]; + return; + } + + MTLViewport framePort = { viewportX, viewportY, viewportWidth, viewportHeight, 0, 1 }; + [commandEncoder setViewport:framePort]; + + // Clamp in float space before casting to unsigned, then clamp to the render target. + const float sx = std::max(0.f, viewportX); + const float sy = std::max(0.f, viewportY); + const float sw = std::max(0.f, viewportWidth); + const float sh = std::max(0.f, viewportHeight); + MTLScissorRect scissor = { + (NSUInteger)sx, + (NSUInteger)sy, + (NSUInteger)sw, + (NSUInteger)sh + }; + if (scissor.x + scissor.width > width) + scissor.width = width - scissor.x; + if (scissor.y + scissor.height > height) + scissor.height = height - scissor.y; + [commandEncoder setScissorRect:scissor]; + + const bool nearest = config::TextureFiltering == 1 || !config::LinearInterpolation; + if (config::Rotate90) + quadRotateDrawer->Draw(commandEncoder, texture, vtx, nearest); + else + quadDrawer->Draw(commandEncoder, texture, vtx, nearest); + + [commandEncoder popDebugGroup]; +} + +// Sends the presented image, UI included, to Syphon +void MetalContext::RenderVideoRouting() +{ +#ifdef VIDEO_ROUTING + if (!config::VideoRouting) + { + videoRoutingTexture = nil; + os_VideoRoutingTermMetal(); + return; + } + id source = currentDrawable.texture; + int targetWidth = config::VideoRoutingScale ? config::VideoRoutingVRes * width / height : width; + int targetHeight = config::VideoRoutingScale ? config::VideoRoutingVRes : height; + targetWidth = std::clamp(targetWidth, 1, 16384); + targetHeight = std::clamp(targetHeight, 1, 16384); + if ((u32)targetWidth == width && (u32)targetHeight == height) + { + videoRoutingTexture = nil; + os_VideoRoutingPublishFrameTexture(source, commandBuffers[currentImage], 0, 0, width, height); + return; + } + // Scale the image to the requested size + if (videoRoutingTexture == nil || videoRoutingTexture.width != (NSUInteger)targetWidth + || videoRoutingTexture.height != (NSUInteger)targetHeight) + { + MTLTextureDescriptor *desc = [MTLTextureDescriptor texture2DDescriptorWithPixelFormat:source.pixelFormat + width:targetWidth height:targetHeight mipmapped:NO]; + desc.usage = MTLTextureUsageRenderTarget | MTLTextureUsageShaderRead; + desc.storageMode = MTLStorageModePrivate; + videoRoutingTexture = [device newTextureWithDescriptor:desc]; + [videoRoutingTexture setLabel:@"Video Routing"]; + } + MTLRenderPassDescriptor *passDesc = [[MTLRenderPassDescriptor alloc] init]; + passDesc.colorAttachments[0].texture = videoRoutingTexture; + passDesc.colorAttachments[0].loadAction = MTLLoadActionDontCare; + passDesc.colorAttachments[0].storeAction = MTLStoreActionStore; + id encoder = [commandBuffers[currentImage] renderCommandEncoderWithDescriptor:passDesc]; + [encoder setLabel:@"Video Routing Scale"]; + if (quadPipeline->BindPipeline(encoder)) + { + MetalQuadVertex vtx[4] { + { -1, -1, 0, 0, 1 }, + { 1, -1, 0, 1, 1 }, + { -1, 1, 0, 0, 0 }, + { 1, 1, 0, 1, 0 }, + }; + [encoder setViewport:MTLViewport{ 0, 0, (double)targetWidth, (double)targetHeight, 0, 1 }]; + quadDrawer->Draw(encoder, source, vtx, false); + } + [encoder endEncoding]; + os_VideoRoutingPublishFrameTexture(videoRoutingTexture, commandBuffers[currentImage], 0, 0, targetWidth, targetHeight); +#endif +} + +void MetalContext::PresentFrame(id texture, MTLViewport viewport, float aspectRatio) +{ + // nextDrawable returns an autoreleased object. Drain it every frame so the layer's + // drawable pool isn't exhausted when presenting from a thread without a pool. + @autoreleasepool { + lastFrameTexture = texture; + lastFrameViewport = viewport; + lastFrameAR = aspectRatio; + + if (texture != nil && IsValid()) + { + NewFrame(); + gui_draw_osd(); + BeginRenderPass(); + + // BeginRenderPass leaves a nil encoder when no drawable was available + if (commandEncoder != nil) + { + if (lastFrameTexture != nil) // Might have been nullified if swap chain recreated + DrawFrame(texture, viewport, aspectRatio); + overlay->Draw(commandEncoder, width, height, settings.display.uiScale, config::FloatVMUs, true); + imguiDriver->renderDrawData(ImGui::GetDrawData(), false); + } + EndFrame(); + } + } // @autoreleasepool +} + +void MetalContext::PresentLastFrame() +{ + if (lastFrameTexture != nil && IsValid()) + DrawFrame(lastFrameTexture, lastFrameViewport, lastFrameAR); +} + +void MetalContext::term() +{ + lastFrameTexture = nil; + videoRoutingTexture = nil; +#ifdef VIDEO_ROUTING + os_VideoRoutingTermMetal(); +#endif + currentDrawable = nil; + imguiDriver.reset(); + if (overlay) + overlay->Term(); + overlay.reset(); + quadDrawer.reset(); + quadPipeline.reset(); + quadPipelineWithAlpha.reset(); + quadRotateDrawer.reset(); + quadRotatePipeline.reset(); + shaderManager.reset(); + commandBuffers.clear(); + commandEncoder = nil; + renderPassDescriptor = nil; + queue = nil; + device = nil; + layer = nil; +#ifdef USE_SDL + if (metalView != nullptr) { + SDL_Metal_DestroyView(metalView); + metalView = nullptr; + } +#endif +} + +bool MetalContext::HasSurfaceDimensionChanged() const +{ + auto size = [layer drawableSize]; + return width != size.width || height != size.height; +} + +void MetalContext::SetWindowSize(u32 width, u32 height) +{ + if (this->width != width || this->height != height) + { + if (width == 0 || height == 0) { + WARN_LOG(RENDERER, "Invalid window size: %dx%d, ignoring", width, height); + return; + } + DEBUG_LOG(RENDERER, "Metal context size change: %dx%d -> %dx%d", this->width, this->height, width, height); + + this->width = width; + this->height = height; + settings.display.width = width; + settings.display.height = height; + + resize(); + } +} + +// Bounded replacement for [commandBuffer waitUntilCompleted]: a command buffer that never +// reports completion must not hang the caller. Commits the command buffer. +static bool commitAndWaitBounded(id commandBuffer, uint64_t timeoutMs, const char *what) +{ + dispatch_semaphore_t sem = dispatch_semaphore_create(0); + [commandBuffer addCompletedHandler:^(id cb) { + (void)cb; + dispatch_semaphore_signal(sem); + }]; + [commandBuffer commit]; + if (dispatch_semaphore_wait(sem, + dispatch_time(DISPATCH_TIME_NOW, (int64_t)timeoutMs * NSEC_PER_MSEC)) != 0) + { + WARN_LOG(RENDERER, "%s: GPU did not signal completion within %llu ms - giving up on this frame", + what, (unsigned long long)timeoutMs); + return false; + } + return true; +} + +bool MetalContext::GetLastFrame(std::vector &data, int &width, int &height) +{ + if (lastFrameTexture == nil) + return false; + + if (width != 0) { + height = width / lastFrameAR; + } + else if (height != 0) { + width = lastFrameAR * height; + } + else + { + width = lastFrameViewport.width; + height = lastFrameViewport.height; + if (config::Rotate90) + std::swap(width, height); + // We need square pixels for PNG + int w = lastFrameAR * height; + if (width > w) + height = width / lastFrameAR; + else + width = w; + } + + // A zero/NaN aspect or an empty viewport (no frame presented yet) gives a 0 or + // absurd size, and newTextureWithDescriptor would abort. + if (width <= 0 || height <= 0 || width > 16384 || height > 16384) + return false; + + MTLTextureDescriptor *renderTargetDesc = [[MTLTextureDescriptor alloc] init]; + renderTargetDesc.width = width; + renderTargetDesc.height = height; + // Must match MetalQuadPipeline, which compiles its colour attachment as + // BGRA8Unorm (metal_quad.mm). An RGBA8 target here trips the Metal API + // validation assert in setRenderPipelineState: and, without validation, + // renders with the channels swapped. + renderTargetDesc.pixelFormat = MTLPixelFormatBGRA8Unorm; + renderTargetDesc.usage = MTLTextureUsageRenderTarget; + renderTargetDesc.storageMode = MTLStorageModePrivate; + + id renderTarget = [device newTextureWithDescriptor:renderTargetDesc]; + [renderTarget setLabel:@"Screenshot Render Target"]; + + NSUInteger bytesPerPixel = 4; + NSUInteger bytesPerRow = width * bytesPerPixel; + NSUInteger bufferSize = bytesPerRow * height; + + id readbackBuffer = [device newBufferWithLength:bufferSize + options:MTLResourceStorageModeShared]; + [readbackBuffer setLabel:@"Screenshot Readback Buffer"]; + + id commandBuffer = [queue commandBuffer]; + [commandBuffer setLabel:@"GetLastFrame"]; + + MTLRenderPassDescriptor *renderPassDesc = [[MTLRenderPassDescriptor alloc] init]; + renderPassDesc.colorAttachments[0].texture = renderTarget; + renderPassDesc.colorAttachments[0].loadAction = MTLLoadActionClear; + renderPassDesc.colorAttachments[0].storeAction = MTLStoreActionStore; + renderPassDesc.colorAttachments[0].clearColor = MTLClearColorMake(0, 0, 0, 1); + + id renderEncoder = [commandBuffer renderCommandEncoderWithDescriptor:renderPassDesc]; + [renderEncoder setLabel:@"GetLastFrame Render"]; + + MTLViewport viewport = { + 0.0, 0.0, + (double)width, (double)height, + 0.0, 1.0 + }; + [renderEncoder setViewport:viewport]; + + // Apply bounds checking to prevent Metal validation errors + MTLScissorRect scissor = { + 0, 0, + (NSUInteger)width, (NSUInteger)height + }; + + // Basic validation - ensure scissor doesn't exceed render target bounds + scissor.width = std::min(scissor.width, (NSUInteger)width); + scissor.height = std::min(scissor.height, (NSUInteger)height); + scissor.width = std::max(scissor.width, (NSUInteger)1); + scissor.height = std::max(scissor.height, (NSUInteger)1); + + [renderEncoder setScissorRect:scissor]; + + MetalQuadVertex vtx[4] = { + { -1.f, -1.f, 0.f, 0.f, 1.f }, + { 1.f, -1.f, 0.f, 1.f, 1.f }, + { -1.f, 1.f, 0.f, 0.f, 0.f }, + { 1.f, 1.f, 0.f, 1.f, 0.f }, + }; + + // Match what the user sees, so the savestate thumbnail is upright. The frame is + // not rotated by the projection; the 90° turn happens at present time in DrawFrame. + if (config::Rotate90) { + quadRotatePipeline->BindPipeline(renderEncoder); + quadRotateDrawer->Draw(renderEncoder, lastFrameTexture, vtx, false); + } else { + quadPipeline->BindPipeline(renderEncoder); + quadDrawer->Draw(renderEncoder, lastFrameTexture, vtx, false); + } + + [renderEncoder endEncoding]; + + // Copy from render target to buffer + id blitEncoder = [commandBuffer blitCommandEncoder]; + [blitEncoder setLabel:@"GetLastFrame Blit"]; + + MTLOrigin sourceOrigin = MTLOriginMake(0, 0, 0); + MTLSize sourceSize = MTLSizeMake(width, height, 1); + + [blitEncoder copyFromTexture:renderTarget + sourceSlice:0 + sourceLevel:0 + sourceOrigin:sourceOrigin + sourceSize:sourceSize + toBuffer:readbackBuffer + destinationOffset:0 + destinationBytesPerRow:bytesPerRow + destinationBytesPerImage:bufferSize]; + + [blitEncoder endEncoding]; + + if (!commitAndWaitBounded(commandBuffer, 1000, "MetalContext::GetLastFrame")) + return false; + + if (commandBuffer.status != MTLCommandBufferStatusCompleted) { + NSError *error = commandBuffer.error; + WARN_LOG(RENDERER, "MetalContext::GetLastFrame: Command buffer failed: %s", + error ? error.localizedDescription.UTF8String : "Unknown error"); + return false; + } + + // Read back the data + const u8 *img = (const u8 *)[readbackBuffer contents]; + data.clear(); + + data.reserve(width * height * 3); + // BGRA -> RGB conversion + for (int y = 0; y < height; y++) { + for (int x = 0; x < width; x++) { + data.push_back(img[2]); // R + data.push_back(img[1]); // G + data.push_back(img[0]); // B + img += 4; // Skip A + } + } + + return true; +} + +void MetalContext::Create(void *window, void *display) { + new MetalContext(window, display); +} + +MetalContext::MetalContext(void *window, void *display) + : GraphicsContext(window, display) +{ + verify(contextInstance == nullptr); + contextInstance = this; + if (!init()) { + // The MetalContext dtor doesn't run when the ctor throws + term(); + contextInstance = nullptr; + throw FlycastException("Metal initialization failed"); + } +} + +MetalContext::~MetalContext() { + verify(contextInstance == this); + term(); + contextInstance = nullptr; +} + +std::string MetalContext::getDriverVersion() +{ + return NSProcessInfo.processInfo.operatingSystemVersionString.UTF8String; +} diff --git a/core/rend/metal/metal_drawer.h b/core/rend/metal/metal_drawer.h new file mode 100644 index 0000000000..ee93785b74 --- /dev/null +++ b/core/rend/metal/metal_drawer.h @@ -0,0 +1,517 @@ +/* + Copyright 2025 flyinghead + + This file is part of Flycast. + + Flycast is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 2 of the License, or + (at your option) any later version. + + Flycast is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with Flycast. If not, see . +*/ + +#pragma once +#include "metal_apple.h" + +#include "metal_texture.h" +#include "metal_shaders.h" +#include "metal_pipeline.h" +#include "metal_buffer.h" +#include "metal_quad.h" +#include "metal_commandpool.h" +#include "rend/texconv.h" +#include "rend/transform_matrix.h" +#include "rend/sorter.h" +#include "hw/pvr/pvr_mem.h" +#include +#include + +// Fragment push block for the stencil modifier-volume passes (ModVolShaderSource +// PushBlock, fragment buffer 1) and the OIT translucent modvol pass (buffer 5). +// 32 bytes, float4-aligned, so the MSL and C++ layouts agree byte for byte. +struct MetalModVolPushBlock +{ + float clipTest[4] {}; // x0, y0, x1, y1 in framebuffer pixels (Inside clip only) + float shaderColor = 1.f; // Final pass darkening alpha + int clipInside = 0; // 1 = discard fragments inside clipTest + float pad[2] {}; + + /// Loads the per-volume tile clip. Returns true when the block changed and + /// must be re-pushed to the encoder. + bool setTileClip(TileClipping mode, const MTLScissorRect& rect) + { + const int inside = mode == TileClipping::Inside ? 1 : 0; + const float next[4] = { + (float)rect.x, (float)rect.y, + (float)(rect.x + rect.width), (float)(rect.y + rect.height) + }; + bool changed = inside != clipInside; + if (inside) + for (int i = 0; i < 4 && !changed; i++) + changed = next[i] != clipTest[i]; + if (!changed) + return false; + clipInside = inside; + if (inside) + std::copy(next, next + 4, clipTest); + return true; + } +}; +static_assert(sizeof(MetalModVolPushBlock) == 32, "must match the MSL PushBlock"); + +class MetalBaseDrawer +{ +public: + void SetCommandPool(MetalCommandPool *commandPool) { this->commandPool = commandPool; } + // Commit 90301d5c3 removed the _pvrrc global: the renderer hands each + // drawer the rend_context it is about to draw, exactly like Vulkan's + // BaseDrawer::setRendContext. + void setRendContext(rend_context *rendContext) { + this->rendContext = rendContext; + } + +protected: + TileClipping SetTileClip(id encoder, u32 val, MTLScissorRect& clipRect); + void SetBaseScissor(MTLViewport viewport); + + void SetScissor(id encoder, const MTLScissorRect& scissor) + { + if (scissor.x != currentScissor.x || + scissor.y != currentScissor.y || + scissor.width != currentScissor.width || + scissor.height != currentScissor.height) + { + // Clamp scissor rect to base scissor bounds to prevent Metal validation errors + MTLScissorRect clampedScissor = scissor; + + // First, clamp positions to be within base scissor bounds + NSUInteger baseMaxX = baseScissor.x + baseScissor.width; + NSUInteger baseMaxY = baseScissor.y + baseScissor.height; + + clampedScissor.x = std::max(clampedScissor.x, baseScissor.x); + clampedScissor.y = std::max(clampedScissor.y, baseScissor.y); + clampedScissor.x = std::min(clampedScissor.x, baseMaxX); + clampedScissor.y = std::min(clampedScissor.y, baseMaxY); + + // Then clamp width/height to ensure they don't exceed bounds + NSUInteger maxWidth = baseMaxX - clampedScissor.x; + NSUInteger maxHeight = baseMaxY - clampedScissor.y; + + clampedScissor.width = std::min(clampedScissor.width, maxWidth); + clampedScissor.height = std::min(clampedScissor.height, maxHeight); + + // Ensure minimum size (Metal requires non-zero dimensions) + clampedScissor.width = std::max(clampedScissor.width, (NSUInteger)1); + clampedScissor.height = std::max(clampedScissor.height, (NSUInteger)1); + + if (clampedScissor.x != scissor.x || clampedScissor.y != scissor.y || + clampedScissor.width != scissor.width || clampedScissor.height != scissor.height) { + DEBUG_LOG(RENDERER, "Clamped scissor rect: requested=(%d,%d,%d,%d) -> clamped=(%d,%d,%d,%d), base=(%d,%d,%d,%d)", + (int)scissor.x, (int)scissor.y, (int)scissor.width, (int)scissor.height, + (int)clampedScissor.x, (int)clampedScissor.y, (int)clampedScissor.width, (int)clampedScissor.height, + (int)baseScissor.x, (int)baseScissor.y, (int)baseScissor.width, (int)baseScissor.height); + } + + [encoder setScissorRect:clampedScissor]; + currentScissor = clampedScissor; + } + } + + MetalBufferData* GetMainBuffer(u32 size) + { + MetalBufferData *buffer; + if (!mainBuffers.empty()) + { + buffer = mainBuffers.back().release(); + mainBuffers.pop_back(); + if (buffer->bufferSize < size) { + commandPool->addToFlight(new MetalDeleter(buffer)); + u32 newSize = (u32)buffer->bufferSize; + while (newSize < size) + newSize *= 2; + INFO_LOG(RENDERER, "Increasing main buffer size %llu -> %d", (unsigned long long)buffer->bufferSize, newSize); + + buffer = new MetalBufferData(newSize); + } + } + else + { + buffer = new MetalBufferData(std::max(512 * 1024u, size)); + } + + class BufferHolder : public MetalDeletable + { + public: + BufferHolder(MetalBufferData *buffer, MetalBaseDrawer *drawer) : buffer(buffer), drawer(drawer) {} + + ~BufferHolder() override { + drawer->mainBuffers.emplace_back(buffer); + } + + private: + MetalBufferData *buffer; + MetalBaseDrawer *drawer; + }; + commandPool->addToFlight(new BufferHolder(buffer, this)); + + return buffer; + } + + template + T MakeFragmentUniforms() + { + T fragUniforms; + + //VERT and RAM fog color constants + FOG_COL_VERT.getRGBColor(fragUniforms.sp_FOG_COL_VERT); + FOG_COL_RAM.getRGBColor(fragUniforms.sp_FOG_COL_RAM); + + //Fog density constant + fragUniforms.sp_FOG_DENSITY = FOG_DENSITY.get() * config::ExtraDepthScale; + + rendContext->fog_clamp_min.getRGBAColor(fragUniforms.colorClampMin); + rendContext->fog_clamp_max.getRGBAColor(fragUniforms.colorClampMax); + + fragUniforms.cp_AlphaTestValue = (PT_ALPHA_REF & 0xFF) / 255.0f; + + return fragUniforms; + } + + template + void packNaomi2Uniforms(MetalBufferPacker& packer, Offsets& offsets, std::vector& n2uniforms, bool trModVolIncluded) + { + size_t n2UniformSize = sizeof(MetalN2VertexShaderUniforms) + MetalBufferPacker::align(sizeof(MetalN2VertexShaderUniforms), kConstantBufferAlign); + int items = (int)(rendContext->global_param_op.size() + rendContext->global_param_pt.size() + rendContext->global_param_tr.size() + rendContext->global_param_mvo.size()); + if (trModVolIncluded) + items += rendContext->global_param_mvo_tr.size(); + n2uniforms.resize(items * n2UniformSize); + size_t bufIdx = 0; + auto addUniform = [&](const PolyParam& pp, int polyNumber) { + if (pp.isNaomi2()) + { + MetalN2VertexShaderUniforms& uni = *(MetalN2VertexShaderUniforms *)&n2uniforms[bufIdx]; + memcpy(glm::value_ptr(uni.mvMat), rendContext->matrices[pp.mvMatrix].mat, sizeof(uni.mvMat)); + memcpy(glm::value_ptr(uni.normalMat), rendContext->matrices[pp.normalMatrix].mat, sizeof(uni.normalMat)); + memcpy(glm::value_ptr(uni.projMat), rendContext->matrices[pp.projMatrix].mat, sizeof(uni.projMat)); + uni.bumpMapping = pp.pcw.Texture == 1 && pp.tcw.PixelFmt == PixelBumpMap; + uni.polyNumber = polyNumber; + for (size_t i = 0; i < 2; i++) + { + uni.envMapping[i] = pp.envMapping[i]; + uni.glossCoef[i] = pp.glossCoef[i]; + uni.constantColor[i] = pp.constantColor[i]; + } + } + bufIdx += n2UniformSize; + }; + for (const PolyParam& pp : rendContext->global_param_op) + addUniform(pp, 0); + size_t ptOffset = bufIdx; + for (const PolyParam& pp : rendContext->global_param_pt) + addUniform(pp, 0); + size_t trOffset = bufIdx; + if (!rendContext->global_param_tr.empty()) + { + u32 firstVertexIdx = rendContext->idx[rendContext->global_param_tr[0].first]; + for (const PolyParam& pp : rendContext->global_param_tr) + addUniform(pp, (int)(((&pp - &rendContext->global_param_tr[0]) << 17) - firstVertexIdx)); + } + size_t mvOffset = bufIdx; + for (const ModifierVolumeParam& mvp : rendContext->global_param_mvo) + { + if (mvp.isNaomi2()) + { + MetalN2VertexShaderUniforms& uni = *(MetalN2VertexShaderUniforms *)&n2uniforms[bufIdx]; + memcpy(glm::value_ptr(uni.mvMat), rendContext->matrices[mvp.mvMatrix].mat, sizeof(uni.mvMat)); + memcpy(glm::value_ptr(uni.projMat), rendContext->matrices[mvp.projMatrix].mat, sizeof(uni.projMat)); + } + bufIdx += n2UniformSize; + } + size_t trMvOffset = bufIdx; + if (trModVolIncluded) + for (const ModifierVolumeParam& mvp : rendContext->global_param_mvo_tr) + { + if (mvp.isNaomi2()) + { + MetalN2VertexShaderUniforms& uni = *(MetalN2VertexShaderUniforms *)&n2uniforms[bufIdx]; + memcpy(glm::value_ptr(uni.mvMat), rendContext->matrices[mvp.mvMatrix].mat, sizeof(uni.mvMat)); + memcpy(glm::value_ptr(uni.projMat), rendContext->matrices[mvp.projMatrix].mat, sizeof(uni.projMat)); + } + bufIdx += n2UniformSize; + } + offsets.naomi2OpaqueOffset = packer.addUniform(n2uniforms.data(), bufIdx); + offsets.naomi2PunchThroughOffset = offsets.naomi2OpaqueOffset + ptOffset; + offsets.naomi2TranslucentOffset = offsets.naomi2OpaqueOffset + trOffset; + offsets.naomi2ModVolOffset = offsets.naomi2OpaqueOffset + mvOffset; + offsets.naomi2TrModVolOffset = offsets.naomi2OpaqueOffset + trMvOffset; + } + + u64 packNaomi2Lights(MetalBufferPacker& packer) + { + u64 offset = -1; + + if (!rendContext->lightModels.empty()) + { + // Pad every model to the same constant-buffer stride used when binding. + for (const auto& model : rendContext->lightModels) + { + u64 modelOffset = packer.addUniform(&model, sizeof(model)); + if (offset == (u64)-1) + offset = modelOffset; + } + } + + return offset; + } + + MTLCullMode toMetalCullMode(int cullMode) { + return cullMode == 3 ? MTLCullModeBack + : cullMode == 2 ? MTLCullModeFront + : MTLCullModeNone; + } + + // Framebuffer emulation: copies the rendered frame back into VRAM so + // presentFramebuffer() can show it. Shared by both screen drawers, like + // Vulkan's BaseDrawer::scaleAndWriteFramebuffer. Commits the current + // frame's command buffer and waits for it (EndFrameAndWait). + void scaleAndWriteFramebuffer(id finalTexture); + + void releaseReadbackTextures() { + scalePipeline.Term(); + cachedScaledTexture = nil; + cachedScaledWidth = cachedScaledHeight = 0; + cachedReadableTexture = nil; + cachedReadableWidth = cachedReadableHeight = 0; + } + + MTLScissorRect baseScissor {}; + MTLScissorRect currentScissor {}; + TransformMatrix matrices { true }; + MetalCommandPool *commandPool = nullptr; + std::vector> mainBuffers; + rend_context *rendContext = nullptr; + // The renderer's shader manager, set by the screen drawers' Init(). + // scaleAndWriteFramebuffer() takes its quad shaders from it. + MetalShaders *shaderManager = nullptr; + +private: + // Framebuffer-emulation readback scratch; a member for the same reason as + // MetalTextureDrawer::rttReadback -- scaleAndWriteFramebuffer() runs every + // frame under EmulateFramebuffer and was allocating ~1.2MB per call. + PixelBuffer fbReadback; + MetalQuadPipeline scalePipeline { false, false, false }; + MetalQuadDrawer scaleDrawer; + + // The two MTLTextures scaleAndWriteFramebuffer() needs, cached across + // frames. Both were allocated per call, which is a good deal more expensive + // than the malloc above. Safe to reuse: the only consumer is the blit that + // commandPool->EndFrameAndWait() synchronizes before getBytes, so the GPU + // is provably done with last frame's copy before this frame touches it. + // Reallocated only when the surface dimensions change. + id cachedScaledTexture = nil; + u32 cachedScaledWidth = 0; + u32 cachedScaledHeight = 0; + id cachedReadableTexture = nil; + u32 cachedReadableWidth = 0; + u32 cachedReadableHeight = 0; +}; + +class MetalDrawer : public MetalBaseDrawer +{ +public: + virtual ~MetalDrawer() = default; + + bool Draw(const MetalTexture *fogTexture, const MetalTexture *paletteTexture); + virtual void EndRenderPass() { + renderPassStarted = false; + } + + virtual void Term() { + + } + +protected: + virtual id BeginRenderPass() = 0; + void Init(MetalSamplers *samplers, MetalPipelineManager pipelineManager) { + this->samplers = samplers; + this->pipelineManager = std::make_unique(pipelineManager); + } + + id currentEncoder = nil; + MetalSamplers *samplers = nullptr; + bool renderPassStarted = false; + +private: + void DrawPoly(id encoder, u32 listType, bool sortTriangles, const PolyParam& poly, u32 first, u32 count); + // False (and logs, rate-limited) when [first, first+count) runs past the idx + // array uploaded this frame. See the definition for why. + bool indexRangeValid(u64 first, u64 count, const char *site) const; + + // Redundant-state elimination for the per-polygon draw loop. + // + // DrawPoly unconditionally re-issued pipeline, depth-stencil, cull mode, + // stencil reference, texture, sampler and push constants for EVERY polygon. + // Metal encoder state is sticky, so setting an identical value again is + // pure overhead — an ObjC message send plus driver-side encoding — and a + // busy scene submits thousands of polys, most of which share state with + // their neighbour because that is how the TA groups them. + // + // Output is bit-identical by construction: a set is skipped only when the + // value already matches what this encoder was last given. + // + // Object pointers are compared by identity, which is sound because the + // pipeline/sampler/depth-stencil managers hand back the same object for the + // same key. Textures are only ever COMPARED, never dereferenced, and the + // cache is invalidated at the start of every draw list — so a freed texture + // cannot be mistaken for a live one at the same address across lists. + // + // MUST be invalidated whenever anything else touches the encoder, or a new + // encoder begins. Call sites: DrawList, DrawSorted, DrawModVols. + struct DrawStateCache + { + id pipeline = nil; + id depthStencil = nil; + id fragTexture = nil; + id fragSampler = nil; + MTLCullMode cullMode = MTLCullModeNone; + u32 stencilRef = 0; + std::array pushConstants {}; + bool haveCullMode = false; + bool haveStencilRef = false; + bool havePushConstants = false; + + // Naomi2 only. The per-poly vertex-buffer binds at indices 1 (N2 vertex + // uniforms) and 2 (light model) are the one pair of encoder sets that + // genuinely varies per polygon -- but only on Naomi2, where the offset + // is base + polyIndex * stride. On Dreamcast/Naomi1 both are constant, + // so that path hoists the index-1 bind out of the loop entirely + // (MetalDrawer::Draw) instead of caching it here. + struct BufferBinding { + id buffer = nil; + u64 offset = 0; + bool operator!=(const BufferBinding& o) const { return buffer != o.buffer || offset != o.offset; } + }; + BufferBinding n2Uniform; + BufferBinding n2Lights; + bool haveN2Uniform = false; + bool haveN2Lights = false; + + void invalidate() { *this = DrawStateCache(); } + }; + DrawStateCache drawState; + void DrawSorted(id encoder, const std::vector& polys, u32 first, u32 last, bool multipass); + void DrawList(id encoder, u32 listType, bool sortTriangles, const std::vector& polys, u32 first, u32 last); + void DrawModVols(id encoder, int first, int count); + void UploadMainBuffer(const MetalVertexShaderUniforms& vertexUniforms, const MetalFragmentShaderUniforms& fragmentUniforms); + + struct { + u64 indexOffset = 0; + u64 modVolOffset = 0; + u64 vertexUniformOffset = 0; + u64 fragmentUniformOffset = 0; + u64 naomi2OpaqueOffset = 0; + u64 naomi2PunchThroughOffset = 0; + u64 naomi2TranslucentOffset = 0; + u64 naomi2ModVolOffset = 0; + u64 naomi2TrModVolOffset = 0; + u64 lightsOffset = (u64)-1; // Initialize to -1 to indicate unset + // Element count of the idx array UploadMainBuffer packed this frame; the + // bound every indexed draw is checked against (indexRangeValid). + u64 indexCount = 0; + } offsets; + id curMainBuffer = nil; + u32 currentBaseOffset = 0; + std::unique_ptr pipelineManager = nullptr; + bool dithering = false; + /// True when Draw() already bound the index-1 vertex buffer for the whole + /// frame, so DrawPoly must not re-bind it. Non-Naomi2 platforms only. + bool hoistedVertexBind = false; +}; + +class MetalScreenDrawer : public MetalDrawer +{ +public: + ~MetalScreenDrawer() override { + cleanupFramebuffers(); + } + void Init(MetalSamplers *samplers, MetalShaders *shaders, const MTLViewport& viewport); + void Term() override { + EndRenderPass(); + cleanupFramebuffers(); + frameRendered = false; + } + + void EndRenderPass() override; + bool PresentFrame() + { + EndRenderPass(); + if (!frameRendered) + return false; + frameRendered = false; + MetalContext::Instance()->PresentFrame(colorAttachment, viewport, aspectRatio); + + return true; + } + +protected: + id BeginRenderPass() override; + +private: + void cleanupFramebuffers() { + releaseReadbackTextures(); + releaseAttachments(); + } + // Hands the attachments to the command pool so they outlive any command + // buffer still drawing into them. + void releaseAttachments() { + if (commandPool != nullptr && (colorAttachment != nil || depthAttachment != nil)) + commandPool->addToFlight(new MetalDeleter(std::vector> { colorAttachment, depthAttachment })); + colorAttachment = nil; + depthAttachment = nil; + loadPassDescriptor = nil; + clearPassDescriptor = nil; + clearNeeded = true; + } + id colorAttachment = nil; + id depthAttachment = nil; + MTLRenderPassDescriptor *loadPassDescriptor = nil; + MTLRenderPassDescriptor *clearPassDescriptor = nil; + MTLViewport viewport {}; + bool clearNeeded = true; + bool frameRendered = false; + float aspectRatio = 0.f; + bool emulateFramebuffer = false; +}; + +class MetalTextureDrawer : public MetalDrawer +{ +public: + void Init(MetalSamplers *samplers, MetalShaders *shaders, MetalTextureCache *textureCache); + + void EndRenderPass() override; + +protected: + id BeginRenderPass() override; + +private: + u32 textureAddr = 0; + // RTT readback scratch. A member, not a per-call local: RTT-heavy scenes + // (Sonic Adventure reflections, DOA2 intro) run this path several times a + // frame, and a local meant a malloc/free per RTT. Grow-only, so it settles + // at the largest RTT seen. Render-thread only; fully overwritten by + // getBytes before WriteTextureToVRam reads it, so it carries no state. + PixelBuffer rttReadback; + + MetalTexture *texture = nullptr; + MTLRenderPassDescriptor *rttPassDescriptor = nil; + id colorAttachment; + id depthAttachment; + MetalTextureCache *textureCache = nullptr; +}; diff --git a/core/rend/metal/metal_drawer.mm b/core/rend/metal/metal_drawer.mm new file mode 100644 index 0000000000..a58fe069ef --- /dev/null +++ b/core/rend/metal/metal_drawer.mm @@ -0,0 +1,1187 @@ + /* + Copyright 2025 flyinghead + + This file is part of Flycast. + + Flycast is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 2 of the License, or + (at your option) any later version. + + Flycast is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with Flycast. If not, see . +*/ + +#include "metal_drawer.h" +#include "metal_texture_utils.h" +#include "rend/TexCache.h" +#include "hw/pvr/pvr_mem.h" +#include +#include +#include +#include +#include +#include +#include + +TileClipping MetalBaseDrawer::SetTileClip(id encoder, u32 val, MTLScissorRect& clipRect) { + // Since 31d5ddb92: tile clipping lives in TransformMatrix now + // (rend/tileclip.h is gone). Mirrors Vulkan BaseDrawer::SetTileClip. + Rect rect; + TileClipping clipMode = matrices.getTileClip(val, rect); + if (clipMode != TileClipping::Off) + { + clipRect.x = std::max(rect.origin.x, 0); + clipRect.y = std::max(rect.origin.y, 0); + clipRect.width = std::max(rect.size.x, 0); + clipRect.height = std::max(rect.size.y, 0); + } + if (clipMode == TileClipping::Outside) + SetScissor(encoder, clipRect); + else + SetScissor(encoder, baseScissor); + + return clipMode; +} + +void MetalBaseDrawer::SetBaseScissor(MTLViewport viewport) { + // Since 31d5ddb92 folded the widescreen / EmulateFramebuffer / + // RenderToTextureBuffer / tile-vs-fb clip decisions into + // TransformMatrix::getBaseScissor(), shared by every renderer; this is the + // Vulkan BaseDrawer::SetBaseScissor body plus the clamp to the render + // target that Metal validation requires (a scissor rect outside the + // attachment is a validation abort, and the hardware scaler can push the + // logical rect past the physical target, e.g. 2x vertical 480->960). + const Rect scissor = matrices.getBaseScissor(); + const NSUInteger maxWidth = (NSUInteger)std::max(viewport.width, 0.0); + const NSUInteger maxHeight = (NSUInteger)std::max(viewport.height, 0.0); + + baseScissor = MTLScissorRect(); + baseScissor.x = std::min((NSUInteger)std::max(scissor.origin.x, 0), maxWidth); + baseScissor.y = std::min((NSUInteger)std::max(scissor.origin.y, 0), maxHeight); + baseScissor.width = std::min((NSUInteger)std::max(scissor.size.x, 0), maxWidth - baseScissor.x); + baseScissor.height = std::min((NSUInteger)std::max(scissor.size.y, 0), maxHeight - baseScissor.y); + // Metal requires non-zero dimensions, and the rect must stay inside the target + baseScissor.width = std::max(baseScissor.width, (NSUInteger)1); + baseScissor.height = std::max(baseScissor.height, (NSUInteger)1); + if (maxWidth > 0 && baseScissor.x + baseScissor.width > maxWidth) + baseScissor.x = maxWidth - baseScissor.width; + if (maxHeight > 0 && baseScissor.y + baseScissor.height > maxHeight) + baseScissor.y = maxHeight - baseScissor.height; + + DEBUG_LOG(RENDERER, "SetBaseScissor: viewport %.0fx%.0f, base (%d,%d,%d,%d) -> clamped (%d,%d,%d,%d) vscale=%d hscale=%d", + viewport.width, viewport.height, + scissor.origin.x, scissor.origin.y, scissor.size.x, scissor.size.y, + (int)baseScissor.x, (int)baseScissor.y, (int)baseScissor.width, (int)baseScissor.height, + rendContext->scaler_ctl.vscalefactor, rendContext->scaler_ctl.hscale); +} + +// Issue `setter` only when the encoder was not already given this exact value. +#define MTL_SET_IF_CHANGED(have, cached, value, setter) \ + do { \ + if (!(have) || (cached) != (value)) { \ + setter; \ + (cached) = (value); \ + (have) = true; \ + } \ + } while (0) + +// A draw whose index range runs past the idx array UploadMainBuffer packed +// reads whatever follows it in the ring slice (the vertex/fragment uniforms) as +// indices (seen with Unreal Tournament). Without Metal validation that is an +// out-of-bounds GPU read: garbage geometry or a GPU fault. The cause is not +// known yet; this skips the draw and logs which site. Rate-limited: a bad frame +// can hit it for hundreds of polys. +bool MetalDrawer::indexRangeValid(u64 first, u64 count, const char *site) const +{ + if (first + count <= offsets.indexCount) + return true; + static std::atomic s_lastLogUs{0}; + static std::atomic s_suppressed{0}; + const u64 nowUs = (u64)std::chrono::duration_cast( + std::chrono::steady_clock::now().time_since_epoch()).count(); + u64 last = s_lastLogUs.load(std::memory_order_relaxed); + if (nowUs - last >= 2'000'000 && s_lastLogUs.compare_exchange_strong(last, nowUs)) + { + WARN_LOG(RENDERER, "Metal: skipped out-of-range draw at %s: first=%llu count=%llu idx=%llu " + "(op=%zu pt=%zu tr=%zu sorted=%zu modvol=%zu, %u more suppressed)", + site, (unsigned long long)first, (unsigned long long)count, + (unsigned long long)offsets.indexCount, + rendContext->global_param_op.size(), rendContext->global_param_pt.size(), + rendContext->global_param_tr.size(), rendContext->sortedTriangles.size(), + rendContext->global_param_mvo.size(), s_suppressed.exchange(0)); + } + else + { + s_suppressed.fetch_add(1, std::memory_order_relaxed); + } + return false; +} + +void MetalDrawer::DrawPoly(id encoder, u32 listType, bool sortTriangles, const PolyParam &poly, u32 first, u32 count) +{ + if (!indexRangeValid(first, count, listType == ListType_Opaque ? "op" + : listType == ListType_Punch_Through ? "pt" : "tr")) + return; + MTLScissorRect scissorRect {}; + TileClipping tileClip = SetTileClip(encoder, poly.tileclip, scissorRect); + + float trilinearAlpha = 1.0f; + if (poly.tsp.FilterMode > 1 && poly.pcw.Texture && listType != ListType_Punch_Through && poly.tcw.MipMapped == 1) + { + trilinearAlpha = 0.25f * (poly.tsp.MipMapD & 0x3); + if (poly.tsp.FilterMode == 2) + // Trilinear pass A + trilinearAlpha = 1.0f - trilinearAlpha; + } + int gpuPalette = poly.texture == nullptr || !poly.texture->gpuPalette ? 0 + : poly.tsp.FilterMode + 1; + float palette_index = 0.0f; + if (gpuPalette != 0) + { + if (config::TextureFiltering == 1) + gpuPalette = 1; + else if (config::TextureFiltering == 2) + gpuPalette = 2; + if (poly.tcw.PixelFmt == PixelPal4) + palette_index = float(poly.tcw.PalSelect << 4) / 1023.0f; + else + palette_index = float(poly.tcw.PalSelect >> 4 << 8) / 1023.0f; + } + + std::array pushConstants {}; + + if (tileClip == TileClipping::Inside || trilinearAlpha != 1.0f || gpuPalette != 0) + { + pushConstants = { + (float)scissorRect.x, + (float)scissorRect.y, + (float)scissorRect.x + (float)scissorRect.width, + (float)scissorRect.y + (float)scissorRect.height, + trilinearAlpha, + palette_index + }; + } else { + pushConstants = { 0, 0, 0, 0, 0, 0 }; + } + + MTL_SET_IF_CHANGED(drawState.havePushConstants, drawState.pushConstants, pushConstants, + [encoder setFragmentBytes:pushConstants.data() length:sizeof(pushConstants) atIndex:1]); + + bool shadowed = listType == ListType_Opaque || listType == ListType_Punch_Through; + + auto pipeline = pipelineManager->GetPipeline(listType, sortTriangles, poly, gpuPalette, dithering, true); + if (pipeline == nil) { + // Pipeline compile failed. Skip this draw + // rather than asserting on setRenderPipelineState(nil); the poly is dropped + // for this frame but the app stays alive. + return; + } + { + // nil doubles as "nothing cached yet" for the object slots — a real + // pipeline is never nil here, the nil case returned above. + bool havePipeline = drawState.pipeline != nil; + MTL_SET_IF_CHANGED(havePipeline, drawState.pipeline, pipeline, + [encoder setRenderPipelineState:pipeline]); + + id depthStencil = + pipelineManager->GetDepthStencilStates(listType, sortTriangles, shadowed, poly, true); + bool haveDepthStencil = drawState.depthStencil != nil; + MTL_SET_IF_CHANGED(haveDepthStencil, drawState.depthStencil, depthStencil, + [encoder setDepthStencilState:depthStencil]); + + const MTLCullMode cullMode = toMetalCullMode(poly.isp.CullMode); + MTL_SET_IF_CHANGED(drawState.haveCullMode, drawState.cullMode, cullMode, + [encoder setCullMode:cullMode]); + + if (shadowed) { + const u32 stencilRef = poly.pcw.Shadow != 0 ? 0x80u : 0u; + MTL_SET_IF_CHANGED(drawState.haveStencilRef, drawState.stencilRef, stencilRef, + [encoder setStencilReferenceValue:stencilRef]); + } + } + + + if (poly.texture != nullptr) { + id texture = ((MetalTexture *)poly.texture)->GetReadOnlyTexture(); + bool haveTexture = drawState.fragTexture != nil; + MTL_SET_IF_CHANGED(haveTexture, drawState.fragTexture, texture, + [encoder setFragmentTexture:texture atIndex:0]); + + // Texture sampler + id samplerState = samplers->GetSampler(poly, listType == ListType_Punch_Through, false, true); + if (samplerState == nil) { + ERROR_LOG(RENDERER, "GetSampler returned nil! poly.texture=%p, FilterMode=%d, ClampU=%d, ClampV=%d, listType=%d", + poly.texture, (int)poly.tsp.FilterMode, (int)poly.tsp.ClampU, (int)poly.tsp.ClampV, (int)listType); + // Skip binding nil sampler to prevent objc_msg_send crash + return; + } + bool haveSampler = drawState.fragSampler != nil; + MTL_SET_IF_CHANGED(haveSampler, drawState.fragSampler, samplerState, + [encoder setFragmentSamplerState:samplerState atIndex:0]); + } else if (poly.pcw.Texture) { + // Shader expects texture parameters but poly.texture is null + // This can happen in some edge cases - bind default texture and sampler + // Create a minimal 1x1 white texture as placeholder + static id defaultTexture = nil; + if (defaultTexture == nil) { + MTLTextureDescriptor* texDesc = [MTLTextureDescriptor texture2DDescriptorWithPixelFormat:MTLPixelFormatRGBA8Unorm + width:1 height:1 mipmapped:NO]; + defaultTexture = [MetalContext::Instance()->GetDevice() newTextureWithDescriptor:texDesc]; + uint32_t whitePixel = 0xFFFFFFFF; + [defaultTexture replaceRegion:MTLRegionMake2D(0, 0, 1, 1) mipmapLevel:0 withBytes:&whitePixel bytesPerRow:4]; + } + { + bool haveTexture = drawState.fragTexture != nil; + MTL_SET_IF_CHANGED(haveTexture, drawState.fragTexture, defaultTexture, + [encoder setFragmentTexture:defaultTexture atIndex:0]); + } + + TSP defaultTsp = {}; + id defaultSampler = samplers->GetSampler(defaultTsp); + if (defaultSampler == nil) { + ERROR_LOG(RENDERER, "GetSampler returned nil for default TSP!"); + return; + } + bool haveDefaultSampler = drawState.fragSampler != nil; + MTL_SET_IF_CHANGED(haveDefaultSampler, drawState.fragSampler, defaultSampler, + [encoder setFragmentSamplerState:defaultSampler atIndex:0]); + } + // Note: When poly.pcw.Texture is false, the shader is compiled without texture/sampler parameters, + // so we don't bind anything in that case to avoid Metal validation errors + + // Whether this poly still needs the index-1 (and, on Naomi2, index-2) + // vertex-buffer binds issued here. + // + // On a non-Naomi2 platform `offset` and `index` below both stay 0, so this + // block re-bound curMainBuffer at currentBaseOffset + 0 to index 1 with + // BYTE-IDENTICAL arguments for every textured polygon — thousands of ObjC + // message sends per frame, on every Dreamcast game, for a binding that + // never changes within a frame. Draw() now issues it once (see + // hoistedVertexBind) and this block is skipped. Naomi2 polys still come + // through: their offset really is per-polygon. + const bool skipVertexBind = hoistedVertexBind && !poly.isNaomi2(); + if ((poly.pcw.Texture || poly.isNaomi2()) && !skipVertexBind) + { + u64 offset = 0; + u32 index = 0; + if (poly.isNaomi2()) + { + switch (listType) + { + case ListType_Opaque: + offset = offsets.naomi2OpaqueOffset; + index = (u32)(&poly - &rendContext->global_param_op[0]); + // Bounds check to prevent invalid offsets + if (index >= rendContext->global_param_op.size()) { + WARN_LOG(RENDERER, "Invalid Naomi2 opaque poly index: %u >= %zu", index, rendContext->global_param_op.size()); + return; + } + break; + case ListType_Punch_Through: + offset = offsets.naomi2PunchThroughOffset; + index = (u32)(&poly - &rendContext->global_param_pt[0]); + // Bounds check to prevent invalid offsets + if (index >= rendContext->global_param_pt.size()) { + WARN_LOG(RENDERER, "Invalid Naomi2 punch-through poly index: %u >= %zu", index, rendContext->global_param_pt.size()); + return; + } + break; + case ListType_Translucent: + offset = offsets.naomi2TranslucentOffset; + index = (u32)(&poly - &rendContext->global_param_tr[0]); + // Bounds check to prevent invalid offsets + if (index >= rendContext->global_param_tr.size()) { + WARN_LOG(RENDERER, "Invalid Naomi2 translucent poly index: %u >= %zu", index, rendContext->global_param_tr.size()); + return; + } + break; + } + } + + // Stride must be a multiple of the constant-buffer alignment so each + // `base + index * size` binding stays aligned (256 on the Simulator). + size_t size = sizeof(MetalN2VertexShaderUniforms) + MetalBufferPacker::align(sizeof(MetalN2VertexShaderUniforms), kConstantBufferAlign); + u64 finalOffset = currentBaseOffset + offset + index * size; + // Bounds check for final offset to prevent buffer overflow + if (finalOffset >= [curMainBuffer length]) { + WARN_LOG(RENDERER, "Buffer offset out of bounds: %llu >= %lu", finalOffset, (unsigned long)[curMainBuffer length]); + return; + } + const DrawStateCache::BufferBinding n2Uniform { curMainBuffer, finalOffset }; + MTL_SET_IF_CHANGED(drawState.haveN2Uniform, drawState.n2Uniform, n2Uniform, + [encoder setVertexBuffer:n2Uniform.buffer offset:n2Uniform.offset atIndex:1]); + + if (offsets.lightsOffset != -1) { + size = sizeof(N2LightModel) + MetalBufferPacker::align(sizeof(N2LightModel), kConstantBufferAlign); + // Bounds check for lightModel to prevent buffer overflow + if (poly.lightModel >= 256) { // Reasonable upper bound for light models + WARN_LOG(RENDERER, "Invalid light model index: %u", poly.lightModel); + return; + } + u64 lightsOffset = currentBaseOffset + offsets.lightsOffset + poly.lightModel * size; + // Bounds check for final lights offset + if (lightsOffset >= [curMainBuffer length]) { + WARN_LOG(RENDERER, "Lights buffer offset out of bounds: %llu >= %lu", lightsOffset, (unsigned long)[curMainBuffer length]); + return; + } + const DrawStateCache::BufferBinding n2Lights { curMainBuffer, lightsOffset }; + MTL_SET_IF_CHANGED(drawState.haveN2Lights, drawState.n2Lights, n2Lights, + [encoder setVertexBuffer:n2Lights.buffer offset:n2Lights.offset atIndex:2]); + } + } + + MTLPrimitiveType primitive = sortTriangles && !config::PerStripSorting ? MTLPrimitiveTypeTriangle : MTLPrimitiveTypeTriangleStrip; + + [encoder drawIndexedPrimitives:primitive + indexCount:count + indexType:MTLIndexTypeUInt32 + indexBuffer:curMainBuffer + indexBufferOffset:currentBaseOffset + offsets.indexOffset + first * sizeof(u32)]; +} + +void MetalDrawer::DrawSorted(id encoder, const std::vector &polys, u32 first, u32 last, bool multipass) +{ + if (first == last) + return; + // A fresh encoder, or one another routine has just written state on, makes + // every cached value a lie. Reset at every entry point that draws — the + // cache is only ever valid within one uninterrupted run of DrawPoly calls. + drawState.invalidate(); + + + [encoder pushDebugGroup:@"DrawSorted"]; + + for (u32 idx = first; idx < last; idx++) + DrawPoly(encoder, ListType_Translucent, true, rendContext->global_param_tr[polys[idx].polyIndex], polys[idx].first, polys[idx].count); + if (multipass && config::TranslucentPolygonDepthMask) + { + // Write to the depth buffer now. The next render pass might need it. (Cosmic Smash) + for (u32 idx = first; idx < last; idx++) + { + const SortedTriangle& param = polys[idx]; + const PolyParam& polyParam = rendContext->global_param_tr[param.polyIndex]; + if (polyParam.isp.ZWriteDis) + continue; + // Defensive: never bind a nil pipeline (asserts/crashes). The format + // fix in CreateDepthPassPipeline keeps this non-nil; this guard means + // a future pipeline-build failure degrades (skips the depth write) + // instead of crashing. + id depthPipeline = pipelineManager->GetDepthPassPipeline(polyParam.isNaomi2()); + if (depthPipeline == nil) + continue; + [encoder setRenderPipelineState:depthPipeline]; + [encoder setDepthStencilState:pipelineManager->GetDepthPassDepthStencilStates(polyParam.isNaomi2())]; + + MTLScissorRect scissorRect {}; + SetTileClip(encoder, polyParam.tileclip, scissorRect); + + [encoder setCullMode:toMetalCullMode(polyParam.isp.CullMode)]; + + if (!indexRangeValid(param.first, param.count, "sorted-depth")) + continue; + [encoder drawIndexedPrimitives:MTLPrimitiveTypeTriangle + indexCount:param.count + indexType:MTLIndexTypeUInt32 + indexBuffer:curMainBuffer + indexBufferOffset:currentBaseOffset + offsets.indexOffset + param.first * sizeof(u32)]; + } + } + + [encoder popDebugGroup]; +} + +void MetalDrawer::DrawList(id encoder, u32 listType, bool sortTriangles, const std::vector &polys, u32 first, u32 last) +{ + if (first == last) + return; + + // A fresh encoder, or one another routine has just written state on, makes + // every cached value a lie. Reset at every entry point that draws — the + // cache is only ever valid within one uninterrupted run of DrawPoly calls. + drawState.invalidate(); + + [encoder pushDebugGroup:@"DrawList"]; + + const PolyParam *pp_end = polys.data() + last; + for (const PolyParam *pp = &polys[first]; pp != pp_end; pp++) + if (pp->count > 2) + DrawPoly(encoder, listType, sortTriangles, *pp, pp->first, pp->count); + + [encoder popDebugGroup]; +} + +void MetalDrawer::DrawModVols(id encoder, int first, int count) +{ + if (count == 0 || rendContext->modtrig.empty() || !config::ModifierVolumes) + return; + + // DrawModVols sets its own pipeline/depth-stencil on this encoder, so the + // next DrawList must not trust anything cached from before it. + drawState.invalidate(); + + [encoder pushDebugGroup:@"DrawModVols"]; + [encoder setVertexBufferOffset:currentBaseOffset + offsets.modVolOffset atIndex:30]; + + ModifierVolumeParam* params = &rendContext->global_param_mvo[first]; + + int mod_base = -1; + id state; + id depth_state; + + // The tile clip fields are refreshed per volume below (Inside mode is a shader discard). + MetalModVolPushBlock pushBlock; + pushBlock.shaderColor = 1 - FPU_SHAD_SCALE.scale_factor / 256.f; + [encoder setFragmentBytes:&pushBlock length:sizeof(pushBlock) atIndex:1]; + + for (int cmv = 0; cmv < count; cmv++) { + ModifierVolumeParam& param = params[cmv]; + + if (param.count == 0) + continue; + + if (param.isNaomi2()) + [encoder setVertexBuffer:curMainBuffer offset:currentBaseOffset + offsets.naomi2ModVolOffset + + (first + cmv) * (sizeof(MetalN2VertexShaderUniforms) + + MetalBufferPacker::align(sizeof(MetalN2VertexShaderUniforms), kConstantBufferAlign)) atIndex:1]; + + u32 mv_mode = param.isp.DepthMode; + + if (mod_base == -1) + mod_base = param.first; + + if (!param.isp.VolumeLast && mv_mode > 0) { + state = pipelineManager->GetModifierVolumePipeline(ModVolMode::Or, param.isNaomi2()); // OR'ing (open volume or quad) + depth_state = pipelineManager->GetModVolDepthStencilStates(ModVolMode::Or, param.isNaomi2()); + } else { + state = pipelineManager->GetModifierVolumePipeline(ModVolMode::Xor, param.isNaomi2()); // XOR'ing (closed volume) + depth_state = pipelineManager->GetModVolDepthStencilStates(ModVolMode::Xor, param.isNaomi2()); + } + + // Skip if the modvol pipeline failed to compile (Simulator compiler crash) + // rather than asserting on setRenderPipelineState(nil). + if (state == nil) + continue; + [encoder setRenderPipelineState:state]; + [encoder setDepthStencilState:depth_state]; + [encoder setCullMode:toMetalCullMode(param.isp.CullMode)]; + [encoder setStencilReferenceValue:2]; + MTLScissorRect scissorRect {}; + TileClipping clipMode = SetTileClip(encoder, param.tileclip, scissorRect); + if (pushBlock.setTileClip(clipMode, scissorRect)) + [encoder setFragmentBytes:&pushBlock length:sizeof(pushBlock) atIndex:1]; + + [encoder drawPrimitives:MTLPrimitiveTypeTriangle + vertexStart:param.first * 3 + vertexCount:param.count * 3]; + + if (mv_mode == 1 || mv_mode == 2) + { + // Sum the area + state = pipelineManager->GetModifierVolumePipeline(mv_mode == 1 ? ModVolMode::Inclusion : ModVolMode::Exclusion, param.isNaomi2()); + depth_state = pipelineManager->GetModVolDepthStencilStates(mv_mode == 1 ? ModVolMode::Inclusion : ModVolMode::Exclusion, param.isNaomi2()); + if (state != nil) { + [encoder setRenderPipelineState:state]; + [encoder setDepthStencilState:depth_state]; + [encoder setCullMode:toMetalCullMode(param.isp.CullMode)]; + [encoder setStencilReferenceValue:1]; + [encoder drawPrimitives:MTLPrimitiveTypeTriangle + vertexStart: mod_base * 3 + vertexCount: (param.first + param.count - mod_base) * 3]; + } + mod_base = -1; + } + } + [encoder setVertexBufferOffset:currentBaseOffset atIndex:30]; + + // Reset the tile clip before the screen-covering Final quad (Vulkan does + // SetTileClip(0) here) — otherwise the last volume's Outside tile clip + // leaves a stale scissor that crops the shadow/light darkening pass. + MTLScissorRect fullScissor {}; + SetTileClip(encoder, 0, fullScissor); + if (pushBlock.setTileClip(TileClipping::Off, fullScissor)) + [encoder setFragmentBytes:&pushBlock length:sizeof(pushBlock) atIndex:1]; + + state = pipelineManager->GetModifierVolumePipeline(ModVolMode::Final, false); + depth_state = pipelineManager->GetModVolDepthStencilStates(ModVolMode::Final, false); + // Skip the final modvol pass if its pipeline failed to compile (Simulator + // compiler crash) — but still balance the debug group below. + if (state != nil && indexRangeValid(0, 4, "modvol-final")) { + [encoder setRenderPipelineState:state]; + [encoder setDepthStencilState:depth_state]; + [encoder setCullMode:toMetalCullMode(0)]; + [encoder setStencilReferenceValue:0x81]; + [encoder drawIndexedPrimitives:MTLPrimitiveTypeTriangleStrip + indexCount:4 + indexType:MTLIndexTypeUInt32 + indexBuffer:curMainBuffer + indexBufferOffset:currentBaseOffset + offsets.indexOffset]; + } + + [encoder popDebugGroup]; +} + +void MetalDrawer::UploadMainBuffer(const MetalVertexShaderUniforms &vertexUniforms, const MetalFragmentShaderUniforms &fragmentUniforms) { + MetalBufferPacker packer; + + // Vertex + packer.add(rendContext->verts.data(), rendContext->verts.size() * sizeof(decltype(*rendContext->verts.data()))); + // Modifier Volumes + offsets.modVolOffset = packer.add(rendContext->modtrig.data(), rendContext->modtrig.size() * sizeof(decltype(*rendContext->modtrig.data()))); + // Index + offsets.indexOffset = packer.add(rendContext->idx.data(), rendContext->idx.size() * sizeof(decltype(*rendContext->idx.data()))); + offsets.indexCount = rendContext->idx.size(); + // Uniform buffers + offsets.vertexUniformOffset = packer.addUniform(&vertexUniforms, sizeof(vertexUniforms)); + offsets.fragmentUniformOffset = packer.addUniform(&fragmentUniforms, sizeof(fragmentUniforms)); + + std::vector n2uniforms; + if (settings.platform.isNaomi2()) + { + packNaomi2Uniforms(packer, offsets, n2uniforms, false); + offsets.lightsOffset = packNaomi2Lights(packer); + } + + // Each upload stays exclusive until the command pool retires its GPU work. + verify(packer.size() <= std::numeric_limits::max()); + MetalBufferData *upload = GetMainBuffer((u32)packer.size()); + verify(upload->buffer != nil); + packer.upload(*upload); + currentBaseOffset = 0; + curMainBuffer = upload->buffer; +} + +bool MetalDrawer::Draw(const MetalTexture *fogTexture, const MetalTexture *paletteTexture) { + MetalFragmentShaderUniforms fragUniforms = MakeFragmentUniforms(); + // Only non-Naomi2 content has a frame-constant index-1 binding to hoist. + // Keyed on the PLATFORM, matching UploadMainBuffer's own gate on + // packNaomi2Uniforms -- if that did not run, the naomi2*Offset fields are + // meaningless and DrawPoly must not be short-circuited on them. + hoistedVertexBind = !settings.platform.isNaomi2(); + dithering = config::EmulateFramebuffer && rendContext->fb_W_CTRL.fb_dither && rendContext->fb_W_CTRL.fb_packmode <= 3; + if (dithering) { + switch (rendContext->fb_W_CTRL.fb_packmode) + { + case 0: // 0555 KRGB 16 bit + case 3: // 1555 ARGB 16 bit + fragUniforms.ditherDivisor[0] = fragUniforms.ditherDivisor[1] = fragUniforms.ditherDivisor[2] = 2.f; + break; + case 1: // 565 RGB 16 bit + fragUniforms.ditherDivisor[0] = fragUniforms.ditherDivisor[2] = 2.f; + fragUniforms.ditherDivisor[1] = 4.f; + break; + case 2: // 4444 ARGB 16 bit + fragUniforms.ditherDivisor[0] = fragUniforms.ditherDivisor[1] = fragUniforms.ditherDivisor[2] = 1.f; + break; + default: + break; + } + fragUniforms.ditherDivisor[3] = 1.f; + } + + currentScissor = MTLScissorRect {}; + + @autoreleasepool { + id renderEncoder = BeginRenderPass(); + + [renderEncoder setFragmentTexture:fogTexture->GetTexture() atIndex:2]; + [renderEncoder setFragmentTexture:paletteTexture->GetTexture() atIndex:3]; + + // Fog sampler + TSP fogTsp = {}; + fogTsp.FilterMode = 1; + fogTsp.ClampU = 1; + fogTsp.ClampV = 1; + id fogSampler = samplers->GetSampler(fogTsp); + if (fogSampler == nil) { + ERROR_LOG(RENDERER, "GetSampler returned nil for fog TSP!"); + return false; + } + [renderEncoder setFragmentSamplerState:fogSampler atIndex:2]; + + // Palette sampler + TSP palTsp = {}; + palTsp.FilterMode = 0; + palTsp.ClampU = 1; + palTsp.ClampV = 1; + id paletteSampler = samplers->GetSampler(palTsp); + if (paletteSampler == nil) { + ERROR_LOG(RENDERER, "GetSampler returned nil for palette TSP!"); + return false; + } + [renderEncoder setFragmentSamplerState:paletteSampler atIndex:3]; + + setFirstProvokingVertex(*rendContext); + + // Upload vertex and index buffers + MetalVertexShaderUniforms vtxUniforms {}; + vtxUniforms.ndcMat = matrices.GetNormalMatrix(); + + [renderEncoder setFrontFacingWinding:MTLWindingCounterClockwise]; + + UploadMainBuffer(vtxUniforms, fragUniforms); + + [renderEncoder setVertexBuffer:curMainBuffer offset:currentBaseOffset + 0 atIndex:30]; + [renderEncoder setVertexBuffer:curMainBuffer offset:currentBaseOffset + offsets.vertexUniformOffset atIndex:0]; + if (hoistedVertexBind) { + // The per-textured-poly index-1 bind, lifted out of DrawPoly. On a + // non-Naomi2 platform its arguments are exactly these, every time. + // This is the only encoder in the frame (BeginRenderPass runs once + // above; every render pass below reuses it) and nothing else in + // this drawer binds vertex index 1, so one bind covers the frame. + // + // Difference from the old code, stated rather than buried: index 1 + // is now bound even in a frame containing zero textured polys. A + // buffer no shader reads is inert. + [renderEncoder setVertexBuffer:curMainBuffer offset:currentBaseOffset + 0 atIndex:1]; + } + [renderEncoder setFragmentBuffer:curMainBuffer offset:currentBaseOffset + offsets.fragmentUniformOffset atIndex:0]; + + RenderPass previous_pass {}; + for (int render_pass = 0; render_pass < (int)rendContext->render_passes.size(); render_pass++) { + const RenderPass& current_pass = rendContext->render_passes[render_pass]; + + DEBUG_LOG(RENDERER, "Render pass %d OP %d PT %d TR %d MV %d autosort %d", render_pass + 1, + current_pass.op_count - previous_pass.op_count, + current_pass.pt_count - previous_pass.pt_count, + current_pass.tr_count - previous_pass.tr_count, + current_pass.mvo_count - previous_pass.mvo_count, current_pass.autosort); + DrawList(renderEncoder, ListType_Opaque, false, rendContext->global_param_op, previous_pass.op_count, current_pass.op_count); + DrawList(renderEncoder, ListType_Punch_Through, false, rendContext->global_param_pt, previous_pass.pt_count, current_pass.pt_count); + DrawModVols(renderEncoder, previous_pass.mvo_count, current_pass.mvo_count - previous_pass.mvo_count); + if (current_pass.autosort) { + if (!config::PerStripSorting) + DrawSorted(renderEncoder, rendContext->sortedTriangles, previous_pass.sorted_tr_count, current_pass.sorted_tr_count, render_pass + 1 < (int)rendContext->render_passes.size()); + else + DrawList(renderEncoder, ListType_Translucent, true, rendContext->global_param_tr, previous_pass.tr_count, current_pass.tr_count); + } else { + DrawList(renderEncoder, ListType_Translucent, false, rendContext->global_param_tr, previous_pass.tr_count, current_pass.tr_count); + } + previous_pass = current_pass; + } + } + + curMainBuffer = nil; + + return !rendContext->isRTT; +} + +void MetalTextureDrawer::Init(MetalSamplers *samplers, MetalShaders *shaders, MetalTextureCache *textureCache) +{ + MetalDrawer::Init(samplers, MetalPipelineManager(shaders)); + + this->textureCache = textureCache; + + rttPassDescriptor = [[MTLRenderPassDescriptor alloc] init]; +} + +id MetalTextureDrawer::BeginRenderPass() { + DEBUG_LOG(RENDERER, "RenderToTexture packmode=%d stride=%d - %d x %d @ %06x", rendContext->fb_W_CTRL.fb_packmode, rendContext->fb_W_LINESTRIDE * 8, + rendContext->fbClip.size.x, rendContext->fbClip.size.y, rendContext->fb_W_SOF1 & VRAM_MASK); + + textureAddr = rendContext->fb_W_SOF1 & VRAM_MASK; + // Since 31d5ddb92: the render target is exactly the framebuffer size + // Renderer_if already computed for this context (getScaledFramebufferSize: + // pow2 of the tile/fb clip, upscaled, when rendering into the texture + // cache; the raw tile-clip size, scaler-adjusted, when writing back to + // VRAM). The old getFramebufferWidth/getRenderToTextureDimensions helpers + // are gone; mirrors Vulkan TextureDrawer::BeginRenderPass. + u32 width = rendContext->framebufferWidth; + u32 height = rendContext->framebufferHeight; + + // Validate dimensions to prevent crashes with extreme values + if (width == 0 || height == 0 || width > 16384 || height > 16384) { + ERROR_LOG(RENDERER, "Invalid RTT dimensions: %dx%d, falling back to safe values", width, height); + width = std::max(8u, std::min(width, 1024u)); + height = std::max(8u, std::min(height, 1024u)); + DEBUG_LOG(RENDERER, "RTT Fallback dimensions: %dx%d", width, height); + } + matrices.CalcMatrices(rendContext, width, height); + DEBUG_LOG(RENDERER, "RTT Dimensions: %dx%d", width, height); + + id commandBuffer = commandPool->Allocate(); + + if (!depthAttachment || width > depthAttachment.width || height > depthAttachment.height) + { + DEBUG_LOG(RENDERER, "Creating new depth attachment: %dx%d", width, height); + MTLTextureDescriptor *depthDescriptor = [[MTLTextureDescriptor alloc] init]; + depthDescriptor.width = width; + depthDescriptor.height = height; + depthDescriptor.pixelFormat = MTLPixelFormatDepth32Float_Stencil8; + depthDescriptor.usage = MTLTextureUsageRenderTarget; + // Simulate shared memory on Apple Silicon + // but not simulator, where we can't use shared memory +#if (TARGET_OS_IOS || TARGET_OS_TV) && !TARGET_OS_SIMULATOR + depthDescriptor.storageMode = MTLStorageModeShared; +#else + depthDescriptor.storageMode = MTLStorageModePrivate; +#endif + + depthAttachment = [MetalContext::Instance()->GetDevice() newTextureWithDescriptor:depthDescriptor]; + [depthAttachment setLabel:@"Rtt Depth Attachment"]; + } else { + DEBUG_LOG(RENDERER, "Reusing existing depth attachment: %dx%d", (int)depthAttachment.width, (int)depthAttachment.height); + } + + id colorImage; + + // Branch orientation matches Vulkan (drawer.cpp:511): the DEFAULT config + // (RenderToTextureBuffer=false) renders straight into the texture-cache + // texture the game will sample; readback mode renders into a scratch + // attachment and writes the pixels back to emulated VRAM at EndRenderPass. + // This was inverted: the default path rendered into the scratch that + // nothing reads, so every render-to-texture effect sampled STALE VRAM — + // THPS2/Mat Hoffman's RTT blob shadow showed the font atlas ("shadow too + // dark and too big" with garbled glyphs). + if (!config::RenderToTextureBuffer) + { + // Texture-cache key: the unscaled pow2 PVR framebuffer size (upstream + // getPvrFramebufferSize), not the upscaled render-target size. + int wpo2, hpo2; + getPvrFramebufferSize(*rendContext, wpo2, hpo2); + texture = textureCache->getRTTexture(textureAddr, rendContext->fb_W_CTRL.fb_packmode, wpo2, hpo2); + if (textureCache->IsInFlight(texture, false)) + { + texture->CreateReadOnlyCopy(commandBuffer); + texture->deferDeleteResource(commandPool); + } + textureCache->SetInFlight(texture); + + // Check if we need to recreate the texture. Usage matters too: the + // cache entry may hold a texture decoded by the regular upload path + // (ShaderRead only) — binding that as a render-pass color attachment + // is a Metal validation abort. + bool needsRecreation = !texture->GetTexture() || + texture->GetTexture().width != width || + texture->GetTexture().height != height || + !(texture->GetTexture().usage & MTLTextureUsageRenderTarget); + + if (needsRecreation) + { + DEBUG_LOG(RENDERER, "Creating RTT texture: %dx%d", width, height); + MTLTextureDescriptor *colorDescriptor = [[MTLTextureDescriptor alloc] init]; + colorDescriptor.width = width; + colorDescriptor.height = height; + colorDescriptor.pixelFormat = MTLPixelFormatBGRA8Unorm; + colorDescriptor.usage = MTLTextureUsageRenderTarget | MTLTextureUsageShaderRead; + // CPU-visible storage must be managed on Intel/AMD GPUs. + colorDescriptor.storageMode = metalCpuTextureStorageMode(MetalContext::Instance()->GetDevice()); + + id newTexture = [MetalContext::Instance()->GetDevice() newTextureWithDescriptor:colorDescriptor]; + [newTexture setLabel:@"Rtt Color Attachment"]; + texture->SetTexture(newTexture, width, height); + } else { + DEBUG_LOG(RENDERER, "Reusing existing RTT texture: %dx%d", (int)texture->GetTexture().width, (int)texture->GetTexture().height); + } + colorImage = texture->GetTexture(); + } + else + { + if (!colorAttachment || width > colorAttachment.width || height > colorAttachment.height) + { + DEBUG_LOG(RENDERER, "Creating new color attachment: %dx%d", width, height); + MTLTextureDescriptor *colorDescriptor = [[MTLTextureDescriptor alloc] init]; + colorDescriptor.width = width; + colorDescriptor.height = height; + colorDescriptor.pixelFormat = MTLPixelFormatBGRA8Unorm; + colorDescriptor.usage = MTLTextureUsageRenderTarget; + // Readback requires CPU-visible storage on every GPU family. + colorDescriptor.storageMode = metalCpuTextureStorageMode(MetalContext::Instance()->GetDevice()); + colorAttachment = [MetalContext::Instance()->GetDevice() newTextureWithDescriptor:colorDescriptor]; + [colorAttachment setLabel:@"Rtt Color Attachment"]; + } else { + DEBUG_LOG(RENDERER, "Reusing existing color attachment: %dx%d", (int)colorAttachment.width, (int)colorAttachment.height); + } + colorImage = colorAttachment; + } + + auto colorAttachmentDesc = rttPassDescriptor.colorAttachments[0]; + [colorAttachmentDesc setTexture:colorImage]; + [colorAttachmentDesc setLoadAction:MTLLoadActionClear]; + [colorAttachmentDesc setStoreAction:MTLStoreActionStore]; + [colorAttachmentDesc setClearColor:MTLClearColorMake(0.0, 0.0, 0.0, 1.0)]; + + auto depthAttachmentDesc = rttPassDescriptor.depthAttachment; + [depthAttachmentDesc setTexture:depthAttachment]; + [depthAttachmentDesc setLoadAction:MTLLoadActionClear]; + [depthAttachmentDesc setStoreAction:MTLStoreActionDontCare]; + [depthAttachmentDesc setClearDepth:0.0]; + + auto stencilAttachmentDesc = rttPassDescriptor.stencilAttachment; + [stencilAttachmentDesc setTexture:depthAttachment]; + [stencilAttachmentDesc setLoadAction:MTLLoadActionClear]; + [stencilAttachmentDesc setStoreAction:MTLStoreActionDontCare]; + [stencilAttachmentDesc setClearStencil:0]; + + currentEncoder = [commandBuffer renderCommandEncoderWithDescriptor:rttPassDescriptor]; + [currentEncoder pushDebugGroup:@"RenderToTexture"]; + + // Log actual render target dimensions from the encoder + DEBUG_LOG(RENDERER, "ACTUAL render target dimensions: color=%dx%d, depth=%dx%d", + (int)colorImage.width, (int)colorImage.height, + (int)depthAttachment.width, (int)depthAttachment.height); + + // Viewport is the logical target (width x height, what CalcMatrices was + // given) — the readback attachment is grow-only and may be larger. The + // base scissor comes from TransformMatrix::getBaseScissor() (tile clip, or + // tile ∩ fb clip when rendering into the texture cache), clamped to the + // viewport. Same as Vulkan TextureDrawer::BeginRenderPass after 31d5ddb92. + MTLViewport viewport = { + 0.0, + 0.0, + (double)width, + (double)height, + 1.0, + 0.0 + }; + [currentEncoder setViewport:viewport]; + SetBaseScissor(viewport); + DEBUG_LOG(RENDERER, "RTT Viewport: %.0fx%.0f baseScissor (%d,%d,%d,%d)", viewport.width, viewport.height, + (int)baseScissor.x, (int)baseScissor.y, (int)baseScissor.width, (int)baseScissor.height); + SetScissor(currentEncoder, baseScissor); + + return currentEncoder; +} + +void MetalTextureDrawer::EndRenderPass() +{ + [currentEncoder popDebugGroup]; + [currentEncoder endEncoding]; + currentEncoder = nil; + + // Readback covers the whole (scaler-adjusted) framebuffer; WriteTextureToVRam + // applies fbClip itself now (31d5ddb92). + u32 fbw = rendContext->framebufferWidth; + u32 fbh = rendContext->framebufferHeight; + + if (config::RenderToTextureBuffer) + { + // Managed textures need their GPU contents synchronized before CPU reads. + metalSynchronizeTextureForCpu(commandPool->Allocate(), colorAttachment); + commandPool->EndFrameAndWait(); + + id srcTexture = colorAttachment; + if (!srcTexture) { + ERROR_LOG(RENDERER, "RTT readback failed: no source texture"); + MetalDrawer::EndRenderPass(); + return; + } + + // Never read past the attachment (the dimension fallback above can shrink it). + fbw = std::min(fbw, (u32)srcTexture.width); + fbh = std::min(fbh, (u32)srcTexture.height); + const u32 rowBytes = fbw * 4; // BGRA8 + rttReadback.init(fbw, fbh); + [srcTexture getBytes:rttReadback.data() + bytesPerRow:rowBytes + fromRegion:MTLRegionMake2D(0, 0, fbw, fbh) + mipmapLevel:0]; + + // CPU-side convert and write back to VRAM in the Dreamcast format + u16 *dst = (u16 *)&vram[textureAddr]; + // Metal render targets are BGRA8; WriteTextureToVRam packs from RGBA byte order + // (what the Vulkan/GL readbacks hand it). Without the swap red and blue trade + // places in VRAM — a tint for ordinary RTT, but fatal for games that re-read the + // 565 target as 4444, where the alpha nibble IS red's top bits (THPS2's skater + // shadow: cyan background 08ffff -> 0x0FFF -> alpha 0; swapped -> 0xFFE1 -> + // opaque yellow, the whole floor darkened and no blob). + { + u8 *px = (u8 *)rttReadback.data(); + for (u32 i = 0, n = fbw * fbh; i < n; i++, px += 4) + std::swap(px[0], px[2]); + } + // Unlock and invalidate the texture-cache pages this writeback covers BEFORE + // writing. Two reasons: + // - Left to the write itself, every locked page raises a protection fault that + // the core's signal handler resolves. That is invisible on a device, but with + // a debugger attached it stops as EXC_BAD_ACCESS in TexPixelWriter::write. + // - A texture that re-reads the render target in another pixel format must + // decode it again (THPS2 renders its shadow in 565 and samples it as 4444, so + // alpha = red's top bits; a stale decode is an opaque decal that darkens the + // whole floor with no blob). + { + const u32 lineBytes = std::max(rendContext->fb_W_LINESTRIDE * 8, fbw * 2); + const u32 bytes = std::max(fbh, 1u) * lineBytes; + const u32 start = textureAddr & VRAM_MASK; + for (u32 off = start & ~(PAGE_SIZE - 1); off < start + bytes && off < VRAM_SIZE; off += PAGE_SIZE) + VramLockedWriteOffset(off); + } + WriteTextureToVRam(fbw, fbh, (u8 *)rttReadback.data(), dst, rendContext->fb_W_CTRL, rendContext->fb_W_LINESTRIDE * 8, rendContext->fbClip); + } + else + { + commandPool->EndFrame(); + if (texture) { + texture->dirty = 0; + texture->unprotectVRam(); + } + } + + MetalDrawer::EndRenderPass(); +} + +void MetalScreenDrawer::Init(MetalSamplers *samplers, MetalShaders *shaders, const MTLViewport &viewport) { + emulateFramebuffer = config::EmulateFramebuffer; + this->shaderManager = shaders; + + // Validate viewport dimensions + if (viewport.width <= 0 || viewport.height <= 0 || viewport.width > 16384 || viewport.height > 16384) { + WARN_LOG(RENDERER, "Invalid viewport dimensions: %.0fx%.0f, skipping initialization", viewport.width, viewport.height); + return; + } + + bool dimensionsChanged = this->viewport.height != viewport.height || + this->viewport.width != viewport.width || + this->viewport.originX != viewport.originX || + this->viewport.originY != viewport.originY || + this->viewport.zfar != viewport.zfar || + this->viewport.znear != viewport.znear; + + if (dimensionsChanged) { + DEBUG_LOG(RENDERER, "MetalScreenDrawer dimension change: %.0fx%.0f -> %.0fx%.0f", + this->viewport.width, this->viewport.height, viewport.width, viewport.height); + + releaseAttachments(); + } + this->viewport = viewport; + + if (depthAttachment == nil) + { + MTLTextureDescriptor *descriptor = [[MTLTextureDescriptor alloc] init]; + descriptor.width = (NSUInteger)viewport.width; + descriptor.height = (NSUInteger)viewport.height; + descriptor.pixelFormat = MTLPixelFormatDepth32Float_Stencil8; + descriptor.usage = MTLTextureUsageRenderTarget | MTLTextureUsageShaderRead; +#if (TARGET_OS_IOS || TARGET_OS_TV) && !TARGET_OS_SIMULATOR + descriptor.storageMode = MTLStorageModeShared; +#else + descriptor.storageMode = MTLStorageModePrivate; +#endif + depthAttachment = [MetalContext::Instance()->GetDevice() newTextureWithDescriptor:descriptor]; + [depthAttachment setLabel:@"Screen Depth Attachment"]; + } + + if (colorAttachment == nil) + { + MTLTextureDescriptor *texDescriptor = [[MTLTextureDescriptor alloc] init]; + texDescriptor.width = viewport.width; + texDescriptor.height = viewport.height; + texDescriptor.pixelFormat = MTLPixelFormatBGRA8Unorm; + texDescriptor.usage = MTLTextureUsageRenderTarget | MTLTextureUsageShaderRead; + + colorAttachment = [MetalContext::Instance()->GetDevice() newTextureWithDescriptor:texDescriptor]; + [colorAttachment setLabel:@"Screen Color Attachment"]; + + loadPassDescriptor = [[MTLRenderPassDescriptor alloc] init]; + auto depth = loadPassDescriptor.depthAttachment; + [depth setTexture:depthAttachment]; + [depth setLoadAction:MTLLoadActionClear]; + [depth setStoreAction:MTLStoreActionDontCare]; + // Reversed log depth: greater = closer, so "empty" must clear to + // 0.0 (farthest), matching Vulkan's ClearDepthStencilValue{0,0} + // (drawer.cpp:571) and the RTT descriptor above. Metal's default + // clearDepth is 1.0 = nearest, which fails every Greater/GEqual + // test on pixels the background plane doesn't cover. + [depth setClearDepth:0.0]; + + auto stencil = loadPassDescriptor.stencilAttachment; + [stencil setTexture:depthAttachment]; + [stencil setLoadAction:MTLLoadActionClear]; + [stencil setStoreAction:MTLStoreActionDontCare]; + [stencil setClearStencil:0]; + + auto color = loadPassDescriptor.colorAttachments[0]; + [color setTexture:colorAttachment]; + [color setLoadAction:MTLLoadActionLoad]; + [color setStoreAction:MTLStoreActionStore]; + + clearPassDescriptor = [loadPassDescriptor copy]; + [clearPassDescriptor.colorAttachments[0] setLoadAction:MTLLoadActionClear]; + clearNeeded = true; + } + frameRendered = false; + + MetalDrawer::Init(samplers, MetalPipelineManager(shaderManager)); +} + +id MetalScreenDrawer::BeginRenderPass() { + DEBUG_LOG(RENDERER, "=== SCREEN DRAWER BeginRenderPass ==="); + + if (!renderPassStarted) + { + frameRendered = false; + id commandBuffer = commandPool->Allocate(); + MTLRenderPassDescriptor* passDescriptor = clearNeeded || rendContext->clearFramebuffer ? clearPassDescriptor : loadPassDescriptor; + clearNeeded = false; + currentEncoder = [commandBuffer renderCommandEncoderWithDescriptor:passDescriptor]; + currentScissor = MTLScissorRect {}; + renderPassStarted = true; + + DEBUG_LOG(RENDERER, "Screen render pass started"); + } + + [currentEncoder setViewport:viewport]; + DEBUG_LOG(RENDERER, "Screen viewport set: %.0fx%.0f at (%.0f,%.0f)", viewport.width, viewport.height, viewport.originX, viewport.originY); + + matrices.CalcMatrices(rendContext, viewport.width, viewport.height); + + SetBaseScissor(viewport); + DEBUG_LOG(RENDERER, "Screen baseScissor calculated: (%d,%d,%d,%d)", + (int)baseScissor.x, (int)baseScissor.y, (int)baseScissor.width, (int)baseScissor.height); + + DEBUG_LOG(RENDERER, "About to call SetScissor with baseScissor"); + SetScissor(currentEncoder, baseScissor); + DEBUG_LOG(RENDERER, "SetScissor completed"); + + return currentEncoder; +} + +void MetalBaseDrawer::scaleAndWriteFramebuffer(id finalTexture) +{ + u32 width = rendContext->globClip.x; + u32 height = rendContext->globClip.y; + // Since 31d5ddb92: the scaler (SCALER_CTL) target size and the final + // VRAM clip (tile clip scaled, intersected with the fb clip) are computed + // once in getWriteFBToVramParams for every renderer. + glm::ivec2 scaledSize; + Rect finalClip; + getWriteFBToVramParams(*rendContext, scaledSize, finalClip); + + id scaledTexture = nil; + + // Scale the framebuffer if needed + if (scaledSize.x != (int)width || scaledSize.y != (int)height) + { + const u32 scaledW = scaledSize.x; + const u32 scaledH = scaledSize.y; + + if (cachedScaledTexture == nil || cachedScaledWidth != scaledW || cachedScaledHeight != scaledH) + { + MTLTextureDescriptor *texDesc = [MTLTextureDescriptor texture2DDescriptorWithPixelFormat:MTLPixelFormatBGRA8Unorm + width:scaledW + height:scaledH + mipmapped:NO]; + texDesc.usage = MTLTextureUsageShaderRead | MTLTextureUsageRenderTarget; + texDesc.storageMode = MTLStorageModePrivate; + cachedScaledTexture = [MetalContext::Instance()->GetDevice() newTextureWithDescriptor:texDesc]; + cachedScaledWidth = scaledW; + cachedScaledHeight = scaledH; + } + scaledTexture = cachedScaledTexture; + + id commandBuffer = commandPool->Allocate(); + MTLRenderPassDescriptor *pass = [MTLRenderPassDescriptor renderPassDescriptor]; + pass.colorAttachments[0].texture = scaledTexture; + pass.colorAttachments[0].loadAction = MTLLoadActionDontCare; + pass.colorAttachments[0].storeAction = MTLStoreActionStore; + id encoder = [commandBuffer renderCommandEncoderWithDescriptor:pass]; + scalePipeline.Init(shaderManager); + scaleDrawer.Init(&scalePipeline); + const float u = std::min(width, (u32)finalTexture.width) / (float)finalTexture.width; + const float v = std::min(height, (u32)finalTexture.height) / (float)finalTexture.height; + MetalQuadVertex vertices[4] { + { -1, -1, 0, 0, v }, { 1, -1, 0, u, v }, + { -1, 1, 0, 0, 0 }, { 1, 1, 0, u, 0 } + }; + [encoder setViewport:MTLViewport { 0, 0, (double)scaledW, (double)scaledH, 0, 1 }]; + if (scalePipeline.BindPipeline(encoder)) + scaleDrawer.Draw(encoder, finalTexture, vertices, false); + [encoder endEncoding]; + + finalTexture = scaledTexture; + width = scaledW; + height = scaledH; + } + + // Readback target (BGRA to match framebuffer format). Cached across frames: + // EndFrameAndWait() below is the sync point, so last frame's copy is + // complete before this frame's blit writes into it again. + if (cachedReadableTexture == nil || cachedReadableWidth != width || cachedReadableHeight != height) + { + MTLTextureDescriptor *readableDesc = [MTLTextureDescriptor texture2DDescriptorWithPixelFormat:MTLPixelFormatBGRA8Unorm + width:width + height:height + mipmapped:NO]; + readableDesc.usage = MTLTextureUsageShaderRead; +#if TARGET_OS_IOS || TARGET_OS_TV + // iOS/tvOS: Use shared memory (unified memory architecture) + readableDesc.storageMode = MTLStorageModeShared; +#else + // macOS: Use managed memory for CPU readback + // TODO: MacOS Can use shared memory on Apple silcon, but must detect first + readableDesc.storageMode = MTLStorageModeManaged; +#endif + cachedReadableTexture = [MetalContext::Instance()->GetDevice() newTextureWithDescriptor:readableDesc]; + cachedReadableWidth = width; + cachedReadableHeight = height; + } + id readableTexture = cachedReadableTexture; + + id commandBuffer = commandPool->Allocate(); + id blitEncoder = [commandBuffer blitCommandEncoder]; + + // The OIT drawer's attachments are sized from its viewport, not from + // globClip, so bound the copy by the source too: an oversized sourceSize + // is a validation error. + [blitEncoder copyFromTexture:finalTexture + sourceSlice:0 + sourceLevel:0 + sourceOrigin:MTLOriginMake(0, 0, 0) + sourceSize:MTLSizeMake(std::min(width, (u32)finalTexture.width), + std::min(height, (u32)finalTexture.height), 1) + toTexture:readableTexture + destinationSlice:0 + destinationLevel:0 + destinationOrigin:MTLOriginMake(0, 0, 0)]; + +#if !TARGET_OS_IOS && !TARGET_OS_TV + // macOS: Explicit synchronization needed for managed memory + [blitEncoder synchronizeResource:readableTexture]; +#endif + [blitEncoder endEncoding]; + + // Submit command buffer and wait (matches Vulkan's EndFrameAndWait) + commandPool->EndFrameAndWait(); + + // Read back the texture data + fbReadback.init(width, height); + [readableTexture getBytes:fbReadback.data() + bytesPerRow:width * 4 + fromRegion:MTLRegionMake2D(0, 0, width, height) + mipmapLevel:0]; + + // Write to VRAM (use BGRA template specialization to match Metal's BGRA format). + // WriteFramebuffer clamps finalClip to width/height itself. + WriteFramebuffer<2, 1, 0, 3>(width, height, (u8 *)fbReadback.data(), rendContext->fb_W_SOF1 & VRAM_MASK, + rendContext->fb_W_CTRL, rendContext->fb_W_LINESTRIDE * 8, finalClip); + + // Both textures are owned by the cache now -- just drop the local refs. + scaledTexture = nil; + readableTexture = nil; +} + +void MetalScreenDrawer::EndRenderPass() { + if (!renderPassStarted) + return; + + [currentEncoder endEncoding]; + currentEncoder = nil; + + if (emulateFramebuffer) + { + // scaleAndWriteFramebuffer will handle EndFrameAndWait internally + scaleAndWriteFramebuffer(colorAttachment); + } + else + { + commandPool->EndFrame(); + aspectRatio = getOutputFramebufferAspectRatio(); + } + MetalDrawer::EndRenderPass(); + frameRendered = true; +} diff --git a/core/rend/metal/metal_driver.h b/core/rend/metal/metal_driver.h new file mode 100644 index 0000000000..c70df11288 --- /dev/null +++ b/core/rend/metal/metal_driver.h @@ -0,0 +1,154 @@ +/* + Copyright 2025 flyinghead + + This file is part of Flycast. + + Flycast is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 2 of the License, or + (at your option) any later version. + + Flycast is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with Flycast. If not, see . +*/ + +#pragma once +#include "metal_apple.h" +#include "ui/imgui_driver.h" +#include "imgui_impl_metal.h" +#include "metal_context.h" +#include + +#include "metal_texture.h" + +class MetalDriver final : public ImGuiDriver { +public: + MetalDriver() { + ImGui_ImplMetal_Init(MetalContext::Instance()->GetDevice()); + } + + void reset() override + { + ImGuiDriver::reset(); + textures.clear(); + ImGui_ImplMetal_Shutdown(); + } + + ~MetalDriver() { + reset(); + } + + void newFrame() override { + MetalContext *context = MetalContext::Instance(); + + // Use existing descriptor and encoder when available + if (context->GetDescriptor() != nullptr) { + ImGui_ImplMetal_NewFrame(MetalContext::Instance()->GetDescriptor()); + } else { + // ImGui only reads the attachment formats from this descriptor. + // Use a 1x1 texture in the layer's format rather than taking a + // swapchain drawable that would never be presented. + const MTLPixelFormat format = [context->GetLayer() pixelFormat]; + if (formatTexture == nil || [formatTexture pixelFormat] != format) + { + MTLTextureDescriptor *texDesc = [MTLTextureDescriptor texture2DDescriptorWithPixelFormat:format + width:1 height:1 mipmapped:NO]; + [texDesc setUsage:MTLTextureUsageRenderTarget]; + [texDesc setStorageMode:MTLStorageModePrivate]; + formatTexture = [context->GetDevice() newTextureWithDescriptor:texDesc]; + } + descriptor = [[MTLRenderPassDescriptor alloc] init]; + + [descriptor setDefaultRasterSampleCount:1]; + + auto color = [descriptor colorAttachments][0]; + [color setClearColor:MTLClearColorMake(0.f, 0.f, 0.f, 1.f)]; + [color setTexture:formatTexture]; + [color setLoadAction:MTLLoadActionClear]; + [color setStoreAction:MTLStoreActionStore]; + + ImGui_ImplMetal_NewFrame(descriptor); + } + } + + void renderDrawData(ImDrawData *drawData, bool gui_open) override { + MetalContext *context = MetalContext::Instance(); + + if (!context->IsValid()) + return; + + bool rendering = context->IsRendering(); + if (!rendering) + context->NewFrame(); + if (!rendering || newFrameStarted) + { + context->BeginRenderPass(); + if (renderer->RenderLastFrame()) + context->PresentLastFrame(); + } + + // GetEncoder() is nil when BeginRenderPass skipped the frame (no drawable + // available) — don't hand ImGui a nil encoder. + if (context->GetEncoder() != nil) + ImGui_ImplMetal_RenderDrawData(drawData, context->GetCommandBuffer(), context->GetEncoder()); + + if (!rendering || newFrameStarted) + context->EndFrame(); + newFrameStarted = false; + } + + void present() override { + MetalContext::Instance()->Present(); + } + + ImTextureID getTexture(const std::string &name) override { + auto it = textures.find(name); + if (it != textures.end()) + return (ImTextureID)(intptr_t)(__bridge void*)it->second.texture->GetTexture(); + + return ImTextureID{}; + } + + ImTextureID updateTexture(const std::string &name, const u8 *data, int width, int height, bool nearestSampling) override { + Texture texture(std::make_unique()); + texture.texture->tex_type = TextureType::_8888; + texture.texture->UploadToGPU(width, height, data, false); + + auto textureID = (ImTextureID)(intptr_t)(__bridge void*)texture.texture->GetTexture(); + + textures[name] = std::move(texture); + + return textureID; + } + + void deleteTexture(const std::string &name) override { + auto it = textures.find(name); + // Guard the lookup before dereferencing — deleteTexture is called from + // ImguiStateTexture::invalidate() during the unload/savestate path, which + // can fire when the named texture was already removed by a prior game's + // unload (game re-load) or the driver was reinitialized. Without this, + // it->second dereferences end() and aborts under libc++ hardening + // (__libcpp_verbose_abort). Mirrors the end() guard in getTexture(). + if (it == textures.end()) + return; + textures.erase(name); + } + +private: + struct Texture { + Texture() = default; + Texture(std::unique_ptr&& texture) : texture(std::move(texture)) {} + + std::unique_ptr texture; + }; + + MTLRenderPassDescriptor* descriptor; + id formatTexture; + std::unordered_map textures; + bool newFrameStarted = false; +}; diff --git a/core/rend/metal/metal_overlay.h b/core/rend/metal/metal_overlay.h new file mode 100644 index 0000000000..7c53e645e6 --- /dev/null +++ b/core/rend/metal/metal_overlay.h @@ -0,0 +1,50 @@ +/* + Copyright 2025 flyinghead + + This file is part of Flycast. + + Flycast is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 2 of the License, or + (at your option) any later version. + + Flycast is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with Flycast. If not, see . +*/ +#pragma once +#include "metal_apple.h" +#include "metal_quad.h" + +#include +#include + +class MetalTexture; + +// Floating VMU screens and lightgun crosshairs, drawn on top of the frame +// (Metal equivalent of VulkanOverlay) +class MetalOverlay +{ +public: + MetalOverlay(); + ~MetalOverlay(); + + void Init(MetalQuadPipeline *pipeline); + void Term(); + void Draw(id commandEncoder, u32 width, u32 height, float scaling, bool vmu, bool crosshair); + +private: + std::unique_ptr createTexture(int width, int height, const u8 *data); + void drawQuad(id commandEncoder, u32 width, u32 height, + float x, float y, float w, float h, id texture, const float *color); + + std::array, 8> vmuTextures; + std::array vmuLastChanged {}; + std::unique_ptr xhairTexture; + std::unique_ptr drawer; + MetalQuadPipeline *pipeline = nullptr; +}; diff --git a/core/rend/metal/metal_overlay.mm b/core/rend/metal/metal_overlay.mm new file mode 100644 index 0000000000..7511aee67a --- /dev/null +++ b/core/rend/metal/metal_overlay.mm @@ -0,0 +1,158 @@ +/* + Copyright 2025 flyinghead + + This file is part of Flycast. + + Flycast is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 2 of the License, or + (at your option) any later version. + + Flycast is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with Flycast. If not, see . +*/ +#include "metal_overlay.h" +#include "metal_texture.h" +#include "cfg/option.h" +#include "rend/osd.h" + +#include + +MetalOverlay::MetalOverlay() = default; +MetalOverlay::~MetalOverlay() = default; + +void MetalOverlay::Init(MetalQuadPipeline *pipeline) +{ + this->pipeline = pipeline; + drawer = std::make_unique(); + drawer->Init(pipeline); + vmuLastChanged.fill({}); +} + +void MetalOverlay::Term() +{ + // Command buffers retain the textures they sample, so the references can + // be dropped even if a frame using them is still in flight. + for (auto& tex : vmuTextures) + tex.reset(); + xhairTexture.reset(); + drawer.reset(); +} + +std::unique_ptr MetalOverlay::createTexture(int width, int height, const u8 *data) +{ + auto texture = std::make_unique(); + texture->tex_type = TextureType::_8888; + texture->UploadToGPU(width, height, data, false); + + return texture; +} + +void MetalOverlay::drawQuad(id commandEncoder, u32 width, u32 height, + float x, float y, float w, float h, id texture, const float *color) +{ + // The scissor rect must lie within the render target + const float x0 = std::max(0.f, x); + const float y0 = std::max(0.f, y); + const float x1 = std::min((float)width, x + w); + const float y1 = std::min((float)height, y + h); + if (x1 <= x0 || y1 <= y0) + return; + MTLScissorRect scissor = { (NSUInteger)x0, (NSUInteger)y0, (NSUInteger)(x1 - x0), (NSUInteger)(y1 - y0) }; + if (scissor.width == 0 || scissor.height == 0) + return; + + // Flipped compared to DrawFrame: the VMU image is stored bottom row first + MetalQuadVertex vtx[4] { + { -1.f, -1.f, 0.f, 0.f, 0.f }, + { 1.f, -1.f, 0.f, 1.f, 0.f }, + { -1.f, 1.f, 0.f, 0.f, 1.f }, + { 1.f, 1.f, 0.f, 1.f, 1.f }, + }; + [commandEncoder setViewport:(MTLViewport){ x, y, w, h, 0, 1 }]; + [commandEncoder setScissorRect:scissor]; + drawer->Draw(commandEncoder, texture, vtx, true, color); +} + +void MetalOverlay::Draw(id commandEncoder, u32 width, u32 height, float scaling, bool vmu, bool crosshair) +{ + if (drawer == nullptr || commandEncoder == nil) + return; + [commandEncoder pushDebugGroup:@"Overlay"]; + if (vmu) + { + const float vmu_padding = 8.f * scaling; + const float vmu_height = 32.f * scaling * 2.f; + const float vmu_width = 48.f * scaling * 2.f; + static const float color[4] = { 0.75f, 0.75f, 0.75f, 0.75f }; + + for (size_t i = 0; i < vmuTextures.size(); i++) + { + std::unique_ptr& texture = vmuTextures[i]; + if (!vmu_lcd_status[i]) + { + texture.reset(); + continue; + } + // A new texture each time the screen changes: a frame still in + // flight may be sampling the current one. + if (texture == nullptr || ::vmuLastChanged[i] != vmuLastChanged[i]) + { + texture = createTexture(48, 32, (const u8 *)vmu_lcd_data[i]); + vmuLastChanged[i] = ::vmuLastChanged[i]; + } + + const float w = vmu_width; + const float h = vmu_height; + float x; + float y; + if (i & 2) + x = width - vmu_padding - w; + else + x = vmu_padding; + if (i & 4) + { + y = height - vmu_padding - h; + if (i & 1) + y -= vmu_padding + h; + } + else + { + y = vmu_padding; + if (i & 1) + y += vmu_padding + h; + } + drawQuad(commandEncoder, width, height, x, y, w, h, texture->GetTexture(), color); + } + } + if (crosshair) + { + for (size_t i = 0; i < config::CrosshairColor.size(); i++) + { + if (!crosshairNeeded(i)) + continue; + if (xhairTexture == nullptr) + xhairTexture = createTexture(16, 16, (const u8 *)getCrosshairTextureData()); + + auto [x, y] = getCrosshairPosition(i); + const float w = config::CrosshairSize * scaling; + const float h = config::CrosshairSize * scaling; + x -= w / 2; + y -= h / 2; + const u32 color = config::CrosshairColor[i]; + const float xhairColor[4] { + (color & 0xff) / 255.f, + ((color >> 8) & 0xff) / 255.f, + ((color >> 16) & 0xff) / 255.f, + ((color >> 24) & 0xff) / 255.f + }; + drawQuad(commandEncoder, width, height, x, y, w, h, xhairTexture->GetTexture(), xhairColor); + } + } + [commandEncoder popDebugGroup]; +} diff --git a/core/rend/metal/metal_pipeline.h b/core/rend/metal/metal_pipeline.h new file mode 100644 index 0000000000..a93afe1316 --- /dev/null +++ b/core/rend/metal/metal_pipeline.h @@ -0,0 +1,350 @@ +/* + Copyright 2025 flyinghead + + This file is part of Flycast. + + Flycast is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 2 of the License, or + (at your option) any later version. + + Flycast is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with Flycast. If not, see . +*/ + +#pragma once +#include "metal_apple.h" +#include "types.h" +#include + +#include "cfg/option.h" +#include "hw/pvr/ta_ctx.h" +#include "metal_shaders.h" + +class MetalRenderer; + +enum class ModVolMode { Xor, Or, Inclusion, Exclusion, Final }; + +class MetalPipelineManager +{ +public: + /// oitTileDepth: pipelines for the OIT drawers' render pass on Apple GPUs, + /// which carries the opaque depth in colour attachment 1 (R32Float, tile + /// memory). Every pipeline used in that pass declares the attachment; only + /// draws that write the depth attachment write it. The non-OIT renderer + /// constructs this with false and its pipelines are unchanged. + explicit MetalPipelineManager(MetalShaders *shaderManager, bool oitTileDepth = false); + virtual ~MetalPipelineManager() = default; + + void term() + { + pipelines.clear(); + depthPassPipelines.clear(); + depthStencilStates.clear(); + depthPassDepthStencilStates.clear(); + // The memos below alias entries of the maps just cleared. They hold + // strong ARC references, so a stale memo is a wrong-object bug rather + // than a use-after-free -- but wrong-object is still wrong. Any future + // code that clears these maps MUST drop the memos here too. + lastPipeline = nil; + lastDepthStencil = nil; + } + + id GetBlitPassPipeline() { + if (blitPassPipeline != nullptr) + return blitPassPipeline; + + CreateBlitPassPipeline(); + + return blitPassPipeline; + } + + id GetDepthPassPipeline(bool naomi2) + { + u32 pipehash = hash(naomi2); + const auto &pipeline = depthPassPipelines.find(pipehash); + if (pipeline != depthPassPipelines.end() && pipeline->second != nullptr) + return pipeline->second; + CreateDepthPassPipeline(naomi2); + + return depthPassPipelines[pipehash]; + } + + id GetModifierVolumePipeline(ModVolMode mode, bool naomi2) + { + u32 pipehash = hash(mode, naomi2); + const auto &pipeline = modVolPipelines.find(pipehash); + if (pipeline != modVolPipelines.end() && pipeline->second != nullptr) + return pipeline->second; + CreateModVolPipeline(mode, naomi2); + + return modVolPipelines[pipehash]; + } + + // `useMemo` opts into the one-entry last-key memo below. Only the per-poly + // MetalDrawer::DrawPoly loop uses it. + id GetPipeline(u32 listType, bool sortTriangles, const PolyParam& pp, int gpuPalette, bool dithering, + bool useMemo = false, bool area1 = false) + { + u64 pipehash = hash(listType, sortTriangles, &pp, gpuPalette, dithering, area1); + // The TA hands us long runs of polys that share state, so the same key + // repeats hundreds of times in a row; a std::map lookup per poly is a + // pointer chase through a red-black tree for an answer we just had. + if (useMemo && lastPipeline != nil && lastPipelineKey == pipehash) + return lastPipeline; + const auto &pipeline = pipelines.find(pipehash); + if (pipeline != pipelines.end() && pipeline->second != nullptr) { + memoPipeline(useMemo, pipehash, pipeline->second); + return pipeline->second; + } + CreatePipeline(listType, sortTriangles, pp, gpuPalette, dithering, area1); + + id created = pipelines[pipehash]; + // Deliberately not memoising nil: a failed compile must stay retryable + // on the next poly, which is what the map path already does. + memoPipeline(useMemo, pipehash, created); + + return created; + } + + id GetModVolDepthStencilStates(ModVolMode mode, bool naomi2) + { + u32 pipehash = hash(mode, naomi2); + const auto &state = modVolStencilStates.find(pipehash); + if (state != modVolStencilStates.end() && state->second != nullptr) + return state->second; + CreateModVolDepthStencilState(mode, naomi2); + + return modVolStencilStates[pipehash]; + } + + id GetDepthPassDepthStencilStates(bool naomi2) + { + u32 pipehash = hash(naomi2); + const auto &state = depthPassDepthStencilStates.find(pipehash); + if (state != depthPassDepthStencilStates.end() && state->second != nullptr) + return state->second; + CreateDepthPassDepthStencilState(naomi2); + + return depthPassDepthStencilStates[pipehash]; + } + + /// See GetPipeline for what `useMemo` is and why it defaults off. + id GetDepthStencilStates(u32 listType, bool sortTriangles, bool shadowed, const PolyParam& pp, + bool useMemo = false, int stencilArea = 0) + { + u64 pipehash = hash(listType, sortTriangles, shadowed, &pp, stencilArea); + + if (useMemo && lastDepthStencil != nil && lastDepthStencilKey == pipehash) + return lastDepthStencil; + const auto &state = depthStencilStates.find(pipehash); + if (state != depthStencilStates.end() && state->second != nullptr) { + memoDepthStencil(useMemo, pipehash, state->second); + return state->second; + } + CreateDepthStencilState(listType, sortTriangles, shadowed, pp, stencilArea); + + id created = depthStencilStates[pipehash]; + memoDepthStencil(useMemo, pipehash, created); + + return created; + } + +private: + void memoPipeline(bool useMemo, u64 key, id value) { + if (useMemo && value != nil) { + lastPipelineKey = key; + lastPipeline = value; + } + } + void memoDepthStencil(bool useMemo, u64 key, id value) { + if (useMemo && value != nil) { + lastDepthStencilKey = key; + lastDepthStencil = value; + } + } + + void CreateBlitPassPipeline(); + void CreateModVolPipeline(ModVolMode mode, bool naomi2); + void CreateDepthPassPipeline(bool naomi2); + void CreatePipeline(u32 listType, bool sortTriangles, const PolyParam& pp, int gpuPalette, bool dithering, bool area1 = false); + + void CreateModVolDepthStencilState(ModVolMode mode, bool naomi2); + void CreateDepthPassDepthStencilState(bool naomi2); + /// stencilArea: 0 normal; 1 draw only inside a modifier volume (stencil == 0x81), + /// 2 draw only outside (two-volume polys, second/first parameter set). + void CreateDepthStencilState(u32 listType, bool sortTriangles, bool shadowed, const PolyParam& pp, int stencilArea = 0); + + u64 hash(u32 listType, bool sortTriangles, const PolyParam *pp, int gpuPalette, bool dithering, bool area1 = false) const + { + u64 hash = pp->pcw.Gouraud | (pp->pcw.Offset << 1) | (pp->pcw.Texture << 2) | (pp->pcw.Shadow << 3) + | (((pp->tileclip >> 28) == 3) << 4); + hash |= ((listType >> 1) << 5); + bool ignoreTexAlpha = pp->tsp.IgnoreTexA || pp->tcw.PixelFmt == Pixel565; + hash |= (pp->tsp.ShadInstr << 7) | (ignoreTexAlpha << 9) | (pp->tsp.UseAlpha << 10) + | (pp->tsp.ColorClamp << 11) | ((config::Fog ? pp->tsp.FogCtrl : 2) << 12) | (pp->tsp.SrcInstr << 14) + | (pp->tsp.DstInstr << 17); + hash |= (pp->isp.ZWriteDis << 20) | (pp->isp.CullMode << 21) | (pp->isp.DepthMode << 23); + hash |= ((u64)sortTriangles << 26) | ((u64)gpuPalette << 27) | ((u64)pp->isNaomi2() << 29); + hash |= (u64)(!settings.platform.isNaomi2() && config::NativeDepthInterpolation) << 30; + hash |= (u64)(pp->tcw.PixelFmt == PixelBumpMap) << 31; + hash |= (u64)dithering << 32; + hash |= (u64)area1 << 34; + + return hash; + } + u64 hash(u32 listType, bool sortTriangles, bool shadowed, const PolyParam *pp, int stencilArea = 0) const + { + u64 hash = pp->pcw.Gouraud | (pp->pcw.Offset << 1) | (pp->pcw.Texture << 2) | (pp->pcw.Shadow << 3) + | (((pp->tileclip >> 28) == 3) << 4); + hash |= ((listType >> 1) << 5); + bool ignoreTexAlpha = pp->tsp.IgnoreTexA || pp->tcw.PixelFmt == Pixel565; + hash |= (pp->tsp.ShadInstr << 7) | (ignoreTexAlpha << 9) | (pp->tsp.UseAlpha << 10) + | (pp->tsp.ColorClamp << 11) | ((config::Fog ? pp->tsp.FogCtrl : 2) << 12) | (pp->tsp.SrcInstr << 14) + | (pp->tsp.DstInstr << 17); + hash |= (pp->isp.ZWriteDis << 20) | (pp->isp.CullMode << 21) | (pp->isp.DepthMode << 23); + hash |= ((u64)sortTriangles << 26) | ((u64)pp->isNaomi2() << 29); + hash |= (u64)(!settings.platform.isNaomi2() && config::NativeDepthInterpolation) << 30; + hash |= (u64)(pp->tcw.PixelFmt == PixelBumpMap) << 31; + hash |= (u64)(stencilArea & 3) << 32; + + return hash; + } + u32 hash(ModVolMode mode, bool naomi2) const + { + return ((int)mode << 2) | ((int)naomi2 << 5) | ((int)(!settings.platform.isNaomi2() && config::NativeDepthInterpolation) << 6); + } + u32 hash(bool naomi2) const + { + return ((int)naomi2 << 2) | ((int)(!settings.platform.isNaomi2() && config::NativeDepthInterpolation) << 3); + } + + MTLVertexDescriptor* GetMainVertexInputDescriptor(bool full = true, bool naomi2 = false) const + { + MTLVertexDescriptor *vertexDesc = [[MTLVertexDescriptor alloc] init]; + + auto pos = [vertexDesc attributes][0]; // pos + [pos setFormat:MTLVertexFormatFloat3]; + [pos setOffset:offsetof(Vertex, x)]; + [pos setBufferIndex:30]; + + if (full) { + auto col = [vertexDesc attributes][1]; // base color + [col setFormat:MTLVertexFormatUChar4Normalized]; + [col setOffset:offsetof(Vertex, col)]; + [col setBufferIndex:30]; + + auto spc = [vertexDesc attributes][2]; // offset color + [spc setFormat:MTLVertexFormatUChar4Normalized]; + [spc setOffset:offsetof(Vertex, spc)]; + [spc setBufferIndex:30]; + + auto u = [vertexDesc attributes][3]; // tex coord + [u setFormat:MTLVertexFormatFloat2]; + [u setOffset:offsetof(Vertex, u)]; + [u setBufferIndex:30]; + + auto col1 = [vertexDesc attributes][4]; + [col1 setFormat:MTLVertexFormatUChar4Normalized]; + [col1 setOffset:offsetof(Vertex, col1)]; + [col1 setBufferIndex:30]; + + auto spc1 = [vertexDesc attributes][5]; + [spc1 setFormat:MTLVertexFormatUChar4Normalized]; + [spc1 setOffset:offsetof(Vertex, spc1)]; + [spc1 setBufferIndex:30]; + + auto u1 = [vertexDesc attributes][6]; // tex coord + [u1 setFormat:MTLVertexFormatFloat2]; + [u1 setOffset:offsetof(Vertex, u1)]; + [u1 setBufferIndex:30]; + + if (naomi2) { + auto nx = [vertexDesc attributes][7]; // naomi2 normal + [nx setFormat:MTLVertexFormatFloat3]; + [nx setOffset:offsetof(Vertex, nx)]; + [nx setBufferIndex:30]; + } + } + + auto layout = [vertexDesc layouts][30]; + [layout setStride:sizeof(Vertex)]; + [layout setStepRate:1]; + [layout setStepFunction:MTLVertexStepFunctionPerVertex]; + + return vertexDesc; + } + + static inline MTLBlendFactor GetBlendFactor(u32 instr, bool src) { + switch (instr) { + case 0: // zero + return MTLBlendFactorZero; + case 1: // one + return MTLBlendFactorOne; + case 2: // other color + return src ? MTLBlendFactorDestinationColor : MTLBlendFactorSourceColor; + case 3: // inverse other color + return src ? MTLBlendFactorOneMinusDestinationColor : MTLBlendFactorOneMinusSourceColor; + case 4: // src alpha + return MTLBlendFactorSourceAlpha; + case 5: // inverse src alpha + return MTLBlendFactorOneMinusSourceAlpha; + case 6: // dst alpha + return MTLBlendFactorDestinationAlpha; + case 7: // inverse dst alpha + return MTLBlendFactorOneMinusDestinationAlpha; + default: + die("Unsupported blend instruction"); + return MTLBlendFactorZero; + } + } + + // One-entry memos for the two per-polygon map lookups. nil doubles as + // "nothing memoised": only non-nil values are ever stored, so there is no + // separate validity flag to forget to clear. Must be dropped in term(). + u64 lastPipelineKey = 0; + id lastPipeline = nil; + u64 lastDepthStencilKey = 0; + id lastDepthStencil = nil; + + id blitPassPipeline = nil; + std::map> pipelines; + std::map> modVolPipelines; + std::map> depthPassPipelines; + + std::map> modVolStencilStates; + std::map> depthStencilStates; + std::map> depthPassDepthStencilStates; + + /// Declare colour attachment 1 for the OIT tile-memory opaque depth. + void setOitDepthAttachment(MTLRenderPipelineDescriptor *descriptor, bool writeDepth) const + { + if (!oitTileDepth) + return; + auto attachment = [descriptor colorAttachments][1]; + [attachment setPixelFormat:MTLPixelFormatR32Float]; + [attachment setBlendingEnabled:NO]; + [attachment setWriteMask:writeDepth ? MTLColorWriteMaskRed : MTLColorWriteMaskNone]; + } + +protected: + MetalShaders *shaderManager; + bool oitTileDepth = false; +}; + +static const MTLCompareFunction depthOps[] = +{ + MTLCompareFunctionNever, // 0 Never + MTLCompareFunctionLess, // 1 Less + MTLCompareFunctionEqual, // 2 Equal + MTLCompareFunctionLessEqual, // 3 Less Or Equal + MTLCompareFunctionGreater, // 4 Greater + MTLCompareFunctionNotEqual, // 5 Not Equal + MTLCompareFunctionGreaterEqual, // 6 Greater Or Equal + MTLCompareFunctionAlways, // 7 Always +}; \ No newline at end of file diff --git a/core/rend/metal/metal_pipeline.mm b/core/rend/metal/metal_pipeline.mm new file mode 100644 index 0000000000..77916f6197 --- /dev/null +++ b/core/rend/metal/metal_pipeline.mm @@ -0,0 +1,370 @@ +/* + Copyright 2025 flyinghead + + This file is part of Flycast. + + Flycast is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 2 of the License, or + (at your option) any later version. + + Flycast is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with Flycast. If not, see . +*/ + +#include "metal_pipeline.h" + +#include "metal_context.h" +#include "metal_renderer.h" + +MetalPipelineManager::MetalPipelineManager(MetalShaders *shaderManager, bool oitTileDepth) { + this->shaderManager = shaderManager; + this->oitTileDepth = oitTileDepth; +} + +void MetalPipelineManager::CreateBlitPassPipeline() { + MTLRenderPipelineDescriptor *descriptor = [[MTLRenderPipelineDescriptor alloc] init]; + [descriptor setLabel:@"Blit Pass"]; + + auto attachment = [descriptor colorAttachments][0]; + [attachment setPixelFormat:MTLPixelFormatBGRA8Unorm]; + + [descriptor setVertexFunction:shaderManager->GetBlitVertexShader()]; + [descriptor setFragmentFunction:shaderManager->GetBlitFragmentShader()]; + if (descriptor.vertexFunction == nil || descriptor.fragmentFunction == nil) { + ERROR_LOG(RENDERER, "CreateBlitPassPipeline: shader compile failed"); + return; + } + + NSError *error = nil; + auto state = [MetalContext::Instance()->GetDevice() newRenderPipelineStateWithDescriptor:descriptor error:&error]; + + if (state == nil) { + ERROR_LOG(RENDERER, "Failed to create Blit Pipeline State: %s", [[error localizedDescription] UTF8String]);; + } + + blitPassPipeline = state; +} + +void MetalPipelineManager::CreateModVolPipeline(ModVolMode mode, bool naomi2) { + MTLVertexDescriptor *vertexDesc = nil; + MTLRenderPipelineDescriptor *descriptor = [[MTLRenderPipelineDescriptor alloc] init]; + + [descriptor setLabel:@"Mod Vol Pass"]; + + if (mode == ModVolMode::Final) { + [descriptor setVertexDescriptor:GetMainVertexInputDescriptor(false, naomi2)]; + } + else { + vertexDesc = [[MTLVertexDescriptor alloc] init]; + + auto layout = [vertexDesc layouts][30]; + [layout setStride:sizeof(float) * 3]; + + auto attribute = [vertexDesc attributes][0]; + [attribute setOffset:0]; + [attribute setBufferIndex:30]; + [attribute setFormat:MTLVertexFormatFloat3]; + + [descriptor setVertexDescriptor:vertexDesc]; + } + + auto attachment = [descriptor colorAttachments][0]; + [attachment setBlendingEnabled:mode == ModVolMode::Final]; + [attachment setSourceRGBBlendFactor:MTLBlendFactorSourceAlpha]; + [attachment setDestinationRGBBlendFactor:MTLBlendFactorOneMinusSourceAlpha]; + [attachment setRgbBlendOperation:MTLBlendOperationAdd]; + [attachment setSourceAlphaBlendFactor:MTLBlendFactorSourceAlpha]; + [attachment setDestinationAlphaBlendFactor:MTLBlendFactorOneMinusSourceAlpha]; + [attachment setAlphaBlendOperation:MTLBlendOperationAdd]; + [attachment setWriteMask:mode != ModVolMode::Final ? MTLColorWriteMaskNone : MTLColorWriteMaskAll]; + [attachment setPixelFormat:MTLPixelFormatBGRA8Unorm]; + setOitDepthAttachment(descriptor, false); + + [descriptor setDepthAttachmentPixelFormat:MTLPixelFormatDepth32Float_Stencil8]; + [descriptor setStencilAttachmentPixelFormat:MTLPixelFormatDepth32Float_Stencil8]; + + MetalModVolShaderParams shaderParams { naomi2, !settings.platform.isNaomi2() && config::NativeDepthInterpolation }; + [descriptor setVertexFunction:shaderManager->GetModVolVertexShader(shaderParams)]; + [descriptor setFragmentFunction:shaderManager->GetModVolFragmentShader(!settings.platform.isNaomi2() && config::NativeDepthInterpolation)]; + if (descriptor.vertexFunction == nil || descriptor.fragmentFunction == nil) { + ERROR_LOG(RENDERER, "CreateModVolPipeline: shader compile failed"); + return; + } + + NSError *error = nil; + auto state = [MetalContext::Instance()->GetDevice() newRenderPipelineStateWithDescriptor:descriptor error:&error]; + + if (state == nullptr) { + ERROR_LOG(RENDERER, "Failed to create Depth Render Pipeline State: %s", [[error localizedDescription] UTF8String]); + } + + modVolPipelines[hash(mode, naomi2)] = state; +} + +void MetalPipelineManager::CreateDepthPassPipeline(bool naomi2) +{ + MTLRenderPipelineDescriptor *descriptor = [[MTLRenderPipelineDescriptor alloc] init]; + [descriptor setLabel:@"Depth Pass"]; + [descriptor setVertexDescriptor:GetMainVertexInputDescriptor(false, false)]; + + auto attachment = [descriptor colorAttachments][0]; + [attachment setBlendingEnabled:false]; + [attachment setSourceRGBBlendFactor:MTLBlendFactorZero]; + [attachment setDestinationRGBBlendFactor:MTLBlendFactorZero]; + [attachment setRgbBlendOperation:MTLBlendOperationAdd]; + [attachment setSourceAlphaBlendFactor:MTLBlendFactorZero]; + [attachment setDestinationAlphaBlendFactor:MTLBlendFactorZero]; + [attachment setAlphaBlendOperation:MTLBlendOperationAdd]; + [attachment setWriteMask:MTLColorWriteMaskNone]; + // Even with writeMask None, the color attachment's pixelFormat MUST match the + // render pass's framebuffer (BGRA8Unorm) or binding asserts: "render pipeline's + // pixelFormat (MTLPixelFormatInvalid) does not match the framebuffer's". The + // depth-pass shares the main color pass, so set it like the other pipelines. + [attachment setPixelFormat:MTLPixelFormatBGRA8Unorm]; + setOitDepthAttachment(descriptor, false); + + // REQUIRED: this pipeline's fragment shader writes depth, so the descriptor + // MUST declare the depth/stencil attachment format — otherwise Metal refuses + // to build it ("depthAttachmentPixelFormat is not valid and shader writes to + // depth"), returns nil, and the later setRenderPipelineState(nil) asserts/ + // crashes at boot for any game that uses a depth pass (e.g. Virtua Cop). + // The ModVol and main-draw pipelines already set these; this one was missing. + [descriptor setDepthAttachmentPixelFormat:MTLPixelFormatDepth32Float_Stencil8]; + [descriptor setStencilAttachmentPixelFormat:MTLPixelFormatDepth32Float_Stencil8]; + + MetalModVolShaderParams shaderParams { naomi2, !settings.platform.isNaomi2() && config::NativeDepthInterpolation }; + [descriptor setVertexFunction:shaderManager->GetModVolVertexShader(shaderParams)]; + [descriptor setFragmentFunction:shaderManager->GetModVolFragmentShader(!settings.platform.isNaomi2() && config::NativeDepthInterpolation)];; + if (descriptor.vertexFunction == nil || descriptor.fragmentFunction == nil) { + ERROR_LOG(RENDERER, "CreateDepthPassPipeline: shader compile failed"); + return; + } + + NSError *error = nil; + auto state = [MetalContext::Instance()->GetDevice() newRenderPipelineStateWithDescriptor:descriptor error:&error]; + + if (state == nil) { + ERROR_LOG(RENDERER, "Failed to create Depth Render Pipeline State: %s", [[error localizedDescription] UTF8String]); + } + + depthPassPipelines[hash(naomi2)] = state; +} + +void MetalPipelineManager::CreatePipeline(u32 listType, bool sortTriangles, const PolyParam &pp, int gpuPalette, bool dithering, bool area1) { + MTLRenderPipelineDescriptor *descriptor = [[MTLRenderPipelineDescriptor alloc] init]; + [descriptor setLabel:@"Main Draw"]; + [descriptor setVertexDescriptor:GetMainVertexInputDescriptor(true, pp.isNaomi2())]; + + u32 src = pp.tsp.SrcInstr; + u32 dst = pp.tsp.DstInstr; + + auto attachment = [descriptor colorAttachments][0]; + [attachment setBlendingEnabled:true]; + [attachment setSourceRGBBlendFactor:GetBlendFactor(src, true)]; + [attachment setDestinationRGBBlendFactor:GetBlendFactor(dst, false)]; + [attachment setRgbBlendOperation:MTLBlendOperationAdd]; + [attachment setSourceAlphaBlendFactor:GetBlendFactor(src, true)]; + [attachment setDestinationAlphaBlendFactor:GetBlendFactor(dst, false)]; + [attachment setAlphaBlendOperation:MTLBlendOperationAdd]; + [attachment setWriteMask:MTLColorWriteMaskAll]; + [attachment setPixelFormat:MTLPixelFormatBGRA8Unorm]; + // The tile-memory opaque depth must equal the depth attachment, so write it + // exactly when this draw writes depth (same rule as CreateDepthStencilState). + // Colour and depth writes pass the same depth/stencil tests. + const bool writesDepth = !sortTriangles + && (listType == ListType_Punch_Through || !pp.isp.ZWriteDis); + setOitDepthAttachment(descriptor, writesDepth); + + [descriptor setDepthAttachmentPixelFormat:MTLPixelFormatDepth32Float_Stencil8]; + [descriptor setStencilAttachmentPixelFormat:MTLPixelFormatDepth32Float_Stencil8]; + + bool divPosZ = !settings.platform.isNaomi2() && config::NativeDepthInterpolation; + + MetalVertexShaderParams vertParams = {}; + vertParams.gouraud = pp.pcw.Gouraud == 1; + vertParams.naomi2 = pp.isNaomi2(); + vertParams.divPosZ = divPosZ; + vertParams.area1 = area1; + + MetalFragmentShaderParams fragParams = {}; + fragParams.alphaTest = listType == ListType_Punch_Through; + fragParams.bumpmap = pp.tcw.PixelFmt == PixelBumpMap; + fragParams.clamping = pp.tsp.ColorClamp; + fragParams.insideClipTest = (pp.tileclip >> 28) == 3; + fragParams.fog = config::Fog ? pp.tsp.FogCtrl : 2; + fragParams.gouraud = pp.pcw.Gouraud; + fragParams.ignoreTexAlpha = pp.tsp.IgnoreTexA || pp.tcw.PixelFmt == Pixel565; + fragParams.offset = pp.pcw.Offset; + fragParams.shaderInstr = pp.tsp.ShadInstr; + fragParams.texture = pp.pcw.Texture; + fragParams.trilinear = pp.pcw.Texture && pp.tsp.FilterMode > 1 && listType != ListType_Punch_Through && pp.tcw.MipMapped == 1; + fragParams.useAlpha = pp.tsp.UseAlpha; + fragParams.palette = gpuPalette; + fragParams.divPosZ = divPosZ; + fragParams.dithering = dithering; + fragParams.oitTileDepth = oitTileDepth && writesDepth; + + id vertexFn = shaderManager->GetVertexShader(vertParams); + id fragmentFn = shaderManager->GetFragmentShader(fragParams); + if (vertexFn == nil || fragmentFn == nil) { + ERROR_LOG(RENDERER, "CreatePipeline: shader compile failed"); + return; + } + [descriptor setVertexFunction:vertexFn]; + [descriptor setFragmentFunction:fragmentFn]; + + NSError *error = nil; + auto state = [MetalContext::Instance()->GetDevice() newRenderPipelineStateWithDescriptor:descriptor error:&error]; + + if (state == nullptr) { + ERROR_LOG(RENDERER, "Failed to create Render Pipeline State: %s", [[error localizedDescription] UTF8String]); + // Don't cache a nil pipeline: caching it poisons the slot permanently + // (GetPipeline's nullptr check would re-trigger CreatePipeline, but storing + // nil here means the draw site gets nil and setRenderPipelineState(nil) + // hard-asserts). Leave the slot empty so a later frame can retry, and let + // the caller skip the draw this frame. + return; + } + + pipelines[hash(listType, sortTriangles, &pp, gpuPalette, dithering, area1)] = state; +} + +void MetalPipelineManager::CreateModVolDepthStencilState(ModVolMode mode, bool naomi2) { + MTLDepthStencilDescriptor *descriptor = [[MTLDepthStencilDescriptor alloc] init]; + [descriptor setDepthWriteEnabled:false]; + [descriptor setDepthCompareFunction:mode == ModVolMode::Xor || mode == ModVolMode::Or ? MTLCompareFunctionGreater : MTLCompareFunctionAlways]; + + MTLStencilDescriptor *stencilDescriptor = [[MTLStencilDescriptor alloc] init]; + switch (mode) + { + case ModVolMode::Xor: + [stencilDescriptor setStencilFailureOperation:MTLStencilOperationKeep]; + [stencilDescriptor setDepthStencilPassOperation:MTLStencilOperationInvert]; + [stencilDescriptor setDepthFailureOperation:MTLStencilOperationKeep]; + [stencilDescriptor setStencilCompareFunction:MTLCompareFunctionAlways]; + [stencilDescriptor setReadMask:0]; + [stencilDescriptor setWriteMask:2]; + break; + case ModVolMode::Or: + [stencilDescriptor setStencilFailureOperation:MTLStencilOperationKeep]; + [stencilDescriptor setDepthStencilPassOperation:MTLStencilOperationReplace]; + [stencilDescriptor setDepthFailureOperation:MTLStencilOperationKeep]; + [stencilDescriptor setStencilCompareFunction:MTLCompareFunctionAlways]; + [stencilDescriptor setReadMask:2]; + [stencilDescriptor setWriteMask:2]; + break; + case ModVolMode::Inclusion: + [stencilDescriptor setStencilFailureOperation:MTLStencilOperationZero]; + [stencilDescriptor setDepthStencilPassOperation:MTLStencilOperationReplace]; + [stencilDescriptor setDepthFailureOperation:MTLStencilOperationZero]; + [stencilDescriptor setStencilCompareFunction:MTLCompareFunctionLessEqual]; + [stencilDescriptor setReadMask:3]; + [stencilDescriptor setWriteMask:3]; + break; + case ModVolMode::Exclusion: + [stencilDescriptor setStencilFailureOperation:MTLStencilOperationZero]; + [stencilDescriptor setDepthStencilPassOperation:MTLStencilOperationKeep]; + [stencilDescriptor setDepthFailureOperation:MTLStencilOperationZero]; + [stencilDescriptor setStencilCompareFunction:MTLCompareFunctionEqual]; + [stencilDescriptor setReadMask:3]; + [stencilDescriptor setWriteMask:3]; + break; + case ModVolMode::Final: + [stencilDescriptor setStencilFailureOperation:MTLStencilOperationZero]; + [stencilDescriptor setDepthStencilPassOperation:MTLStencilOperationZero]; + [stencilDescriptor setDepthFailureOperation:MTLStencilOperationZero]; + [stencilDescriptor setStencilCompareFunction:MTLCompareFunctionEqual]; + [stencilDescriptor setReadMask:0x81]; + [stencilDescriptor setWriteMask:3]; + break; + } + + [descriptor setFrontFaceStencil:stencilDescriptor]; + [descriptor setBackFaceStencil:stencilDescriptor]; + + auto state = [MetalContext::Instance()->GetDevice() newDepthStencilStateWithDescriptor:descriptor]; + + modVolStencilStates[hash(mode, naomi2)] = state; +} + +void MetalPipelineManager::CreateDepthPassDepthStencilState(bool naomi2) { + MTLDepthStencilDescriptor *descriptor = [[MTLDepthStencilDescriptor alloc] init]; + [descriptor setLabel:@"Sorted Depth Pass"]; + [descriptor setDepthWriteEnabled:true]; + [descriptor setDepthCompareFunction:MTLCompareFunctionGreaterEqual]; + + auto state = [MetalContext::Instance()->GetDevice() newDepthStencilStateWithDescriptor:descriptor]; + + depthPassDepthStencilStates[hash(naomi2)] = state; +} + +void MetalPipelineManager::CreateDepthStencilState(u32 listType, bool sortTriangles, bool shadowed, const PolyParam &pp, int stencilArea) { + MTLDepthStencilDescriptor *descriptor = [[MTLDepthStencilDescriptor alloc] init]; + if (shadowed) + [descriptor setLabel:@"Main Shadowed Depth-Stencil State"]; + else + [descriptor setLabel:@"Main Depth-Stencil State"]; + + MTLCompareFunction compareFunction; + if (listType == ListType_Punch_Through || sortTriangles) { + compareFunction = MTLCompareFunctionGreaterEqual; + } else { + compareFunction = depthOps[pp.isp.DepthMode]; + } + + bool depthWriteEnabled; + if (sortTriangles) { + depthWriteEnabled = false; + } else { + // Z Write Disable seems to be ignored for punch-through. + // Fixes Worms World Party, Bust-a-Move 4 and Re-Volt + if (listType == ListType_Punch_Through) { + depthWriteEnabled = true; + } else { + depthWriteEnabled = !pp.isp.ZWriteDis; + } + } + + MTLStencilDescriptor *stencilDescriptor = [[MTLStencilDescriptor alloc] init]; + [stencilDescriptor setStencilFailureOperation:MTLStencilOperationKeep]; + [stencilDescriptor setDepthStencilPassOperation:MTLStencilOperationKeep]; + + if (stencilArea != 0) { + // Two-volume poly, one parameter set per draw: pass only inside (1) or only + // outside (2) the modifier-volume mark. The inside draw of an opaque/PT poly + // repaints pixels the first draw already wrote (so depth compares >=) and + // clears the mark so the Final darkening pass leaves its colour alone. + [stencilDescriptor setStencilCompareFunction:stencilArea == 1 ? MTLCompareFunctionEqual : MTLCompareFunctionNotEqual]; + [stencilDescriptor setReadMask:0x81]; + if (stencilArea == 1 && shadowed) { + [stencilDescriptor setDepthStencilPassOperation:MTLStencilOperationZero]; + [stencilDescriptor setWriteMask:0x81]; + compareFunction = MTLCompareFunctionGreaterEqual; + } else { + [stencilDescriptor setWriteMask:0]; + } + } else if (shadowed) { + [stencilDescriptor setDepthStencilPassOperation:MTLStencilOperationReplace]; + [stencilDescriptor setStencilCompareFunction:MTLCompareFunctionAlways]; + [stencilDescriptor setReadMask:0]; + [stencilDescriptor setWriteMask:0x80]; + } + + [descriptor setDepthCompareFunction:compareFunction]; + [descriptor setDepthWriteEnabled:depthWriteEnabled]; + + if (shadowed || stencilArea != 0) { + [descriptor setBackFaceStencil:stencilDescriptor]; + [descriptor setFrontFaceStencil:stencilDescriptor]; + } + + auto state = [MetalContext::Instance()->GetDevice() newDepthStencilStateWithDescriptor:descriptor]; + + depthStencilStates[hash(listType, sortTriangles, shadowed, &pp, stencilArea)] = state; +} diff --git a/core/rend/metal/metal_quad.h b/core/rend/metal/metal_quad.h new file mode 100644 index 0000000000..f721bf9155 --- /dev/null +++ b/core/rend/metal/metal_quad.h @@ -0,0 +1,88 @@ +/* + Copyright 2025 flyinghead + + This file is part of Flycast. + + Flycast is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 2 of the License, or + (at your option) any later version. + + Flycast is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with Flycast. If not, see . +*/ + +#pragma once +#include "metal_apple.h" + +#include "types.h" +#include "metal_shaders.h" +#include "metal_buffer.h" + +struct MetalQuadVertex +{ + float x, y, z; + float u, v; +}; + +class MetalQuadPipeline +{ +public: + MetalQuadPipeline(bool ignoreTexAlpha, bool rotate = false, bool blend = true) + : rotate(rotate), ignoreTexAlpha(ignoreTexAlpha), blend(blend) {} + void Init(MetalShaders *shaderManager); + void Term() { + pipeline = nil; + linearSampler = nil; + nearestSampler = nil; + } + // Returns false if the pipeline failed to compile (e.g. the iOS Simulator's + // MTLCompilerService crashes under Metal validation). Callers must skip the + // draw rather than letting setRenderPipelineState(nil) hard-assert. + bool BindPipeline(id commandEncoder) { + id p = GetPipeline(); + if (p == nil) + return false; + [commandEncoder setRenderPipelineState:p]; + return true; + } + + id GetLinearSampler() { return linearSampler; } + id GetNearestSampler() { return nearestSampler; } +private: + id GetPipeline() { + if (!pipeline) + CreatePipeline(); + return pipeline; + } + void CreatePipeline(); + + + id pipeline; + id linearSampler; + id nearestSampler; + MetalShaders *shaderManager = nullptr; + bool rotate; + bool ignoreTexAlpha; + bool blend; +}; + +class MetalQuadDrawer +{ +public: + MetalQuadDrawer() = default; + MetalQuadDrawer(MetalQuadDrawer &&) = default; + MetalQuadDrawer(const MetalQuadDrawer &) = delete; + MetalQuadDrawer& operator=(MetalQuadDrawer &&) = default; + MetalQuadDrawer& operator=(const MetalQuadDrawer &) = delete; + + void Init(MetalQuadPipeline *pipeline); + void Draw(id commandEncoder, id texture, MetalQuadVertex vertices[4] = nullptr, bool nearestFilter = false, const float *color = nullptr); +private: + MetalQuadPipeline *pipeline = nullptr; +}; diff --git a/core/rend/metal/metal_quad.mm b/core/rend/metal/metal_quad.mm new file mode 100644 index 0000000000..423cecfa0d --- /dev/null +++ b/core/rend/metal/metal_quad.mm @@ -0,0 +1,124 @@ +/* + Copyright 2025 flyinghead + + This file is part of Flycast. + + Flycast is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 2 of the License, or + (at your option) any later version. + + Flycast is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with Flycast. If not, see . +*/ + +#include "metal_quad.h" +#include "metal_context.h" + +void MetalQuadPipeline::CreatePipeline() +{ + MTLRenderPipelineDescriptor *pipelineDescriptor = [[MTLRenderPipelineDescriptor alloc] init]; + [pipelineDescriptor setVertexFunction:shaderManager->GetQuadVertexShader(rotate)]; + [pipelineDescriptor setFragmentFunction:shaderManager->GetQuadFragmentShader(ignoreTexAlpha)]; + + [pipelineDescriptor setInputPrimitiveTopology:MTLPrimitiveTopologyClassTriangle]; + + auto color = pipelineDescriptor.colorAttachments[0]; + [color setBlendingEnabled:blend]; + [color setSourceRGBBlendFactor:MTLBlendFactorSourceAlpha]; + [color setDestinationRGBBlendFactor:MTLBlendFactorOneMinusSourceAlpha]; + [color setRgbBlendOperation:MTLBlendOperationAdd]; + // One, not SourceAlpha: keeps an opaque target opaque, for video routing + [color setSourceAlphaBlendFactor:MTLBlendFactorOne]; + [color setDestinationAlphaBlendFactor:MTLBlendFactorOneMinusSourceAlpha]; + [color setAlphaBlendOperation:MTLBlendOperationAdd]; + [color setWriteMask:MTLColorWriteMaskAll]; + [color setPixelFormat:MTLPixelFormatBGRA8Unorm]; + + MTLVertexDescriptor *vertexDescriptor = [[MTLVertexDescriptor alloc] init]; + auto pos = vertexDescriptor.attributes[0]; + [pos setFormat:MTLVertexFormatFloat3]; + [pos setBufferIndex:0]; + [pos setOffset:offsetof(MetalQuadVertex, x)]; + + auto uv = vertexDescriptor.attributes[1]; + [uv setFormat:MTLVertexFormatFloat2]; + [uv setBufferIndex:0]; + [uv setOffset:offsetof(MetalQuadVertex, u)]; + + auto layout = vertexDescriptor.layouts[0]; + [layout setStride:sizeof(MetalQuadVertex)]; + + [pipelineDescriptor setVertexDescriptor:vertexDescriptor]; + + NSError *error = nil; + pipeline = [MetalContext::Instance()->GetDevice() newRenderPipelineStateWithDescriptor:pipelineDescriptor error:&error]; + + if (pipeline == nil) + { + ERROR_LOG(RENDERER, "Failed to create quad pipeline: %s", [[error localizedDescription] UTF8String]); + } +} + +void MetalQuadPipeline::Init(MetalShaders *shaderManager) +{ + this->shaderManager = shaderManager; + if (linearSampler == nil) + { + MTLSamplerDescriptor *samplerDescriptor = [[MTLSamplerDescriptor alloc] init]; + [samplerDescriptor setMinFilter:MTLSamplerMinMagFilterLinear]; + [samplerDescriptor setMagFilter:MTLSamplerMinMagFilterLinear]; + [samplerDescriptor setMipFilter:MTLSamplerMipFilterLinear]; + [samplerDescriptor setSAddressMode:MTLSamplerAddressModeClampToEdge]; + [samplerDescriptor setTAddressMode:MTLSamplerAddressModeClampToEdge]; + [samplerDescriptor setRAddressMode:MTLSamplerAddressModeClampToEdge]; + linearSampler = [MetalContext::Instance()->GetDevice() newSamplerStateWithDescriptor:samplerDescriptor]; + } + if (nearestSampler == nil) + { + MTLSamplerDescriptor *samplerDescriptor = [[MTLSamplerDescriptor alloc] init]; + [samplerDescriptor setMinFilter:MTLSamplerMinMagFilterNearest]; + [samplerDescriptor setMagFilter:MTLSamplerMinMagFilterNearest]; + [samplerDescriptor setMipFilter:MTLSamplerMipFilterNearest]; + [samplerDescriptor setSAddressMode:MTLSamplerAddressModeClampToEdge]; + [samplerDescriptor setTAddressMode:MTLSamplerAddressModeClampToEdge]; + [samplerDescriptor setRAddressMode:MTLSamplerAddressModeClampToEdge]; + nearestSampler = [MetalContext::Instance()->GetDevice() newSamplerStateWithDescriptor:samplerDescriptor]; + } +} + +void MetalQuadDrawer::Init(MetalQuadPipeline *pipeline) { + this->pipeline = pipeline; +} + +void MetalQuadDrawer::Draw(id commandEncoder, id texture, MetalQuadVertex *vertices, bool nearestFilter, const float *color) +{ + if (!pipeline->BindPipeline(commandEncoder)) + return; + const MetalQuadVertex defaults[4] { + { -1, -1, 0, 0, 1 }, { 1, -1, 0, 1, 1 }, + { -1, 1, 0, 0, 0 }, { 1, 1, 0, 1, 0 } + }; + [commandEncoder setVertexBytes:vertices != nullptr ? vertices : defaults + length:sizeof(defaults) atIndex:0]; + + if (texture != nil) + { + [commandEncoder setFragmentTexture:texture atIndex:0]; + [commandEncoder setFragmentSamplerState:nearestFilter ? pipeline->GetNearestSampler() : pipeline->GetLinearSampler() atIndex:0]; + } + + if (color == nullptr) + { + static float fullWhite[] { 1.f, 1.f, 1.f, 1.f }; + color = fullWhite; + } + + [commandEncoder setFragmentBytes:color length:sizeof(float) * 4 atIndex:0]; + [commandEncoder drawPrimitives:MTLPrimitiveTypeTriangleStrip vertexStart:0 vertexCount:4]; +} diff --git a/core/rend/metal/metal_renderer.h b/core/rend/metal/metal_renderer.h new file mode 100644 index 0000000000..fc70aecd75 --- /dev/null +++ b/core/rend/metal/metal_renderer.h @@ -0,0 +1,87 @@ +/* + Copyright 2025 flyinghead + + This file is part of Flycast. + + Flycast is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 2 of the License, or + (at your option) any later version. + + Flycast is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with Flycast. If not, see . +*/ + +#pragma once +#include "metal_apple.h" +#include "metal_pipeline.h" +#include "metal_shaders.h" +#include "metal_texture.h" +#include "metal_buffer.h" +#include "metal_drawer.h" +#include "metal_commandpool.h" + +#include "hw/pvr/Renderer_if.h" +#include "rend/texconv.h" +#include "rend/transform_matrix.h" + +class BaseMetalRenderer : public Renderer +{ +protected: + bool BaseInit(); + +public: + void Term() override; + BaseTextureCacheData *GetTexture(TSP tsp, TCW tcw, int area) override; + void Process(TA_context* ctx) override; + void RenderFramebuffer(const FramebufferInfo& info) override; + void WaitIdle(); + + bool RenderLastFrame() override { + return !clearLastFrame; + } + + bool GetLastFrame(std::vector& data, int& width, int& height) override { + return MetalContext::Instance()->GetLastFrame(data, width, height); + } + +protected: + virtual void resize(int w, int h) + { + viewport.width = w; + viewport.height = h; + } + + void clearTextureCache() override { textureCache.Clear(); } + + void CheckFogTexture(); + void CheckPaletteTexture(); + bool presentFramebuffer(); + + MetalShaders shaderManager; + std::unique_ptr fogTexture; + std::unique_ptr paletteTexture; + MetalCommandPool texCommandPool; + MetalCommandPool fbCommandPool; + id texCommandBuffer = nil; + std::vector> framebufferTextures; + int framebufferTexIndex = 0; + // Scratch buffer for RenderFramebuffer(). A member, not a local, so the + // ~1.2MB (640x480x4) allocation is made once instead of every vblank -- + // RenderFramebuffer runs per-vblank under EmulateFramebuffer and on every + // direct VRAM framebuffer write (BIOS, menus, load screens, 2D titles). + // Render-thread only; holds no game state across a reload. + PixelBuffer framebufferScratch; + MetalTextureCache textureCache; + MTLViewport viewport = MTLViewport { 0, 0, 640, 480, 0, 1 }; + bool framebufferRendered = false; + // The context being rendered (set in Process, handed to the drawers in + // Render). Replaces the removed _pvrrc global (90301d5c3). + rend_context *rendContext = nullptr; +}; + diff --git a/core/rend/metal/metal_renderer.mm b/core/rend/metal/metal_renderer.mm new file mode 100644 index 0000000000..cec8d5ff70 --- /dev/null +++ b/core/rend/metal/metal_renderer.mm @@ -0,0 +1,477 @@ +/* + Copyright 2025 flyinghead + + This file is part of Flycast. + + Flycast is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 2 of the License, or + (at your option) any later version. + + Flycast is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with Flycast. If not, see . +*/ + +#include "metal_renderer.h" +#include "hw/pvr/ta.h" +#include "hw/pvr/Renderer_if.h" +#include "rend/texconv.h" + +bool BaseMetalRenderer::BaseInit() +{ + texCommandPool.Init(); + fbCommandPool.Init(); + custom_texture.setCapabilities(CustomTextureCapabilities::rgbaOnly(CustomTextureBackend::Metal, + [MetalContext::Instance()->GetDevice() supportsFamily:MTLGPUFamilyApple1] + && ![MetalContext::Instance()->GetDevice() supportsFamily:MTLGPUFamilyApple3] ? 8192 : 16384)); + + return true; +} + +void BaseMetalRenderer::Term() +{ + WaitIdle(); + MetalContext::Instance()->PresentFrame(nil, MTLViewport {}, 0); +#ifdef VIDEO_ROUTING + os_VideoRoutingTermMetal(); +#endif + texCommandPool.Term(); + fbCommandPool.Term(); + textureCache.Clear(); + fogTexture = nil; + paletteTexture = nil; + framebufferTextures.clear(); + framebufferTexIndex = 0; + shaderManager.term(); +} + +BaseTextureCacheData *BaseMetalRenderer::GetTexture(TSP tsp, TCW tcw, int area) +{ + MetalTexture* tf = textureCache.getTextureCacheData(tsp, tcw, area); + + if (tf->NeedsUpdate()) { + tf->SetCommandBuffer(texCommandBuffer); + + if (!tf->Update()) + { + tf->SetCommandBuffer(nil); + return nullptr; + } + } + else if (tf->IsCustomTextureAvailable()) { + tf->SetCommandBuffer(texCommandBuffer); + tf->CheckCustomTexture(); + } + tf->SetCommandBuffer(nil); + textureCache.SetInFlight(tf); + + return tf; +} + +void BaseMetalRenderer::Process(TA_context *ctx) +{ + // This runs on the emu/render thread, which has no autorelease pool of its + // own — without one, every autoreleased ObjC temporary from the texture + // uploads below accumulates for the lifetime of the thread. Draw() already + // pools; Process/RenderFramebuffer/PresentFrame need the same treatment. + @autoreleasepool { + rendContext = &ctx->rend; + if (!ctx->rend.isRTT) { + framebufferRendered = false; + if (!config::EmulateFramebuffer) + clearLastFrame = false; + } + if (resetTextureCache) { + textureCache.Clear(); + resetTextureCache = false; + } + + texCommandPool.BeginFrame(); + textureCache.SetCurrentIndex(texCommandPool.GetIndex()); + textureCache.Cleanup(); + + texCommandBuffer = texCommandPool.Allocate(); + + ta_parse(ctx, true); + + // TODO can't update fog or palette twice in multi render + CheckFogTexture(); + CheckPaletteTexture(); + texCommandBuffer = nil; + } // @autoreleasepool +} + +void BaseMetalRenderer::RenderFramebuffer(const FramebufferInfo &info) +{ + @autoreleasepool { + framebufferTexIndex = (framebufferTexIndex + 1) % 3; + + if (framebufferTextures.size() != 3) + framebufferTextures.resize(3); + + std::unique_ptr& curTexture = framebufferTextures[framebufferTexIndex]; + if (!curTexture) + { + curTexture = std::make_unique(); + curTexture->tex_type = TextureType::_8888; + } + + fbCommandPool.BeginFrame(); + id fbCommandBuffer = fbCommandPool.Allocate(); + + curTexture->SetCommandBuffer(fbCommandBuffer); + if (info.fb_r_ctrl.fb_enable == 0 || info.vo_control.blank_video == 1) + { + // Video output disabled + u8 rgba[]{ (u8)info.vo_border_col._red, (u8)info.vo_border_col._green, (u8)info.vo_border_col._blue, 255 }; + curTexture->UploadToGPU(1, 1, rgba, false); + } + else + { + int width; + int height; + ReadFramebuffer(info, framebufferScratch, width, height); + + curTexture->UploadToGPU(width, height, (u8*)framebufferScratch.data(), false); + } + curTexture->SetCommandBuffer(nil); + fbCommandBuffer = nil; + fbCommandPool.EndFrame(); + framebufferRendered = true; + clearLastFrame = false; + } // @autoreleasepool +} + +void BaseMetalRenderer::WaitIdle() +{ +// [commandBuffer waitUntilCompleted]; +// commandBuffer = nil; +} + +void BaseMetalRenderer::CheckFogTexture() { + + if (!fogTexture) + { + fogTexture = std::make_unique(); + fogTexture->tex_type = TextureType::_8; + updateFogTable = true; + } + if (!updateFogTable || !config::Fog) + return; + updateFogTable = false; + u8 texData[256]; + MakeFogTexture(texData); + + fogTexture->SetCommandBuffer(texCommandBuffer); + fogTexture->UploadToGPU(128, 2, texData, false); + fogTexture->SetCommandBuffer(nil); +} + +void BaseMetalRenderer::CheckPaletteTexture() { + + if (!paletteTexture) + { + paletteTexture = std::make_unique(); + paletteTexture->tex_type = TextureType::_8888; + } + else if (!updatePalette) + return; + updatePalette = false; + + paletteTexture->SetCommandBuffer(texCommandBuffer); + paletteTexture->UploadToGPU(1024, 1, (u8 *)palette32_ram, false); + paletteTexture->SetCommandBuffer(nil); +} + +bool BaseMetalRenderer::presentFramebuffer() +{ + if (framebufferTexIndex >= (int)framebufferTextures.size()) + return false; + MetalTexture *fbTexture = framebufferTextures[framebufferTexIndex].get(); + if (fbTexture == nullptr) + return false; + + MTLViewport viewport = { 0, 0, (float)fbTexture->GetTexture().width, (float)fbTexture->GetTexture().height, 1.0, 0 }; + + MetalContext::Instance()->PresentFrame(fbTexture->GetTexture(), viewport, + getDCFramebufferAspectRatio()); + return true; +} + +// NOTE: 'final' removed so OITMetalRenderer (in oit/oit_renderer.mm) can +// subclass and override the transparency-handling methods incrementally. +// The base class otherwise stays the regular Metal renderer for non-OIT +// games and serves as a fallback for everything OIT hasn't ported yet. +class MetalRenderer : public BaseMetalRenderer +{ +public: + bool Init() override + { + NOTICE_LOG(RENDERER, "MetalRenderer::Init"); + + // Returning false lets rend_init_renderer() fall back to rend_norend() + if (MetalContext::Instance() == nullptr) { + WARN_LOG(RENDERER, "MetalRenderer::Init: Metal GPU context unavailable, skipping"); + return false; + } + + textureDrawer.Init(&samplerManager, &shaderManager, &textureCache); + textureDrawer.SetCommandPool(&texCommandPool); + + screenDrawer.Init(&samplerManager, &shaderManager, viewport); + screenDrawer.SetCommandPool(&texCommandPool); + BaseInit(); + emulateFramebuffer = config::EmulateFramebuffer; + + return true; + } + + void Term() override + { + NOTICE_LOG(RENDERER, "MetalRenderer::Term"); + WaitIdle(); + screenDrawer.Term(); + textureDrawer.Term(); + texCommandPool.Term(); + samplerManager.term(); + BaseMetalRenderer::Term(); + } + + void Process(TA_context* ctx) override + { + if (emulateFramebuffer != config::EmulateFramebuffer) + { + screenDrawer.EndRenderPass(); + WaitIdle(); + screenDrawer.Term(); + screenDrawer.Init(&samplerManager, &shaderManager, viewport); + // BaseInit(screenDrawer.GetRenderPass()); + emulateFramebuffer = config::EmulateFramebuffer; + } + else if (ctx->rend.isRTT) { + screenDrawer.EndRenderPass(); + } + BaseMetalRenderer::Process(ctx); + } + + bool Render() override + { + MetalDrawer *drawer; + if (rendContext->isRTT) + drawer = &textureDrawer; + else { + resize(rendContext->framebufferWidth, rendContext->framebufferHeight); + drawer = &screenDrawer; + } + drawer->setRendContext(rendContext); + + drawer->Draw(fogTexture.get(), paletteTexture.get()); + // Always end the render pass here. Process() does its texture work on + // this pool's command buffer, and mipmap generation opens a blit + // encoder there: Metal allows one active encoder per command buffer, + // so a screen pass left open for a second render before Present() + // (unthreaded, DelayFrameSwapping) would still be encoding when the + // next Process() runs. A repeated screen render starts a new pass + // that loads the color attachment. Present() is unaffected: its + // EndRenderPass() is then a no-op and frameRendered stays set. + drawer->EndRenderPass(); + if (!config::EmulateFramebuffer && !rendContext->isRTT && config::ThreadedRendering) + { + // GPU-completion-before-RENDER_DONE invariant. + // + // In threaded mode the SH4 thread blocks in rend_end_render() on + // renderEnd until PvrMessageQueue::render() calls renderEnd.Set() + // immediately after this Render() returns. EndRenderPass() above + // only commits the screen command buffer, so without this the SH4 + // thread would be released (and games like Sonic Adventure, + // Resident Evil 2 and Unreal Tournament read VRAM/framebuffer on + // the holly_RENDER_DONE interrupt) while the GPU is still drawing, + // yielding garbage or boot failures. + // + // Block on the just-committed buffer's MTLSharedEvent until the + // GPU finishes, mirroring the EndFrameAndWait() the RTT and + // framebuffer-emulation paths already do. With + // ThreadedRendering=false the SH4 thread never waits on renderEnd. + texCommandPool.WaitForLastFrame(); + } + + return !rendContext->isRTT; + } + + bool Present() override + { + if (clearLastFrame) + return false; + if (config::EmulateFramebuffer || framebufferRendered) + return presentFramebuffer(); + else + return screenDrawer.PresentFrame(); + } + +protected: + void resize(int w, int h) override + { + if ((u32)w == viewport.width && (u32)h == viewport.height) + return; + BaseMetalRenderer::resize(w, h); + // WaitIdle(); + screenDrawer.Init(&samplerManager, &shaderManager, viewport); + } + +private: + MetalSamplers samplerManager; + MetalScreenDrawer screenDrawer; + MetalTextureDrawer textureDrawer; + bool emulateFramebuffer = false; +}; + +Renderer* rend_Metal() +{ + return new MetalRenderer(); +} + +// --------------------------------------------------------------------------- +// Order-Independent Transparency (per-pixel sorting) Metal renderer. +// Port of core/rend/vulkan/oit: translucent fragments are collected into a +// per-pixel linked list, then sorted and blended in a final resolve pass. +// --------------------------------------------------------------------------- + +#include "oit/metal_oit_buffer.h" +#include "oit/metal_oit_pipeline.h" +#include "oit/metal_oit_drawer.h" + +// Screen, RTT and presentation commands share a queue. The bounded wait below +// is for CPU-side render completion; GPU resource ordering does not depend on it. + +class OITMetalRenderer : public MetalRenderer +{ +public: + bool Init() override + { + if (!MetalRenderer::Init()) + return false; + if (viewport.width > 0 && viewport.height > 0) + oitBuffers.Init((int)viewport.width, (int)viewport.height); + + // The OIT pipeline manager + MSL library are owned by + // MetalOITScreenDrawer (its screenPipelineManager). No standalone + // copy needed — that would just compile the same MSL twice. + oitScreenDrawer.Init(&shaderManager, &oitBuffers, viewport, &oitSamplers); + oitScreenDrawer.SetCommandPool(&texCommandPool); + oitTextureDrawer.Init(&shaderManager, &oitBuffers, &textureCache, &oitSamplers); + oitTextureDrawer.SetCommandPool(&texCommandPool); + oitEmulateFramebuffer = config::EmulateFramebuffer; + + return true; + } + + void Term() override + { + oitScreenDrawer.Term(); + oitTextureDrawer.Term(); + oitSamplers.term(); + oitBuffers.Term(); + MetalRenderer::Term(); + } + + void Process(TA_context* ctx) override + { + if (oitEmulateFramebuffer != config::EmulateFramebuffer) + { + oitScreenDrawer.EndFrame(); + WaitIdle(); + oitScreenDrawer.Term(); + oitScreenDrawer.Init(&shaderManager, &oitBuffers, viewport, &oitSamplers); + oitScreenDrawer.SetCommandPool(&texCommandPool); + oitEmulateFramebuffer = config::EmulateFramebuffer; + } + else if (ctx->rend.isRTT) { + oitScreenDrawer.EndFrame(); + } + BaseMetalRenderer::Process(ctx); + } + + bool Render() override + { + if (viewport.width <= 0 || viewport.height <= 0) + return MetalRenderer::Render(); + + if (rendContext->isRTT) { + oitTextureDrawer.setRendContext(rendContext); + oitTextureDrawer.NewFrame(); + oitTextureDrawer.Draw(fogTexture.get(), paletteTexture.get()); + oitTextureDrawer.EndFrame(); + return false; + } + + resize(rendContext->framebufferWidth, rendContext->framebufferHeight); + oitScreenDrawer.setRendContext(rendContext); + oitScreenDrawer.NewFrame(); + oitScreenDrawer.Draw(fogTexture.get(), paletteTexture.get()); + // EndFrame/PresentFrame happen in Present() below — matches the + // non-OIT lifecycle where Render only fills the command buffer. + // + // Same GPU-completion-before-RENDER_DONE invariant as + // MetalRenderer::Render() above, and the cross-queue present fix + // described at the top of this file. Unconditional: the OIT screen + // drawer shares texCommandPool, so end the frame now (commits via + // commandPool->EndFrame()) and block on the committed buffer's + // MTLSharedEvent before returning. That both keeps renderEnd.Set() in + // PvrMessageQueue::render() from releasing the SH4 thread early and + // stops MetalContext's present queue sampling the attachment mid-write. + // Present()->PresentFrame() is re-entrant here: its EndFrame() is a + // no-op (frameStarted now false) and frameRendered stays set, so the + // frame still presents. + oitScreenDrawer.EndFrame(); + texCommandPool.WaitForLastFrame(); + return true; + } + + bool Present() override + { + if (clearLastFrame) + return false; + if (config::EmulateFramebuffer || framebufferRendered) + return presentFramebuffer(); + return oitScreenDrawer.PresentFrame(); + } + +protected: + // Port of OITVulkanRenderer::resize: the screen drawer renders at the + // PVR framebuffer size scaled by rend.Resolution, which Renderer_if + // computes into framebufferWidth/Height. Without this the OIT viewport + // stayed at BaseMetalRenderer's 640x480 default. + // + // No GPU wait needed here (BaseMetalRenderer::WaitIdle is a stub): every + // screen Render() ends with EndFrame() + WaitForLastFrame() and every RTT + // frame with EndFrameAndWait(), so nothing is still writing the old + // a-buffer or attachments, and command buffers retain what they reference. + // + // Skips MetalRenderer::resize on purpose: that re-inits the regular + // screen drawer, which this renderer never draws with. + void resize(int w, int h) override + { + if ((u32)w == viewport.width && (u32)h == viewport.height) + return; + BaseMetalRenderer::resize(w, h); + // The a-buffer head-pointer array is one u32 per pixel. + oitBuffers.Init(w, h); + oitScreenDrawer.Init(&shaderManager, &oitBuffers, viewport, &oitSamplers); + } + + MetalOITBuffers oitBuffers; + MetalSamplers oitSamplers; + MetalOITScreenDrawer oitScreenDrawer; + MetalOITTextureDrawer oitTextureDrawer; + bool oitEmulateFramebuffer = false; +}; + +Renderer* rend_OITMetal() +{ + return new OITMetalRenderer(); +} diff --git a/core/rend/metal/metal_shaders.h b/core/rend/metal/metal_shaders.h new file mode 100644 index 0000000000..548c1ee617 --- /dev/null +++ b/core/rend/metal/metal_shaders.h @@ -0,0 +1,226 @@ +/* + Copyright 2025 flyinghead + + This file is part of Flycast. + + Flycast is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 2 of the License, or + (at your option) any later version. + + Flycast is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with Flycast. If not, see . +*/ + +#pragma once +#include "metal_apple.h" + +#include "types.h" + +#include "types.h" +#include +#include + +struct MetalVertexShaderParams +{ + bool gouraud; + bool naomi2; + bool divPosZ; + /// When true, vertex shader emits flat vtx_index for OIT collect (polyNumber + vertex_id). + bool oitCollect = false; + /// Two-volume polys: read the second parameter set (col1/spc1/uv1). The drawer + /// issues such a poly twice, once per set, gated by the modifier-volume stencil. + bool area1 = false; + + u32 hash() { return (u32)gouraud | ((u32)naomi2 << 1) | ((u32)divPosZ << 2) | ((u32)oitCollect << 3) | ((u32)area1 << 4); } +}; + +struct MetalFragmentShaderParams +{ + bool alphaTest; + bool insideClipTest; + bool useAlpha; + bool texture; + bool ignoreTexAlpha; + int shaderInstr; + bool offset; + int fog; + bool gouraud; + bool bumpmap; + bool clamping; + bool trilinear; + int palette; + bool divPosZ; + bool dithering; + // When true, fs_main is specialised for the OIT collect pass (linked-list append). + bool oitMode = false; + // OIT drawers on Apple GPUs keep the opaque depth in tile memory (colour + // attachment 1): OP/PT variants write it, collect variants read it with + // framebuffer fetch instead of sampling a depth copy at texture 4. + bool oitTileDepth = false; + // Collect only: use the [[early_fragment_tests]] entry point (fs_main_early) + // so the stencil test rejects fragments before the a-buffer append. + bool earlyFragmentTests = false; + + u32 hash() + { + return ((u32)alphaTest) | ((u32)insideClipTest << 1) | ((u32)useAlpha << 2) + | ((u32)texture << 3) | ((u32)ignoreTexAlpha << 4) | (shaderInstr << 5) + | ((u32)offset << 7) | ((u32)fog << 8) | ((u32)gouraud << 10) + | ((u32)bumpmap << 11) | ((u32)clamping << 12) | ((u32)trilinear << 13) + | ((u32)palette << 14) | ((u32)divPosZ << 16) | ((u32)dithering << 17) + | ((u32)oitMode << 18) | ((u32)oitTileDepth << 19) | ((u32)earlyFragmentTests << 20); + } +}; + +struct MetalModVolShaderParams +{ + bool naomi2; + bool divPosZ; + + u32 hash() { return (u32)naomi2 | ((u32)divPosZ << 1); } +}; + +// std140 alignment required +struct MetalVertexShaderUniforms +{ + glm::mat4 ndcMat; +}; + +// std140 alignment required +struct alignas(16) MetalFragmentShaderUniforms +{ + float colorClampMin[4]; + float colorClampMax[4]; + float sp_FOG_COL_RAM[4]; // Only using 3 elements but easier for std140 + float sp_FOG_COL_VERT[4]; // same comment + float ditherDivisor[4]; + float cp_AlphaTestValue; + float sp_FOG_DENSITY; +}; +// MSL float4 members give this block 16-byte alignment, including tail padding. +// The final packed block must cover the shader's full argument size. +static_assert(sizeof(MetalFragmentShaderUniforms) == 96); + +// std140 alignment required +struct MetalN2VertexShaderUniforms +{ + glm::mat4 mvMat; + glm::mat4 normalMat; + glm::mat4 projMat; + int envMapping[2]; + int bumpMapping; + int polyNumber; + + float glossCoef[2]; + int constantColor[2]; +}; + +class MetalShaders +{ +public: + MetalShaders(); + + id GetBlitVertexShader() { return blitVertexShader; } + id GetBlitFragmentShader() { return blitFragmentShader; } + + id GetModVolVertexShader(const MetalModVolShaderParams& params) { return getShader(modVolVertexShaders, params); } + id GetModVolFragmentShader(bool divPosZ) { + auto modVolFragmentShader = modVolFragmentShaders.find(divPosZ); + if (modVolFragmentShader != modVolFragmentShaders.end()) + return modVolFragmentShader->second; + + modVolFragmentShaders[divPosZ] = compileShader(divPosZ); + return modVolFragmentShaders[divPosZ]; + } + + id GetQuadVertexShader(bool rotate) { + if (rotate) + { + if (quadRotateVertexShader == nil) + quadRotateVertexShader = compileQuadVertexShader(true); + return quadRotateVertexShader; + } + else + { + if (quadVertexShader == nil) + quadVertexShader = compileQuadVertexShader(false); + return quadVertexShader; + } + } + + id GetQuadFragmentShader(bool ignoreTexAlpha) { + if (ignoreTexAlpha) + { + if (quadNoAlphaFragmentShader == nil) + quadNoAlphaFragmentShader = compileQuadFragmentShader(true); + return quadNoAlphaFragmentShader; + } + else + { + if (quadFragmentShader == nil) + quadFragmentShader = compileQuadFragmentShader(false); + return quadFragmentShader; + } + } + + id GetVertexShader(const MetalVertexShaderParams& params) { return getShader(vertexShaders, params); } + id GetFragmentShader(const MetalFragmentShaderParams& params) { return getShader(fragmentShaders, params); } + + void term() + { + vertexShaders.clear(); + fragmentShaders.clear(); + } + +private: + id blitShaderLibrary; + id modVolShaderLibrary; + id n2ModVolVertexShaderLibrary; + id vertexShaderLibrary; + id n2VertexShaderLibrary; + id fragmentShaderLibrary; + id quadShaderLibrary; + MTLFunctionConstantValues* vertexShaderConstants; + MTLFunctionConstantValues* fragmentShaderConstants; + MTLFunctionConstantValues* modVolShaderConstants; + MTLFunctionConstantValues* quadShaderConstants; + + template + id getShader(std::map> &map, T params) + { + u32 h = params.hash(); + auto it = map.find(h); + if (it != map.end()) + return it->second; + id fn = compileShader(params); + if (fn != nil) + map[h] = fn; + return fn; + } + id compileShader(const MetalVertexShaderParams& params); + id compileShader(const MetalFragmentShaderParams& params); + id compileShader(const MetalModVolShaderParams& params); + id compileShader(bool divPosZ); + id compileQuadVertexShader(bool rotate); + id compileQuadFragmentShader(bool ignoreTexAlpha); + + id blitVertexShader; + id blitFragmentShader; + + std::map> modVolVertexShaders; + std::map> modVolFragmentShaders; + + std::map> vertexShaders; + std::map> fragmentShaders; + + id quadVertexShader; + id quadRotateVertexShader; + id quadFragmentShader; + id quadNoAlphaFragmentShader; +}; diff --git a/core/rend/metal/metal_shaders.mm b/core/rend/metal/metal_shaders.mm new file mode 100644 index 0000000000..8a6897e7ad --- /dev/null +++ b/core/rend/metal/metal_shaders.mm @@ -0,0 +1,1402 @@ +/* + Copyright 2025 flyinghead + + This file is part of Flycast. + + Flycast is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 2 of the License, or + (at your option) any later version. + + Flycast is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with Flycast. If not, see . +*/ + +#include "metal_shaders.h" + +#include "metal_context.h" + +static const char* metalErrorString(NSError* error) +{ + if (error == nil) + return "no NSError (Metal specialization failed silently)"; + const char* desc = error.localizedDescription.UTF8String; + return desc ? desc : "unknown Metal error"; +} + +static const char VertexShaderSource[] = R"( +#include +#include + +using namespace metal; + +constant bool pp_gouraud [[function_constant(0)]]; +constant bool div_pos_z [[function_constant(1)]]; +constant bool pp_area1 [[function_constant(2)]]; // two-volume: use the second parameter set + +constant bool is_flat = pp_gouraud == 0; +constant bool is_not_flat = !is_flat; + +struct VertexShaderUniforms +{ + float4x4 ndc_mat; +}; + +struct VertexIn +{ + float4 in_pos [[attribute(0)]]; + float4 in_base [[attribute(1)]]; + float4 in_offs [[attribute(2)]]; + float2 in_uv [[attribute(3)]]; + float4 in_base1 [[attribute(4)]]; + float4 in_offs1 [[attribute(5)]]; + float2 in_uv1 [[attribute(6)]]; +}; + +struct VertexOut +{ + float4 flat_vtx_base [[flat, function_constant(is_flat)]]; + float4 flat_vtx_offs [[flat, function_constant(is_flat)]]; + float4 vtx_base [[function_constant(is_not_flat)]]; + float4 vtx_offs [[function_constant(is_not_flat)]]; + float3 vtx_uv; + float4 position [[position, invariant]]; +}; + +struct VertexOutOIT +{ + float4 flat_vtx_base [[flat, function_constant(is_flat)]]; + float4 flat_vtx_offs [[flat, function_constant(is_flat)]]; + float4 vtx_base [[function_constant(is_not_flat)]]; + float4 vtx_offs [[function_constant(is_not_flat)]]; + float3 vtx_uv; + uint vtx_index [[flat]]; + float4 position [[position, invariant]]; +}; + +vertex VertexOut vs_main(VertexIn in [[stage_in]], constant VertexShaderUniforms& uniforms [[buffer(0)]]) +{ + float4 vpos = uniforms.ndc_mat * in.in_pos; + const float4 v_base = pp_area1 ? in.in_base1 : in.in_base; + const float4 v_offs = pp_area1 ? in.in_offs1 : in.in_offs; + const float2 v_uv = pp_area1 ? in.in_uv1 : in.in_uv; + + if (div_pos_z) { + vpos /= vpos.z; + vpos.z = vpos.w; + } + + VertexOut out = {}; + if (is_flat) { + out.flat_vtx_base = v_base; + out.flat_vtx_offs = v_offs; + } else { + out.vtx_base = v_base; + out.vtx_offs = v_offs; + } + out.vtx_uv = float3(v_uv, vpos.z); + + if (pp_gouraud && !div_pos_z) { + if (is_flat) { + out.flat_vtx_base *= vpos.z; + out.flat_vtx_offs *= vpos.z; + } else { + out.vtx_base *= vpos.z; + out.vtx_offs *= vpos.z; + } + } + + if (!div_pos_z) { + out.vtx_uv.xy *= vpos.z; + vpos.w = 1.0; + vpos.z = 0.0; + } + + out.position = vpos; + + return out; +} + +vertex VertexOutOIT vs_main_oit(VertexIn in [[stage_in]], constant VertexShaderUniforms& uniforms [[buffer(0)]], + constant int& poly_number [[buffer(1)]], uint vid [[vertex_id]]) +{ + float4 vpos = uniforms.ndc_mat * in.in_pos; + const float4 v_base = pp_area1 ? in.in_base1 : in.in_base; + const float4 v_offs = pp_area1 ? in.in_offs1 : in.in_offs; + const float2 v_uv = pp_area1 ? in.in_uv1 : in.in_uv; + + if (div_pos_z) { + vpos /= vpos.z; + vpos.z = vpos.w; + } + + VertexOutOIT out = {}; + if (is_flat) { + out.flat_vtx_base = v_base; + out.flat_vtx_offs = v_offs; + } else { + out.vtx_base = v_base; + out.vtx_offs = v_offs; + } + out.vtx_uv = float3(v_uv, vpos.z); + + if (pp_gouraud && !div_pos_z) { + if (is_flat) { + out.flat_vtx_base *= vpos.z; + out.flat_vtx_offs *= vpos.z; + } else { + out.vtx_base *= vpos.z; + out.vtx_offs *= vpos.z; + } + } + + if (!div_pos_z) { + out.vtx_uv.xy *= vpos.z; + vpos.w = 1.0; + vpos.z = 0.0; + } + + out.position = vpos; + out.vtx_index = uint(poly_number) + vid; + + return out; +} +)"; + +static const char FragmentShaderSource[] = R"( +#include +#include +#define PI 3.1415926 + +using namespace metal; + +// OIT per-pixel linked-list element, gated under pp_oit_mode. Layout +// must match the `Pixel` struct used by the resolve pass in +// metal_oit_shaders.h (16 B: packed RGBA8 color, depth, seq_num, next). +struct OITPixel { + uint color; + float depth; + uint seq_num; + uint next; +}; + +struct OITViewportUniforms { + uint viewportWidth; + uint viewportHeight; + uint pixelBufferSize; +}; + +constant bool cp_alpha_test [[function_constant(0)]]; +constant bool pp_clip_inside [[function_constant(1)]]; +constant bool pp_use_alpha [[function_constant(2)]]; +constant bool pp_texture [[function_constant(3)]]; +constant bool pp_ignore_tex_a [[function_constant(4)]]; +constant int pp_shad_instr [[function_constant(5)]]; +constant bool pp_offset [[function_constant(6)]]; +constant int pp_fog_ctrl [[function_constant(7)]]; +constant bool pp_gouraud [[function_constant(8)]]; +constant bool pp_bump_map [[function_constant(9)]]; +constant bool color_clamping [[function_constant(10)]]; +constant bool pp_trilinear [[function_constant(11)]]; +constant int pp_palette [[function_constant(12)]]; +constant bool div_pos_z [[function_constant(13)]]; +constant bool dithering [[function_constant(14)]]; +// When true, fs_main appends a fragment to the OIT per-pixel linked list +// instead of writing the colour to the framebuffer. +constant bool pp_oit_mode [[function_constant(15)]]; +// Opaque depth for the collect's manual depth test kept in tile memory +// (Apple GPUs): OP/PT draws also write their depth to colour attachment 1, and +// the collect reads it back with framebuffer fetch. When false the collect +// reads a copy of the depth attachment bound at texture 4 instead. +constant bool oit_tile_depth [[function_constant(16)]]; + +constant bool has_fog_table = pp_fog_ctrl != 2; +constant bool has_palette = pp_palette != 0; +constant bool is_flat = pp_gouraud == 0; +constant bool is_not_flat = !is_flat; +constant bool oit_depth_out = oit_tile_depth && !pp_oit_mode; +constant bool oit_depth_fetch = oit_tile_depth && pp_oit_mode; +constant bool oit_depth_tex = !oit_tile_depth && pp_oit_mode; + +struct FragmentShaderUniforms +{ + float4 color_clamp_min; + float4 color_clamp_max; + float4 sp_fog_col_ram; + float4 sp_fog_col_vert; + float4 dither_divisor; + float cp_alpha_test_value; + float sp_fog_density; +}; + +struct PushBlock +{ + float4 clip_test; + float trilinear_alpha; + float palette_index; + float2 pad; +}; + +struct VertexOut +{ + float4 flat_vtx_base [[flat, function_constant(is_flat)]]; + float4 flat_vtx_offs [[flat, function_constant(is_flat)]]; + float4 vtx_base [[function_constant(is_not_flat)]]; + float4 vtx_offs [[function_constant(is_not_flat)]]; + float3 vtx_uv; + uint vtx_index [[flat, function_constant(pp_oit_mode)]]; + float4 position [[position]]; +}; + +struct FragmentOut +{ + float4 color [[color(0)]]; + // Tile-memory opaque depth, R32Float. Masked out (writeMask None) for + // every draw that doesn't write the depth attachment. + float opaque_depth [[color(1), function_constant(oit_depth_out)]]; + float depth [[depth(any)]]; +}; + +// fs_main_early: OIT collect draws that must be stencil-tested before the +// fragment function runs. No [[depth]] output, which [[early_fragment_tests]] +// forbids. +struct FragmentOutEarly +{ + float4 color [[color(0)]]; +}; + +struct FragmentResult +{ + float4 color; + float depth; +}; + +float fog_mode2(float w, constant FragmentShaderUniforms& uniforms, + texture2d fog_table, sampler fog_table_sampler) +{ + float z = 0.0; + + if (div_pos_z) { + z = clamp(uniforms.sp_fog_density / w, 1.0, 255.9999); + } else { + z = clamp(uniforms.sp_fog_density * w, 1.0, 255.9999); + } + + float exp = floor(log2(z)); + float m = z * 16.0 / powr(2.0, exp) - 16.0; + float idx = floor(m) + exp * 16.0 + 0.5; + float4 fog_coef = fog_table.sample(fog_table_sampler, float2(idx / 128.0, 0.75 - (m - floor(m)) / 2.0)); + return fog_coef.r; +} + +float4 color_clamp(float4 col, constant FragmentShaderUniforms& uniforms) +{ + if (color_clamping) + { + return clamp(col, uniforms.color_clamp_min, uniforms.color_clamp_max); + } else { + return col; + } +} + +float4 get_palette_entry(texture2d palette, sampler palette_sampler, + float col_idx, constant PushBlock& push_constants) +{ + float2 c = float2(col_idx * 255.0 / 1023.0 + push_constants.palette_index, 0.5); + return palette.sample(palette_sampler, c); +} + +float4 palette_pixel(texture2d texture, sampler texture_sampler, + texture2d palette, sampler palette_sampler, + float3 coords, constant PushBlock& push_constants) +{ + if (div_pos_z) { + return get_palette_entry(palette, palette_sampler, texture.sample(texture_sampler, coords.xy).r, push_constants); + } else { + return get_palette_entry(palette, palette_sampler, texture.sample(texture_sampler, float2(coords.xy / coords.z)).r, push_constants); + } +} + +float4 palette_pixel_bilinear(texture2d texture, sampler texture_sampler, + texture2d palette, sampler palette_sampler, + float3 coords, constant PushBlock& push_constants) +{ + if (!div_pos_z) { + coords.xy /= coords.z; + } + + float2 tex_size = float2(texture.get_width(), texture.get_height()); + float2 pix_coord = coords.xy * tex_size - 0.5; // Coordinates of top left pixel + float2 origin_pix_coords = floor(pix_coord); + + float2 sample_uv = (origin_pix_coords + 0.5) / tex_size; // UV coordinates of center of top left pixel + + // Sample from all surrounding texels + float4 c00 = get_palette_entry(palette, palette_sampler, texture.sample(texture_sampler, sample_uv).r, push_constants); + float4 c01 = get_palette_entry(palette, palette_sampler, texture.sample(texture_sampler, sample_uv, int2(0, 1)).r, push_constants); + float4 c11 = get_palette_entry(palette, palette_sampler, texture.sample(texture_sampler, sample_uv, int2(1, 1)).r, push_constants); + float4 c10 = get_palette_entry(palette, palette_sampler, texture.sample(texture_sampler, sample_uv, int2(1, 0)).r, push_constants); + + float2 weight = pix_coord - origin_pix_coords; + + // Bi-linear mixing + float4 temp0 = mix(c00, c10, weight.x); + float4 temp1 = mix(c01, c11, weight.x); + return mix(temp0, temp1, weight.y); +} + +inline FragmentResult fs_impl(VertexOut in, constant FragmentShaderUniforms& uniforms, + constant PushBlock& push_constants, + texture2d tex, sampler tex_sampler, + texture2d fog_table, sampler fog_table_sampler, + texture2d palette, sampler palette_sampler, + device atomic_uint* oit_counter, device OITPixel* oit_pixels, + device atomic_uint* oit_head, constant OITViewportUniforms& oit_vp, + float oit_opaque_depth) +{ + float w; + + if (div_pos_z) { + w = 100000.0 / in.vtx_uv.z; + } else { + w = 100000.0 * in.vtx_uv.z; + } + + float depth = log2(1.0 + max(w, -0.999999)) / 34.0; + + if (pp_oit_mode) { + // OIT collect: manual depth test against the opaque + punch-through + // depth (GEqual, as the autosort depth state), before anything else so + // occluded fragments skip the texturing below. The hardware test can't + // do this: fs_main writes [[depth]], so it runs late, after the + // a-buffer append has already happened. Matches Vulkan's + // subpassLoad(DepthTex) test in oit_shaders.cpp. + if (depth < oit_opaque_depth) { + discard_fragment(); + return FragmentResult { float4(0.0), depth }; + } + } + + // Clip inside the box + if (pp_clip_inside) { + if (in.position.x >= push_constants.clip_test.x && in.position.x <= push_constants.clip_test.z + && in.position.y >= push_constants.clip_test.y && in.position.y <= push_constants.clip_test.w) { + discard_fragment(); + return FragmentResult { float4(0.0), depth }; + } + } + + float4 color; + float4 offset; + + if (is_flat) { + color = in.flat_vtx_base; + offset = in.flat_vtx_offs; + } else { + color = in.vtx_base; + offset = in.vtx_offs; + } + + if (pp_gouraud && !div_pos_z) { + color /= in.vtx_uv.z; + offset /= in.vtx_uv.z; + } + + if (!pp_use_alpha) { + color.a = 1.0; + } + + if (pp_fog_ctrl == 3) { + color = float4(uniforms.sp_fog_col_ram.rgb, fog_mode2(in.vtx_uv.z, uniforms, fog_table, fog_table_sampler)); + } + + if (pp_texture) { + float4 tex_col; + + if (pp_palette == 0) { + if (div_pos_z) { + tex_col = tex.sample(tex_sampler, in.vtx_uv.xy); + } else { + tex_col = tex.sample(tex_sampler, float2(in.vtx_uv.xy / in.vtx_uv.z)); + } + } else { + if (pp_palette == 1) { + tex_col = palette_pixel(tex, tex_sampler, palette, palette_sampler, in.vtx_uv, push_constants); + } else { + tex_col = palette_pixel_bilinear(tex, tex_sampler, palette, palette_sampler, in.vtx_uv, push_constants); + } + } + + if (pp_bump_map) { + float s = PI / 2.0 * (tex_col.a * 15.0 * 16.0 + tex_col.r * 15.0) / 255.0; + float r = 2.0 * PI * (tex_col.g * 15.0 * 16.0 + tex_col.b * 15.0) / 255.0; + tex_col.a = clamp(offset.a + offset.r * sin(s) + offset.g * cos(s) * cos(r - 2.0 * PI * offset.b), 0.0, 1.0); + tex_col.rgb = float3(1.0, 1.0, 1.0); + } else { + if (pp_ignore_tex_a) + tex_col.a = 1.0; + } + + if (pp_shad_instr == 0) { + color = tex_col; + } else if (pp_shad_instr == 1) { + color.rgb *= tex_col.rgb; + color.a = tex_col.a; + } else if (pp_shad_instr == 2) { + color.rgb = mix(color.rgb, tex_col.rgb, tex_col.a); + } else if (pp_shad_instr == 3) { + color *= tex_col; + } + + if (pp_offset && !pp_bump_map) { + color.rgb += offset.rgb; + } + } + + color = color_clamp(color, uniforms); + + if (pp_fog_ctrl == 0) { + color.rgb = mix(color.rgb, uniforms.sp_fog_col_ram.rgb, fog_mode2(in.vtx_uv.z, uniforms, fog_table, fog_table_sampler)); + } + + if (pp_fog_ctrl == 1 && pp_offset && !pp_bump_map) { + color.rgb = mix(color.rgb, uniforms.sp_fog_col_vert.rgb, offset.a); + } + + if (pp_trilinear) + color *= push_constants.trilinear_alpha; + + if (cp_alpha_test) { + color.a = round(color.a * 255.0) / 255.0; + if (uniforms.cp_alpha_test_value > color.a) + discard_fragment(); + color.a = 1.0; + } + + if (dithering) { + constexpr float dither_table[16] = { + 5, 13, 7, 15, + 9, 1, 11, 3, + 6, 14, 4, 12, + 10, 2, 8, 0 + }; + + float r = dither_table[int(fmod(in.position.y, 4.0)) * 4 + int(fmod(in.position.x, 4.0))]; + float4 dv = float4(r, r, r, 1.0) / uniforms.dither_divisor; + color = clamp(floor(color * 255 + dv) / 255, 0, 1); + } + + if (pp_oit_mode) { + // OIT collect path. The colour computed above is the per-poly + // fragment colour we want to deposit into the per-pixel linked + // list; the resolve pass will sort by depth and back-to-front + // blend. + // + // (The manual depth test against the opaque depth ran at the top.) + // Step 1: atomically allocate a slot in the pixel buffer. + uint idx = atomic_fetch_add_explicit(oit_counter, 1u, memory_order_relaxed); + if (idx >= oit_vp.pixelBufferSize) { + // Buffer overflow — drop the fragment. MSL's + // discard_fragment() doesn't early-exit like GLSL's + // `discard`, so we must guard the writes below as well. + // Matches the Vulkan OIT behaviour at + // core/rend/vulkan/oit/oit_shaders.cpp:123. + discard_fragment(); + return FragmentResult { float4(0.0), depth }; + } + + // Step 2: compute the per-pixel head-pointer cell. + uint x = uint(in.position.x); + uint y = uint(in.position.y); + uint cell = x + y * oit_vp.viewportWidth; + + // Step 3: swap our slot index into the head; the previous head + // becomes our `next` link. + uint prev_head = atomic_exchange_explicit(&oit_head[cell], idx, memory_order_relaxed); + + // Step 4: pack the colour (RGBA8) and write the pixel record. + float4 c = clamp(color, 0.0, 1.0); + uint packed = (uint(c.r * 255.0) << 24) + | (uint(c.g * 255.0) << 16) + | (uint(c.b * 255.0) << 8) + | uint(c.a * 255.0); + + oit_pixels[idx].color = packed; + oit_pixels[idx].depth = depth; + oit_pixels[idx].seq_num = in.vtx_index; + oit_pixels[idx].next = prev_head; + + // The pipeline's colour writeMask is None for the OIT collect + // pass — the return value is discarded. + return FragmentResult { float4(0.0), depth }; + } + + return FragmentResult { color, depth }; +} + +#define FS_MAIN_ARGS \ + VertexOut in [[stage_in]], constant FragmentShaderUniforms& uniforms [[buffer(0)]], \ + constant PushBlock& push_constants [[buffer(1)]], \ + texture2d tex [[texture(0), function_constant(pp_texture)]], sampler tex_sampler [[sampler(0), function_constant(pp_texture)]], \ + texture2d fog_table [[texture(2), function_constant(has_fog_table)]], sampler fog_table_sampler [[sampler(2), function_constant(has_fog_table)]], \ + texture2d palette [[texture(3), function_constant(has_palette)]], sampler palette_sampler [[sampler(3), function_constant(has_palette)]], \ + /* OIT collect bindings, only present when pp_oit_mode is true. The drawer */ \ + /* binds buffers 2-5 on the collect encoder; non-OIT pipelines never see */ \ + /* these parameters (function_constant gating elides them entirely). */ \ + device atomic_uint* oit_counter [[buffer(2), function_constant(pp_oit_mode)]], \ + device OITPixel* oit_pixels [[buffer(3), function_constant(pp_oit_mode)]], \ + device atomic_uint* oit_head [[buffer(4), function_constant(pp_oit_mode)]], \ + constant OITViewportUniforms& oit_vp [[buffer(5), function_constant(pp_oit_mode)]], \ + /* Opaque + punch-through depth for the collect's manual depth test: */ \ + /* framebuffer fetch of the tile-memory copy, or a blitted depth copy. */ \ + float oit_opaque_fetch [[color(1), function_constant(oit_depth_fetch)]], \ + depth2d oit_opaque_tex [[texture(4), function_constant(oit_depth_tex)]] + +inline float oit_opaque_depth(VertexOut in, float fetched, depth2d tex) +{ + if (oit_depth_fetch) + return fetched; + if (oit_depth_tex) + return tex.read(uint2(in.position.xy)); + return 0.0; +} + +#define FS_IMPL_CALL \ + fs_impl(in, uniforms, push_constants, tex, tex_sampler, fog_table, fog_table_sampler, \ + palette, palette_sampler, oit_counter, oit_pixels, oit_head, oit_vp, \ + oit_opaque_depth(in, oit_opaque_fetch, oit_opaque_tex)) + +fragment FragmentOut fs_main(FS_MAIN_ARGS) +{ + FragmentResult r = FS_IMPL_CALL; + FragmentOut out; + out.color = r.color; + out.depth = r.depth; + // The depth attachment stores the fragment depth clamped to [0, 1]; keep + // the tile copy bit-identical to it. + if (oit_depth_out) + out.opaque_depth = saturate(r.depth); + return out; +} + +// OIT collect of the two-volume translucent polys. Each parameter set is +// drawn gated on the modifier-volume stencil mark (area 1 inside, area 2 +// outside). fs_main writes [[depth]], which forces the depth/stencil tests to +// run after the fragment function — after the a-buffer append — so a rejected +// fragment was collected anyway. Here the stencil test runs first and only +// fragments of the right area reach the append. Depth is still tested in +// fs_impl (the hardware compare is Always: position.z isn't the log depth). +[[early_fragment_tests]] +fragment FragmentOutEarly fs_main_early(FS_MAIN_ARGS) +{ + FragmentResult r = FS_IMPL_CALL; + FragmentOutEarly out; + out.color = r.color; + return out; +} +)"; + +static const char BlitShader[] = R"( +#include +using namespace metal; + +struct VertexOut { + float4 position [[position]]; + float2 texCoord; +}; + +vertex VertexOut vs_main(uint vertexID [[vertex_id]]) { + // Predefined positions and texture coordinates for a full-screen quad + float4 positions[4] = { + float4(-1.0, -1.0, 0.0, 1.0), // Bottom-left + float4( 1.0, -1.0, 0.0, 1.0), // Bottom-right + float4(-1.0, 1.0, 0.0, 1.0), // Top-left + float4( 1.0, 1.0, 0.0, 1.0) // Top-right + }; + + float2 texCoords[4] = { + float2(0.0, 1.0), // Bottom-left + float2(1.0, 1.0), // Bottom-right + float2(0.0, 0.0), // Top-left + float2(1.0, 0.0) // Top-right + }; + + VertexOut out; + out.position = positions[vertexID]; + out.texCoord = texCoords[vertexID]; + return out; +} + +fragment float4 fs_main(VertexOut in [[stage_in]], + texture2d sourceTexture [[texture(0)]]) { + constexpr sampler textureSampler(mag_filter::linear, min_filter::linear); + return sourceTexture.sample(textureSampler, in.texCoord); +} +)"; + +static const char ModVolShaderSource[] = R"( +#include + +using namespace metal; + +constant bool div_pos_z [[function_constant(0)]]; + +struct VertexShaderUniforms +{ + float4x4 ndc_mat; +}; + +struct VertexIn +{ + float4 in_pos [[attribute(0)]]; +}; + +struct VertexOut +{ + float depth; + float4 position [[position]]; +}; + +struct FragmentOut +{ + float4 color [[color(0)]]; + float depth [[depth(any)]]; +}; + +// Mirrors MetalModVolPushBlock (metal_drawer.h): 32 bytes, float4-aligned. +struct PushBlock +{ + float4 clip_test; // x0, y0, x1, y1 in framebuffer pixels (Inside clip only) + float sp_shader_color; // Final pass darkening alpha + int clip_inside; // 1 = discard fragments inside clip_test + float2 pad; +}; + +vertex VertexOut vs_main(VertexIn in [[stage_in]], constant VertexShaderUniforms& uniforms [[buffer(0)]]) { + float4 vpos = uniforms.ndc_mat * in.in_pos; + + VertexOut out = {}; + + if (div_pos_z) { + vpos /= vpos.z; + vpos.z = vpos.w; + out.depth = vpos.w; + } else { + out.depth = vpos.z; + vpos.w = 1.0; + vpos.z = 0.0; + } + + out.position = vpos; + return out; +} + +fragment FragmentOut fs_main(VertexOut in [[stage_in]], + constant PushBlock& push_constants [[buffer(1)]]) { + FragmentOut out = {}; + + // TA user tile clip, Inside mode: the volume doesn't mark pixels inside the + // rect (Outside mode is the scissor). Same test as the main fs_main + // pp_clip_inside branch; discard_fragment skips the stencil op below. + if (push_constants.clip_inside != 0 + && in.position.x >= push_constants.clip_test.x && in.position.x <= push_constants.clip_test.z + && in.position.y >= push_constants.clip_test.y && in.position.y <= push_constants.clip_test.w) + discard_fragment(); + + float w; + + if (div_pos_z) { + w = 100000.0 / in.depth; + } else { + w = 100000.0 * in.depth; + } + + out.depth = log2(1.0 + max(w, -0.999999)) / 34.0; + out.color = float4(0.0, 0.0, 0.0, push_constants.sp_shader_color); + return out; +} +)"; + +static const char QuadShaderSource[] = R"( +#include + +using namespace metal; + +constant bool rotate_quad [[function_constant(0)]]; +constant bool ignore_tex_alpha [[function_constant(1)]]; + +struct VertexIn +{ + float3 pos [[attribute(0)]]; + float2 uv [[attribute(1)]]; +}; + +struct VertexOut +{ + float4 position [[position]]; + float2 uv; +}; + +struct PushBlock +{ + float4 color; +}; + +vertex VertexOut vs_main(VertexIn in [[stage_in]]) { + VertexOut out = {}; + + if (!rotate_quad) { + out.position = float4(in.pos, 1.0); + } else { + out.position = float4(-in.pos.y, in.pos.x, in.pos.z, 1.0); + } + + out.uv = in.uv; + return out; +} + +fragment float4 fs_main(VertexOut in [[stage_in]], + constant PushBlock& push_constants [[buffer(0)]], + texture2d tex [[texture(0)]], + sampler samp [[sampler(0)]]) { + float4 color; + + if (ignore_tex_alpha) { + color.rgb = push_constants.color.rgb * tex.sample(samp, in.uv).rgb; + color.a = push_constants.color.a; + } else { + color = push_constants.color * tex.sample(samp, in.uv); + } + + return color; +} +)"; + +static const char N2VertexShaderSource[] = R"( +#include + +using namespace metal; + +constant bool pp_gouraud [[function_constant(0)]]; + +constant bool is_flat = pp_gouraud == 0; +constant bool is_not_flat = !is_flat; + +struct VertexShaderUniforms +{ + float4x4 ndc_mat; +}; + +struct N2VertexShaderUniforms +{ + float4x4 mv_mat; + float4x4 normal_mat; + float4x4 proj_mat; + int2 env_mapping; + int bump_mapping; + int poly_number; + + float2 gloss_coef; + int2 constant_color; +}; + +struct N2VertexIn +{ + float4 in_pos [[attribute(0)]]; + float4 in_base [[attribute(1)]]; + float4 in_offs [[attribute(2)]]; + float2 in_uv [[attribute(3)]]; + float3 in_normal [[attribute(7)]]; +}; + +struct VertexOut +{ + float4 flat_vtx_base [[flat, function_constant(is_flat)]]; + float4 flat_vtx_offs [[flat, function_constant(is_flat)]]; + float4 vtx_base [[function_constant(is_not_flat)]]; + float4 vtx_offs [[function_constant(is_not_flat)]]; + float3 vtx_uv; + float4 position [[position, invariant]]; +}; + +struct VertexOutOIT +{ + float4 flat_vtx_base [[flat, function_constant(is_flat)]]; + float4 flat_vtx_offs [[flat, function_constant(is_flat)]]; + float4 vtx_base [[function_constant(is_not_flat)]]; + float4 vtx_offs [[function_constant(is_not_flat)]]; + float3 vtx_uv; + uint vtx_index [[flat]]; + float4 position [[position, invariant]]; +}; + +#define PI 3.1415926 + +#define LMODE_SINGLE_SIDED 0 +#define LMODE_DOUBLE_SIDED 1 +#define LMODE_DOUBLE_SIDED_WITH_TOLERANCE 2 +#define LMODE_SPECIAL_EFFECT 3 +#define LMODE_THIN_SURFACE 4 +#define LMODE_BUMP_MAP 5 + +#define ROUTING_SPEC_TO_OFFSET 1 +#define ROUTING_DIFF_TO_OFFSET 2 +#define ROUTING_ATTENUATION 1 // not handled +#define ROUTING_FOG 2 // not handled +#define ROUTING_ALPHA 4 +#define ROUTING_SUB 8 + +struct N2Light +{ + float4 color; + float4 direction; // For parallel/spot + float4 position; // For spot/point + + int parallel; + int routing; + int dmode; + int smode; + + int2 diffuse; + int2 specular; + + float attn_dist_a; + float attn_dist_b; + float attn_angle_a; // For spot + float attn_angle_b; + + int dist_attn_mode; // For spot/point + int _pad1; + int _pad2; + int _pad3; +}; + +struct N2Lights +{ + N2Light lights[16]; + float4 ambient_base[2]; + float4 ambient_offset[2]; + int2 ambient_material_base; + int2 ambient_material_offset; + int light_count; + int use_base_over; + int bump_id0; + int bump_id1; +}; + +void w_divide(thread float4& vpos, float4x4 ndc_mat, thread VertexOut& out) +{ + vpos = float4(vpos.xy / vpos.w, 1.0 / vpos.w, 1.0); + vpos = ndc_mat * vpos; + if (pp_gouraud == 1) { + if (is_flat) { + out.flat_vtx_base *= vpos.z; + out.flat_vtx_offs *= vpos.z; + } else { + out.vtx_base *= vpos.z; + out.vtx_offs *= vpos.z; + } + } + out.vtx_uv = float3(out.vtx_uv.xy * vpos.z, vpos.z); + vpos.w = 1.0; + vpos.z = 0.0; +} + +void w_divide_oit(thread float4& vpos, float4x4 ndc_mat, thread VertexOutOIT& out) +{ + vpos = float4(vpos.xy / vpos.w, 1.0 / vpos.w, 1.0); + vpos = ndc_mat * vpos; + if (pp_gouraud == 1) { + if (is_flat) { + out.flat_vtx_base *= vpos.z; + out.flat_vtx_offs *= vpos.z; + } else { + out.vtx_base *= vpos.z; + out.vtx_offs *= vpos.z; + } + } + out.vtx_uv = float3(out.vtx_uv.xy * vpos.z, vpos.z); + vpos.w = 1.0; + vpos.z = 0.0; +} + +void compute_colors(constant N2VertexShaderUniforms& n2_uniforms, constant N2Lights& n2_lights, + thread float4& base_col, thread float4& offset_col, int vol_idx, float3 position, float3 normal) +{ + if (n2_uniforms.constant_color[vol_idx] == 1) + return; + + float3 diffuse = float3(0.0); + float3 specular = float3(0.0); + float diffuse_alpha = 0.0; + float specular_alpha = 0.0; + float3 reflect_dir = reflect(normalize(position), normal); + const float BASE_FACTOR = 2.0; + + for (int i = 0; i < n2_lights.light_count; i++) + { + float3 light_dir; // direction to the light + float3 light_color = n2_lights.lights[i].color.rgb; + if (n2_lights.lights[i].parallel == 1) + { + light_dir = normalize(n2_lights.lights[i].direction.xyz); + } + else + { + light_dir = normalize(n2_lights.lights[i].position.xyz - position); + if (n2_lights.lights[i].attn_dist_a != 1.0 || n2_lights.lights[i].attn_dist_b != 0.0) + { + float distance = length(n2_lights.lights[i].position.xyz - position); + if (n2_lights.lights[i].dist_attn_mode == 0) + distance = 1.0 / distance; + light_color *= clamp(n2_lights.lights[i].attn_dist_b * distance + n2_lights.lights[i].attn_dist_a, 0.0, 1.0); + } + if (n2_lights.lights[i].attn_angle_a != 1.0 || n2_lights.lights[i].attn_angle_b != 0.0) + { + float3 spot_dir = n2_lights.lights[i].direction.xyz; + float cos_angle = 1.0 - max(0.0, dot(light_dir, spot_dir)); + light_color *= clamp(cos_angle * n2_lights.lights[i].attn_angle_b + n2_lights.lights[i].attn_angle_a, 0.0, 1.0); + } + } + if (n2_lights.lights[i].diffuse[vol_idx] == 1) + { + float factor = (n2_lights.lights[i].routing & ROUTING_SUB) != 0 ? -BASE_FACTOR : BASE_FACTOR; + if (n2_lights.lights[i].dmode == LMODE_SINGLE_SIDED) + factor *= max(dot(normal, light_dir), 0.0); + else if (n2_lights.lights[i].dmode == LMODE_DOUBLE_SIDED) + factor *= abs(dot(normal, light_dir)); + + if ((n2_lights.lights[i].routing & ROUTING_ALPHA) != 0) + diffuse_alpha += light_color.r * factor; + else + { + if ((n2_lights.lights[i].routing & ROUTING_DIFF_TO_OFFSET) == 0) + diffuse += light_color * factor * base_col.rgb; + else + specular += light_color * factor * base_col.rgb; + } + } + if (n2_lights.lights[i].specular[vol_idx] == 1) + { + float factor = (n2_lights.lights[i].routing & ROUTING_SUB) != 0 ? -BASE_FACTOR : BASE_FACTOR; + if (n2_lights.lights[i].smode == LMODE_SINGLE_SIDED) + factor *= clamp(powr(max(dot(light_dir, reflect_dir), 0.0), n2_uniforms.gloss_coef[vol_idx]), 0.0, 1.0); + else if (n2_lights.lights[i].smode == LMODE_DOUBLE_SIDED) + factor *= clamp(powr(abs(dot(light_dir, reflect_dir)), n2_uniforms.gloss_coef[vol_idx]), 0.0, 1.0); + + if ((n2_lights.lights[i].routing & ROUTING_ALPHA) != 0) + specular_alpha += light_color.r * factor; + else + { + if ((n2_lights.lights[i].routing & ROUTING_SPEC_TO_OFFSET) == 0) + diffuse += light_color * factor * offset_col.rgb; + else + specular += light_color * factor * offset_col.rgb; + } + } + } + // ambient light + if (n2_lights.ambient_material_base[vol_idx] == 1) + diffuse += n2_lights.ambient_base[vol_idx].rgb * base_col.rgb; + else + diffuse += n2_lights.ambient_base[vol_idx].rgb; + if (n2_lights.ambient_material_offset[vol_idx] == 1) + specular += n2_lights.ambient_offset[vol_idx].rgb * offset_col.rgb; + else + specular += n2_lights.ambient_offset[vol_idx].rgb; + base_col.rgb = diffuse; + offset_col.rgb = specular; + + base_col.a += diffuse_alpha; + offset_col.a += specular_alpha; + if (n2_lights.use_base_over == 1) + { + float4 overflow = max(base_col - float4(1.0), 0.0); + offset_col += overflow; + } + base_col = clamp(base_col, 0.0, 1.0); + offset_col = clamp(offset_col, 0.0, 1.0); +} + +void compute_env_map(thread float3& uv, float3 position, float3 normal) +{ + // Spherical mapping + // float3 r = reflect(normalize(position), normal); + // float m = 2.0 * sqrt(r.x * r.x + r.y * r.y + (r.z + 1.0) * (r.z + 1.0)); + // uv.xy += r.xy / m + 0.5; + + // Cheap env mapping + uv.xy += (normal.xy / 2.0) + 0.5; + uv.xy = clamp(uv.xy, 0.0, 1.0); +} + +vertex VertexOut vs_main(N2VertexIn in [[stage_in]], + constant VertexShaderUniforms& uniforms [[buffer(0)]], + constant N2VertexShaderUniforms& n2_uniforms [[buffer(1)]], + constant N2Lights& n2_lights [[buffer(2)]]) +{ + float4 vpos = n2_uniforms.mv_mat * in.in_pos; + + float3 vnorm = normalize(float3x3(n2_uniforms.normal_mat[0].xyz, + n2_uniforms.normal_mat[1].xyz, + n2_uniforms.normal_mat[2].xyz) * in.in_normal); + + float4 base = in.in_base; + float4 offset = in.in_offs; + + // TODO bump mapping + if (n2_uniforms.bump_mapping == 0) { + compute_colors(n2_uniforms, n2_lights, + base, offset, 0, vpos.xyz, vnorm); + base += offset; + } + + VertexOut out = {}; + + if (is_flat) { + out.flat_vtx_base = base; + out.flat_vtx_offs = offset; + } else { + out.vtx_base = base; + out.vtx_offs = offset; + } + + out.vtx_uv.xy = in.in_uv; + + if (n2_uniforms.env_mapping[0] == 1) + compute_env_map(out.vtx_uv, vpos.xyz, vnorm); + + vpos = n2_uniforms.proj_mat * vpos; + w_divide(vpos, uniforms.ndc_mat, out); + + out.position = vpos; + + return out; +} + +vertex VertexOutOIT vs_main_oit(N2VertexIn in [[stage_in]], + constant VertexShaderUniforms& uniforms [[buffer(0)]], + constant N2VertexShaderUniforms& n2_uniforms [[buffer(1)]], + constant N2Lights& n2_lights [[buffer(2)]], + uint vid [[vertex_id]]) +{ + float4 vpos = n2_uniforms.mv_mat * in.in_pos; + + float3 vnorm = normalize(float3x3(n2_uniforms.normal_mat[0].xyz, + n2_uniforms.normal_mat[1].xyz, + n2_uniforms.normal_mat[2].xyz) * in.in_normal); + + float4 base = in.in_base; + float4 offset = in.in_offs; + + // TODO bump mapping + if (n2_uniforms.bump_mapping == 0) { + compute_colors(n2_uniforms, n2_lights, + base, offset, 0, vpos.xyz, vnorm); + base += offset; + } + + VertexOutOIT out = {}; + + if (is_flat) { + out.flat_vtx_base = base; + out.flat_vtx_offs = offset; + } else { + out.vtx_base = base; + out.vtx_offs = offset; + } + + out.vtx_uv.xy = in.in_uv; + + if (n2_uniforms.env_mapping[0] == 1) + compute_env_map(out.vtx_uv, vpos.xyz, vnorm); + + vpos = n2_uniforms.proj_mat * vpos; + w_divide_oit(vpos, uniforms.ndc_mat, out); + + out.position = vpos; + out.vtx_index = uint(n2_uniforms.poly_number) + vid; + + return out; +} +)"; + +extern const char MTLN2ModVolVertexShaderSource[] = R"( +#include + +using namespace metal; + +struct VertexShaderUniforms +{ + float4x4 ndc_mat; +}; + +struct N2VertexShaderUniforms +{ + float4x4 mv_mat; + float4x4 normal_mat; + float4x4 proj_mat; + int2 env_mapping; + int bump_mapping; + int poly_number; + + float2 gloss_coef; + int2 constant_color; +}; + +struct VertexIn +{ + float4 in_pos [[attribute(0)]]; +}; + +struct VertexOut +{ + float depth; + float4 position [[position]]; +}; + +void w_divide(thread float4& vpos, float4x4 ndc_mat, thread VertexOut& out) +{ + vpos = float4(vpos.xy / vpos.w, 1.0 / vpos.w, 1.0); + vpos = ndc_mat * vpos; + out.depth = vpos.z; + vpos.w = 1.0; + vpos.z = 0.0; +} + +vertex VertexOut vs_main(VertexIn in [[stage_in]], + constant VertexShaderUniforms& uniforms [[buffer(0)]], + constant N2VertexShaderUniforms& n2_uniforms [[buffer(1)]]) +{ + VertexOut out = {}; + + float4 vpos = n2_uniforms.mv_mat * in.in_pos; + vpos.z = min(vpos.z, -0.001); + vpos = n2_uniforms.proj_mat * vpos; + w_divide(vpos, uniforms.ndc_mat, out); + + out.position = vpos; + + return out; +} +)"; + +MetalShaders::MetalShaders() { + auto device = MetalContext::Instance()->GetDevice(); + + MTLCompileOptions* compileOptions = [[MTLCompileOptions alloc] init]; + [compileOptions setFastMathEnabled:YES]; + // Each poly compiles its own function-constant variant, so the same mesh + // edge can be rasterized by two differently-optimized vertex functions + // (OP face vs PT eyes/brows). Under fast math the position path + // (w_divide's two divides) is free to codegen differently per variant, + // opening sub-pixel cracks and Z poke-through on shared edges (Shenmue + // faces). preserveInvariance + [[invariant]] on the position outputs pins + // the position math to bit-identical results across variants; fast math + // still applies to everything unmarked. + if (@available(macOS 11.0, iOS 14.0, tvOS 14.0, *)) + [compileOptions setPreserveInvariance:YES]; + + NSError* error = nil; + fragmentShaderLibrary = [device newLibraryWithSource:[NSString stringWithUTF8String:FragmentShaderSource] options:compileOptions error:&error]; + fragmentShaderConstants = [[MTLFunctionConstantValues alloc] init]; + + if (!fragmentShaderLibrary) { + ERROR_LOG(RENDERER, "%s", [[error localizedDescription] UTF8String]); + assert(false); + } + + vertexShaderLibrary = [device newLibraryWithSource:[NSString stringWithUTF8String:VertexShaderSource] options:compileOptions error:&error]; + vertexShaderConstants = [[MTLFunctionConstantValues alloc] init]; + + if (!vertexShaderLibrary) { + ERROR_LOG(RENDERER, "vertexShaderLibrary compile failed: %s", metalErrorString(error)); + assert(false); + } + + n2VertexShaderLibrary = [device newLibraryWithSource:[NSString stringWithUTF8String:N2VertexShaderSource] options:compileOptions error:&error]; + + if (!n2VertexShaderLibrary) { + ERROR_LOG(RENDERER, "%s", [[error localizedDescription] UTF8String]); + assert(false); + } + + blitShaderLibrary = [device newLibraryWithSource:[NSString stringWithUTF8String:BlitShader] options:compileOptions error:&error]; + + if (!blitShaderLibrary) { + ERROR_LOG(RENDERER, "%s", [[error localizedDescription] UTF8String]); + assert(false); + } + + blitVertexShader = [blitShaderLibrary newFunctionWithName:@"vs_main" constantValues:[[MTLFunctionConstantValues alloc] init] error:&error]; + + if (!blitVertexShader) { + ERROR_LOG(RENDERER, "%s", [[error localizedDescription] UTF8String]); + assert(false); + } + + blitFragmentShader = [blitShaderLibrary newFunctionWithName:@"fs_main" constantValues:[[MTLFunctionConstantValues alloc] init] error:&error]; + + if (!blitFragmentShader) { + ERROR_LOG(RENDERER, "%s", [[error localizedDescription] UTF8String]); + assert(false); + } + + modVolShaderLibrary = [device newLibraryWithSource:[NSString stringWithUTF8String:ModVolShaderSource] options:compileOptions error:&error]; + modVolShaderConstants = [[MTLFunctionConstantValues alloc] init]; + + if (!modVolShaderLibrary) { + ERROR_LOG(RENDERER, "%s", [[error localizedDescription] UTF8String]); + assert(false); + } + + n2ModVolVertexShaderLibrary = [device newLibraryWithSource:[NSString stringWithUTF8String:MTLN2ModVolVertexShaderSource] options:compileOptions error:&error]; + + if (!n2ModVolVertexShaderLibrary) { + ERROR_LOG(RENDERER, "%s", [[error localizedDescription] UTF8String]); + assert(false); + } + + quadShaderLibrary = [device newLibraryWithSource:[NSString stringWithUTF8String:QuadShaderSource] options:compileOptions error:&error]; + quadShaderConstants = [[MTLFunctionConstantValues alloc] init]; + + if (!quadShaderLibrary) { + ERROR_LOG(RENDERER, "%s", [[error localizedDescription] UTF8String]); + assert(false); + } + +} + +id MetalShaders::compileShader(const MetalVertexShaderParams ¶ms) { + MTLFunctionConstantValues* constants = [[MTLFunctionConstantValues alloc] init]; + [constants setConstantValue:¶ms.gouraud type:MTLDataTypeBool atIndex:0]; + + NSError* error = nil; + id function = nil; + const char* entryPoint = params.oitCollect ? "vs_main_oit" : "vs_main"; + + if (params.naomi2) { + function = [n2VertexShaderLibrary newFunctionWithName:[NSString stringWithUTF8String:entryPoint] + constantValues:constants + error:&error]; + } else { + [constants setConstantValue:¶ms.divPosZ type:MTLDataTypeBool atIndex:1]; + [constants setConstantValue:¶ms.area1 type:MTLDataTypeBool atIndex:2]; + function = [vertexShaderLibrary newFunctionWithName:[NSString stringWithUTF8String:entryPoint] + constantValues:constants + error:&error]; + } + + if (!function) { + ERROR_LOG(RENDERER, + "compileShader(vertex %s): %s (gouraud=%d naomi2=%d divPosZ=%d oitCollect=%d)", + entryPoint, metalErrorString(error), + params.gouraud, params.naomi2, params.divPosZ, params.oitCollect); + return nil; + } + + return function; +} + +id MetalShaders::compileShader(const MetalFragmentShaderParams ¶ms) { + [fragmentShaderConstants setConstantValue:¶ms.alphaTest type:MTLDataTypeBool atIndex:0]; + [fragmentShaderConstants setConstantValue:¶ms.insideClipTest type:MTLDataTypeBool atIndex:1]; + [fragmentShaderConstants setConstantValue:¶ms.useAlpha type:MTLDataTypeBool atIndex:2]; + [fragmentShaderConstants setConstantValue:¶ms.texture type:MTLDataTypeBool atIndex:3]; + [fragmentShaderConstants setConstantValue:¶ms.ignoreTexAlpha type:MTLDataTypeBool atIndex:4]; + [fragmentShaderConstants setConstantValue:¶ms.shaderInstr type:MTLDataTypeInt atIndex:5]; + [fragmentShaderConstants setConstantValue:¶ms.offset type:MTLDataTypeBool atIndex:6]; + [fragmentShaderConstants setConstantValue:¶ms.fog type:MTLDataTypeInt atIndex:7]; + [fragmentShaderConstants setConstantValue:¶ms.gouraud type:MTLDataTypeBool atIndex:8]; + [fragmentShaderConstants setConstantValue:¶ms.bumpmap type:MTLDataTypeBool atIndex:9]; + [fragmentShaderConstants setConstantValue:¶ms.clamping type:MTLDataTypeBool atIndex:10]; + [fragmentShaderConstants setConstantValue:¶ms.trilinear type:MTLDataTypeBool atIndex:11]; + [fragmentShaderConstants setConstantValue:¶ms.palette type:MTLDataTypeInt atIndex:12]; + [fragmentShaderConstants setConstantValue:¶ms.divPosZ type:MTLDataTypeBool atIndex:13]; + [fragmentShaderConstants setConstantValue:¶ms.dithering type:MTLDataTypeBool atIndex:14]; + [fragmentShaderConstants setConstantValue:¶ms.oitMode type:MTLDataTypeBool atIndex:15]; + [fragmentShaderConstants setConstantValue:¶ms.oitTileDepth type:MTLDataTypeBool atIndex:16]; + + NSError* error = nil; + + NSString *name = params.oitMode && params.earlyFragmentTests ? @"fs_main_early" : @"fs_main"; + id function = [fragmentShaderLibrary newFunctionWithName:name constantValues:fragmentShaderConstants error:&error]; + + if (!function) { + ERROR_LOG(RENDERER, "compileShader(fragment): %s", metalErrorString(error)); + return nil; + } + + return function; +} + +id MetalShaders::compileShader(const MetalModVolShaderParams ¶ms) { + [modVolShaderConstants setConstantValue:¶ms.divPosZ type:MTLDataTypeBool atIndex:0]; + + NSError* error = nil; + + id function; + + if (params.naomi2) { + function = [n2ModVolVertexShaderLibrary newFunctionWithName:@"vs_main" constantValues:[[MTLFunctionConstantValues alloc] init] error:&error]; + } else { + function = [modVolShaderLibrary newFunctionWithName:@"vs_main" constantValues:modVolShaderConstants error:&error]; + } + + if (!function) { + ERROR_LOG(RENDERER, "compileShader(modvol): %s", metalErrorString(error)); + return nil; + } + + return function; +} + +id MetalShaders::compileShader(bool divPosZ) { + [modVolShaderConstants setConstantValue:&divPosZ type:MTLDataTypeBool atIndex:0]; + + NSError* error = nil; + + id function = [modVolShaderLibrary newFunctionWithName:@"fs_main" constantValues:modVolShaderConstants error:&error]; + + if (!function) { + ERROR_LOG(RENDERER, "compileShader(modvol fragment): %s", metalErrorString(error)); + return nil; + } + + return function; +} + +id MetalShaders::compileQuadVertexShader(bool rotate) +{ + [quadShaderConstants setConstantValue:&rotate type:MTLDataTypeBool atIndex:0]; + + NSError* error = nil; + + id function = [quadShaderLibrary newFunctionWithName:@"vs_main" constantValues:quadShaderConstants error:&error]; + if (!function) { + ERROR_LOG(RENDERER, "compileShader(quad vertex): %s", metalErrorString(error)); + return nil; + } + + return function; +} + +id MetalShaders::compileQuadFragmentShader(bool ignoreTexAlpha) +{ + [quadShaderConstants setConstantValue:&ignoreTexAlpha type:MTLDataTypeBool atIndex:1]; + + NSError* error = nil; + + id function = [quadShaderLibrary newFunctionWithName:@"fs_main" constantValues:quadShaderConstants error:&error]; + if (!function) { + ERROR_LOG(RENDERER, "compileShader(quad fragment): %s", metalErrorString(error)); + return nil; + } + + return function; +} diff --git a/core/rend/metal/metal_texture.h b/core/rend/metal/metal_texture.h new file mode 100644 index 0000000000..e2c10b77aa --- /dev/null +++ b/core/rend/metal/metal_texture.h @@ -0,0 +1,304 @@ +/* + Copyright 2025 flyinghead + + This file is part of Flycast. + + Flycast is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 2 of the License, or + (at your option) any later version. + + Flycast is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with Flycast. If not, see . +*/ + +#pragma once +#include "metal_apple.h" +#include "rend/TexCache.h" +#include "metal_context.h" +#include "metal.h" + +#include + +class MetalTexture final : public BaseTextureCacheData +{ +public: + MetalTexture(TSP tsp = {}, TCW tcw = {}, int area = 0) : BaseTextureCacheData(tsp, tcw, area) {} + + std::string GetId() override { + // gpuResourceID was added in iOS 16 / macOS 13 / tvOS 16. Older + // SDKs don't declare the selector at all, so an @available check + // alone still fails to compile against an iOS 15 / macOS 12 SDK + // (the protocol method does not exist for the compiler to resolve). + // Gate the call on the SDK first, then keep the runtime check for + // older OS versions on a newer SDK build. + // The fallback uses (__bridge void *) so the cast is well-defined + // under both ARC and MRR (raw `reinterpret_cast` on an `id` trips + // -Warc-bridge-casts-disallowed-in-nonarc and ARC errors in some + // configurations); we only need a stable, unique-for-lifetime + // value, which the bridged void* hash provides. +#if (defined(__IPHONE_OS_VERSION_MAX_ALLOWED) && __IPHONE_OS_VERSION_MAX_ALLOWED >= 160000) \ + || (defined(__MAC_OS_X_VERSION_MAX_ALLOWED) && __MAC_OS_X_VERSION_MAX_ALLOWED >= 130000) \ + || (defined(__TV_OS_VERSION_MAX_ALLOWED) && __TV_OS_VERSION_MAX_ALLOWED >= 160000) + if (@available(iOS 16.0, macOS 13.0, tvOS 16.0, *)) + return std::to_string([texture gpuResourceID]._impl); +#endif + return std::to_string(reinterpret_cast((__bridge void *)texture)); + } + id GetTexture() const { return texture; } + void UploadToGPU(int width, int height, const u8 *data, bool mipmapped, bool mipmapsIncluded = false) override; + void SetCommandBuffer(id commandBuffer) { this->commandBuffer = commandBuffer; } + void SetTexture(id texture, u32 width, u32 height) { + this->texture = texture; + this->width = width; + this->height = height; + } + void SetInFlight(bool inFlight) { + this->isInFlight = inFlight; + } + void deferDeleteResource(MetalFlightManager *manager); + id GetReadOnlyTexture() const { return readOnlyTexture ? readOnlyTexture : texture; } + void CreateReadOnlyCopy(id commandBuffer); + +private: + void Init(u32 width, u32 height, MTLPixelFormat format, u32 dataSize, bool mipmapped, bool mipmapsIncluded); + void SetImage(u32 srcSize, const void *srcData, bool genMipmaps); + void GenerateMipmaps(); + + MTLPixelFormat format = MTLPixelFormatInvalid; + u32 width = 0; + u32 height = 0; + u32 mipmapLevels = 1; + id commandBuffer = nil; + id texture = nil; + id readOnlyTexture = nil; + bool isInFlight = false; + + friend class MetalTextureCache; +}; + +class MetalSamplers +{ +public: + explicit MetalSamplers(); + ~MetalSamplers(); + + static const u32 TSP_Mask = 0x7ef00; + + void term() { + samplers.clear(); + fallbackSampler = nil; + fallbackFailedLogged = false; + // Memo aliases an entry of the map just cleared. Strong ARC reference, + // so stale means wrong-sampler, not a dangling pointer -- still wrong. + lastSampler = nil; + } + + // `useMemo` opts into the one-entry last-key memo in the TSP overload. + // Only the hot per-poly call in MetalDrawer::DrawPoly uses it. + id GetSampler(const PolyParam& poly, bool punchThrough, bool texture1 = false, bool useMemo = false) { + TSP tsp = texture1 ? poly.tsp1 : poly.tsp; + if (poly.texture != nullptr && poly.texture->gpuPalette) + tsp.FilterMode = 0; + else if (config::TextureFiltering == 1) + tsp.FilterMode = 0; + else if (config::TextureFiltering == 2) + tsp.FilterMode = 1; + // Forward, never memo here: FilterMode is rewritten just above from + // gpuPalette and config::TextureFiltering, so the only key that can + // safely identify a sampler is the one computed after this point. + return GetSampler(tsp, punchThrough, useMemo); + } + + id GetSampler(TSP tsp, bool punchThrough = false, bool useMemo = false) { + const u32 hash = (tsp.full & TSP_Mask) | punchThrough; // MipMapD, FilterMode, ClampU, ClampV, FlipU, FlipV + // Consecutive polys overwhelmingly share a sampler; the map subscript + // below is a tree walk (and an insert on miss) for a repeat answer. + if (useMemo && lastSampler != nil && lastSamplerKey == hash) + return lastSampler; + id sampler = samplers[hash]; + + if (!sampler) { + auto desc = [[MTLSamplerDescriptor alloc] init]; + + if (tsp.FilterMode != 0) { + if (punchThrough) { + [desc setMinFilter:MTLSamplerMinMagFilterLinear]; + [desc setMagFilter:MTLSamplerMinMagFilterLinear]; + [desc setMipFilter:MTLSamplerMipFilterNearest]; + } else { + [desc setMinFilter:MTLSamplerMinMagFilterLinear]; + [desc setMagFilter:MTLSamplerMinMagFilterLinear]; + [desc setMipFilter:MTLSamplerMipFilterLinear]; + } + } + else { + [desc setMinFilter:MTLSamplerMinMagFilterNearest]; + [desc setMagFilter:MTLSamplerMinMagFilterNearest]; + [desc setMipFilter:MTLSamplerMipFilterNearest]; + } + + auto sRepeat = tsp.ClampU ? MTLSamplerAddressModeClampToEdge : tsp.FlipU ? MTLSamplerAddressModeMirrorRepeat : MTLSamplerAddressModeRepeat; + auto tRepeat = tsp.ClampV ? MTLSamplerAddressModeClampToEdge : tsp.FlipV ? MTLSamplerAddressModeMirrorRepeat : MTLSamplerAddressModeRepeat; + + DEBUG_LOG(RENDERER, "Sampler settings: FlipU=%d, FlipV=%d, sRepeat=%d, tRepeat=%d", + (int)tsp.FlipU, (int)tsp.FlipV, (int)sRepeat, (int)tRepeat); + + [desc setSAddressMode:sRepeat]; + [desc setTAddressMode:tRepeat]; + [desc setRAddressMode:tRepeat]; + // Note: Don't set compareFunction for regular color textures + if (tsp.FilterMode == 1 && !punchThrough) { + // Metal requires maxAnisotropy in [1, 16]. The user-facing + // option is Option, so clamp in *signed* space first: + // a negative value would underflow when converted to u32 + // and incorrectly pin to 16 instead of 1. + NSUInteger anisotropy = static_cast( + std::clamp(config::AnisotropicFiltering, 1, 16)); + [desc setMaxAnisotropy:anisotropy]; + } else { + [desc setMaxAnisotropy:1]; + } + + auto device = MetalContext::Instance()->GetDevice(); + DEBUG_LOG(RENDERER, "Creating sampler with device=%p, FilterMode=%d, ClampU=%d, ClampV=%d", + device, (int)tsp.FilterMode, (int)tsp.ClampU, (int)tsp.ClampV); + + sampler = [device newSamplerStateWithDescriptor:desc]; + + if (sampler == nil) { + // newSamplerStateWithDescriptor can return nil if the + // device can't satisfy the descriptor (e.g. anisotropy + // on a software renderer, OOM, or unsupported combos). + // Fall back to a single shared minimal-nearest sampler + // so callers never receive nil and Metal validation + // doesn't crash deep inside the encoder. + sampler = GetOrCreateFallbackSampler(); + } + // Only cache real samplers. Caching nil here would mean every + // subsequent lookup for this hash short-circuits with nil and + // bypasses the fallback path above. + if (sampler != nil) + samplers[hash] = sampler; + } + + // Only non-nil is memoised, so nil doubles as "nothing memoised" and + // a sampler that failed to create stays retryable next poly. + if (useMemo && sampler != nil) { + lastSamplerKey = hash; + lastSampler = sampler; + } + + return sampler; + } + +private: + // One-entry memo for the per-polygon lookup above. Dropped in term(). + u32 lastSamplerKey = 0; + id lastSampler = nil; + + id GetOrCreateFallbackSampler() { + if (fallbackSampler != nil) + return fallbackSampler; + + auto desc = [[MTLSamplerDescriptor alloc] init]; + [desc setMinFilter:MTLSamplerMinMagFilterNearest]; + [desc setMagFilter:MTLSamplerMinMagFilterNearest]; + [desc setMipFilter:MTLSamplerMipFilterNearest]; + fallbackSampler = [MetalContext::Instance()->GetDevice() newSamplerStateWithDescriptor:desc]; + + if (fallbackSampler == nil) { + // Log once. If the device can't produce even a default nearest + // sampler something is very wrong, but spamming every frame + // doesn't help diagnose it. + if (!fallbackFailedLogged) { + ERROR_LOG(RENDERER, "Sampler creation failed and fallback sampler is unavailable"); + fallbackFailedLogged = true; + } + } else if (!fallbackLogged) { + ERROR_LOG(RENDERER, "Sampler creation failed; using shared nearest fallback"); + fallbackLogged = true; + } + + return fallbackSampler; + } + + std::unordered_map> samplers; + id fallbackSampler = nil; + bool fallbackLogged = false; + bool fallbackFailedLogged = false; +}; + +class MetalTextureCache final : public BaseTextureCache +{ +public: + MetalTextureCache() {} + + void SetCurrentIndex(int index) + { + if (index == (int)currentIndex) + return; + if (currentIndex < inFlightTextures.size()) + std::for_each(inFlightTextures[currentIndex].begin(), inFlightTextures[currentIndex].end(), + [](MetalTexture *texture) { + texture->SetInFlight(false); + texture->readOnlyTexture = nil; + }); + currentIndex = index; + EmptyTrash(inFlightTextures); + } + + bool IsInFlight(MetalTexture *texture, bool previous) + { + for (u32 i = 0; i < inFlightTextures.size(); i++) + if ((!previous || i != currentIndex) + && inFlightTextures[i].find(texture) != inFlightTextures[i].end()) + return true; + return false; + } + + void SetInFlight(MetalTexture *texture) + { + texture->SetInFlight(true); + inFlightTextures[currentIndex].insert(texture); + } + + void Cleanup(); + + void Clear() + { + for (auto& set : inFlightTextures) + { + for (MetalTexture *tex : set) + tex->SetInFlight(false); + set.clear(); + } + BaseTextureCache::Clear(); + } + +private: + bool clearTexture(MetalTexture *tex) + { + for (auto& set : inFlightTextures) + set.erase(tex); + + return tex->Delete(); + } + + template + void EmptyTrash(T& v) + { + if (v.size() < currentIndex + 1) + v.resize(currentIndex + 1); + else + v[currentIndex].clear(); + } + + std::vector> inFlightTextures; + u32 currentIndex = ~0; +}; diff --git a/core/rend/metal/metal_texture.mm b/core/rend/metal/metal_texture.mm new file mode 100644 index 0000000000..8daa37ff03 --- /dev/null +++ b/core/rend/metal/metal_texture.mm @@ -0,0 +1,342 @@ +/* + Copyright 2025 flyinghead + + This file is part of Flycast. + + Flycast is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 2 of the License, or + (at your option) any later version. + + Flycast is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with Flycast. If not, see . +*/ + +#include "metal_texture.h" +#include "metal_texture_utils.h" +#include +#include + +// Only Apple GPUs support the packed 16-bit pixel formats A1BGR5/B5G6R5/ABGR4 +// that the Dreamcast 16-bit texture types map to. Allocating such a texture on +// any other GPU aborts in Metal validation. Expand those to RGBA8 when the device +// doesn't support them. Channel order matches how each packed format samples on +// Apple GPUs, so the shader output is identical. +static inline u32 metalSimExpand16ToRGBA8(u16 p, TextureType tt) +{ + // `p` is NOT raw Dreamcast ARGB — flycast's TexCache has already converted the + // texel into the GPU-format layout that the device's native Metal format expects. + // Those layouts (confirmed by flycast's Vulkan renderer + the MoltenVK Metal↔VK + // equivalence) are: + // _565 -> R5G6B5 (Metal B5G6R5Unorm == VK R5G6B5) : R[15:11] G[10:5] B[4:0] + // _5551 -> R5G5B5A1 (Metal A1BGR5Unorm == VK R5G5B5A1) : R[15:11] G[10:6] B[5:1] A[0] + // _4444 -> R4G4B4A4 (Metal ABGR4Unorm == VK R4G4B4A4) : R[15:12] G[11:8] B[7:4] A[3:0] + // Decode each to RGBA8 (memory byte order R,G,B,A) to match what the device + // produces. (Earlier this used ARGB1555/ARGB4444 with alpha in the HIGH bits, + // which read alpha from red's MSB on _5551 -> wrong colors + speckled 1-bit alpha.) + u32 r, g, b, a; + switch (tt) { + case TextureType::_565: // R5G6B5: R[15:11] G[10:5] B[4:0] + r = (p >> 11) & 0x1f; g = (p >> 5) & 0x3f; b = p & 0x1f; + return (r << 3 | r >> 2) | ((g << 2 | g >> 4) << 8) | ((b << 3 | b >> 2) << 16) | (0xFFu << 24); + case TextureType::_5551: // R5G5B5A1: R[15:11] G[10:6] B[5:1] A[0] + r = (p >> 11) & 0x1f; g = (p >> 6) & 0x1f; b = (p >> 1) & 0x1f; a = p & 1; + return (r << 3 | r >> 2) | ((g << 3 | g >> 2) << 8) | ((b << 3 | b >> 2) << 16) | ((a ? 0xFFu : 0u) << 24); + default: // _4444 R4G4B4A4: R[15:12] G[11:8] B[7:4] A[3:0] + r = (p >> 12) & 0xf; g = (p >> 8) & 0xf; b = (p >> 4) & 0xf; a = p & 0xf; + return (r << 4 | r) | ((g << 4 | g) << 8) | ((b << 4 | b) << 16) | ((a << 4 | a) << 24); + } +} + +void MetalTexture::UploadToGPU(int width, int height, const u8 *data, bool mipmapped, bool mipmapsIncluded) +{ + if (!MetalContext::Instance()->SupportsPacked16BitFormats() + && (tex_type == TextureType::_5551 || tex_type == TextureType::_565 || tex_type == TextureType::_4444)) + { + // Total 16-bit source bytes (mirrors the dataSize math below for 16-bit). + u32 srcBytes = (u32)width * height * 2; + if (mipmapsIncluded) { + int w = width / 2; u32 size = srcBytes / 4; + while (w) { srcBytes += ((size + 3) >> 2) << 2; size /= 4; w /= 2; } + } + const u32 pixelCount = srcBytes / 2; + std::vector rgba(pixelCount); + const u16 *src16 = (const u16 *)data; + for (u32 i = 0; i < pixelCount; i++) + rgba[i] = metalSimExpand16ToRGBA8(src16[i], tex_type); + + if (width != (int)this->width || height != (int)this->height + || MTLPixelFormatRGBA8Unorm != this->format || this->texture == nil) + Init(width, height, MTLPixelFormatRGBA8Unorm, pixelCount * 4, mipmapped, mipmapsIncluded); + + const u32 *conv = rgba.data(); + if (mipmapLevels > 1 && mipmapsIncluded) + { + // Mirror SetImage's included-mipmap level walk, but RGBA8 (4 bpp). + u32 elem = 0; + for (u32 i = 0; i < mipmapLevels; i++) { + const u32 levelPixels = 1u << (2 * i); + u32 mipLevel = mipmapLevels - i - 1; + u32 mipWidth = std::max((u32)(texture.width >> mipLevel), 1u); + u32 mipHeight = std::max((u32)(texture.height >> mipLevel), 1u); + MTLRegion region = MTLRegionMake2D(0, 0, mipWidth, mipHeight); + [texture replaceRegion:region mipmapLevel:mipLevel withBytes:(conv + elem) bytesPerRow:mipWidth * 4]; + elem += levelPixels; + } + } + else + { + MTLRegion region = MTLRegionMake2D(0, 0, texture.width, texture.height); + [texture replaceRegion:region mipmapLevel:0 withBytes:conv bytesPerRow:(u32)texture.width * 4]; + if (mipmapLevels > 1 && mipmapped && !mipmapsIncluded) + GenerateMipmaps(); + } + return; + } + + MTLPixelFormat format = MTLPixelFormatInvalid; + u32 dataSize = width * height * 2; + switch (tex_type) + { + case TextureType::_5551: + if (@available(macOS 11.0, *)) + format = MTLPixelFormatA1BGR5Unorm; + break; + case TextureType::_565: + if (@available(macOS 11.0, *)) + format = MTLPixelFormatB5G6R5Unorm; + break; + case TextureType::_4444: + if (@available(macOS 11.0, *)) + format = MTLPixelFormatABGR4Unorm; + break; + case TextureType::_8888: + format = MTLPixelFormatRGBA8Unorm; + dataSize *= 2; + break; + case TextureType::_8: + format = MTLPixelFormatR8Unorm; + dataSize /= 2; + break; + } + if (mipmapsIncluded) + { + int w = width / 2; + u32 size = dataSize / 4; + while (w) + { + dataSize += ((size + 3) >> 2) << 2; // offset must be a multiple of 4 + size /= 4; + w /= 2; + } + } + + if (width != this->width || height != this->height + || format != this->format || this->texture == nil) + Init(width, height, format, dataSize, mipmapped, mipmapsIncluded); + + SetImage(dataSize, data, mipmapped && !mipmapsIncluded); +} + +void MetalTexture::Init(u32 width, u32 height, MTLPixelFormat format, u32 dataSize, bool mipmapped, bool mipmapsIncluded) +{ + this->width = width; + this->height = height; + this->format = format; + mipmapLevels = 1; + if (mipmapped) + mipmapLevels += floor(log2(std::max(width, height))); + + MTLTextureDescriptor *desc = [[MTLTextureDescriptor alloc] init]; + + [desc setWidth:width]; + [desc setHeight:height]; + [desc setPixelFormat:format]; + [desc setMipmapLevelCount:mipmapLevels]; + [desc setStorageMode:metalCpuTextureStorageMode(MetalContext::Instance()->GetDevice())]; + [desc setUsage:MTLTextureUsageShaderRead]; + + auto device = MetalContext::Instance()->GetDevice(); + + texture = [device newTextureWithDescriptor:desc]; +} + +void MetalTexture::SetImage(u32 srcSize, const void *srcData, bool genMipmaps) { + u32 bpp; + switch (tex_type) { + case TextureType::_8888: + bpp = 4; + break; + case TextureType::_8: + bpp = 1; + break; + default: + bpp = 2; + break; + } + + if (mipmapLevels > 1 && !genMipmaps) + { + // Walk the packed (smallest-first) mip chain and upload each level. + // _8888 used to be excluded here and fell through to the single + // base-level replaceRegion below, which uploaded the ENTIRE packed mip + // chain as the base image -> doubled / too-small / garbled textures + // (RE and Aerowings 2 menus use mipmapped 8888 textures). Using bpp for + // the per-level source size makes it correct for both 8888 (4) and + // 16-bit (2), matching Vulkan's staging mip-copy path (texture.cpp:451). + u8 *src = (u8 *)srcData; + + for (u32 i = 0; i < mipmapLevels; i++) { + const u32 size = (1 << (2 * i)) * bpp; + + u32 mipLevel = mipmapLevels - i - 1; + u32 mipWidth = (u32)std::max(texture.width >> mipLevel, 1ul); + u32 mipHeight = (u32)std::max(texture.height >> mipLevel, 1ul); + + MTLRegion region = MTLRegionMake2D(0, 0, mipWidth, mipHeight); + [texture replaceRegion:region + mipmapLevel:mipLevel + withBytes:src + bytesPerRow:mipWidth * bpp]; + + src += size; + } + } + else + { + u32 rowBytes = (u32)(texture.width * bpp); + + MTLRegion region = MTLRegionMake2D(0, 0, texture.width, texture.height); + [texture replaceRegion:region + mipmapLevel:0 + withBytes:srcData + bytesPerRow:rowBytes]; + + if (mipmapLevels > 1 && genMipmaps) { + GenerateMipmaps(); + } + } +} + +void MetalTexture::GenerateMipmaps() +{ + verify((bool)commandBuffer); + [commandBuffer setLabel:@"Mipmap Generation"]; + + id blitEncoder = [commandBuffer blitCommandEncoder]; + + // Was a hand-rolled level loop ported from Vulkan (vulkan/texture.cpp:505), + // which uses vkCmdBlitImage — a SCALING blit: src rect (mipWidth, mipHeight), + // dst rect (mipWidth/2, mipHeight/2), eLinear. The port kept the src size but + // used -copyFromTexture:, which does NOT scale, so each level got a full-size + // source region written into a half-size destination. Metal API validation + // asserts on it; with validation off the command buffer completes clean and + // every mip level holds a CROP of the top-left corner of the level above + // instead of a downsample. + // -generateMipmapsForTexture: is the real equivalent of Vulkan's scaling blit + // (also a linear filter). Verified under MTL_DEBUG_LAYER against Init()'s exact + // descriptor: StorageModeShared + ShaderRead only — no RenderTarget usage needed. + [blitEncoder generateMipmapsForTexture:texture]; + + [blitEncoder endEncoding]; +} + +void MetalTexture::deferDeleteResource(MetalFlightManager *manager) +{ + class ResourceDeleter : public MetalDeletable + { + public: + ResourceDeleter(MetalTexture *texture) + { + std::swap(this->texture, texture->texture); + std::swap(this->readOnlyTexture, texture->readOnlyTexture); + } + + ~ResourceDeleter() override { + texture = nil; + readOnlyTexture = nil; + } + + private: + id texture = nil; + id readOnlyTexture; + }; + manager->addToFlight(new ResourceDeleter(this)); +} + +void MetalTexture::CreateReadOnlyCopy(id commandBuffer) +{ + if (!texture || readOnlyTexture) + return; + + MTLTextureDescriptor *desc = [[MTLTextureDescriptor alloc] init]; + [desc setWidth:texture.width]; + [desc setHeight:texture.height]; + [desc setPixelFormat:texture.pixelFormat]; + [desc setMipmapLevelCount:texture.mipmapLevelCount]; + [desc setStorageMode:MTLStorageModePrivate]; + [desc setUsage:MTLTextureUsageShaderRead]; + + readOnlyTexture = [texture.device newTextureWithDescriptor:desc]; + [readOnlyTexture setLabel:@"RTT Read-Only Copy"]; + + id blitEncoder = [commandBuffer blitCommandEncoder]; + [blitEncoder copyFromTexture:texture + sourceSlice:0 + sourceLevel:0 + sourceOrigin:MTLOriginMake(0, 0, 0) + sourceSize:MTLSizeMake(texture.width, texture.height, 1) + toTexture:readOnlyTexture + destinationSlice:0 + destinationLevel:0 + destinationOrigin:MTLOriginMake(0, 0, 0)]; + + for (NSUInteger level = 1; level < texture.mipmapLevelCount; level++) { + NSUInteger mipWidth = MAX(texture.width >> level, 1); + NSUInteger mipHeight = MAX(texture.height >> level, 1); + + [blitEncoder copyFromTexture:texture + sourceSlice:0 + sourceLevel:level + sourceOrigin:MTLOriginMake(0, 0, 0) + sourceSize:MTLSizeMake(mipWidth, mipHeight, 1) + toTexture:readOnlyTexture + destinationSlice:0 + destinationLevel:level + destinationOrigin:MTLOriginMake(0, 0, 0)]; + } + + [blitEncoder endEncoding]; +} + +MetalSamplers::MetalSamplers() = default; +MetalSamplers::~MetalSamplers() { + term(); +} + +void MetalTextureCache::Cleanup() +{ + std::vector list; + + u32 TargetFrame = std::max((u32)120, FrameCount) - 120; + + for (const auto& [id, texture] : cache) + { + if (texture.dirty && texture.dirty < TargetFrame) + list.push_back(id); + + if (list.size() > 5) + break; + } + + for (u64 id : list) + { + if (clearTexture(&cache[id])) + cache.erase(id); + } +} \ No newline at end of file diff --git a/core/rend/metal/metal_texture_utils.h b/core/rend/metal/metal_texture_utils.h new file mode 100644 index 0000000000..0a19827ee5 --- /dev/null +++ b/core/rend/metal/metal_texture_utils.h @@ -0,0 +1,37 @@ +#pragma once + +#import +#include + +inline MTLStorageMode metalCpuTextureStorageMode(id device) +{ +#if TARGET_OS_OSX || TARGET_OS_MACCATALYST + // Intel GPUs also report unified memory, but cannot use shared textures. + if (![device supportsFamily:MTLGPUFamilyApple1]) + return MTLStorageModeManaged; +#endif + return MTLStorageModeShared; +} + +inline bool metalSupportsPacked16BitFormats(id device) +{ +#if TARGET_OS_SIMULATOR + return false; +#else + if (@available(macOS 11.0, iOS 13.0, tvOS 13.0, *)) + return [device supportsFamily:MTLGPUFamilyApple1]; + return false; +#endif +} + +inline void metalSynchronizeTextureForCpu(id commands, id texture) +{ +#if TARGET_OS_OSX || TARGET_OS_MACCATALYST + if (texture.storageMode == MTLStorageModeManaged) + { + id blit = [commands blitCommandEncoder]; + [blit synchronizeResource:texture]; + [blit endEncoding]; + } +#endif +} diff --git a/core/rend/metal/oit/metal_oit_buffer.h b/core/rend/metal/oit/metal_oit_buffer.h new file mode 100644 index 0000000000..1609f95f84 --- /dev/null +++ b/core/rend/metal/oit/metal_oit_buffer.h @@ -0,0 +1,140 @@ +/* + This file is part of Flycast. + + Flycast is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 2 of the License, or + (at your option) any later version. + + Flycast is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with Flycast. If not, see . +*/ +// Per-pixel storage for Metal Order-Independent Transparency. +// Port of core/rend/vulkan/oit/oit_buffer.h's OITBuffers. +// +// pixelBuffer - linked-list fragments (color + depth + next index), one slot +// per translucent fragment, sized by config::PixelBufferSize. +// pixelCounter - a single atomic_uint, the next free index into pixelBuffer. +// Reset to 0 each frame with a blit fill. +// abufferPointer - width x height head pointers, or a sentinel for "no fragments". +// Reallocated when the framebuffer grows. +// +// All three are MTLResourceStorageModePrivate, matching Vulkan's eDeviceLocal. +#pragma once +#include "../metal_apple.h" + +#include "types.h" +#include "cfg/option.h" +#include "../metal_context.h" + +#include + +class MetalOITBuffers +{ +public: + /// Allocate / reallocate per-pixel storage to accommodate at least the + /// given dimensions. Idempotent on repeat calls with the same or + /// smaller dimensions. The framebuffer resize handler should call this + /// before any OIT draw activity in the new size. + void Init(int width, int height) + { + if (width <= maxWidth && height <= maxHeight) + return; + maxWidth = std::max(maxWidth, width); + maxHeight = std::max(maxHeight, height); + + auto device = MetalContext::Instance()->GetDevice(); + const MTLResourceOptions opts = MTLResourceStorageModePrivate; + + if (pixelBuffer == nil) + { + // Cap to a sane upper bound. Vulkan used VkPhysicalDeviceLimits:: + // maxMemoryAllocationSize; Metal exposes + // MTLDevice.maxBufferLength which is the equivalent ceiling. + pixelBufferSize = (u64)config::PixelBufferSize; + const u64 cap = (u64)[device maxBufferLength]; + const u64 sz = std::min(pixelBufferSize, cap); + pixelBuffer = [device newBufferWithLength:sz options:opts]; + [pixelBuffer setLabel:@"Flycast OIT pixel buffer"]; + } + if (pixelCounter == nil) + { + pixelCounter = [device newBufferWithLength:4 options:opts]; + [pixelCounter setLabel:@"Flycast OIT pixel counter"]; + } + + // Head-pointer storage: one u32 per pixel. Reallocate any time the + // framebuffer grows — the previous buffer is dropped and the GPU + // will release it once nothing else references it. Caller is + // responsible for inserting a barrier / waiting for the GPU to + // drain prior work that touched the old buffer before resize. + abufferPointer = [device newBufferWithLength:(maxWidth * maxHeight * sizeof(u32)) + options:opts]; + [abufferPointer setLabel:@"Flycast OIT abuffer pointer"]; + + firstFrameAfterInit = true; + } + + /// Per-frame housekeeping: re-allocate the pixel buffer if the user + /// changed config::PixelBufferSize between frames. Equivalent to + /// Vulkan's OnNewFrame. Called from the renderer's per-frame entry. + void OnNewFrame() + { + firstFrameAfterInit = false; + if (pixelBufferSize != (u64)config::PixelBufferSize) + { + pixelBufferSize = (u64)config::PixelBufferSize; + auto device = MetalContext::Instance()->GetDevice(); + const u64 cap = (u64)[device maxBufferLength]; + const u64 sz = std::min(pixelBufferSize, cap); + pixelBuffer = [device newBufferWithLength:sz + options:MTLResourceStorageModePrivate]; + [pixelBuffer setLabel:@"Flycast OIT pixel buffer"]; + } + } + + /// Zero the per-frame pixel counter. Vulkan does this via a buffer + /// copy from a pre-staged 4-byte reset buffer; on Metal we use the + /// blit encoder's fillBuffer: directly which avoids the staging + /// buffer entirely. + void ResetPixelCounter(id blit) + { + if (pixelCounter != nil) + [blit fillBuffer:pixelCounter range:NSMakeRange(0, 4) value:0]; + } + + void Term() + { + pixelBuffer = nil; + pixelCounter = nil; + abufferPointer = nil; + maxWidth = 0; + maxHeight = 0; + pixelBufferSize = 0; + firstFrameAfterInit = false; + } + + bool isFirstFrameAfterInit() const { return firstFrameAfterInit; } + + id getPixelBuffer() const { return pixelBuffer; } + id getPixelCounter() const { return pixelCounter; } + id getAbufferPointer() const { return abufferPointer; } + + int getMaxWidth() const { return maxWidth; } + int getMaxHeight() const { return maxHeight; } + +private: + id pixelBuffer = nil; + id pixelCounter = nil; + id abufferPointer = nil; + + bool firstFrameAfterInit = false; + int maxWidth = 0; + int maxHeight = 0; + u64 pixelBufferSize = 0; +}; diff --git a/core/rend/metal/oit/metal_oit_drawer.h b/core/rend/metal/oit/metal_oit_drawer.h new file mode 100644 index 0000000000..605061843f --- /dev/null +++ b/core/rend/metal/oit/metal_oit_drawer.h @@ -0,0 +1,375 @@ +/* + This file is part of Flycast. + + Flycast is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 2 of the License, or + (at your option) any later version. + + Flycast is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with Flycast. If not, see . +*/ +// Metal OIT drawer. Port of core/rend/vulkan/oit/oit_drawer.h. +// +// Class hierarchy: +// MetalBaseDrawer +// └── MetalOITDrawer +// ├── MetalOITScreenDrawer +// └── MetalOITTextureDrawer +#pragma once +#include "../metal_apple.h" + +#include "types.h" +#include "../metal.h" +#include "../metal_drawer.h" +#include "../metal_quad.h" +#include "../metal_texture.h" +#include "metal_oit_buffer.h" +#include "metal_oit_pipeline.h" + +#include +#include +#include + +class MetalShaders; + +class MetalOITDrawer : public MetalBaseDrawer +{ +public: + virtual ~MetalOITDrawer() = default; + + /// Top-level frame draw entry. Mirrors Vulkan OITDrawer::Draw(). + /// Will issue: opaque pass, OIT collect pass (translucent), OIT + /// resolve pass, present. + bool Draw(const MetalTexture *fogTexture, const MetalTexture *paletteTexture); + + /// Frame lifecycle. NewFrame returns the active command buffer for + /// the current frame so screen/texture drawers can layer their own + /// pre/post work. EndFrame closes the buffer and commits. + virtual id NewFrame() = 0; + virtual void EndFrame() = 0; + +protected: + void Init(MetalOITPipelineManager *pipelineManager, MetalOITBuffers *oitBuffers, + MetalSamplers *samplers = nullptr, + MetalPipelineManager *regularPipelineManager = nullptr) + { + this->pipelineManager = pipelineManager; + this->oitBuffers = oitBuffers; + this->samplers = samplers; + this->regularPipelineManager = regularPipelineManager; + this->tileDepth = pipelineManager != nullptr && pipelineManager->UseTileDepth(); + } + + void Term() + { + ReleaseBuffers(); + opaqueDepthCopy = nil; + opaqueDepthTile = nil; + resolveDepthStencil = nil; + } + + /// Drop the attachments and resolve background so the next MakeBuffers() + /// allocates them at exactly the requested size. + void ReleaseBuffers() + { + releaseAttachments(); + resolveBackground = nil; + maxWidth = 0; + maxHeight = 0; + } + + /// Grow the shared per-pixel storage, the resolve background and this + /// drawer's own attachments to (width,height). Re-creates only if the + /// requested size exceeds the cached max dimensions. + void MakeBuffers(int width, int height); + /// The render targets a drawer owns besides the shared buffers. The screen + /// drawer has one color/depth pair; the RTT drawer renders straight into + /// the texture it is given and needs none. + virtual bool makeAttachments(id device, int width, int height) { return true; } + virtual void releaseAttachments() {} + + virtual MTLRenderPassDescriptor *getOitRenderPassDescriptor(int renderPassIndex, + int renderPassCount, + bool initialPass) = 0; + + void resetOitPixelCounter(); + void bindCommonFragmentState(id encoder, + const MetalTexture *fogTexture, + const MetalTexture *paletteTexture); + void bindOitCollectBuffers(id encoder, int w, int h); + void drawResolve(id encoder, bool finalPass, int w, int h); + /// Blit `depth` into opaqueDepthCopy (growing it as needed) for the + /// collect shader's manual depth test. Must run outside any render encoder. + void copyOpaqueDepth(id depth, int w, int h); + /// Tile depth: add the memoryless opaque-depth attachment (colour 1) to the + /// OP/PT/modvol/collect encoder's pass descriptor. Returns false if the + /// texture couldn't be created. + bool attachOpaqueDepthTile(MTLRenderPassDescriptor *passDesc); + /// Tile depth, render passes after the first: write opaqueDepthCopy (the + /// depth the pass loaded) into colour 1 with a full-screen draw. + void seedOpaqueDepthTile(id encoder); + id getAlwaysDepthStencilState(); + /// Marks the opaque modifier volumes of this render pass in the stencil, draws + /// the two-volume polys' second parameter set inside the marks (and the + /// translucent ones' first set outside), then applies the shadow-scale Final. + void drawOpaqueModVols(id encoder, int first, int count, + const RenderPass &prev, const RenderPass &cur, int w, int h); + /// Two-volume polys (pcw.Volume: a second colour/offset/uv + tsp/tcw/texture set + /// selected per pixel by the modifier volumes). Metal cannot read the stencil in + /// the fragment shader, so each such poly is drawn once per set with a stencil + /// test instead; `area` 1 = second set inside the mark, 2 = first set outside. + /// The translucent collect draws use the [[early_fragment_tests]] fs_main_early + /// so that test runs before the a-buffer append. + static bool isTwoVolumePoly(const PolyParam &pp) { + return pp.tsp1.full != (u32)-1 || pp.tcw1.full != (u32)-1; + } + static PolyParam area1Params(const PolyParam &pp) { + PolyParam p = pp; + p.tsp = pp.tsp1; + p.tcw = pp.tcw1; + p.texture = pp.texture1; + return p; + } + void drawTwoVolumePolys(id encoder, const RenderPass &prev, + const RenderPass &cur, int w, int h); + void drawRegularPoly(id encoder, u32 listType, + bool sortTriangles, const PolyParam &poly, + u32 first, u32 count, int area = 0); + void drawTranslucentDepthOnly(id encoder, + bool autosort, u32 first, u32 last); + + // Per-frame state. Names mirror Vulkan OITDrawer for easy cross-reference. + MTLViewport viewport {}; + /// Scratch copy of the opaque color attachment, blitted between the + /// collect and resolve encoders and sampled by oit_resolve_fragment. + /// Replaces the [[color(0)]] framebuffer fetch the resolve shader used + /// to do, which isn't supported by every Metal implementation. + id resolveBackground = nil; + /// Scratch copy of the opaque + punch-through depth, blitted before the + /// collect draws and read by fs_main's OIT path for its manual depth test + /// (Vulkan reads the same depth as a subpass input). Sized lazily from + /// the pass's depth attachment so the screen and RTT drawers share it. + id opaqueDepthCopy = nil; + /// Tile-memory opaque depth (colour attachment 1, R32Float, memoryless, + /// cleared to 0 = the depth clear value, never stored). OP/PT draws write + /// their depth to it and the collect reads it by framebuffer fetch, so the + /// manual depth test needs no encoder break. Used when tileDepth. + id opaqueDepthTile = nil; + /// MetalOITTileDepthSupported() for this device; fixed at Init. + bool tileDepth = false; + /// Depth/stencil state for the resolve quad: always pass, no depth write, + /// no stencil test. Vulkan bakes the equivalent into its final pipeline as + /// a default-constructed PipelineDepthStencilStateCreateInfo; on Metal + /// depth/stencil state is encoder state, so it must be set explicitly or + /// the resolve inherits whatever DrawModifierVolumes left bound. + id resolveDepthStencil = nil; + id currentCommandBuffer = nil; + int maxWidth = 0; + int maxHeight = 0; + bool needAttachmentTransition = false; + +protected: + // Drawer-side orchestration. Iterates rendContext->global_param_tr + // and emits per-poly drawIndexedPrimitives through the collect + // pipeline. Each poly gets the same per-poly setup the regular + // MetalDrawer does (pipeline state, depth/stencil, cull, scissor, + // PushBlock setBytes) — the only difference is the pipeline comes + // from MetalOITPipelineManager::GetCollectPipeline so fs_main runs + // with oitMode=true. + void DrawList(id encoder, u32 listType, + bool sortTriangles, const std::vector& polys, + u32 first, u32 last, bool oitCollect = true); + /// triangleList: the index range is an unstripped triangle list (only + /// DrawSorted, which walks rendContext->sortedTriangles). Everything else indexes + /// the triangle strips makeIndex() builds for global_param_tr. + void DrawPoly(id encoder, u32 listType, + bool sortTriangles, const PolyParam& poly, + u32 first, u32 count, bool oitCollect = true, + bool depthOnly = false, bool triangleList = false, int area = 0); + void DrawSorted(id encoder, + const std::vector& polys, + u32 first, u32 last); + /// TR modifier volumes, in the resolve encoder. With + /// MetalOITFragmentOrdering::EncoderSplit the encoder is ended and reopened + /// from passDesc (set up again by setupEncoder) between a volume's marks and + /// its sum, so `encoder` is updated in place. + void DrawModifierVolumes(__strong id &encoder, + MTLRenderPassDescriptor *passDesc, + const std::function)> &setupEncoder, + int first, int count, bool useSharedMvo = false); + + // The autosort path deliberately calls DrawList on global_param_tr instead of DrawSorted -- + // matching Vulkan, because ta_vtx.cpp only builds sortedTriangles when + // !perPixel and OIT counts as perPixel, so sortedTriangles is always + // empty here. See the comment at the DrawList call site. + + struct Offsets { + u64 indexOffset = 0; + u64 modVolOffset = 0; + u64 vertexUniformOffset = 0; + u64 fragmentUniformOffset = 0; + u64 polyParamsOffset = 0; + u64 polyParamsSize = 0; + u64 naomi2OpaqueOffset = 0; + u64 naomi2PunchThroughOffset = 0; + u64 naomi2TranslucentOffset = 0; + u64 naomi2ModVolOffset = 0; + u64 naomi2TrModVolOffset = 0; + u64 lightsOffset = (u64)-1; + } offsets; + + void UploadMainBuffer(const MetalVertexShaderUniforms &vertexUniforms, + const MetalFragmentShaderUniforms &fragmentUniforms); + + // Regular (non-OIT) pipeline manager for opaque + punch-through + // draws that render into the OIT colour attachment before + // the collect pass. Owned by the screen drawer subclass; passed in + // via Init. Required for full visual output — without it the OIT + // path renders only translucent geometry on a black background. + MetalPipelineManager *regularPipelineManager = nullptr; + MetalOITPipelineManager *pipelineManager = nullptr; + MetalOITBuffers *oitBuffers = nullptr; + MetalSamplers *samplers = nullptr; + id curMainBuffer = nil; + u32 currentBaseOffset = 0; + bool dithering = false; + /// Per-channel dither divisor derived from fb_W_CTRL.fb_packmode in Draw() + /// (Vulkan: oit_drawer.cpp). Consumed by the resolve pass. + float ditherDivisor[4] = { 0.f, 0.f, 0.f, 1.f }; +}; + +class MetalOITScreenDrawer : public MetalOITDrawer +{ +public: + /// Initialise for screen-bound output. + void Init(MetalShaders *shaderManager, MetalOITBuffers *oitBuffers, + const MTLViewport &vp, MetalSamplers *samplers = nullptr) + { + emulateFramebuffer = config::EmulateFramebuffer; + this->shaderManager = shaderManager; + if (!screenPipelineManager) { + screenPipelineManager = std::make_unique(shaderManager, oitBuffers); + screenPipelineManager->Init(); + } + if (!regularPipelineManager_) { + regularPipelineManager_ = std::make_unique( + shaderManager, screenPipelineManager->UseTileDepth()); + } + MetalOITDrawer::Init(screenPipelineManager.get(), oitBuffers, samplers, + regularPipelineManager_.get()); + // MakeBuffers only ever grows the attachments, but the screen drawer + // presents (and under EmulateFramebuffer reads back) its whole color + // attachment, so it must match the viewport exactly. Vulkan's + // OITScreenDrawer::Init recreates its framebuffers at the new extent. + if (vp.width != viewport.width || vp.height != viewport.height) + ReleaseBuffers(); + viewport = vp; + } + + void Term() + { + releaseReadbackTextures(); + regularPipelineManager_.reset(); + screenPipelineManager.reset(); + MetalOITDrawer::Term(); + } + + id NewFrame() override; + void EndFrame() override; + + /// End the frame, commit the OIT command buffer, and hand the resolved + /// color attachment to MetalContext::PresentFrame for surface + /// presentation. Returns false if there's nothing to present (e.g. + /// the current frame produced no encoders). Defined in + /// metal_oit_drawer.mm. + bool PresentFrame(); + +protected: + MTLRenderPassDescriptor *getOitRenderPassDescriptor(int renderPassIndex, + int renderPassCount, + bool initialPass) override; + bool makeAttachments(id device, int width, int height) override; + void releaseAttachments() override + { + colorAttachment = nil; + depthAttachment = nil; + passDescriptor = nil; + } + +private: + // The screen target. Kept across renders: with delayed swapping, a second + // render may need to load the first one before either is presented. + id colorAttachment = nil; + id depthAttachment = nil; + MTLRenderPassDescriptor *passDescriptor = nil; + bool clearNeeded = true; + std::unique_ptr screenPipelineManager; + std::unique_ptr regularPipelineManager_; + bool frameRendered = false; + float aspectRatio = 0.f; + bool frameStarted = false; + bool emulateFramebuffer = false; +}; + +class MetalOITTextureDrawer : public MetalOITDrawer +{ +public: + void Init(MetalShaders *shaderManager, MetalOITBuffers *oitBuffers, + MetalTextureCache *textureCache, MetalSamplers *samplers = nullptr) + { + if (!rttPipelineManager) { + rttPipelineManager = std::make_unique(shaderManager, oitBuffers); + rttPipelineManager->Init(); + } + if (!regularPipelineManager_) { + regularPipelineManager_ = std::make_unique( + shaderManager, rttPipelineManager->UseTileDepth()); + } + MetalOITDrawer::Init(rttPipelineManager.get(), oitBuffers, samplers, + regularPipelineManager_.get()); + this->textureCache = textureCache; + if (rttPassDescriptor == nil) + rttPassDescriptor = [MTLRenderPassDescriptor renderPassDescriptor]; + } + + void Term() + { + texture = nullptr; + rttColorImage = nil; + rttDepthAttachment = nil; + colorAttachment = nil; + rttPassDescriptor = nil; + regularPipelineManager_.reset(); + rttPipelineManager.reset(); + MetalOITDrawer::Term(); + } + + id NewFrame() override; + void EndFrame() override; + +protected: + MTLRenderPassDescriptor *getOitRenderPassDescriptor(int renderPassIndex, + int renderPassCount, + bool initialPass) override; + + +private: + u32 textureAddr = 0; + // RTT readback scratch; see MetalTextureDrawer::rttReadback. + PixelBuffer rttReadback; + + MetalTexture *texture = nullptr; + MetalTextureCache *textureCache = nullptr; + id colorAttachment = nil; + id rttColorImage = nil; + id rttDepthAttachment = nil; + MTLRenderPassDescriptor *rttPassDescriptor = nil; + std::unique_ptr rttPipelineManager; + std::unique_ptr regularPipelineManager_; +}; diff --git a/core/rend/metal/oit/metal_oit_drawer.mm b/core/rend/metal/oit/metal_oit_drawer.mm new file mode 100644 index 0000000000..124666e051 --- /dev/null +++ b/core/rend/metal/oit/metal_oit_drawer.mm @@ -0,0 +1,1661 @@ +/* + This file is part of Flycast. + + Flycast is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 2 of the License, or + (at your option) any later version. + + Flycast is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with Flycast. If not, see . +*/ +// Metal OIT drawer. Port of core/rend/vulkan/oit/oit_drawer.cpp. +// +// Per Draw(): +// 1. blit encoder: reset the pixel counter and set every a-buffer head pointer to EOL +// 2. collect render encoder: opaque and punch-through polys, then translucent +// fragments appended to the per-pixel linked lists (color writes masked off) +// 3. resolve render encoder: translucent modifier volumes, then the resolve pass +// sorts and blends each pixel's list over the opaque background +#include "metal_oit_drawer.h" +#include "../metal_texture_utils.h" +#include "../metal_context.h" +#include "hw/pvr/ta.h" + +#include +#include + +namespace { + +// Build (or reuse) a ResolveUniforms upload buffer. Three uints, tiny — +// passed via setFragmentBytes so no MTLBuffer allocation is needed at +// the call site. Centralised here so collect and resolve see the same +// viewport sizing. +// Must match ResolveUniforms in metal_oit_shaders.h: MSL float4 is 16-byte +// aligned, so the struct is 48 bytes (ditherDivisor at 16, applyDither at 32). +struct alignas(16) MetalOITResolveUniformsCPU { + uint32_t viewportWidth; + uint32_t viewportHeight; + uint32_t pixelBufferSize; + float shadeScale; + float ditherDivisor[4]; + uint32_t applyDither; +}; +static_assert(offsetof(MetalOITResolveUniformsCPU, ditherDivisor) == 16, "ResolveUniforms layout"); +static_assert(offsetof(MetalOITResolveUniformsCPU, applyDither) == 32, "ResolveUniforms layout"); +static_assert(sizeof(MetalOITResolveUniformsCPU) == 48, "ResolveUniforms layout"); + +} // namespace + +bool MetalOITDrawer::Draw(const MetalTexture *fogTexture, + const MetalTexture *paletteTexture) +{ + // Runs on the emu/render thread (no pool of its own) — same rationale as + // the @autoreleasepool in the non-OIT MetalDrawer::Draw. + @autoreleasepool { + if (commandPool == nullptr) { + WARN_LOG(RENDERER, "MetalOITDrawer::Draw: no command pool"); + return false; + } + if (oitBuffers == nullptr || pipelineManager == nullptr) { + WARN_LOG(RENDERER, "MetalOITDrawer::Draw: pipeline manager or OIT buffers missing"); + return false; + } + const int w = (int)viewport.width; + const int h = (int)viewport.height; + if (w <= 0 || h <= 0) + return false; + pipelineManager->Init(); + MakeBuffers(w, h); + if (resolveBackground == nil) + return false; + + if (currentCommandBuffer == nil) + currentCommandBuffer = commandPool->Allocate(); + if (currentCommandBuffer == nil) + return false; + [currentCommandBuffer pushDebugGroup:@"OIT Frame"]; + + dithering = config::EmulateFramebuffer && rendContext->fb_W_CTRL.fb_dither + && rendContext->fb_W_CTRL.fb_packmode <= 3; + ditherDivisor[0] = ditherDivisor[1] = ditherDivisor[2] = 0.f; + ditherDivisor[3] = 1.f; + if (dithering) { + switch (rendContext->fb_W_CTRL.fb_packmode) + { + case 0: // 0555 KRGB 16 bit + case 3: // 1555 ARGB 16 bit + ditherDivisor[0] = ditherDivisor[1] = ditherDivisor[2] = 2.f; + break; + case 1: // 565 RGB 16 bit + ditherDivisor[0] = ditherDivisor[2] = 2.f; + ditherDivisor[1] = 4.f; + break; + case 2: // 4444 ARGB 16 bit + ditherDivisor[0] = ditherDivisor[1] = ditherDivisor[2] = 1.f; + break; + default: + break; + } + } + bool firstFrameAfterInit = oitBuffers->isFirstFrameAfterInit(); + oitBuffers->OnNewFrame(); + + if (firstFrameAfterInit) { + id blit = [currentCommandBuffer blitCommandEncoder]; + id head = oitBuffers->getAbufferPointer(); + // Fill the whole buffer, not just this frame's w*h: it is sized for + // the largest target seen so far and shared with the other drawer, + // and each pass indexes it with its own width as the stride. Cells + // left at their initial zero would read as a link to pixel entry 0. + if (head != nil) + [blit fillBuffer:head range:NSMakeRange(0, [head length]) value:0xFF]; + [blit endEncoding]; + } + + // Metal reads [[flat]] varyings from the FIRST vertex; Dreamcast flat + // shading uses the LAST. The Vulkan OIT drawer does this fix-up too + // (oit_drawer.cpp) when VK_EXT_provoking_vertex is unavailable. Without + // it every flat-shaded poly takes its color/alpha from the wrong vertex — + // most visibly the THPS2 / Mat Hoffman player-shadow decals, which carry + // their real color only on the provoking vertex and rendered invisible. + // Must run before UploadMainBuffer so the reordered verts/idx get uploaded. + setFirstProvokingVertex(*rendContext); + + // Matrices must be computed BEFORE the uniforms snapshot them — the + // non-OIT drawers do this in BeginRenderPass, and Vulkan's OIT drawer + // calls CalcMatrices at the top of Draw. Reading GetNormalMatrix first + // uploaded the previous frame's ndcMat (uninitialized on the first + // frame after init/resize). + matrices.CalcMatrices(rendContext, w, h); + SetBaseScissor(viewport); + + MetalVertexShaderUniforms vtxUniforms {}; + vtxUniforms.ndcMat = matrices.GetNormalMatrix(); + MetalFragmentShaderUniforms fragUniforms = + MakeFragmentUniforms(); + std::copy(std::begin(ditherDivisor), std::end(ditherDivisor), fragUniforms.ditherDivisor); + UploadMainBuffer(vtxUniforms, fragUniforms); + + const int renderPassCount = (int)rendContext->render_passes.size(); + RenderPass previous_pass {}; + for (int rp = 0; rp < renderPassCount; ++rp) { + const RenderPass &cur = rendContext->render_passes[rp]; + const bool initialPass = rp == 0; + const bool finalPass = rp == renderPassCount - 1; + + resetOitPixelCounter(); + + MTLRenderPassDescriptor *passDesc = + getOitRenderPassDescriptor(rp, renderPassCount, initialPass); + if (passDesc == nil) + continue; + + auto setupEncoder = [&](id e) { + currentScissor = MTLScissorRect {}; + [e setViewport:viewport]; + [e setFrontFacingWinding:MTLWindingCounterClockwise]; + [e setVertexBuffer:curMainBuffer offset:currentBaseOffset + 0 atIndex:30]; + [e setVertexBuffer:curMainBuffer + offset:currentBaseOffset + offsets.vertexUniformOffset + atIndex:0]; + [e setFragmentBuffer:curMainBuffer + offset:currentBaseOffset + offsets.fragmentUniformOffset + atIndex:0]; + bindCommonFragmentState(e, fogTexture, paletteTexture); + }; + + // The collect fragments must be depth-tested against the opaque + + // punch-through depth in the shader. fs_main writes [[depth(any)]], so + // the hardware depth test runs after the fragment function, and the + // a-buffer append (device atomics) has already happened by then: the + // collect pass's depth-stencil state only gates the masked-out colour + // write and rejects nothing. Vulkan tests manually against the depth + // subpass input (oit_shaders.cpp, "Manual depth testing"). + // + // Apple GPUs (tileDepth): the OP/PT draws also write their depth to a + // memoryless colour attachment and the collect reads it back with + // framebuffer fetch — the depth never leaves tile memory. Elsewhere the + // encoder is ended after OP/PT and the depth attachment blitted to a + // sampled copy (below), which on a TBDR GPU would store and reload the + // colour and depth attachments. + const bool collectTr = cur.autosort && cur.tr_count > previous_pass.tr_count; + bool useTileDepth = tileDepth && attachOpaqueDepthTile(passDesc); + if (tileDepth && !useTileDepth) + continue; // every pipeline here declares the tile attachment + // Passes after the first load the depth of the earlier ones (and their + // translucent depth-only writes); the tile copy starts cleared, so seed + // it from a copy taken before the encoder opens (no extra encoder break: + // the previous pass's resolve encoder already stored the depth). + const bool seedTile = useTileDepth && !initialPass && collectTr; + if (seedTile) + copyOpaqueDepth(passDesc.depthAttachment.texture, w, h); + + id enc = + [currentCommandBuffer renderCommandEncoderWithDescriptor:passDesc]; + [enc pushDebugGroup:@"OIT Render Pass"]; + setupEncoder(enc); + if (seedTile) + seedOpaqueDepthTile(enc); + + // OP + PT (Metal merges Vulkan depth+color subpasses) + if (regularPipelineManager != nullptr) { + for (u32 i = previous_pass.op_count; i < cur.op_count; ++i) { + const PolyParam &pp = rendContext->global_param_op[i]; + if (pp.count > 2) + drawRegularPoly(enc, ListType_Opaque, false, pp, pp.first, pp.count); + } + for (u32 i = previous_pass.pt_count; i < cur.pt_count; ++i) { + const PolyParam &pp = rendContext->global_param_pt[i]; + if (pp.count > 2) + drawRegularPoly(enc, ListType_Punch_Through, false, pp, pp.first, pp.count); + } + } + + // Copy fallback (no tile depth): end the encoder, copy the depth to a + // sampled texture and reopen; fs_main reads the copy at texture 4. + if (!useTileDepth && collectTr) { + [enc popDebugGroup]; + [enc endEncoding]; + copyOpaqueDepth(passDesc.depthAttachment.texture, w, h); + passDesc.colorAttachments[0].loadAction = MTLLoadActionLoad; + passDesc.depthAttachment.loadAction = MTLLoadActionLoad; + passDesc.stencilAttachment.loadAction = MTLLoadActionLoad; + enc = [currentCommandBuffer renderCommandEncoderWithDescriptor:passDesc]; + [enc pushDebugGroup:@"OIT Collect Pass"]; + setupEncoder(enc); + [enc setFragmentTexture:opaqueDepthCopy atIndex:4]; + } + + if (regularPipelineManager != nullptr) { + drawOpaqueModVols(enc, (int)previous_pass.mvo_count, + (int)cur.mvo_count - (int)previous_pass.mvo_count, + previous_pass, cur, w, h); + } + + // Translucent collect or regular blended TR + if (cur.autosort) { + bindOitCollectBuffers(enc, w, h); + // Always draw the raw translucent list, never rendContext->sortedTriangles. + // + // ta_vtx.cpp:1194 only builds sortedTriangles when `!perPixel`, and + // parseRenderPass counts Metal_OIT as perPixel — OIT sorts per pixel + // in the a-buffer, so the core deliberately skips the CPU sort and + // leaves sortedTriangles empty with sorted_tr_count == 0. The old + // code called DrawSorted() on that empty vector whenever + // !PerStripSorting, and since reconcileStaleOITRenderer refuses to + // enable OIT unless PerStripSorting is off, that dead branch was the + // one taken 100% of the time: DrawSorted returned immediately on + // first == last, the collect pass emitted zero fragments (verified: + // OIT pixel counter read back 0 with 11 translucent polys queued), + // and the resolve composited an empty a-buffer — leaving only the + // flat-shaded opaque layer on screen. That is the blank Dreamcast + // BIOS boot swirl and BIOS menu. + // + // Vulkan's OIT drawer (oit_drawer.cpp:434) has no DrawSorted path at + // all — both autosort branches walk global_param_tr with tr_count. + DrawList(enc, ListType_Translucent, true, rendContext->global_param_tr, + previous_pass.tr_count, cur.tr_count, true); + } else { + DrawList(enc, ListType_Translucent, false, rendContext->global_param_tr, + previous_pass.tr_count, cur.tr_count, false); + } + + // The collect fragments write the a-buffer (pixel records + head + // pointers) through device-memory atomics, and Metal does NOT order + // those writes against later draws within the same render pass — + // a fragment->fragment render-encoder memoryBarrier is invalid on + // Apple GPUs (see MetalOITFragmentOrdering). The + // TR-modvol and resolve draws below READ those lists, so they must + // run in a second encoder: Metal's automatic hazard tracking orders + // buffer access between passes. The single merged encoder read the + // a-buffer racily — intermittent gray/ghost frames in the simulator, + // consistently missing HUD-under-translucency on device TBDR. (The + // file header's "two-encoder dance" described exactly this split.) + [enc popDebugGroup]; + [enc endEncoding]; + + // Snapshot the opaque result for the resolve shader. The resolve used + // to read the attachment in place via [[color(0)]] framebuffer fetch, + // but that construct is unimplemented in the iOS Simulator's Metal: + // CreateResolvePipeline failed with "reading from a rendertarget is + // not supported" on every frame, drawResolve returned early, and the + // whole translucent list was collected into the a-buffer and then + // thrown away. Copying to a plain texture composites identically and + // builds everywhere. Metal's automatic hazard tracking orders the + // blit after the collect encoder and before the resolve encoder. + id opaqueTex = passDesc.colorAttachments[0].texture; + if (resolveBackground != nil && opaqueTex != nil) { + const NSUInteger copyW = std::min((NSUInteger)w, + std::min(opaqueTex.width, resolveBackground.width)); + const NSUInteger copyH = std::min((NSUInteger)h, + std::min(opaqueTex.height, resolveBackground.height)); + if (copyW > 0 && copyH > 0) { + id bgBlit = [currentCommandBuffer blitCommandEncoder]; + [bgBlit copyFromTexture:opaqueTex + sourceSlice:0 + sourceLevel:0 + sourceOrigin:MTLOriginMake(0, 0, 0) + sourceSize:MTLSizeMake(copyW, copyH, 1) + toTexture:resolveBackground + destinationSlice:0 + destinationLevel:0 + destinationOrigin:MTLOriginMake(0, 0, 0)]; + [bgBlit endEncoding]; + } + } + + passDesc.colorAttachments[0].loadAction = MTLLoadActionLoad; + passDesc.depthAttachment.loadAction = MTLLoadActionLoad; + passDesc.stencilAttachment.loadAction = MTLLoadActionLoad; + // The tile depth is dead after the collect, and a memoryless attachment + // can't be loaded: the resolve encoder's pipelines don't declare it. + passDesc.colorAttachments[1].texture = nil; + enc = [currentCommandBuffer renderCommandEncoderWithDescriptor:passDesc]; + [enc pushDebugGroup:@"OIT Resolve Pass"]; + setupEncoder(enc); + + // TR modvol after collect (Vulkan final subpass) + if (cur.mv_op_tr_shared) { + DrawModifierVolumes(enc, passDesc, setupEncoder, (int)previous_pass.mvo_count, + (int)cur.mvo_count - (int)previous_pass.mvo_count, + true); + } else { + DrawModifierVolumes(enc, passDesc, setupEncoder, (int)previous_pass.mvo_tr_count, + (int)cur.mvo_tr_count - (int)previous_pass.mvo_tr_count, + false); + } + + drawResolve(enc, finalPass, w, h); + + if (!finalPass) + drawTranslucentDepthOnly(enc, cur.autosort, previous_pass.tr_count, cur.tr_count); + + [enc popDebugGroup]; + [enc endEncoding]; + previous_pass = cur; + } + + [currentCommandBuffer popDebugGroup]; + return true; + } // @autoreleasepool +} + +void MetalOITDrawer::copyOpaqueDepth(id depth, int w, int h) +{ + if (depth == nil) + return; + if (opaqueDepthCopy == nil || opaqueDepthCopy.width < depth.width + || opaqueDepthCopy.height < depth.height + || opaqueDepthCopy.pixelFormat != depth.pixelFormat) + { + MTLTextureDescriptor *desc = + [MTLTextureDescriptor texture2DDescriptorWithPixelFormat:depth.pixelFormat + width:depth.width + height:depth.height + mipmapped:NO]; + desc.usage = MTLTextureUsageShaderRead; + desc.storageMode = MTLStorageModePrivate; + opaqueDepthCopy = [MetalContext::Instance()->GetDevice() newTextureWithDescriptor:desc]; + opaqueDepthCopy.label = @"OIT opaque depth copy"; + } + const NSUInteger copyW = std::min((NSUInteger)w, depth.width); + const NSUInteger copyH = std::min((NSUInteger)h, depth.height); + if (opaqueDepthCopy == nil || copyW == 0 || copyH == 0) + return; + id blit = [currentCommandBuffer blitCommandEncoder]; + [blit copyFromTexture:depth + sourceSlice:0 + sourceLevel:0 + sourceOrigin:MTLOriginMake(0, 0, 0) + sourceSize:MTLSizeMake(copyW, copyH, 1) + toTexture:opaqueDepthCopy + destinationSlice:0 + destinationLevel:0 + destinationOrigin:MTLOriginMake(0, 0, 0)]; + [blit endEncoding]; +} + +bool MetalOITDrawer::attachOpaqueDepthTile(MTLRenderPassDescriptor *passDesc) +{ + id color = passDesc.colorAttachments[0].texture; + if (color == nil) + return false; + if (opaqueDepthTile == nil || opaqueDepthTile.width != color.width + || opaqueDepthTile.height != color.height) + { + MTLTextureDescriptor *desc = + [MTLTextureDescriptor texture2DDescriptorWithPixelFormat:MTLPixelFormatR32Float + width:color.width + height:color.height + mipmapped:NO]; + desc.usage = MTLTextureUsageRenderTarget; + desc.storageMode = MTLStorageModePrivate; + if (@available(macOS 11.0, iOS 10.0, tvOS 10.0, *)) + desc.storageMode = MTLStorageModeMemoryless; + id device = MetalContext::Instance()->GetDevice(); + opaqueDepthTile = [device newTextureWithDescriptor:desc]; + if (opaqueDepthTile == nil && desc.storageMode != MTLStorageModePrivate) { + desc.storageMode = MTLStorageModePrivate; + opaqueDepthTile = [device newTextureWithDescriptor:desc]; + } + if (opaqueDepthTile == nil) { + WARN_LOG(RENDERER, "MetalOITDrawer: can't create the opaque depth tile attachment"); + return false; + } + opaqueDepthTile.label = @"OIT opaque depth (tile)"; + } + passDesc.colorAttachments[1].texture = opaqueDepthTile; + passDesc.colorAttachments[1].loadAction = MTLLoadActionClear; + passDesc.colorAttachments[1].storeAction = MTLStoreActionDontCare; + // 0 = the depth attachment's clear value: nothing opaque, every + // translucent fragment passes the GEqual test. + passDesc.colorAttachments[1].clearColor = MTLClearColorMake(0.0, 0.0, 0.0, 0.0); + return true; +} + +id MetalOITDrawer::getAlwaysDepthStencilState() +{ + if (resolveDepthStencil == nil) { + id device = MetalContext::Instance()->GetDevice(); + if (device != nil) { + MTLDepthStencilDescriptor *dsDesc = [[MTLDepthStencilDescriptor alloc] init]; + dsDesc.depthCompareFunction = MTLCompareFunctionAlways; + dsDesc.depthWriteEnabled = NO; + dsDesc.label = @"OIT Resolve DS"; + resolveDepthStencil = [device newDepthStencilStateWithDescriptor:dsDesc]; + } + } + return resolveDepthStencil; +} + +void MetalOITDrawer::seedOpaqueDepthTile(id encoder) +{ + id pso = pipelineManager->GetSeedOpaqueDepthPipeline(); + id ds = getAlwaysDepthStencilState(); + if (pso == nil || ds == nil || opaqueDepthCopy == nil) + return; + [encoder pushDebugGroup:@"OIT seed opaque depth"]; + [encoder setRenderPipelineState:pso]; + [encoder setDepthStencilState:ds]; + [encoder setCullMode:MTLCullModeNone]; + SetScissor(encoder, baseScissor); + [encoder setFragmentTexture:opaqueDepthCopy atIndex:4]; + [encoder drawPrimitives:MTLPrimitiveTypeTriangle vertexStart:0 vertexCount:3]; + [encoder popDebugGroup]; +} + +void MetalOITDrawer::resetOitPixelCounter() +{ + id blit = [currentCommandBuffer blitCommandEncoder]; + oitBuffers->ResetPixelCounter(blit); + [blit endEncoding]; +} + +void MetalOITDrawer::bindCommonFragmentState(id encoder, + const MetalTexture *fogTexture, + const MetalTexture *paletteTexture) +{ + if (fogTexture != nullptr && samplers != nullptr) { + [encoder setFragmentTexture:fogTexture->GetTexture() atIndex:2]; + TSP fogTsp = {}; + fogTsp.FilterMode = 1; + fogTsp.ClampU = 1; + fogTsp.ClampV = 1; + id fogSampler = samplers->GetSampler(fogTsp); + if (fogSampler != nil) + [encoder setFragmentSamplerState:fogSampler atIndex:2]; + } + if (paletteTexture != nullptr && samplers != nullptr) { + [encoder setFragmentTexture:paletteTexture->GetTexture() atIndex:3]; + TSP palTsp = {}; + palTsp.FilterMode = 0; + palTsp.ClampU = 1; + palTsp.ClampV = 1; + id palSampler = samplers->GetSampler(palTsp); + if (palSampler != nil) + [encoder setFragmentSamplerState:palSampler atIndex:3]; + } +} + +void MetalOITDrawer::bindOitCollectBuffers(id encoder, int w, int h) +{ + [encoder setFragmentBuffer:oitBuffers->getPixelCounter() offset:0 atIndex:2]; + [encoder setFragmentBuffer:oitBuffers->getPixelBuffer() offset:0 atIndex:3]; + [encoder setFragmentBuffer:oitBuffers->getAbufferPointer() offset:0 atIndex:4]; + MetalOITResolveUniformsCPU collectVpUniforms = { + (uint32_t)w, + (uint32_t)h, + (uint32_t)([oitBuffers->getPixelBuffer() length] / 16u), + 0.f, + { 0.f, 0.f, 0.f, 1.f }, + 0u, + }; + [encoder setFragmentBytes:&collectVpUniforms length:sizeof(collectVpUniforms) atIndex:5]; +} + +void MetalOITDrawer::drawResolve(id encoder, bool finalPass, int w, int h) +{ + id pso = pipelineManager->GetResolvePipeline(); + if (pso == nil) + return; + [encoder setRenderPipelineState:pso]; + + // The resolve quad must not be depth- or stencil-tested. Vulkan bakes that + // into the final pipeline (CreateFinalPipeline uses a default-constructed + // PipelineDepthStencilStateCreateInfo — all tests disabled), but on Metal + // depth/stencil state lives on the encoder, and DrawModifierVolumes runs + // immediately before this in the same encoder and leaves its TR-modvol + // state bound. Any scene with translucent modifier volumes would then + // stencil-test the full-screen resolve and drop the composite. Bind an + // explicit always/no-write/no-stencil state instead of inheriting. + if (getAlwaysDepthStencilState() != nil) + [encoder setDepthStencilState:resolveDepthStencil]; + + // Same inheritance trap as the depth/stencil state above, and just as + // damaging: DrawModifierVolumes calls SetTileClip per volume, which sets + // the encoder scissor, and the resolve's full-screen triangle would run + // under whatever tile rect the last modvol left behind. Pixels outside it + // are never resolved — and because the resolve is what atomically swaps + // each pixel's a-buffer head back to EOL, those pixels also keep last + // frame's list head, so the next frame chains onto stale entries. Restore + // the base scissor (Vulkan's final pipeline uses a dynamic scissor set to + // the full viewport). + SetScissor(encoder, baseScissor); + [encoder setFragmentBuffer:oitBuffers->getPixelBuffer() offset:0 atIndex:1]; + [encoder setFragmentBuffer:oitBuffers->getAbufferPointer() offset:0 atIndex:2]; + [encoder setFragmentBuffer:curMainBuffer + offset:currentBaseOffset + offsets.polyParamsOffset + atIndex:4]; + // Opaque background: the scratch copy blitted in Draw() after the collect + // encoder. Vulkan reads its equivalent as a resolve-subpass input + // attachment; the Metal port used [[color(0)]] framebuffer fetch, which + // the iOS Simulator cannot create a pipeline for. + if (resolveBackground != nil) + [encoder setFragmentTexture:resolveBackground atIndex:0]; + + const bool applyDither = dithering && finalPass; + MetalOITResolveUniformsCPU resolveUniforms = { + (uint32_t)w, + (uint32_t)h, + (uint32_t)([oitBuffers->getPixelBuffer() length] / 16u), + // The resolve shader multiplies shadowed TR fragments by this value + // directly (srcColor.rgb *= shadeScale), same as Vulkan's resolve + // (oit_shaders.cpp srcColor.rgb *= shade_scale_factor with + // scale_factor/256). Passing 1-s here inverted shadow darkness around + // 0.5. Note drawOpaqueModVols below correctly keeps 1-s: its final + // quad goes through the non-OIT alpha-blend pattern (SrcAlpha / + // OneMinusSrcAlpha), where alpha 1-s nets dst*s. + FPU_SHAD_SCALE.scale_factor / 256.f, + { ditherDivisor[0], ditherDivisor[1], ditherDivisor[2], ditherDivisor[3] }, + applyDither ? 1u : 0u, + }; + [encoder setFragmentBytes:&resolveUniforms length:sizeof(resolveUniforms) atIndex:3]; + [encoder drawPrimitives:MTLPrimitiveTypeTriangle vertexStart:0 vertexCount:3]; +} + +void MetalOITDrawer::drawRegularPoly(id encoder, u32 listType, + bool sortTriangles, const PolyParam &polyIn, + u32 first, u32 count, int area) +{ + if (regularPipelineManager == nullptr || curMainBuffer == nil) + return; + const PolyParam polyArea1 = area == 1 ? area1Params(polyIn) : PolyParam(); + const PolyParam &poly = area == 1 ? polyArea1 : polyIn; + + MTLScissorRect scissorRect {}; + TileClipping tileClip = SetTileClip(encoder, poly.tileclip, scissorRect); + + float trilinearAlpha = 1.0f; + if (poly.tsp.FilterMode > 1 && poly.pcw.Texture + && listType != ListType_Punch_Through && poly.tcw.MipMapped == 1) { + trilinearAlpha = 0.25f * (poly.tsp.MipMapD & 0x3); + if (poly.tsp.FilterMode == 2) + trilinearAlpha = 1.0f - trilinearAlpha; + } + int gpuPalette = poly.texture == nullptr || !((MetalTexture *)poly.texture)->gpuPalette + ? 0 : poly.tsp.FilterMode + 1; + float palette_index = 0.0f; + if (gpuPalette != 0) { + if (config::TextureFiltering == 1) gpuPalette = 1; + else if (config::TextureFiltering == 2) gpuPalette = 2; + if (poly.tcw.PixelFmt == PixelPal4) + palette_index = float(poly.tcw.PalSelect << 4) / 1023.0f; + else + palette_index = float(poly.tcw.PalSelect >> 4 << 8) / 1023.0f; + } + + std::array pushConstants {}; + if (tileClip == TileClipping::Inside || trilinearAlpha != 1.0f || gpuPalette != 0) { + pushConstants = { + (float)scissorRect.x, + (float)scissorRect.y, + (float)scissorRect.x + (float)scissorRect.width, + (float)scissorRect.y + (float)scissorRect.height, + trilinearAlpha, + palette_index, + }; + } else { + pushConstants = { 0, 0, 0, 0, 0, 0 }; + } + [encoder setFragmentBytes:pushConstants.data() + length:sizeof(pushConstants) + MetalBufferPacker::align(sizeof(pushConstants), 16) + atIndex:1]; + + const bool shadowed = listType == ListType_Opaque || listType == ListType_Punch_Through; + + // Dithering is applied once, by the resolve pass (as in Vulkan OIT, where + // only the final shader dithers); dithering here would be applied twice. + auto pso = regularPipelineManager->GetPipeline(listType, sortTriangles, poly, gpuPalette, false, false, area == 1); + if (pso == nil) + return; + [encoder setRenderPipelineState:pso]; + [encoder setDepthStencilState:regularPipelineManager->GetDepthStencilStates( + listType, sortTriangles, shadowed, poly, false, area)]; + [encoder setCullMode:toMetalCullMode(poly.isp.CullMode)]; + if (area != 0) + [encoder setStencilReferenceValue:0x81]; + else if (shadowed) + [encoder setStencilReferenceValue:poly.pcw.Shadow != 0 ? 0x80 : 0]; + + if (poly.texture != nullptr && samplers != nullptr) { + [encoder setFragmentTexture:((MetalTexture *)poly.texture)->GetReadOnlyTexture() atIndex:0]; + id samplerState = + samplers->GetSampler(poly, listType == ListType_Punch_Through); + if (samplerState == nil) + return; + [encoder setFragmentSamplerState:samplerState atIndex:0]; + } else if (poly.pcw.Texture && samplers != nullptr) { + static id defaultTexture = nil; + if (defaultTexture == nil) { + MTLTextureDescriptor *texDesc = [MTLTextureDescriptor + texture2DDescriptorWithPixelFormat:MTLPixelFormatRGBA8Unorm + width:1 height:1 mipmapped:NO]; + defaultTexture = [MetalContext::Instance()->GetDevice() newTextureWithDescriptor:texDesc]; + uint32_t whitePixel = 0xFFFFFFFF; + [defaultTexture replaceRegion:MTLRegionMake2D(0, 0, 1, 1) + mipmapLevel:0 + withBytes:&whitePixel + bytesPerRow:4]; + } + [encoder setFragmentTexture:defaultTexture atIndex:0]; + TSP defaultTsp = {}; + id defaultSampler = samplers->GetSampler(defaultTsp); + if (defaultSampler == nil) + return; + [encoder setFragmentSamplerState:defaultSampler atIndex:0]; + } + + // Naomi2 per-poly vertex uniforms + lights (mirrors MetalDrawer::DrawPoly). + if (poly.pcw.Texture || poly.isNaomi2()) { + u64 offset = 0; + u32 index = 0; + if (poly.isNaomi2()) { + switch (listType) { + case ListType_Opaque: + offset = offsets.naomi2OpaqueOffset; + index = (u32)(&polyIn - &rendContext->global_param_op[0]); + if (index >= rendContext->global_param_op.size()) + return; + break; + case ListType_Punch_Through: + offset = offsets.naomi2PunchThroughOffset; + index = (u32)(&polyIn - &rendContext->global_param_pt[0]); + if (index >= rendContext->global_param_pt.size()) + return; + break; + default: + break; + } + } + + size_t size = sizeof(MetalN2VertexShaderUniforms) + + MetalBufferPacker::align(sizeof(MetalN2VertexShaderUniforms), kConstantBufferAlign); + u64 finalOffset = currentBaseOffset + offset + index * size; + if (finalOffset >= [curMainBuffer length]) + return; + [encoder setVertexBuffer:curMainBuffer offset:finalOffset atIndex:1]; + + if (offsets.lightsOffset != (u64)-1) { + size = sizeof(N2LightModel) + MetalBufferPacker::align(sizeof(N2LightModel), kConstantBufferAlign); + if (poly.lightModel >= 256) + return; + u64 lightsOffset = currentBaseOffset + offsets.lightsOffset + poly.lightModel * size; + if (lightsOffset >= [curMainBuffer length]) + return; + [encoder setVertexBuffer:curMainBuffer offset:lightsOffset atIndex:2]; + } + } + + const u64 indexOffset = currentBaseOffset + offsets.indexOffset + first * sizeof(u32); + if (indexOffset + count * sizeof(u32) > [curMainBuffer length]) + return; + + [encoder setVertexBuffer:curMainBuffer offset:currentBaseOffset atIndex:30]; + + MTLPrimitiveType primitive = sortTriangles && !config::PerStripSorting + ? MTLPrimitiveTypeTriangle + : MTLPrimitiveTypeTriangleStrip; + [encoder drawIndexedPrimitives:primitive + indexCount:count + indexType:MTLIndexTypeUInt32 + indexBuffer:curMainBuffer + indexBufferOffset:indexOffset]; +} + +void MetalOITDrawer::drawOpaqueModVols(id encoder, int first, int count, + const RenderPass &prev, const RenderPass &cur, int w, int h) +{ + if (count <= 0 || rendContext->modtrig.empty() || !config::ModifierVolumes + || regularPipelineManager == nullptr || curMainBuffer == nil) { + // No marks this pass: the two-volume polys still need their first-set draw. + drawTwoVolumePolys(encoder, prev, cur, w, h); + return; + } + + [encoder setVertexBufferOffset:currentBaseOffset + offsets.modVolOffset atIndex:30]; + // Tile clip fields refreshed per volume below (Inside mode = shader discard). + MetalModVolPushBlock mvPush; + mvPush.shaderColor = 1.0f - FPU_SHAD_SCALE.scale_factor / 256.f; + [encoder setFragmentBytes:&mvPush length:sizeof(mvPush) atIndex:1]; + + ModifierVolumeParam *mvParams = &rendContext->global_param_mvo[first]; + int mod_base = -1; + for (int cmv = 0; cmv < count; ++cmv) { + ModifierVolumeParam ¶m = mvParams[cmv]; + if (param.count == 0) continue; + auto bindVolumeUniforms = [&]() { + if (param.isNaomi2()) + [encoder setVertexBuffer:curMainBuffer offset:currentBaseOffset + offsets.naomi2ModVolOffset + + (first + cmv) * (sizeof(MetalN2VertexShaderUniforms) + MetalBufferPacker::align(sizeof(MetalN2VertexShaderUniforms), kConstantBufferAlign)) atIndex:1]; + }; + bindVolumeUniforms(); + const u32 mv_mode = param.isp.DepthMode; + if (mod_base == -1) mod_base = param.first; + ModVolMode pipeMode = (!param.isp.VolumeLast && mv_mode > 0) + ? ModVolMode::Or : ModVolMode::Xor; + auto pso = regularPipelineManager->GetModifierVolumePipeline(pipeMode, param.isNaomi2()); + auto ds = regularPipelineManager->GetModVolDepthStencilStates(pipeMode, param.isNaomi2()); + if (pso == nil) continue; + [encoder setRenderPipelineState:pso]; + [encoder setDepthStencilState:ds]; + [encoder setCullMode:toMetalCullMode(param.isp.CullMode)]; + [encoder setStencilReferenceValue:2]; + MTLScissorRect sr {}; + TileClipping clipMode = SetTileClip(encoder, param.tileclip, sr); + if (mvPush.setTileClip(clipMode, sr)) + [encoder setFragmentBytes:&mvPush length:sizeof(mvPush) atIndex:1]; + [encoder drawPrimitives:MTLPrimitiveTypeTriangle + vertexStart:param.first * 3 + vertexCount:param.count * 3]; + if (mv_mode == 1 || mv_mode == 2) { + ModVolMode sumMode = mv_mode == 1 ? ModVolMode::Inclusion : ModVolMode::Exclusion; + auto sumPso = regularPipelineManager->GetModifierVolumePipeline(sumMode, param.isNaomi2()); + auto sumDs = regularPipelineManager->GetModVolDepthStencilStates(sumMode, param.isNaomi2()); + if (sumPso != nil) { + [encoder setRenderPipelineState:sumPso]; + [encoder setDepthStencilState:sumDs]; + [encoder setCullMode:toMetalCullMode(param.isp.CullMode)]; + [encoder setStencilReferenceValue:1]; + [encoder drawPrimitives:MTLPrimitiveTypeTriangle + vertexStart:mod_base * 3 + vertexCount:(param.first + param.count - mod_base) * 3]; + } + mod_base = -1; + } + } + [encoder setVertexBufferOffset:currentBaseOffset atIndex:30]; + + // Reset the tile clip before the screen-covering Final quad, exactly as + // MetalDrawer::DrawModifierVolumes does (Vulkan calls SetTileClip(0) here). + // The per-volume SetTileClip above leaves the last volume's rect on the + // encoder, and without this the darkening quad is cropped to it — the + // regular drawer already carried this fix; the OIT port did not. + // Two-volume polys read the marks before the Final pass clears them. + drawTwoVolumePolys(encoder, prev, cur, w, h); + + MTLScissorRect fullScissor {}; + SetTileClip(encoder, 0, fullScissor); + if (mvPush.setTileClip(TileClipping::Off, fullScissor)) + [encoder setFragmentBytes:&mvPush length:sizeof(mvPush) atIndex:1]; + + auto finalPso = regularPipelineManager->GetModifierVolumePipeline(ModVolMode::Final, false); + auto finalDs = regularPipelineManager->GetModVolDepthStencilStates(ModVolMode::Final, false); + if (finalPso != nil) { + [encoder setRenderPipelineState:finalPso]; + [encoder setDepthStencilState:finalDs]; + [encoder setCullMode:toMetalCullMode(0)]; + [encoder setStencilReferenceValue:0x81]; + [encoder drawIndexedPrimitives:MTLPrimitiveTypeTriangleStrip + indexCount:4 + indexType:MTLIndexTypeUInt32 + indexBuffer:curMainBuffer + indexBufferOffset:currentBaseOffset + offsets.indexOffset]; + } +} + +void MetalOITDrawer::drawTwoVolumePolys(id encoder, const RenderPass &prev, + const RenderPass &cur, int w, int h) +{ + if (regularPipelineManager == nullptr || curMainBuffer == nil) + return; + bool any = false; + for (u32 i = prev.tr_count; i < cur.tr_count && !any; ++i) + any = isTwoVolumePoly(rendContext->global_param_tr[i]); + for (u32 i = prev.op_count; i < cur.op_count && !any; ++i) + any = isTwoVolumePoly(rendContext->global_param_op[i]); + for (u32 i = prev.pt_count; i < cur.pt_count && !any; ++i) + any = isTwoVolumePoly(rendContext->global_param_pt[i]); + if (!any) + return; + [encoder pushDebugGroup:@"Two-volume polys"]; + // Translucent: both sets, each gated on the stencil, into the A-buffer (autosort) + // or straight to the colour attachment (per-strip). Naomi2 keeps its own vertex + // shader without the second-set selector, so it stays first-set only. + const bool collect = cur.autosort; + if (collect) + bindOitCollectBuffers(encoder, w, h); + for (u32 i = prev.tr_count; i < cur.tr_count; ++i) { + const PolyParam &pp = rendContext->global_param_tr[i]; + if (pp.count <= 2 || !isTwoVolumePoly(pp)) + continue; + DrawPoly(encoder, ListType_Translucent, cur.autosort, pp, pp.first, pp.count, collect, false, false, 2); + if (!pp.isNaomi2()) + DrawPoly(encoder, ListType_Translucent, cur.autosort, pp, pp.first, pp.count, collect, false, false, 1); + } + // Opaque / punch-through: the first set is already on screen; repaint the second + // set inside the marks (and clear those marks so the Final pass skips them). + for (u32 i = prev.op_count; i < cur.op_count; ++i) { + const PolyParam &pp = rendContext->global_param_op[i]; + if (pp.count > 2 && isTwoVolumePoly(pp) && !pp.isNaomi2()) + drawRegularPoly(encoder, ListType_Opaque, false, pp, pp.first, pp.count, 1); + } + for (u32 i = prev.pt_count; i < cur.pt_count; ++i) { + const PolyParam &pp = rendContext->global_param_pt[i]; + if (pp.count > 2 && isTwoVolumePoly(pp) && !pp.isNaomi2()) + drawRegularPoly(encoder, ListType_Punch_Through, false, pp, pp.first, pp.count, 1); + } + [encoder popDebugGroup]; +} + +void MetalOITDrawer::drawTranslucentDepthOnly(id encoder, + bool autosort, u32 first, u32 last) +{ + if (first == last) + return; + const PolyParam *pp_end = rendContext->global_param_tr.data() + last; + for (const PolyParam *pp = &rendContext->global_param_tr[first]; pp != pp_end; ++pp) { + if (pp->count <= 2) + continue; + DrawPoly(encoder, ListType_Translucent, autosort, *pp, pp->first, pp->count, + false, true); + } +} + +void MetalOITDrawer::MakeBuffers(int width, int height) +{ + // The per-pixel OIT storage is shared by the screen and RTT drawers, so + // grow it even when this drawer's own attachments are already big enough + // (Vulkan OITDrawer::MakeBuffers does the same). No-op unless it grows. + if (oitBuffers != nullptr) + oitBuffers->Init(width, height); + + if (width <= maxWidth && height <= maxHeight) + return; + id device = MetalContext::Instance()->GetDevice(); + if (device == nil) { + WARN_LOG(RENDERER, "MetalOITDrawer::MakeBuffers: no Metal device"); + return; + } + + if (!makeAttachments(device, width, height)) + return; + + // Scratch background for the resolve pass. Same format/size as the color + // attachments; it only ever receives a blit and is sampled by + // oit_resolve_fragment, so ShaderRead is the only usage it needs. + MTLTextureDescriptor *bgDesc = + [MTLTextureDescriptor texture2DDescriptorWithPixelFormat:MTLPixelFormatBGRA8Unorm + width:width + height:height + mipmapped:NO]; + bgDesc.usage = MTLTextureUsageShaderRead; + bgDesc.storageMode = MTLStorageModePrivate; + resolveBackground = [device newTextureWithDescriptor:bgDesc]; + resolveBackground.label = @"OIT resolve background"; + + maxWidth = width; + maxHeight = height; +} + +// ----- MetalOITDrawer: main buffer upload --------------------------------- + +void MetalOITDrawer::UploadMainBuffer(const MetalVertexShaderUniforms &vertexUniforms, + const MetalFragmentShaderUniforms &fragmentUniforms) +{ + MetalBufferPacker packer; + // Vertex data (same buffer layout the regular MetalDrawer uses; + // bound at vertex buffer index 30 via the OIT collect pipeline's + // vertex descriptor in metal_oit_pipeline.h). + packer.add(rendContext->verts.data(), + rendContext->verts.size() * sizeof(decltype(*rendContext->verts.data()))); + offsets.modVolOffset = packer.add(rendContext->modtrig.data(), + rendContext->modtrig.size() * sizeof(decltype(*rendContext->modtrig.data()))); + offsets.indexOffset = packer.add(rendContext->idx.data(), + rendContext->idx.size() * sizeof(decltype(*rendContext->idx.data()))); + offsets.vertexUniformOffset = packer.addUniform(&vertexUniforms, sizeof(vertexUniforms)); + offsets.fragmentUniformOffset = packer.addUniform(&fragmentUniforms, sizeof(fragmentUniforms)); + + std::vector trPolyParams; + if (rendContext->global_param_tr.empty()) + trPolyParams.push_back(0); + else { + trPolyParams.resize(rendContext->global_param_tr.size() * 2); + size_t i = 0; + for (const PolyParam &pp : rendContext->global_param_tr) { + trPolyParams[i++] = (pp.tsp.full & 0xffff00c0) | ((pp.isp.full >> 16) & 0xe400) | ((pp.pcw.full >> 7) & 1); + trPolyParams[i++] = pp.tsp1.full; + } + } + offsets.polyParamsSize = trPolyParams.size() * sizeof(u32); + offsets.polyParamsOffset = packer.addStorage(trPolyParams.data(), offsets.polyParamsSize); + + // Naomi2 per-poly vertex uniforms + lights. + // specialises the vertex shader on pp.isNaomi2() (metal_oit_pipeline.h: + // 210/233) exactly like the regular MetalPipelineManager, so the + // naomi2 vertex shader expects MetalN2VertexShaderUniforms at vertex + // buffer index 1 and N2LightModel at index 2. Pack them here (mirrors + // MetalDrawer::UploadMainBuffer metal_drawer.mm:466-471); DrawPoly + // binds them per-poly. Without this, Naomi2 translucent geometry under + // OIT renders with stale/default model matrices. + // + // trModVolIncluded=true: unlike the regular drawer, the OIT path runs + // TR modvols through this drawer (DrawModifierVolumes uses + // rendContext->global_param_mvo_tr) so the packer must reserve their N2 slots + // for naomi2TrModVolOffset to be valid. + std::vector n2uniforms; + if (settings.platform.isNaomi2()) + { + packNaomi2Uniforms(packer, offsets, n2uniforms, /*trModVolIncluded*/ true); + offsets.lightsOffset = packNaomi2Lights(packer); + } + + // Each upload stays exclusive until the command pool retires its GPU work. + verify(packer.size() <= std::numeric_limits::max()); + MetalBufferData *upload = GetMainBuffer((u32)packer.size()); + verify(upload->buffer != nil); + packer.upload(*upload); + currentBaseOffset = 0; + curMainBuffer = upload->buffer; +} + +// ----- MetalOITDrawer: per-poly orchestration ----------------------------- +// +// These are real implementations, not stubs -- per-poly texture/sampler +// binding, Naomi2 uniforms and the polyNumber constant are all wired, and +// UploadMainBuffer above packs the vertex/index/uniform/tr_poly_params data +// they index into. + +void MetalOITDrawer::DrawModifierVolumes(__strong id &encoder, + MTLRenderPassDescriptor *passDesc, + const std::function)> &setupEncoder, + int first, int count, bool useSharedMvo) +{ + if (count == 0 || rendContext->modtrig.empty() || !config::ModifierVolumes) + return; + if (pipelineManager == nullptr || curMainBuffer == nil || oitBuffers == nullptr) + return; + [encoder pushDebugGroup:@"OIT TR ModVols"]; + + MetalOITResolveUniformsCPU modVolUniforms = { + (uint32_t)viewport.width, + (uint32_t)viewport.height, + (uint32_t)([oitBuffers->getPixelBuffer() length] / 16u), + 0.f, + { 0.f, 0.f, 0.f, 1.f }, + 0u, + }; + // Per-volume tile clip for oit_tr_modvol_fragment (Inside mode = shader skip). + MetalModVolPushBlock trClip; + auto bindModVolState = [&]() { + [encoder setVertexBufferOffset:currentBaseOffset + offsets.modVolOffset atIndex:30]; + id trModVolDs = pipelineManager->GetTrModVolDepthStencilState(); + if (trModVolDs != nil) + [encoder setDepthStencilState:trModVolDs]; + [encoder setFragmentBuffer:oitBuffers->getPixelBuffer() offset:0 atIndex:1]; + [encoder setFragmentBuffer:oitBuffers->getAbufferPointer() offset:0 atIndex:2]; + [encoder setFragmentBytes:&modVolUniforms length:sizeof(modVolUniforms) atIndex:3]; + [encoder setFragmentBytes:&trClip length:sizeof(trClip) atIndex:5]; + [encoder setFragmentBuffer:curMainBuffer + offset:currentBaseOffset + offsets.polyParamsOffset + atIndex:4]; + }; + bindModVolState(); + + // Order a volume's marks before its sum, and the sum before the next + // volume and the resolve: Vulkan's two by-region fragment->fragment + // barriers. See MetalOITFragmentOrdering. + const MetalOITFragmentOrdering ordering = pipelineManager->FragmentOrdering(); + auto orderFragments = [&](u32 tileclip) { + switch (ordering) { + case MetalOITFragmentOrdering::RasterOrderGroups: + break; // the shaders' a-buffer accesses are in raster order group 0 + case MetalOITFragmentOrdering::MemoryBarrier: +#if TARGET_OS_OSX + [encoder memoryBarrierWithScope:MTLBarrierScopeBuffers + afterStages:MTLRenderStageFragment + beforeStages:MTLRenderStageFragment]; +#endif + break; + case MetalOITFragmentOrdering::EncoderSplit: + { + [encoder popDebugGroup]; + [encoder popDebugGroup]; + [encoder endEncoding]; + encoder = [currentCommandBuffer renderCommandEncoderWithDescriptor:passDesc]; + [encoder pushDebugGroup:@"OIT Resolve Pass"]; + setupEncoder(encoder); + [encoder pushDebugGroup:@"OIT TR ModVols"]; + bindModVolState(); + // A new encoder starts with a full-target scissor: drop the cached + // one so SetTileClip sets the volume's rect again. + currentScissor = MTLScissorRect {}; + MTLScissorRect scissorRect {}; + SetTileClip(encoder, tileclip, scissorRect); + break; + } + } + }; + + ModifierVolumeParam *params = useSharedMvo + ? &rendContext->global_param_mvo[first] + : &rendContext->global_param_mvo_tr[first]; + int mod_base = -1; + for (int cmv = 0; cmv < count; ++cmv) { + ModifierVolumeParam ¶m = params[cmv]; + if (param.count == 0) + continue; + auto bindVolumeUniforms = [&]() { + if (param.isNaomi2()) + [encoder setVertexBuffer:curMainBuffer offset:currentBaseOffset + (useSharedMvo ? offsets.naomi2ModVolOffset : offsets.naomi2TrModVolOffset) + + (first + cmv) * (sizeof(MetalN2VertexShaderUniforms) + MetalBufferPacker::align(sizeof(MetalN2VertexShaderUniforms), kConstantBufferAlign)) atIndex:1]; + }; + bindVolumeUniforms(); + const u32 mv_mode = param.isp.DepthMode; + if (mod_base == -1) + mod_base = param.first; + + ModVolMode pipeMode = (!param.isp.VolumeLast && mv_mode > 0) + ? ModVolMode::Or : ModVolMode::Xor; + auto pso = pipelineManager->GetTrModVolPipeline(pipeMode, + param.isp.CullMode, + param.isNaomi2()); + if (pso == nil) + continue; + [encoder setRenderPipelineState:pso]; + [encoder setCullMode:toMetalCullMode(param.isp.CullMode)]; + MTLScissorRect scissorRect {}; + TileClipping clipMode = SetTileClip(encoder, param.tileclip, scissorRect); + if (trClip.setTileClip(clipMode, scissorRect)) + [encoder setFragmentBytes:&trClip length:sizeof(trClip) atIndex:5]; + [encoder drawPrimitives:MTLPrimitiveTypeTriangle + vertexStart:param.first * 3 + vertexCount:param.count * 3]; + + if (mv_mode == 1 || mv_mode == 2) { + orderFragments(param.tileclip); + bindVolumeUniforms(); + + ModVolMode sumMode = (mv_mode == 1) ? ModVolMode::Inclusion + : ModVolMode::Exclusion; + auto sumPso = pipelineManager->GetTrModVolPipeline(sumMode, + param.isp.CullMode, + param.isNaomi2()); + if (sumPso != nil) { + [encoder setRenderPipelineState:sumPso]; + [encoder setCullMode:toMetalCullMode(param.isp.CullMode)]; + [encoder drawPrimitives:MTLPrimitiveTypeTriangle + vertexStart:mod_base * 3 + vertexCount:(param.first + param.count - mod_base) * 3]; + } + mod_base = -1; + + orderFragments(param.tileclip); + bindVolumeUniforms(); + } + } + + [encoder setVertexBufferOffset:currentBaseOffset atIndex:30]; + [encoder popDebugGroup]; +} + +void MetalOITDrawer::DrawSorted(id encoder, + const std::vector& polys, + u32 first, u32 last) +{ + if (first == last) + return; + [encoder pushDebugGroup:@"OIT DrawSorted"]; + for (u32 idx = first; idx < last; ++idx) { + const SortedTriangle &t = polys[idx]; + DrawPoly(encoder, ListType_Translucent, /*sortTriangles*/ true, + rendContext->global_param_tr[t.polyIndex], t.first, t.count, + /*oitCollect*/ true, /*depthOnly*/ false, /*triangleList*/ true); + } + [encoder popDebugGroup]; +} + +void MetalOITDrawer::DrawList(id encoder, u32 listType, + bool sortTriangles, const std::vector& polys, + u32 first, u32 last, bool oitCollect) +{ + if (first == last) + return; + [encoder pushDebugGroup:@"OIT DrawList"]; + const PolyParam *pp_end = polys.data() + last; + for (const PolyParam *pp = &polys[first]; pp != pp_end; pp++) { + // Two-volume translucent polys were drawn by drawTwoVolumePolys. + if (pp->count > 2 && !(listType == ListType_Translucent && isTwoVolumePoly(*pp))) + DrawPoly(encoder, listType, sortTriangles, *pp, pp->first, pp->count, oitCollect); + } + [encoder popDebugGroup]; +} + +void MetalOITDrawer::DrawPoly(id encoder, u32 listType, + bool sortTriangles, const PolyParam& polyIn, + u32 first, u32 count, bool oitCollect, bool depthOnly, + bool triangleList, int area) +{ + const PolyParam polyArea1 = area == 1 ? area1Params(polyIn) : PolyParam(); + const PolyParam &poly = area == 1 ? polyArea1 : polyIn; + if (pipelineManager == nullptr) + return; + if (depthOnly) { + if (regularPipelineManager == nullptr) + return; + } else if (oitCollect) { + // collect path + } else if (regularPipelineManager == nullptr) { + return; + } + + // ---- 1. Scissor / tile clip ---- + MTLScissorRect scissorRect {}; + TileClipping tileClip = SetTileClip(encoder, poly.tileclip, scissorRect); + + // ---- 2. Trilinear alpha + GPU palette ---- + float trilinearAlpha = 1.0f; + if (poly.tsp.FilterMode > 1 && poly.pcw.Texture + && listType != ListType_Punch_Through && poly.tcw.MipMapped == 1) { + trilinearAlpha = 0.25f * (poly.tsp.MipMapD & 0x3); + if (poly.tsp.FilterMode == 2) + trilinearAlpha = 1.0f - trilinearAlpha; + } + int gpuPalette = poly.texture == nullptr || !((MetalTexture *)poly.texture)->gpuPalette + ? 0 : poly.tsp.FilterMode + 1; + float palette_index = 0.0f; + if (gpuPalette != 0) { + if (config::TextureFiltering == 1) gpuPalette = 1; + else if (config::TextureFiltering == 2) gpuPalette = 2; + if (poly.tcw.PixelFmt == PixelPal4) + palette_index = float(poly.tcw.PalSelect << 4) / 1023.0f; + else + palette_index = float(poly.tcw.PalSelect >> 4 << 8) / 1023.0f; + } + + // ---- 3. PushBlock at fragment buffer 1 ---- + std::array pushConstants {}; + if (tileClip == TileClipping::Inside || trilinearAlpha != 1.0f || gpuPalette != 0) { + pushConstants = { + (float)scissorRect.x, + (float)scissorRect.y, + (float)scissorRect.x + (float)scissorRect.width, + (float)scissorRect.y + (float)scissorRect.height, + trilinearAlpha, + palette_index, + }; + } else { + pushConstants = { 0, 0, 0, 0, 0, 0 }; + } + [encoder setFragmentBytes:pushConstants.data() + length:sizeof(pushConstants) + MetalBufferPacker::align(sizeof(pushConstants), 16) + atIndex:1]; + + // ---- 4. Pipeline state ---- + + id pso = nil; + if (depthOnly) { + pso = pipelineManager->GetTranslucentDepthPipeline(listType, sortTriangles, + poly, gpuPalette, false); + } else if (oitCollect) { + pso = pipelineManager->GetCollectPipeline(listType, sortTriangles, + poly, gpuPalette, false, area); + } else { + pso = regularPipelineManager->GetPipeline(listType, sortTriangles, + poly, gpuPalette, false, false, area == 1); + } + if (pso == nil) + return; + [encoder setRenderPipelineState:pso]; + [encoder setCullMode:toMetalCullMode(poly.isp.CullMode)]; + + if (oitCollect && !depthOnly && area != 0) { + // fs_main_early: stencil area test before the a-buffer append. + id ds = pipelineManager->GetTwoVolumeCollectDepthStencilState(area); + if (ds == nil) + return; + [encoder setDepthStencilState:ds]; + [encoder setStencilReferenceValue:0x81]; + } else if (regularPipelineManager != nullptr) { + [encoder setDepthStencilState:regularPipelineManager->GetDepthStencilStates( + listType, sortTriangles, false, poly, false, area)]; + if (area != 0) + [encoder setStencilReferenceValue:0x81]; + } + + + // ---- 5. Texture + sampler binding ---- + if (poly.texture != nullptr && samplers != nullptr) { + auto texture = ((MetalTexture *)poly.texture)->GetReadOnlyTexture(); + [encoder setFragmentTexture:texture atIndex:0]; + id samplerState = + samplers->GetSampler(poly, listType == ListType_Punch_Through); + if (samplerState != nil) + [encoder setFragmentSamplerState:samplerState atIndex:0]; + } + + // ---- 5b. Naomi2 per-poly vertex uniforms + lights ---- + // + // Mirrors MetalDrawer::DrawPoly (metal_drawer.mm:241-303). The collect + // pipeline's naomi2-specialised vertex shader reads the per-poly model + // matrices from vertex buffer index 1 and the light model from index 2. + // Same guard condition (poly.pcw.Texture || poly.isNaomi2()) keeps this + // harmless for textured non-naomi2 polys. Only ListType_Translucent + // flows through the OIT collect DrawPoly, but the switch is kept + // complete for parity / future RTT-OIT reuse. Bounds checks ported + // verbatim — an out-of-range offset returns early rather than binding + // garbage (matches the regular drawer's defensive posture). + if (poly.pcw.Texture || poly.isNaomi2()) + { + u64 offset = 0; + u32 index = 0; + if (poly.isNaomi2()) + { + switch (listType) + { + case ListType_Opaque: + offset = offsets.naomi2OpaqueOffset; + index = (u32)(&polyIn - &rendContext->global_param_op[0]); + if (index >= rendContext->global_param_op.size()) + return; + break; + case ListType_Punch_Through: + offset = offsets.naomi2PunchThroughOffset; + index = (u32)(&polyIn - &rendContext->global_param_pt[0]); + if (index >= rendContext->global_param_pt.size()) + return; + break; + case ListType_Translucent: + offset = offsets.naomi2TranslucentOffset; + index = (u32)(&polyIn - &rendContext->global_param_tr[0]); + if (index >= rendContext->global_param_tr.size()) + return; + break; + default: + break; + } + } + + size_t size = sizeof(MetalN2VertexShaderUniforms) + + MetalBufferPacker::align(sizeof(MetalN2VertexShaderUniforms), kConstantBufferAlign); + u64 finalOffset = currentBaseOffset + offset + index * size; + if (finalOffset >= [curMainBuffer length]) + return; + [encoder setVertexBuffer:curMainBuffer offset:finalOffset atIndex:1]; + + if (offsets.lightsOffset != (u64)-1) + { + size = sizeof(N2LightModel) + MetalBufferPacker::align(sizeof(N2LightModel), kConstantBufferAlign); + if (poly.lightModel >= 256) + return; + u64 lightsOffset = currentBaseOffset + offsets.lightsOffset + poly.lightModel * size; + if (lightsOffset >= [curMainBuffer length]) + return; + [encoder setVertexBuffer:curMainBuffer offset:lightsOffset atIndex:2]; + } + } + + // ---- 6. Draw ---- + // + // curMainBuffer is populated by MetalOITDrawer::UploadMainBuffer, which + // Draw() calls before the collect pass. This guard is a safety net for the + // pre-upload window, not the dormant state an older comment here claimed: + // it stopped being nullptr when UploadMainBuffer landed. + if (curMainBuffer == nil) + return; + + // polyNumber MUST be bound after the Naomi2 block above, not before it. + // Both want vertex buffer index 1, and that block rebinds index 1 whenever + // `poly.pcw.Texture || poly.isNaomi2()` — so for a textured non-Naomi2 + // translucent poly (most of the Dreamcast BIOS menu) it clobbered the + // constant with the packed vertex data. The collect vertex shader then + // computed vtx_index from garbage, and the resolve's + // getPolyNumber(pixel) indexed the wrong entry in tr_poly_params, giving + // correct geometry with wrong/black shading. Vulkan has no such conflict: + // polyNumber is a push constant, not a bound buffer (oit_drawer.cpp:92). + if (oitCollect && listType == ListType_Translucent && !poly.isNaomi2()) { + int polyNumber = 0; + if (!rendContext->global_param_tr.empty()) { + const u32 firstVertexIdx = rendContext->idx[rendContext->global_param_tr[0].first]; + // polyIn, not poly: for a two-volume area-1 draw `poly` is a stack + // copy (area1Params), and its address gave the resolve a garbage + // tr_poly_params index for every second-set fragment. + polyNumber = (int)((&polyIn - &rendContext->global_param_tr[0]) << 17) - (int)firstVertexIdx; + } + [encoder setVertexBytes:&polyNumber length:sizeof(polyNumber) atIndex:1]; + } + + // Strips unless the caller is walking rendContext->sortedTriangles, whose indices + // are an unstripped triangle list. The old rule keyed off + // `sortTriangles && !PerStripSorting`, but every OIT translucent draw sets + // sortTriangles=true with PerStripSorting off while indexing the strip data + // makeIndex() built for global_param_tr — so it told Metal to read strip + // indices as independent triangles. + MTLPrimitiveType primitive = triangleList ? MTLPrimitiveTypeTriangle + : MTLPrimitiveTypeTriangleStrip; + [encoder drawIndexedPrimitives:primitive + indexCount:count + indexType:MTLIndexTypeUInt32 + indexBuffer:curMainBuffer + indexBufferOffset:currentBaseOffset + offsets.indexOffset + first * sizeof(u32)]; +} + +// ----- MetalOITScreenDrawer ----------------------------------------------- + +id MetalOITScreenDrawer::NewFrame() +{ + if (frameStarted) + return currentCommandBuffer; + if (commandPool == nullptr) { + WARN_LOG(RENDERER, "MetalOITScreenDrawer::NewFrame: no command pool"); + return nil; + } + // The regular Metal drawer lazily allocates the command + // buffer when the first draw call lands in BeginRenderPass. For OIT + // the lifecycle is inverted: Draw() owns the command buffer end-to- + // end (allocate -> blit -> two encoders -> hand back), so NewFrame + // is just the "ready for a frame" toggle. + frameStarted = true; + frameRendered = false; + return currentCommandBuffer; +} + +void MetalOITScreenDrawer::EndFrame() +{ + if (!frameStarted) + return; + frameStarted = false; + if (currentCommandBuffer != nil) { + if (emulateFramebuffer) { + // Present() shows the frame from VRAM (presentFramebuffer), so + // copy the slot just rendered back there. Appends its blits to + // this frame's command buffer, then commits and waits. + // Vulkan: OITScreenDrawer::EndFrame. + scaleAndWriteFramebuffer(colorAttachment); + } else { + // Hand the command buffer to the pool — it commits it as part of + // EndFrame and rotates the ring index. Mirrors what MetalScreen + // Drawer::EndRenderPass does after [encoder endEncoding]. + commandPool->EndFrame(); + aspectRatio = getOutputFramebufferAspectRatio(); + } + frameRendered = true; + } + currentCommandBuffer = nil; +} + +bool MetalOITScreenDrawer::makeAttachments(id device, int width, int height) +{ + // BGRA8Unorm matches the swapchain format MetalContext presents and the + // color format baked into the OIT pipeline states (metal_oit_pipeline.h). + MTLTextureDescriptor *colorDesc = + [MTLTextureDescriptor texture2DDescriptorWithPixelFormat:MTLPixelFormatBGRA8Unorm + width:width + height:height + mipmapped:NO]; + colorDesc.usage = MTLTextureUsageRenderTarget | MTLTextureUsageShaderRead; + colorDesc.storageMode = MTLStorageModePrivate; + + // Depth32Float_Stencil8 matches the pipeline's depth/stencil pixel formats. + MTLTextureDescriptor *depthDesc = + [MTLTextureDescriptor texture2DDescriptorWithPixelFormat:MTLPixelFormatDepth32Float_Stencil8 + width:width + height:height + mipmapped:NO]; + depthDesc.usage = MTLTextureUsageRenderTarget; + depthDesc.storageMode = MTLStorageModePrivate; + + colorAttachment = [device newTextureWithDescriptor:colorDesc]; + colorAttachment.label = @"OIT color"; + depthAttachment = [device newTextureWithDescriptor:depthDesc]; + depthAttachment.label = @"OIT depth"; + clearNeeded = true; + + return colorAttachment != nil && depthAttachment != nil; +} + +MTLRenderPassDescriptor *MetalOITScreenDrawer::getOitRenderPassDescriptor( + int renderPassIndex, int renderPassCount, bool initialPass) +{ + (void)renderPassIndex; + (void)renderPassCount; + if (colorAttachment == nil || depthAttachment == nil) + return nil; + if (passDescriptor == nil) + passDescriptor = [MTLRenderPassDescriptor renderPassDescriptor]; + MTLRenderPassDescriptor *desc = passDescriptor; + + desc.colorAttachments[0].texture = colorAttachment; + desc.colorAttachments[0].loadAction = initialPass && (clearNeeded || rendContext->clearFramebuffer) ? MTLLoadActionClear : MTLLoadActionLoad; + desc.colorAttachments[0].storeAction = MTLStoreActionStore; + desc.colorAttachments[0].clearColor = MTLClearColorMake(0.0, 0.0, 0.0, 1.0); + + desc.depthAttachment.texture = depthAttachment; + desc.depthAttachment.loadAction = initialPass ? MTLLoadActionClear : MTLLoadActionLoad; + desc.depthAttachment.storeAction = MTLStoreActionStore; + // Reversed log depth: 0.0 = farthest. Vulkan OIT clears to 0 + // (oit_drawer.cpp ClearDepthStencilValue{0,0}); 1.0 (= nearest) makes + // every Greater/GEqual test fail on pixels the background doesn't cover. + desc.depthAttachment.clearDepth = 0.0; + + desc.stencilAttachment.texture = depthAttachment; + desc.stencilAttachment.loadAction = initialPass ? MTLLoadActionClear : MTLLoadActionLoad; + desc.stencilAttachment.storeAction = MTLStoreActionStore; + desc.stencilAttachment.clearStencil = 0; + + clearNeeded = false; + return desc; +} + +bool MetalOITScreenDrawer::PresentFrame() +{ + EndFrame(); + if (!frameRendered) + return false; + frameRendered = false; + if (colorAttachment == nil) + return false; + MetalContext::Instance()->PresentFrame(colorAttachment, viewport, aspectRatio); + return true; +} + +// ----- MetalOITTextureDrawer ---------------------------------------------- + +id MetalOITTextureDrawer::NewFrame() +{ + DEBUG_LOG(RENDERER, "OIT RTT packmode=%d stride=%d - %d x %d @ %06x", + rendContext->fb_W_CTRL.fb_packmode, rendContext->fb_W_LINESTRIDE * 8, + rendContext->fbClip.size.x, rendContext->fbClip.size.y, rendContext->fb_W_SOF1 & VRAM_MASK); + + textureAddr = rendContext->fb_W_SOF1 & VRAM_MASK; + // Since 31d5ddb92: render target = framebufferWidth/Height computed in + // Renderer_if (see MetalTextureDrawer::BeginRenderPass). Mirrors Vulkan + // OITTextureDrawer::NewFrame. + u32 width = rendContext->framebufferWidth; + u32 height = rendContext->framebufferHeight; + + if (width == 0 || height == 0 || width > 16384 || height > 16384) { + ERROR_LOG(RENDERER, "OIT RTT invalid dimensions: %ux%u", width, height); + width = std::max(8u, std::min(width, 1024u)); + height = std::max(8u, std::min(height, 1024u)); + } + matrices.CalcMatrices(rendContext, width, height); + // Texture-cache key: the unscaled pow2 PVR framebuffer size. + int wpo2, hpo2; + getPvrFramebufferSize(*rendContext, wpo2, hpo2); + + id device = MetalContext::Instance()->GetDevice(); + if (device == nil) + return nil; + + if (commandPool != nullptr && currentCommandBuffer == nil) + currentCommandBuffer = commandPool->Allocate(); + + if (!rttDepthAttachment || width > rttDepthAttachment.width + || height > rttDepthAttachment.height) + { + MTLTextureDescriptor *depthDescriptor = [[MTLTextureDescriptor alloc] init]; + depthDescriptor.width = width; + depthDescriptor.height = height; + depthDescriptor.pixelFormat = MTLPixelFormatDepth32Float_Stencil8; + depthDescriptor.usage = MTLTextureUsageRenderTarget; + depthDescriptor.storageMode = MTLStorageModePrivate; + rttDepthAttachment = [device newTextureWithDescriptor:depthDescriptor]; + [rttDepthAttachment setLabel:@"OIT RTT Depth"]; + } + + if (config::RenderToTextureBuffer) + { + texture = textureCache->getRTTexture(textureAddr, rendContext->fb_W_CTRL.fb_packmode, + wpo2, hpo2); + if (textureCache->IsInFlight(texture, false)) { + texture->CreateReadOnlyCopy(currentCommandBuffer); + texture->deferDeleteResource(commandPool); + } + textureCache->SetInFlight(texture); + + const bool needsRecreation = texture->GetTexture() == nil + || texture->GetTexture().width != width + || texture->GetTexture().height != height + || !(texture->GetTexture().usage & MTLTextureUsageRenderTarget); + if (needsRecreation) { + MTLTextureDescriptor *colorDescriptor = [[MTLTextureDescriptor alloc] init]; + colorDescriptor.width = width; + colorDescriptor.height = height; + colorDescriptor.pixelFormat = MTLPixelFormatBGRA8Unorm; + colorDescriptor.usage = MTLTextureUsageRenderTarget | MTLTextureUsageShaderRead; + colorDescriptor.storageMode = metalCpuTextureStorageMode(MetalContext::Instance()->GetDevice()); + id newTexture = [device newTextureWithDescriptor:colorDescriptor]; + [newTexture setLabel:@"OIT RTT Color"]; + texture->SetTexture(newTexture, width, height); + } + rttColorImage = texture->GetTexture(); + } + else + { + texture = textureCache->getRTTexture(textureAddr, rendContext->fb_W_CTRL.fb_packmode, + wpo2, hpo2); + if (textureCache->IsInFlight(texture, false)) { + texture->CreateReadOnlyCopy(currentCommandBuffer); + texture->deferDeleteResource(commandPool); + } + textureCache->SetInFlight(texture); + + // Default (no VRAM readback): render directly into the texture-cache + // texture the game will sample, like Vulkan's OIT RTT. This branch + // used to fetch the cache texture, mark it in-flight — and then + // render into a private scratch attachment nothing ever read, so the + // decal sampled the texture object's stale contents (THPS2 blob + // shadow showed the font atlas). + const bool needsRecreation = texture->GetTexture() == nil + || texture->GetTexture().width != width + || texture->GetTexture().height != height + || !(texture->GetTexture().usage & MTLTextureUsageRenderTarget); + if (needsRecreation) { + MTLTextureDescriptor *colorDescriptor = [[MTLTextureDescriptor alloc] init]; + colorDescriptor.width = width; + colorDescriptor.height = height; + colorDescriptor.pixelFormat = MTLPixelFormatBGRA8Unorm; + colorDescriptor.usage = MTLTextureUsageRenderTarget | MTLTextureUsageShaderRead; + colorDescriptor.storageMode = metalCpuTextureStorageMode(MetalContext::Instance()->GetDevice()); + id newTexture = [device newTextureWithDescriptor:colorDescriptor]; + [newTexture setLabel:@"OIT RTT Color"]; + texture->SetTexture(newTexture, width, height); + } + rttColorImage = texture->GetTexture(); + } + + viewport.originX = 0.0; + viewport.originY = 0.0; + viewport.width = (double)width; + viewport.height = (double)height; + viewport.znear = 0.0; + viewport.zfar = 1.0; + + MakeBuffers((int)width, (int)height); + + // Base scissor from TransformMatrix::getBaseScissor(), clamped to the target. + SetBaseScissor(viewport); + + return currentCommandBuffer; +} + +void MetalOITTextureDrawer::EndFrame() +{ + if (currentCommandBuffer == nil) + return; + + // Whole (scaler-adjusted) framebuffer; WriteTextureToVRam applies fbClip. + u32 fbw = rendContext->framebufferWidth; + u32 fbh = rendContext->framebufferHeight; + + if (config::RenderToTextureBuffer) + { + metalSynchronizeTextureForCpu(currentCommandBuffer, rttColorImage); + commandPool->EndFrameAndWait(); + + id srcTexture = texture ? texture->GetTexture() : rttColorImage; + if (srcTexture != nil) { + fbw = std::min(fbw, (u32)srcTexture.width); + fbh = std::min(fbh, (u32)srcTexture.height); + rttReadback.init(fbw, fbh); + [srcTexture getBytes:rttReadback.data() + bytesPerRow:fbw * 4 + fromRegion:MTLRegionMake2D(0, 0, fbw, fbh) + mipmapLevel:0]; + u16 *dst = (u16 *)&vram[textureAddr]; + // Metal render targets are BGRA8; WriteTextureToVRam packs from RGBA byte order + // (what the Vulkan/GL readbacks hand it). Without the swap red and blue trade + // places in VRAM — a tint for ordinary RTT, but fatal for games that re-read the + // 565 target as 4444, where the alpha nibble IS red's top bits (THPS2's skater + // shadow: cyan background 08ffff -> 0x0FFF -> alpha 0; swapped -> 0xFFE1 -> + // opaque yellow, the whole floor darkened and no blob). + { + u8 *px = (u8 *)rttReadback.data(); + for (u32 i = 0, n = fbw * fbh; i < n; i++, px += 4) + std::swap(px[0], px[2]); + } + WriteTextureToVRam(fbw, fbh, (u8 *)rttReadback.data(), dst, + rendContext->fb_W_CTRL, rendContext->fb_W_LINESTRIDE * 8, rendContext->fbClip); + } + } + else + { + commandPool->EndFrame(); + if (texture != nullptr) { + texture->dirty = 0; + texture->unprotectVRam(); + } + } + + currentCommandBuffer = nil; + rttColorImage = nil; +} + +MTLRenderPassDescriptor *MetalOITTextureDrawer::getOitRenderPassDescriptor( + int renderPassIndex, int renderPassCount, bool initialPass) +{ + if (rttColorImage == nil) + return nil; + + // Every pass renders straight into the RTT target; non-initial passes + // load the previous pass's composite, and the resolve reads the + // attachment in place via framebuffer fetch. The old scheme bounced + // intermediate passes between ping-pong attachments so the resolve could + // sample a "background" — but for the common single-pass RTT frame that + // sibling was never written, so any TR-covered pixel composited over + // black. + (void)renderPassIndex; + (void)renderPassCount; + MTLRenderPassDescriptor *desc = rttPassDescriptor; + desc.colorAttachments[0].texture = rttColorImage; + desc.colorAttachments[0].loadAction = initialPass ? MTLLoadActionClear : MTLLoadActionLoad; + desc.colorAttachments[0].storeAction = MTLStoreActionStore; + desc.colorAttachments[0].clearColor = MTLClearColorMake(0.0, 0.0, 0.0, 1.0); + + desc.depthAttachment.texture = rttDepthAttachment; + desc.depthAttachment.loadAction = initialPass ? MTLLoadActionClear : MTLLoadActionLoad; + desc.depthAttachment.storeAction = MTLStoreActionStore; + desc.depthAttachment.clearDepth = 0.0; + + desc.stencilAttachment.texture = rttDepthAttachment; + desc.stencilAttachment.loadAction = initialPass ? MTLLoadActionClear : MTLLoadActionLoad; + desc.stencilAttachment.storeAction = MTLStoreActionStore; + desc.stencilAttachment.clearStencil = 0; + return desc; +} diff --git a/core/rend/metal/oit/metal_oit_pipeline.h b/core/rend/metal/oit/metal_oit_pipeline.h new file mode 100644 index 0000000000..481d4e38e8 --- /dev/null +++ b/core/rend/metal/oit/metal_oit_pipeline.h @@ -0,0 +1,758 @@ +/* + This file is part of Flycast. + + Flycast is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 2 of the License, or + (at your option) any later version. + + Flycast is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with Flycast. If not, see . +*/ +// Metal OIT pipeline state manager. Port of core/rend/vulkan/oit/oit_pipeline. +// +// Three pipeline types beyond the regular MetalPipelineManager: +// 1. Collect - fs_main(oitMode=true), color write masked off +// 2. Resolve - linked-list walk + per-poly blend (metal_oit_shaders.h) +// 3. TR modvol - linked-list shadow tagging (oit_tr_modvol_fragment) +#pragma once +#include "../metal_apple.h" + +#include "types.h" +#include "../metal_context.h" +#include "../metal_pipeline.h" +#include "../metal_shaders.h" +#include "metal_oit_buffer.h" +#include "metal_oit_shaders.h" +#include "hw/pvr/ta_ctx.h" + +#include + +/// Whether the OIT render pass keeps the opaque + punch-through depth in tile +/// memory (colour attachment 1, R32Float, memoryless) for the collect's manual +/// depth test, instead of ending the encoder to blit the depth attachment into +/// a sampled copy. Needs programmable blending (a [[color(n)]] fragment input) +/// and memoryless render targets, both Apple2+ in the Metal Feature Set Tables +/// (Apple silicon Macs report the Apple families too; Intel/AMD Macs don't). +/// The Simulator's Metal can't build pipelines that read a render target +/// ("reading from a rendertarget is not supported"), so it takes the copy path. +inline bool MetalOITTileDepthSupported(id device) +{ +#if TARGET_OS_SIMULATOR + (void)device; + return false; +#else + if (device == nil) + return false; + if (@available(macOS 11.0, iOS 13.0, tvOS 13.0, *)) + return [device supportsFamily:MTLGPUFamilyApple2]; + return false; +#endif +} + +/// How the translucent modifier-volume draws order their a-buffer accesses. +/// Each volume's XOR/OR marks must land in a pixel's records before the +/// Inclusion/Exclusion sum reads them, and the sum's SHADOW_ACC writes before +/// the next volume and the resolve (all in one render encoder). Vulkan puts a +/// by-region fragment->fragment pipelineBarrier at both points; the Metal +/// equivalent, a render-encoder memoryBarrierWithScope: with fragment stages, +/// is invalid on Apple GPUs ("afterStages can not contain MTLRenderStageFragment +/// on this device" from the validation layer, and no ordering without it). +enum class MetalOITFragmentOrdering +{ + /// The modvol and resolve shaders put the a-buffer in raster order group 0: + /// overlapping fragments touch it in draw submission order, so no barrier + /// is needed. Every access is to the shaded pixel's own list, which is + /// exactly the overlap a raster order group orders. + RasterOrderGroups, + /// macOS on a non-Apple GPU (Intel/AMD) without raster order groups, where + /// the fragment->fragment render-encoder barrier is valid. + MemoryBarrier, + /// Apple GPU without raster order groups (A8-A10): end the encoder and open + /// a new one, which Metal's hazard tracking orders after the first. + EncoderSplit, +}; + +inline MetalOITFragmentOrdering MetalOITFragmentOrderingFallback(id device) +{ +#if TARGET_OS_OSX + if (device != nil) { + bool appleGpu = false; + if (@available(macOS 10.15, *)) + appleGpu = [device supportsFamily:MTLGPUFamilyApple1]; + if (!appleGpu) + return MetalOITFragmentOrdering::MemoryBarrier; + } +#else + (void)device; +#endif + return MetalOITFragmentOrdering::EncoderSplit; +} + +inline MetalOITFragmentOrdering MetalOITFragmentOrderingFor(id device) +{ + if (device != nil && device.rasterOrderGroupsSupported) + return MetalOITFragmentOrdering::RasterOrderGroups; + return MetalOITFragmentOrderingFallback(device); +} + +class MetalOITPipelineManager +{ +public: + explicit MetalOITPipelineManager(MetalShaders *shaderManager, MetalOITBuffers *oitBuffers) + : shaderManager(shaderManager), oitBuffers(oitBuffers), + tileDepth(MetalOITTileDepthSupported(MetalContext::Instance()->GetDevice())) {} + + /// See MetalOITTileDepthSupported. Fixed for the manager's lifetime; the + /// drawer's regular pipeline manager is built with the same value. + bool UseTileDepth() const { return tileDepth; } + + /// See MetalOITFragmentOrdering. Settled when Init() compiles the library + /// (a failed raster-order compile falls back), so it compiles it first. + MetalOITFragmentOrdering FragmentOrdering() + { + Init(); + return fragmentOrdering; + } + + /// Compile the shared OIT MSL library and cache MTLFunction handles + /// for collect/resolve. Cheap to call repeatedly; first call does the + /// MTLLibrary newLibraryWithSource: compile (Metal does shader + /// compilation lazily, so this can stall the first time it runs). + void Init() + { + const int layers = std::max(8, std::min(128, (int)config::PerPixelLayers)); + if (layers != maxLayers) + { + term(); + maxLayers = layers; + } + if (oitLibrary != nil) + return; + id device = MetalContext::Instance()->GetDevice(); + if (device == nil) { + WARN_LOG(RENDERER, "MetalOITPipelineManager::Init: no Metal device"); + return; + } + std::string src = GetMetalOITShaderSource(); + NSString *srcNS = [NSString stringWithUTF8String:src.c_str()]; + fragmentOrdering = MetalOITFragmentOrderingFor(device); + auto compile = [&](bool rasterOrder, NSError **err) { + MTLCompileOptions *options = [[MTLCompileOptions alloc] init]; + options.preprocessorMacros = @{ @"OIT_RASTER_ORDER" : @(rasterOrder ? 1 : 0), @"OIT_MAX_FRAGMENTS" : @(maxLayers) }; + return [device newLibraryWithSource:srcNS options:options error:err]; + }; + NSError *err = nil; + const bool rasterOrder = fragmentOrdering == MetalOITFragmentOrdering::RasterOrderGroups; + oitLibrary = compile(rasterOrder, &err); + if (oitLibrary == nil && rasterOrder) { + WARN_LOG(RENDERER, "MetalOITPipelineManager::Init: MSL compile with raster order groups failed (%s), retrying without", + err.localizedDescription.UTF8String); + fragmentOrdering = MetalOITFragmentOrderingFallback(device); + err = nil; + oitLibrary = compile(false, &err); + } + if (oitLibrary == nil) { + ERROR_LOG(RENDERER, "MetalOITPipelineManager::Init: MSL compile failed: %s", + err.localizedDescription.UTF8String); + return; + } + INFO_LOG(RENDERER, "Metal OIT: modifier volume fragment ordering: %s", + fragmentOrdering == MetalOITFragmentOrdering::RasterOrderGroups ? "raster order groups" + : fragmentOrdering == MetalOITFragmentOrdering::MemoryBarrier ? "memory barrier" + : "encoder split"); + collectVertexFn = nil; + collectFragmentFn = nil; + seedOpaqueDepthFn = [oitLibrary newFunctionWithName:@"oit_seed_opaque_depth"]; + resolveVertexFn = [oitLibrary newFunctionWithName:@"oit_resolve_vertex"]; + resolveFragmentFn = [oitLibrary newFunctionWithName:@"oit_resolve_fragment"]; + if (resolveVertexFn == nil || resolveFragmentFn == nil) { + ERROR_LOG(RENDERER, "MetalOITPipelineManager::Init: OIT resolve shader entry points missing"); + } + } + + /// Drop all cached pipelines. Called from Term() and when shader + /// reload invalidates them. + void term() + { + collectPipelines.clear(); + trDepthPipelines.clear(); + resolvePipeline = nil; + seedOpaqueDepthPipeline = nil; + twoVolumeCollectDepthStencil[0] = twoVolumeCollectDepthStencil[1] = nil; + seedOpaqueDepthFn = nil; + trModVolPipelines.clear(); + trModVolFragmentFns.clear(); + trModVolDepthStencilState = nil; + collectVertexFn = nil; + collectFragmentFn = nil; + resolveVertexFn = nil; + resolveFragmentFn = nil; + oitLibrary = nil; + } + + /// Collect-pass pipeline for translucent geometry. Cached by the + /// same polygon-state hash MetalPipelineManager uses, so identical + /// poly setups share one pipeline state. + /// + /// area: 0 = regular collect; 1 / 2 = a two-volume poly's second / first + /// parameter set, stencil-gated inside / outside the modifier-volume mark. + /// Areas 1 and 2 use the [[early_fragment_tests]] fragment entry point and + /// must be drawn with GetTwoVolumeCollectDepthStencilState(area). + id GetCollectPipeline(u32 listType, bool sortTriangles, + const PolyParam &pp, int gpuPalette, + bool dithering, int area = 0) + { + u64 pipehash = hashCollect(listType, sortTriangles, &pp, gpuPalette, dithering, area); + const auto it = collectPipelines.find(pipehash); + if (it != collectPipelines.end() && it->second != nil) + return it->second; + CreateCollectPipeline(listType, sortTriangles, pp, gpuPalette, dithering, area); + return collectPipelines[pipehash]; + } + + /// Depth/stencil state for the two-volume collect draws (area 1 or 2). + /// Their fragment function runs after early depth/stencil tests, so the + /// stencil area test rejects fragments before the a-buffer append. The + /// depth compare is Always: the rasterized position.z isn't the log depth + /// fs_main computes, and the collect tests depth in the shader. + id GetTwoVolumeCollectDepthStencilState(int area) + { + if (area != 1 && area != 2) + return nil; + if (twoVolumeCollectDepthStencil[area - 1] != nil) + return twoVolumeCollectDepthStencil[area - 1]; + id device = MetalContext::Instance()->GetDevice(); + if (device == nil) + return nil; + MTLStencilDescriptor *stencil = [[MTLStencilDescriptor alloc] init]; + stencil.stencilCompareFunction = area == 1 ? MTLCompareFunctionEqual + : MTLCompareFunctionNotEqual; + stencil.stencilFailureOperation = MTLStencilOperationKeep; + stencil.depthFailureOperation = MTLStencilOperationKeep; + stencil.depthStencilPassOperation = MTLStencilOperationKeep; + stencil.readMask = 0x81; + stencil.writeMask = 0; + MTLDepthStencilDescriptor *desc = [[MTLDepthStencilDescriptor alloc] init]; + desc.label = area == 1 ? @"OIT two-volume collect (inside)" + : @"OIT two-volume collect (outside)"; + desc.depthCompareFunction = MTLCompareFunctionAlways; + desc.depthWriteEnabled = NO; + desc.frontFaceStencil = stencil; + desc.backFaceStencil = stencil; + twoVolumeCollectDepthStencil[area - 1] = [device newDepthStencilStateWithDescriptor:desc]; + return twoVolumeCollectDepthStencil[area - 1]; + } + + /// Tile depth only: full-screen draw writing colour attachment 1 from a + /// depth copy bound at fragment texture 4 (render passes after the first). + id GetSeedOpaqueDepthPipeline() + { + if (seedOpaqueDepthPipeline != nil || !tileDepth) + return seedOpaqueDepthPipeline; + if (oitLibrary == nil) + Init(); + if (resolveVertexFn == nil || seedOpaqueDepthFn == nil) + return nil; + MTLRenderPipelineDescriptor *desc = [[MTLRenderPipelineDescriptor alloc] init]; + desc.label = @"OIT seed opaque depth"; + desc.vertexFunction = resolveVertexFn; + desc.fragmentFunction = seedOpaqueDepthFn; + desc.rasterSampleCount = 1; + desc.colorAttachments[0].pixelFormat = MTLPixelFormatBGRA8Unorm; + desc.colorAttachments[0].writeMask = MTLColorWriteMaskNone; + desc.colorAttachments[1].pixelFormat = MTLPixelFormatR32Float; + desc.colorAttachments[1].writeMask = MTLColorWriteMaskRed; + desc.depthAttachmentPixelFormat = MTLPixelFormatDepth32Float_Stencil8; + desc.stencilAttachmentPixelFormat = MTLPixelFormatDepth32Float_Stencil8; + NSError *err = nil; + seedOpaqueDepthPipeline = [MetalContext::Instance()->GetDevice() + newRenderPipelineStateWithDescriptor:desc error:&err]; + if (seedOpaqueDepthPipeline == nil) + ERROR_LOG(RENDERER, "GetSeedOpaqueDepthPipeline failed: %s", + err.localizedDescription.UTF8String); + return seedOpaqueDepthPipeline; + } + + /// Final / resolve pipeline. Single state: unlike Vulkan's GetFinalPipeline + /// it has no sortTriangles parameter. + id GetResolvePipeline() + { + if (resolvePipeline != nil) + return resolvePipeline; + CreateResolvePipeline(); + return resolvePipeline; + } + + /// Translucent depth-only (color write masked off). Used after resolve + /// on non-final render passes — Vulkan Pass::Depth TR slice. + id GetTranslucentDepthPipeline(u32 listType, bool sortTriangles, + const PolyParam &pp, int gpuPalette, + bool dithering) + { + u64 pipehash = hashCollect(listType, sortTriangles, &pp, gpuPalette, dithering); + const auto it = trDepthPipelines.find(pipehash); + if (it != trDepthPipelines.end() && it->second != nil) + return it->second; + CreateTranslucentDepthPipeline(listType, sortTriangles, pp, gpuPalette, dithering); + return trDepthPipelines[pipehash]; + } + + /// Translucent modifier-volume pipeline. + id GetTrModVolPipeline(ModVolMode mode, int cullMode, bool naomi2) + { + u32 pipehash = hashModVol(mode, cullMode, naomi2); + const auto it = trModVolPipelines.find(pipehash); + if (it != trModVolPipelines.end() && it->second != nil) + return it->second; + CreateTrModVolPipeline(mode, cullMode, naomi2); + return trModVolPipelines[pipehash]; + } + + /// Depth/stencil disabled — OIT TR modvol only tags the linked list. + id GetTrModVolDepthStencilState() + { + if (trModVolDepthStencilState != nil) + return trModVolDepthStencilState; + id device = MetalContext::Instance()->GetDevice(); + if (device == nil) + return nil; + MTLDepthStencilDescriptor *desc = [[MTLDepthStencilDescriptor alloc] init]; + desc.depthCompareFunction = MTLCompareFunctionAlways; + desc.depthWriteEnabled = NO; + trModVolDepthStencilState = [device newDepthStencilStateWithDescriptor:desc]; + return trModVolDepthStencilState; + } + +private: + id GetTrModVolFragmentFunction(ModVolMode mode, bool divPosZ) + { + u32 key = ((u32)mode << 1) | (divPosZ ? 1u : 0u); + const auto it = trModVolFragmentFns.find(key); + if (it != trModVolFragmentFns.end() && it->second != nil) + return it->second; + if (oitLibrary == nil) + Init(); + if (oitLibrary == nil) + return nil; + MTLFunctionConstantValues *constants = [[MTLFunctionConstantValues alloc] init]; + int mvMode = (int)mode; + bool div = divPosZ; + [constants setConstantValue:&mvMode type:MTLDataTypeInt atIndex:0]; + [constants setConstantValue:&div type:MTLDataTypeBool atIndex:1]; + NSError *err = nil; + id fn = [oitLibrary newFunctionWithName:@"oit_tr_modvol_fragment" + constantValues:constants + error:&err]; + if (fn == nil) { + ERROR_LOG(RENDERER, "GetTrModVolFragmentFunction failed (mode=%d): %s", + (int)mode, err.localizedDescription.UTF8String); + return nil; + } + trModVolFragmentFns[key] = fn; + return fn; + } + + // ---- Pipeline creation + // + // Build the collect pipeline against the REAL Metal + // vertex layout + MetalShaders' specialised vertex function, with + // fs_main(oitMode=true) as the fragment. Writes are masked off on + // the colour attachment; the fragment side appends each translucent + // sample to the OIT per-pixel linked list (see metal_shaders.mm's + // pp_oit_mode branch at the end of fs_main). + void CreateCollectPipeline(u32 listType, bool sortTriangles, + const PolyParam &pp, int gpuPalette, + bool dithering, int area = 0) + { + if (shaderManager == nullptr) { + WARN_LOG(RENDERER, "CreateCollectPipeline: no shader manager"); + return; + } + u64 pipehash = hashCollect(listType, sortTriangles, &pp, gpuPalette, dithering, area); + id device = MetalContext::Instance()->GetDevice(); + + MTLRenderPipelineDescriptor *desc = [[MTLRenderPipelineDescriptor alloc] init]; + desc.label = @"OIT Collect"; + + // Match MetalPipelineManager::CreatePipeline's vertex descriptor. + // Layout intentionally duplicated from MetalPipelineManager:: + // GetMainVertexInputDescriptor (which is private) — keeping + // perfect parity with the regular pipeline's Vertex layout is + // essential or the collect VS won't interpolate correctly. + MTLVertexDescriptor *vertexDesc = [[MTLVertexDescriptor alloc] init]; + auto attrPos = [vertexDesc attributes][0]; + [attrPos setFormat:MTLVertexFormatFloat3]; + [attrPos setOffset:offsetof(Vertex, x)]; + [attrPos setBufferIndex:30]; + auto attrCol = [vertexDesc attributes][1]; + [attrCol setFormat:MTLVertexFormatUChar4Normalized]; + [attrCol setOffset:offsetof(Vertex, col)]; + [attrCol setBufferIndex:30]; + auto attrSpc = [vertexDesc attributes][2]; + [attrSpc setFormat:MTLVertexFormatUChar4Normalized]; + [attrSpc setOffset:offsetof(Vertex, spc)]; + [attrSpc setBufferIndex:30]; + auto attrUv = [vertexDesc attributes][3]; + [attrUv setFormat:MTLVertexFormatFloat2]; + [attrUv setOffset:offsetof(Vertex, u)]; + [attrUv setBufferIndex:30]; + auto attrCol1 = [vertexDesc attributes][4]; + [attrCol1 setFormat:MTLVertexFormatUChar4Normalized]; + [attrCol1 setOffset:offsetof(Vertex, col1)]; + [attrCol1 setBufferIndex:30]; + auto attrSpc1 = [vertexDesc attributes][5]; + [attrSpc1 setFormat:MTLVertexFormatUChar4Normalized]; + [attrSpc1 setOffset:offsetof(Vertex, spc1)]; + [attrSpc1 setBufferIndex:30]; + auto attrUv1 = [vertexDesc attributes][6]; + [attrUv1 setFormat:MTLVertexFormatFloat2]; + [attrUv1 setOffset:offsetof(Vertex, u1)]; + [attrUv1 setBufferIndex:30]; + if (pp.isNaomi2()) { + auto attrN = [vertexDesc attributes][7]; + [attrN setFormat:MTLVertexFormatFloat3]; + [attrN setOffset:offsetof(Vertex, nx)]; + [attrN setBufferIndex:30]; + } + auto layout = [vertexDesc layouts][30]; + [layout setStride:sizeof(Vertex)]; + [layout setStepRate:1]; + [layout setStepFunction:MTLVertexStepFunctionPerVertex]; + [desc setVertexDescriptor:vertexDesc]; + + bool divPosZ = !settings.platform.isNaomi2() && config::NativeDepthInterpolation; + + MetalVertexShaderParams vertParams = {}; + vertParams.gouraud = pp.pcw.Gouraud == 1; + vertParams.naomi2 = pp.isNaomi2(); + vertParams.divPosZ = divPosZ; + vertParams.oitCollect = true; + vertParams.area1 = area == 1; + + MetalFragmentShaderParams fragParams = {}; + fragParams.alphaTest = listType == ListType_Punch_Through; + fragParams.bumpmap = pp.tcw.PixelFmt == PixelBumpMap; + fragParams.clamping = pp.tsp.ColorClamp; + fragParams.insideClipTest = (pp.tileclip >> 28) == 3; + fragParams.fog = config::Fog ? pp.tsp.FogCtrl : 2; + fragParams.gouraud = pp.pcw.Gouraud; + fragParams.ignoreTexAlpha = pp.tsp.IgnoreTexA || pp.tcw.PixelFmt == Pixel565; + fragParams.offset = pp.pcw.Offset; + fragParams.shaderInstr = pp.tsp.ShadInstr; + fragParams.texture = pp.pcw.Texture; + fragParams.trilinear = pp.pcw.Texture && pp.tsp.FilterMode > 1 + && listType != ListType_Punch_Through + && pp.tcw.MipMapped == 1; + fragParams.useAlpha = pp.tsp.UseAlpha; + fragParams.palette = gpuPalette; + fragParams.divPosZ = divPosZ; + fragParams.dithering = dithering; + fragParams.oitMode = true; + fragParams.oitTileDepth = tileDepth; + fragParams.earlyFragmentTests = area != 0; + + [desc setVertexFunction:shaderManager->GetVertexShader(vertParams)]; + [desc setFragmentFunction:shaderManager->GetFragmentShader(fragParams)]; + if (desc.vertexFunction == nil || desc.fragmentFunction == nil) { + ERROR_LOG(RENDERER, "CreateCollectPipeline: shader compile failed"); + return; + } + + desc.rasterSampleCount = 1; + // Colour attachment exists but writes are masked off — the real + // output is the linked-list buffer write in the fragment shader's + // pp_oit_mode branch. + desc.colorAttachments[0].pixelFormat = MTLPixelFormatBGRA8Unorm; + desc.colorAttachments[0].writeMask = MTLColorWriteMaskNone; + desc.colorAttachments[0].blendingEnabled = NO; + if (tileDepth) { + // Read through [[color(1)]]; never written by the collect. + desc.colorAttachments[1].pixelFormat = MTLPixelFormatR32Float; + desc.colorAttachments[1].writeMask = MTLColorWriteMaskNone; + desc.colorAttachments[1].blendingEnabled = NO; + } + desc.depthAttachmentPixelFormat = MTLPixelFormatDepth32Float_Stencil8; + desc.stencilAttachmentPixelFormat = MTLPixelFormatDepth32Float_Stencil8; + + NSError *err = nil; + id state = + [device newRenderPipelineStateWithDescriptor:desc error:&err]; + if (state == nil) { + ERROR_LOG(RENDERER, "CreateCollectPipeline failed: %s", + err.localizedDescription.UTF8String); + return; + } + collectPipelines[pipehash] = state; + } + + void CreateTranslucentDepthPipeline(u32 listType, bool sortTriangles, + const PolyParam &pp, int gpuPalette, + bool dithering) + { + if (shaderManager == nullptr) { + WARN_LOG(RENDERER, "CreateTranslucentDepthPipeline: no shader manager"); + return; + } + u64 pipehash = hashCollect(listType, sortTriangles, &pp, gpuPalette, dithering); + id device = MetalContext::Instance()->GetDevice(); + + MTLRenderPipelineDescriptor *desc = [[MTLRenderPipelineDescriptor alloc] init]; + desc.label = @"OIT TR Depth"; + + MTLVertexDescriptor *vertexDesc = [[MTLVertexDescriptor alloc] init]; + auto attrPos = [vertexDesc attributes][0]; + [attrPos setFormat:MTLVertexFormatFloat3]; + [attrPos setOffset:offsetof(Vertex, x)]; + [attrPos setBufferIndex:30]; + auto attrCol = [vertexDesc attributes][1]; + [attrCol setFormat:MTLVertexFormatUChar4Normalized]; + [attrCol setOffset:offsetof(Vertex, col)]; + [attrCol setBufferIndex:30]; + auto attrSpc = [vertexDesc attributes][2]; + [attrSpc setFormat:MTLVertexFormatUChar4Normalized]; + [attrSpc setOffset:offsetof(Vertex, spc)]; + [attrSpc setBufferIndex:30]; + auto attrUv = [vertexDesc attributes][3]; + [attrUv setFormat:MTLVertexFormatFloat2]; + [attrUv setOffset:offsetof(Vertex, u)]; + [attrUv setBufferIndex:30]; + auto attrCol1 = [vertexDesc attributes][4]; + [attrCol1 setFormat:MTLVertexFormatUChar4Normalized]; + [attrCol1 setOffset:offsetof(Vertex, col1)]; + [attrCol1 setBufferIndex:30]; + auto attrSpc1 = [vertexDesc attributes][5]; + [attrSpc1 setFormat:MTLVertexFormatUChar4Normalized]; + [attrSpc1 setOffset:offsetof(Vertex, spc1)]; + [attrSpc1 setBufferIndex:30]; + auto attrUv1 = [vertexDesc attributes][6]; + [attrUv1 setFormat:MTLVertexFormatFloat2]; + [attrUv1 setOffset:offsetof(Vertex, u1)]; + [attrUv1 setBufferIndex:30]; + if (pp.isNaomi2()) { + auto attrN = [vertexDesc attributes][7]; + [attrN setFormat:MTLVertexFormatFloat3]; + [attrN setOffset:offsetof(Vertex, nx)]; + [attrN setBufferIndex:30]; + } + auto layout = [vertexDesc layouts][30]; + [layout setStride:sizeof(Vertex)]; + [layout setStepRate:1]; + [layout setStepFunction:MTLVertexStepFunctionPerVertex]; + [desc setVertexDescriptor:vertexDesc]; + + bool divPosZ = !settings.platform.isNaomi2() && config::NativeDepthInterpolation; + + MetalVertexShaderParams vertParams = {}; + vertParams.gouraud = pp.pcw.Gouraud == 1; + vertParams.naomi2 = pp.isNaomi2(); + vertParams.divPosZ = divPosZ; + vertParams.oitCollect = false; + + MetalFragmentShaderParams fragParams = {}; + fragParams.alphaTest = listType == ListType_Punch_Through; + fragParams.bumpmap = pp.tcw.PixelFmt == PixelBumpMap; + fragParams.clamping = pp.tsp.ColorClamp; + fragParams.insideClipTest = (pp.tileclip >> 28) == 3; + fragParams.fog = config::Fog ? pp.tsp.FogCtrl : 2; + fragParams.gouraud = pp.pcw.Gouraud; + fragParams.ignoreTexAlpha = pp.tsp.IgnoreTexA || pp.tcw.PixelFmt == Pixel565; + fragParams.offset = pp.pcw.Offset; + fragParams.shaderInstr = pp.tsp.ShadInstr; + fragParams.texture = pp.pcw.Texture; + fragParams.trilinear = pp.pcw.Texture && pp.tsp.FilterMode > 1 + && listType != ListType_Punch_Through + && pp.tcw.MipMapped == 1; + fragParams.useAlpha = pp.tsp.UseAlpha; + fragParams.palette = gpuPalette; + fragParams.divPosZ = divPosZ; + fragParams.dithering = dithering; + fragParams.oitMode = false; + + [desc setVertexFunction:shaderManager->GetVertexShader(vertParams)]; + [desc setFragmentFunction:shaderManager->GetFragmentShader(fragParams)]; + if (desc.vertexFunction == nil || desc.fragmentFunction == nil) { + ERROR_LOG(RENDERER, "CreateTranslucentDepthPipeline: shader compile failed"); + return; + } + + desc.rasterSampleCount = 1; + desc.colorAttachments[0].pixelFormat = MTLPixelFormatBGRA8Unorm; + desc.colorAttachments[0].writeMask = MTLColorWriteMaskNone; + desc.colorAttachments[0].blendingEnabled = NO; + desc.depthAttachmentPixelFormat = MTLPixelFormatDepth32Float_Stencil8; + desc.stencilAttachmentPixelFormat = MTLPixelFormatDepth32Float_Stencil8; + + NSError *err = nil; + id state = + [device newRenderPipelineStateWithDescriptor:desc error:&err]; + if (state == nil) { + ERROR_LOG(RENDERER, "CreateTranslucentDepthPipeline failed: %s", + err.localizedDescription.UTF8String); + return; + } + trDepthPipelines[pipehash] = state; + } + + void CreateResolvePipeline() + { + if (resolveVertexFn == nil || resolveFragmentFn == nil) { + WARN_LOG(RENDERER, "CreateResolvePipeline: OIT shaders not compiled"); + return; + } + id device = MetalContext::Instance()->GetDevice(); + + MTLRenderPipelineDescriptor *desc = [[MTLRenderPipelineDescriptor alloc] init]; + desc.label = @"OIT Resolve"; + desc.vertexFunction = resolveVertexFn; + desc.fragmentFunction = resolveFragmentFn; + desc.rasterSampleCount = 1; + // Resolve writes the composited result to the color buffer. The + // sorting + blend happens IN the shader, so the pipeline blend + // is disabled — we want the shader's output verbatim. + desc.colorAttachments[0].pixelFormat = MTLPixelFormatBGRA8Unorm; + desc.colorAttachments[0].writeMask = MTLColorWriteMaskAll; + desc.colorAttachments[0].blendingEnabled = NO; + desc.depthAttachmentPixelFormat = MTLPixelFormatDepth32Float_Stencil8; + desc.stencilAttachmentPixelFormat = MTLPixelFormatDepth32Float_Stencil8; + + NSError *err = nil; + resolvePipeline = [device newRenderPipelineStateWithDescriptor:desc error:&err]; + if (resolvePipeline == nil) { + ERROR_LOG(RENDERER, "CreateResolvePipeline failed: %s", + err.localizedDescription.UTF8String); + } + } + + // OIT TR modvol walks the per-pixel linked list and atomically tags + // seq_num shadow bits (Vulkan OITTranslucentModvolShaderSource). + void CreateTrModVolPipeline(ModVolMode mode, int cullMode, bool naomi2) + { + if (shaderManager == nullptr) { + WARN_LOG(RENDERER, "CreateTrModVolPipeline: no shader manager"); + return; + } + if (mode == ModVolMode::Final) + return; + id device = MetalContext::Instance()->GetDevice(); + MTLRenderPipelineDescriptor *desc = [[MTLRenderPipelineDescriptor alloc] init]; + [desc setLabel:@"OIT TR ModVol"]; + + MTLVertexDescriptor *vd = [[MTLVertexDescriptor alloc] init]; + auto attr = [vd attributes][0]; + [attr setFormat:MTLVertexFormatFloat3]; + [attr setOffset:0]; + [attr setBufferIndex:30]; + auto layout = [vd layouts][30]; + [layout setStride:sizeof(float) * 3]; + [layout setStepRate:1]; + [layout setStepFunction:MTLVertexStepFunctionPerVertex]; + [desc setVertexDescriptor:vd]; + + auto attachment = [desc colorAttachments][0]; + [attachment setBlendingEnabled:NO]; + [attachment setWriteMask:MTLColorWriteMaskNone]; + [attachment setPixelFormat:MTLPixelFormatBGRA8Unorm]; + + [desc setDepthAttachmentPixelFormat:MTLPixelFormatDepth32Float_Stencil8]; + [desc setStencilAttachmentPixelFormat:MTLPixelFormatDepth32Float_Stencil8]; + + bool divPosZ = !settings.platform.isNaomi2() && config::NativeDepthInterpolation; + MetalModVolShaderParams shaderParams { naomi2, divPosZ }; + id fragmentFn = GetTrModVolFragmentFunction(mode, divPosZ); + if (fragmentFn == nil) + return; + [desc setVertexFunction:shaderManager->GetModVolVertexShader(shaderParams)]; + [desc setFragmentFunction:fragmentFn]; + if (desc.vertexFunction == nil) { + ERROR_LOG(RENDERER, "CreateTrModVolPipeline: vertex shader compile failed"); + return; + } + + NSError *err = nil; + id state = + [device newRenderPipelineStateWithDescriptor:desc error:&err]; + if (state == nil) { + ERROR_LOG(RENDERER, "CreateTrModVolPipeline failed: %s", + err.localizedDescription.UTF8String); + return; + } + trModVolPipelines[hashModVol(mode, cullMode, naomi2)] = state; + } + + // ---- Hash helpers ---- + // + // hashCollect folds in every PolyParam field that affects the + // compiled fragment-shader specialisation OR the pipeline state + // (vertex naomi2 flag, gouraud, depth/blend setup, etc.). Identical + // PolyParam state shares one cached MTLRenderPipelineState — the + // expensive Metal pipeline compile only runs once per unique + // combination. Mirrors the keys MetalPipelineManager::hash uses for + // the regular pipeline cache (see metal_pipeline.h:hash). + u64 hashCollect(u32 listType, bool sortTriangles, const PolyParam *pp, + int gpuPalette, bool dithering, int area = 0) const + { + u64 h = (u64)listType; + h = (h << 2) | (u64)(area & 3); + h = (h << 1) | (sortTriangles ? 1 : 0); + h = (h << 4) | (gpuPalette & 0xF); + h = (h << 1) | (dithering ? 1 : 0); + if (pp != nullptr) { + h = (h << 1) | ((u64)pp->isNaomi2()); + h = (h << 1) | ((u64)(pp->pcw.Gouraud == 1)); + h = (h << 1) | ((u64)pp->pcw.Texture); + h = (h << 1) | ((u64)pp->pcw.Offset); + h = (h << 1) | ((u64)pp->pcw.Shadow); + h = (h << 3) | ((u64)(pp->tsp.ShadInstr & 0x3)); + h = (h << 3) | ((u64)(pp->tsp.FogCtrl & 0x3)); + h = (h << 1) | ((u64)pp->tsp.UseAlpha); + h = (h << 1) | ((u64)pp->tsp.ColorClamp); + h = (h << 1) | ((u64)pp->tsp.IgnoreTexA); + h = (h << 2) | ((u64)(pp->tcw.PixelFmt == PixelBumpMap)); + h = (h << 2) | ((u64)(pp->tcw.PixelFmt == Pixel565)); + h = (h << 2) | ((u64)(pp->tsp.SrcInstr & 0x7)); + h = (h << 2) | ((u64)(pp->tsp.DstInstr & 0x7)); + h = (h << 2) | ((u64)(pp->isp.CullMode & 0x3)); + h = (h << 2) | ((u64)((pp->tileclip >> 28) & 0x3)); + } + return h; + } + + u32 hashModVol(ModVolMode mode, int cullMode, bool naomi2) const + { + return ((u32)mode << 16) | ((u32)cullMode << 1) | (naomi2 ? 1 : 0); + } + + MetalShaders *shaderManager = nullptr; + // Vulkan's OITPipelineManager needs this to populate descriptor sets + // (oit_pipeline.h:140). Metal has no descriptor sets — MetalOITDrawer binds + // the A-buffer/pixel-counter buffers directly at draw time — so this is kept + // only for structural parity with the Vulkan class the port mirrors. + [[maybe_unused]] MetalOITBuffers *oitBuffers = nullptr; + + std::unordered_map> collectPipelines; + std::unordered_map> trDepthPipelines; + std::unordered_map> trModVolPipelines; + std::unordered_map> trModVolFragmentFns; + id trModVolDepthStencilState = nil; + id resolvePipeline = nil; + id seedOpaqueDepthPipeline = nil; + id twoVolumeCollectDepthStencil[2] = { nil, nil }; + bool tileDepth = false; + MetalOITFragmentOrdering fragmentOrdering = MetalOITFragmentOrdering::EncoderSplit; + + // Compiled MSL library + cached function handles. Built once by + // Init() and reused for every pipeline state. Dropped in term(). + int maxLayers = 0; + id oitLibrary = nil; + id collectVertexFn = nil; + id collectFragmentFn = nil; + id resolveVertexFn = nil; + id resolveFragmentFn = nil; + id seedOpaqueDepthFn = nil; +}; diff --git a/core/rend/metal/oit/metal_oit_shaders.h b/core/rend/metal/oit/metal_oit_shaders.h new file mode 100644 index 0000000000..d2399c7201 --- /dev/null +++ b/core/rend/metal/oit/metal_oit_shaders.h @@ -0,0 +1,365 @@ +/* + This file is part of Flycast. + + Flycast is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 2 of the License, or + (at your option) any later version. + + Flycast is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with Flycast. If not, see . +*/ +// MSL sources for the Metal OIT resolve and TR modvol passes. +// The collect pass uses fs_main with pp_oit_mode in metal_shaders.mm. +#pragma once + +#include + +static const char kMetalOITShaderPrologue[] = R"( +#include +#include +using namespace metal; + +// OIT_RASTER_ORDER (a compile-option macro, see MetalOITFragmentOrdering): +// the TR modvol marks, the modvol sums and the resolve all run in one render +// encoder and touch the shaded pixel's a-buffer list; raster order group 0 +// makes overlapping fragments access it in draw submission order. Every +// access in that encoder must be in the group for the ordering to hold. +#if OIT_RASTER_ORDER +#define OIT_ORDERED [[raster_order_group(0)]] +#else +#define OIT_ORDERED +#endif + +constant constexpr uint kEOL = 0xFFFFFFFFu; +constant constexpr uint kMaxFragmentsPerPixel = OIT_MAX_FRAGMENTS; + +constant constexpr uint SHADOW_STENCIL = 0x40000000u; +constant constexpr uint SHADOW_ACC = 0x80000000u; + +constant constexpr int ZERO = 0; +constant constexpr int ONE = 1; +constant constexpr int OTHER_COLOR = 2; +constant constexpr int INVERSE_OTHER_COLOR = 3; +constant constexpr int SRC_ALPHA = 4; +constant constexpr int INVERSE_SRC_ALPHA = 5; +constant constexpr int DST_ALPHA = 6; +constant constexpr int INVERSE_DST_ALPHA = 7; + +struct Pixel { + uint color; + float depth; + uint seq_num; + uint next; +}; + +struct OITPolyParam { + int tsp_isp_pcw; + int tsp1; +}; + +struct ResolveUniforms { + uint viewportWidth; + uint viewportHeight; + uint pixelBufferSize; + float shadeScale; + float4 ditherDivisor; + uint applyDither; +}; + +struct ResolveVertexOut { + float4 position [[position]]; +}; + +inline uint getPolyNumber(Pixel pixel) { return (pixel.seq_num & 0x3FFFFFFFu) >> 17; } +inline uint getPolyIndex(Pixel pixel) { return pixel.seq_num & 0x3FFFFFFFu; } +inline bool isShadowed(Pixel pixel) { return (pixel.seq_num & SHADOW_ACC) == SHADOW_ACC; } +inline bool isTwoVolumes(OITPolyParam pp) { return pp.tsp1 != -1; } + +inline int getTspForArea(OITPolyParam pp, bool area1) { return area1 ? pp.tsp1 : pp.tsp_isp_pcw; } +inline int getSrcBlendFunc(OITPolyParam pp, bool area1) { return (getTspForArea(pp, area1) >> 29) & 7; } +inline int getDstBlendFunc(OITPolyParam pp, bool area1) { return (getTspForArea(pp, area1) >> 26) & 7; } +inline bool getSrcSelect(OITPolyParam pp, bool area1) { return ((getTspForArea(pp, area1) >> 25) & 1) != 0; } +inline bool getDstSelect(OITPolyParam pp, bool area1) { return ((getTspForArea(pp, area1) >> 24) & 1) != 0; } +inline bool getShadowEnable(OITPolyParam pp) { return (pp.tsp_isp_pcw & 1) != 0; } + +inline float4 unpackColors(uint u) +{ + return float4( + float((u >> 24) & 255u) / 255.0, + float((u >> 16) & 255u) / 255.0, + float((u >> 8) & 255u) / 255.0, + float( u & 255u) / 255.0); +} + +constant float kDitherTable[16] = { + 5, 13, 7, 15, + 9, 1, 11, 3, + 6, 14, 4, 12, + 10, 2, 8, 0 +}; +)"; + +static const char kMetalOITResolveVertex[] = R"( +vertex ResolveVertexOut oit_resolve_vertex(uint vid [[vertex_id]]) +{ + float2 pos[3] = { float2(-1.0, -1.0), float2( 3.0, -1.0), float2(-1.0, 3.0) }; + ResolveVertexOut out; + out.position = float4(pos[vid], 0.0, 1.0); + return out; +} +)"; + +static const char kMetalOITResolveFragment[] = R"( +inline int fillAndSortFragmentArray(uint2 coords, + device Pixel *pixel_buffer, + device atomic_uint *abuffer_pointer, + constant ResolveUniforms &ub, + thread uint *pixel_list) +{ + uint idx = atomic_exchange_explicit(&abuffer_pointer[coords.x + coords.y * ub.viewportWidth], + kEOL, memory_order_relaxed); + if (idx == kEOL) + return 0; + + int count = 1; + pixel_list[0] = idx; + idx = pixel_buffer[idx].next; + for (; idx != kEOL && count < int(kMaxFragmentsPerPixel); ++count) { + float depth = pixel_buffer[idx].depth; + uint index = getPolyIndex(pixel_buffer[idx]); + int j = count - 1; + while (j >= 0) { + uint jIdx = pixel_list[j]; + float jdepth = pixel_buffer[jIdx].depth; + uint jindex = getPolyIndex(pixel_buffer[jIdx]); + if (jdepth > depth || (jdepth == depth && jindex > index)) + { + pixel_list[j + 1] = pixel_list[j]; + --j; + } + else + break; + } + pixel_list[j + 1] = idx; + idx = pixel_buffer[idx].next; + } + return count; +} + +inline float4 resolveAlphaBlend(float2 pos, + device Pixel *pixel_buffer, + device atomic_uint *abuffer_pointer, + device const OITPolyParam *tr_poly_params, + float4 opaqueColor, + constant ResolveUniforms &ub) +{ + uint2 coords = uint2(pos); + uint pixel_list[kMaxFragmentsPerPixel]; + int num_frag = fillAndSortFragmentArray(coords, pixel_buffer, abuffer_pointer, ub, pixel_list); + if (num_frag == 0) + discard_fragment(); + + // The opaque background is the CURRENT content of the color attachment, + // read via framebuffer fetch — Metal's equivalent of the Vulkan resolve + // subpass's OP+PT color input attachment, see oit_drawer.cpp. Sampling + // the ping-pong sibling here composited every TR-covered pixel over a + // buffer no pass had written -- black -- which ate HUD sprites and + // opaque-applied shadows under any translucency. + // NOTE: this comment lives inside a raw string; a close-paren followed + // by a double quote would terminate it. + float4 finalColor = opaqueColor; + float4 secondaryBuffer = float4(0.0); + + for (int i = 0; i < num_frag; ++i) { + const Pixel pixel = pixel_buffer[pixel_list[i]]; + const OITPolyParam pp = tr_poly_params[getPolyNumber(pixel)]; + bool area1 = false; + bool shadowed = false; + if (isShadowed(pixel)) { + if (isTwoVolumes(pp)) + area1 = true; + else + shadowed = true; + } + + float4 srcColor; + if (getSrcSelect(pp, area1)) + srcColor = secondaryBuffer; + else { + srcColor = unpackColors(pixel.color); + if (shadowed) + srcColor.rgb *= ub.shadeScale; + } + + float4 dstColor = getDstSelect(pp, area1) ? secondaryBuffer : finalColor; + float4 srcCoef = float4(0.0); + float4 dstCoef = float4(0.0); + + switch (getSrcBlendFunc(pp, area1)) { + case ZERO: srcCoef = float4(0.0); break; + case ONE: srcCoef = float4(1.0); break; + case OTHER_COLOR: srcCoef = dstColor; break; + case INVERSE_OTHER_COLOR: srcCoef = float4(1.0) - dstColor; break; + case SRC_ALPHA: srcCoef = float4(srcColor.a); break; + case INVERSE_SRC_ALPHA: srcCoef = float4(1.0 - srcColor.a); break; + case DST_ALPHA: srcCoef = float4(dstColor.a); break; + case INVERSE_DST_ALPHA: srcCoef = float4(1.0 - dstColor.a); break; + } + switch (getDstBlendFunc(pp, area1)) { + case ZERO: dstCoef = float4(0.0); break; + case ONE: dstCoef = float4(1.0); break; + case OTHER_COLOR: dstCoef = srcColor; break; + case INVERSE_OTHER_COLOR: dstCoef = float4(1.0) - srcColor; break; + case SRC_ALPHA: dstCoef = float4(srcColor.a); break; + case INVERSE_SRC_ALPHA: dstCoef = float4(1.0 - srcColor.a); break; + case DST_ALPHA: dstCoef = float4(dstColor.a); break; + case INVERSE_DST_ALPHA: dstCoef = float4(1.0 - dstColor.a); break; + } + + const float4 result = clamp(dstColor * dstCoef + srcColor * srcCoef, 0.0, 1.0); + if (getDstSelect(pp, area1)) + secondaryBuffer = result; + else + finalColor = result; + } + + if (ub.applyDither != 0u) { + float r = kDitherTable[int(fmod(pos.y, 4.0)) * 4 + int(fmod(pos.x, 4.0))]; + float4 dv = float4(r, r, r, 1.0) / ub.ditherDivisor; + finalColor = clamp(floor(finalColor * 255.0 + dv) / 255.0, 0.0, 1.0); + } + + return finalColor; +} + +fragment float4 oit_resolve_fragment( + ResolveVertexOut in [[stage_in]], + device Pixel *pixel_buffer [[buffer(1)]] OIT_ORDERED, + device atomic_uint *abuffer_pointer [[buffer(2)]] OIT_ORDERED, + constant ResolveUniforms &ub [[buffer(3)]], + device const OITPolyParam *tr_poly_params [[buffer(4)]], + texture2d backgroundTex [[texture(0)]]) +{ + // The opaque background arrives as a plain texture, NOT via [[color(0)]] + // framebuffer fetch. Framebuffer fetch is a TBDR feature the iOS + // Simulator's Metal does not implement: newRenderPipelineStateWithDescriptor + // rejected this function with "reading from a rendertarget is not + // supported", so CreateResolvePipeline returned nil, drawResolve bailed + // out, and every collected translucent fragment was silently dropped — + // the Dreamcast BIOS boot swirl (370 translucent polys over 1 opaque + // background poly) rendered as a bare background. The drawer now blits + // the opaque attachment into a scratch texture between the collect and + // resolve encoders and binds it here, which works on every Metal device. + const float4 opaqueColor = backgroundTex.read(uint2(in.position.xy)); + return resolveAlphaBlend(in.position.xy, pixel_buffer, abuffer_pointer, tr_poly_params, opaqueColor, ub); +} +)"; + +static const char kMetalOITTrModvolFragment[] = R"( +constant int MV_MODE [[function_constant(0)]]; +constant bool DIV_POS_Z [[function_constant(1)]]; + +struct ModVolVertexOut { + float depth; + float4 position [[position]]; +}; + +inline float modvolLogDepth(float depth) +{ + float w = DIV_POS_Z ? (100000.0 / depth) : (100000.0 * depth); + return log2(1.0 + max(w, -0.999999)) / 34.0; +} + +// Mirrors MetalModVolPushBlock (metal_drawer.h): 32 bytes, float4-aligned. +struct ModVolClip { + float4 clip_test; // x0, y0, x1, y1 in framebuffer pixels (Inside clip only) + float sp_shader_color; // unused here (stencil passes' darkening alpha) + int clip_inside; // 1 = skip fragments inside clip_test + float2 pad; +}; + +fragment void oit_tr_modvol_fragment( + ModVolVertexOut in [[stage_in]], + device Pixel *pixel_buffer [[buffer(1)]] OIT_ORDERED, + device atomic_uint *abuffer_pointer [[buffer(2)]] OIT_ORDERED, + constant ResolveUniforms &ub [[buffer(3)]], + device const OITPolyParam *tr_poly_params [[buffer(4)]], + constant ModVolClip &clip [[buffer(5)]]) +{ + // TA user tile clip, Inside mode: the volume doesn't mark pixels inside the + // rect (Outside mode is the scissor). No outputs, so a plain return suffices. + if (clip.clip_inside != 0 + && in.position.x >= clip.clip_test.x && in.position.x <= clip.clip_test.z + && in.position.y >= clip.clip_test.y && in.position.y <= clip.clip_test.w) + return; + + const float frag_depth = modvolLogDepth(in.depth); + const uint2 coords = uint2(in.position.xy); + uint idx = atomic_load_explicit(&abuffer_pointer[coords.x + coords.y * ub.viewportWidth], + memory_order_relaxed); + int list_len = 0; + while (idx != kEOL && list_len < int(kMaxFragmentsPerPixel)) + { + const Pixel pixel = pixel_buffer[idx]; + const OITPolyParam pp = tr_poly_params[getPolyNumber(pixel)]; + if (getShadowEnable(pp)) + { + device atomic_uint *seq_num = (device atomic_uint *)&pixel_buffer[idx].seq_num; + if (MV_MODE == 0) { + if (frag_depth >= pixel.depth) + atomic_fetch_xor_explicit(seq_num, SHADOW_STENCIL, memory_order_relaxed); + } else if (MV_MODE == 1) { + if (frag_depth >= pixel.depth) + atomic_fetch_or_explicit(seq_num, SHADOW_STENCIL, memory_order_relaxed); + } else if (MV_MODE == 2) { + const uint prev_val = atomic_fetch_and_explicit(seq_num, ~(SHADOW_STENCIL), memory_order_relaxed); + if ((prev_val & (SHADOW_STENCIL | SHADOW_ACC)) == SHADOW_STENCIL) + pixel_buffer[idx].seq_num = (pixel.seq_num & ~(1u << 31u)) | (1u << 31u); + } else if (MV_MODE == 3) { + const uint prev_val = atomic_fetch_and_explicit(seq_num, ~(SHADOW_STENCIL | SHADOW_ACC), memory_order_relaxed); + if ((prev_val & (SHADOW_STENCIL | SHADOW_ACC)) == SHADOW_ACC) + pixel_buffer[idx].seq_num = (pixel.seq_num & ~(1u << 31u)) | (1u << 31u); + } + } + idx = pixel.next; + ++list_len; + } +} +)"; + +// Tile-memory opaque depth, render passes after the first: the depth +// attachment is loaded with the earlier passes' depth, but the tile copy in +// colour attachment 1 is memoryless and starts cleared. This full-screen +// draw (oit_resolve_vertex) seeds it from a blitted copy of the depth. +static const char kMetalOITSeedOpaqueDepthFragment[] = R"( +struct SeedOpaqueDepthOut { + float4 color [[color(0)]]; + float opaque_depth [[color(1)]]; +}; + +fragment SeedOpaqueDepthOut oit_seed_opaque_depth(ResolveVertexOut in [[stage_in]], + depth2d depth_copy [[texture(4)]]) +{ + SeedOpaqueDepthOut out; + out.color = float4(0.0); + out.opaque_depth = depth_copy.read(uint2(in.position.xy)); + return out; +} +)"; + +inline std::string GetMetalOITShaderSource() +{ + std::string src; + src += kMetalOITShaderPrologue; + src += kMetalOITResolveVertex; + src += kMetalOITResolveFragment; + src += kMetalOITTrModvolFragment; + src += kMetalOITSeedOpaqueDepthFragment; + return src; +} diff --git a/core/sdl/sdl.cpp b/core/sdl/sdl.cpp index 2ea252c0e1..2554a93edd 100644 --- a/core/sdl/sdl.cpp +++ b/core/sdl/sdl.cpp @@ -9,6 +9,9 @@ #if defined(USE_VULKAN) #include #endif +#if defined(USE_METAL) +#include +#endif #endif #include "hw/maple/maple_devs.h" #include "sdl_gamepad.h" @@ -685,6 +688,11 @@ bool sdl_update_display_metrics(SDL_Window *window, u32 windowFlags) if (windowFlags & SDL_WINDOW_OPENGL) SDL_GL_GetDrawableSize(window, &settings.display.width, &settings.display.height); else +#endif +#ifdef USE_METAL + if (windowFlags & SDL_WINDOW_METAL) + SDL_Metal_GetDrawableSize(window, &settings.display.width, &settings.display.height); + else #endif { settings.display.width = windowWidth; diff --git a/core/stdclass.h b/core/stdclass.h index acfd659b52..583af94dde 100644 --- a/core/stdclass.h +++ b/core/stdclass.h @@ -23,6 +23,13 @@ extern const unsigned long PAGE_SIZE; #define MAX_PAGE_SIZE 16384 #elif defined(__APPLE__) && defined(__aarch64__) #define PAGE_SIZE 16384 +#elif defined(__APPLE__) && defined(__x86_64__) +// Mach headers can define PAGE_SIZE as the runtime vm_page_size variable. +// Keep the maximum a constant for layout checks, regardless of include order. +#ifndef PAGE_SIZE +#define PAGE_SIZE 4096 +#endif +#define MAX_PAGE_SIZE 4096 #elif !defined(PAGE_SIZE) #define PAGE_SIZE 4096 #endif diff --git a/core/types.h b/core/types.h index a43dad1083..78d7d80c69 100644 --- a/core/types.h +++ b/core/types.h @@ -102,6 +102,8 @@ enum class RenderType { DirectX9 = 1, DirectX11 = 2, DirectX11_OIT = 6, + Metal = 7, + Metal_OIT = 8, }; static inline bool isOpenGL(RenderType renderType) { @@ -113,6 +115,9 @@ static inline bool isVulkan(RenderType renderType) { static inline bool isDirectX(RenderType renderType) { return renderType == RenderType::DirectX9 || renderType == RenderType::DirectX11 || renderType == RenderType::DirectX11_OIT; } +static inline bool isMetal(RenderType renderType) { + return renderType == RenderType::Metal || renderType == RenderType::Metal_OIT; +} enum class KeyboardLayout { JP = 1, diff --git a/core/ui/mainui.cpp b/core/ui/mainui.cpp index 20b6f06f50..65a1ec3a9e 100644 --- a/core/ui/mainui.cpp +++ b/core/ui/mainui.cpp @@ -36,6 +36,21 @@ static bool mainui_enabled; u32 MainFrameCount; static bool forceReinit; +// Graphics API used by a renderer type. Switching between renderers of the same API +// doesn't require the graphics context to be recreated. +static int getRenderApi(RenderType renderType) +{ + if (isOpenGL(renderType)) + return 0; + if (isVulkan(renderType)) + return 1; + if (renderType == RenderType::DirectX9) + return 2; + if (isMetal(renderType)) + return 4; + return 3; +} + bool mainui_rend_frame() { FC_PROFILE_SCOPE; @@ -120,8 +135,8 @@ void mainui_loop(bool forceStart) if (config::RendererType != currentRenderer || forceReinit) { mainui_term(); - int prevApi = isOpenGL(currentRenderer) ? 0 : isVulkan(currentRenderer) ? 1 : currentRenderer == RenderType::DirectX9 ? 2 : 3; - int newApi = isOpenGL(config::RendererType) ? 0 : isVulkan(config::RendererType) ? 1 : config::RendererType == RenderType::DirectX9 ? 2 : 3; + int prevApi = getRenderApi(currentRenderer); + int newApi = getRenderApi(config::RendererType); if (newApi != prevApi || forceReinit) { try { diff --git a/core/ui/settings_about.cpp b/core/ui/settings_about.cpp index 24eea30729..fc8c2deb17 100644 --- a/core/ui/settings_about.cpp +++ b/core/ui/settings_about.cpp @@ -103,6 +103,8 @@ void gui_settings_about() header("Vulkan"); else if (isDirectX(config::RendererType)) header("DirectX"); + else if (isMetal(config::RendererType)) + header("Metal"); ImGui::Text(T("Driver Name: %s"), GraphicsContext::Instance()->getDriverName().c_str()); ImGui::Text(T("Version: %s"), GraphicsContext::Instance()->getDriverVersion().c_str()); diff --git a/core/ui/settings_video.cpp b/core/ui/settings_video.cpp index c42620a283..771c2827af 100644 --- a/core/ui/settings_video.cpp +++ b/core/ui/settings_video.cpp @@ -25,7 +25,8 @@ enum RenderAPI { OpenGL, Vulkan, DirectX9, - DirectX11 + DirectX11, + Metal }; void gui_settings_video() @@ -63,6 +64,14 @@ void gui_settings_video() renderApi = DirectX11; perPixel = true; break; + case RenderType::Metal: + renderApi = Metal; + perPixel = false; + break; + case RenderType::Metal_OIT: + renderApi = Metal; + perPixel = true; + break; } constexpr int apiCount = 0 #ifdef USE_VULKAN @@ -76,6 +85,9 @@ void gui_settings_video() #endif #ifdef USE_DX11 + 1 + #endif + #ifdef USE_METAL + + 1 #endif ; @@ -109,6 +121,10 @@ void gui_settings_video() #ifdef USE_DX11 ImGui::RadioButton("DirectX 11", &renderApi, DirectX11); ImGui::NextColumn(); +#endif +#ifdef USE_METAL + ImGui::RadioButton("Metal", &renderApi, Metal); + ImGui::NextColumn(); #endif ImGui::Columns(1, nullptr, false); } @@ -212,7 +228,7 @@ void gui_settings_video() OptionCheckbox(T("Frame Pacing (Experimental)"), config::FramePacing, T("Provide the GPU with presentation timing for each frame to replicate original frame pacing.")); #else - if (isVulkan(config::RendererType)) + if (isVulkan(config::RendererType) || isMetal(config::RendererType)) OptionCheckbox(T("Duplicate frames"), config::DupeFrames, T("Duplicate frames on high refresh rate monitors (120 Hz and higher)")); #endif } @@ -467,5 +483,8 @@ void gui_settings_video() case DirectX11: config::RendererType = perPixel ? RenderType::DirectX11_OIT : RenderType::DirectX11; break; + case Metal: + config::RendererType = perPixel ? RenderType::Metal_OIT : RenderType::Metal; + break; } } diff --git a/core/wsi/CMakeLists.txt b/core/wsi/CMakeLists.txt index 7aa00a034c..ef9584faf9 100644 --- a/core/wsi/CMakeLists.txt +++ b/core/wsi/CMakeLists.txt @@ -1,8 +1,15 @@ target_sources(${PROJECT_NAME} PRIVATE context.cpp context.h - libretro.h - switcher.cpp) + libretro.h) + +if(USE_METAL) + # The Metal context header uses Objective-C types + target_sources(${PROJECT_NAME} PRIVATE switcher.mm) + set_source_files_properties(switcher.mm TARGET_DIRECTORY ${PROJECT_NAME} PROPERTIES COMPILE_OPTIONS "-fobjc-arc") +else() + target_sources(${PROJECT_NAME} PRIVATE switcher.cpp) +endif() if(USE_OPENGL) target_compile_definitions(${PROJECT_NAME} PRIVATE USE_OPENGL) diff --git a/core/wsi/switcher.cpp b/core/wsi/switcher.cpp index 60b4b19bc7..16606625c0 100644 --- a/core/wsi/switcher.cpp +++ b/core/wsi/switcher.cpp @@ -29,6 +29,9 @@ #ifdef USE_VULKAN #include "rend/vulkan/vulkan_context.h" #endif +#ifdef USE_METAL +#include "rend/metal/metal_context.h" +#endif void initRenderApi(void *window, void *display) { @@ -72,6 +75,19 @@ void initRenderApi(void *window, void *display) } } #endif +#ifdef USE_METAL + if (isMetal(config::RendererType)) + { + try { + MetalContext::Create(window, display); + return; + } catch (const std::exception& e) { + // Fall back to OpenGL + WARN_LOG(RENDERER, "Metal init failed. Falling back to OpenGL (%s)", e.what()); + config::RendererType = RenderType::OpenGL; + } + } +#endif #ifdef USE_OPENGL if (!isOpenGL(config::RendererType)) config::RendererType = RenderType::OpenGL; diff --git a/core/wsi/switcher.mm b/core/wsi/switcher.mm new file mode 100644 index 0000000000..02d2ecb690 --- /dev/null +++ b/core/wsi/switcher.mm @@ -0,0 +1,19 @@ +/* + This file is part of Flycast. + + Flycast is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 2 of the License, or + (at your option) any later version. + + Flycast is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with Flycast. If not, see . +*/ +// The Metal context header uses Objective-C types, so the switcher +// must be compiled as Objective-C++ when Metal is enabled. +#include "switcher.cpp" diff --git a/shell/apple/emulator-osx/emulator-osx/osx-main.mm b/shell/apple/emulator-osx/emulator-osx/osx-main.mm index 7a6b7278be..e4947f17a9 100644 --- a/shell/apple/emulator-osx/emulator-osx/osx-main.mm +++ b/shell/apple/emulator-osx/emulator-osx/osx-main.mm @@ -239,11 +239,27 @@ void os_VideoRoutingTermGL() syphonGLServer = NULL; } +#if defined(USE_VULKAN) || defined(USE_METAL) +// Used by the Vulkan and Metal renderers +static SyphonMetalServer* syphonMtlServer; + +static void createSyphonMetalServer(id device) +{ + int boardID = config::loadInt("naomi", "BoardId"); + syphonMtlServer = [[SyphonMetalServer alloc] initWithName:[NSString stringWithFormat:(boardID == 0 ? @"Video Content" : @"Video Content - %d"), boardID] device:device options:nil]; +} + +static void termSyphonMetalServer() +{ + [syphonMtlServer stop]; + [syphonMtlServer release]; + syphonMtlServer = NULL; +} +#endif + #ifdef USE_VULKAN #include "rend/vulkan/vulkan.h" -static SyphonMetalServer* syphonMtlServer; - void os_VideoRoutingPublishFrameTexture(const vk::Device& device, const vk::Image& image, const vk::Queue& queue, float x, float y, float w, float h) { if (syphonMtlServer == NULL) @@ -252,8 +268,7 @@ void os_VideoRoutingPublishFrameTexture(const vk::Device& device, const vk::Imag auto objectsInfo = vk::ExportMetalObjectsInfoEXT(&deviceInfo); device.exportMetalObjectsEXT(&objectsInfo); - int boardID = config::loadInt("naomi", "BoardId"); - syphonMtlServer = [[SyphonMetalServer alloc] initWithName:[NSString stringWithFormat:(boardID == 0 ? @"Video Content" : @"Video Content - %d"), boardID] device:deviceInfo.mtlDevice options:nil]; + createSyphonMetalServer(deviceInfo.mtlDevice); } auto textureInfo = vk::ExportMetalTextureInfoEXT(image); @@ -269,9 +284,24 @@ void os_VideoRoutingPublishFrameTexture(const vk::Device& device, const vk::Imag void os_VideoRoutingTermVk() { - [syphonMtlServer stop]; - [syphonMtlServer release]; - syphonMtlServer = NULL; + termSyphonMetalServer(); +} +#endif + +#ifdef USE_METAL +void os_VideoRoutingPublishFrameTexture(id texture, id commandBuffer, float x, float y, float w, float h) +{ + if (syphonMtlServer != NULL && syphonMtlServer.device != texture.device) + termSyphonMetalServer(); + if (syphonMtlServer == NULL) + createSyphonMetalServer(texture.device); + + [syphonMtlServer publishFrameTexture:texture onCommandBuffer:commandBuffer imageRegion:NSMakeRect(x, y, w, h) flipped:YES]; +} + +void os_VideoRoutingTermMetal() +{ + termSyphonMetalServer(); } #endif diff --git a/tests/metal/oit_layer_limit.mm b/tests/metal/oit_layer_limit.mm new file mode 100644 index 0000000000..264bf5f535 --- /dev/null +++ b/tests/metal/oit_layer_limit.mm @@ -0,0 +1,103 @@ +// Run on macOS (including Intel/AMD) with Metal validation: +// clang++ -std=c++17 -fobjc-arc -framework Metal -framework Foundation \ +// tests/metal/oit_layer_limit.mm -o /tmp/oit_layer_limit +// MTL_DEBUG_LAYER=1 /tmp/oit_layer_limit +#import +#import +#include "../../core/rend/metal/oit/metal_oit_shaders.h" +#include +#include + +static void require(bool ok, const char *message) +{ + if (!ok) { + fprintf(stderr, "%s\n", message); + exit(1); + } +} + +static void testDevice(id device) +{ + @autoreleasepool { + printf("GPU: %s\n", device.name.UTF8String); + id queue = [device newCommandQueue]; + NSString *source = [NSString stringWithUTF8String:GetMetalOITShaderSource().c_str()]; + // Both ordering specializations compile the resolve and modifier-volume shaders. + for (bool rasterOrder : { false, true }) { + if (rasterOrder && !device.rasterOrderGroupsSupported) + continue; + for (unsigned layers : { 8u, 32u, 64u, 128u }) { + MTLCompileOptions *options = [MTLCompileOptions new]; + options.preprocessorMacros = @{ @"OIT_RASTER_ORDER": @(rasterOrder), @"OIT_MAX_FRAGMENTS": @(layers) }; + NSError *error = nil; + id library = [device newLibraryWithSource:source options:options error:&error]; + require(library != nil, error.localizedDescription.UTF8String); + MTLRenderPipelineDescriptor *pipelineDesc = [MTLRenderPipelineDescriptor new]; + pipelineDesc.vertexFunction = [library newFunctionWithName:@"oit_resolve_vertex"]; + pipelineDesc.fragmentFunction = [library newFunctionWithName:@"oit_resolve_fragment"]; + pipelineDesc.colorAttachments[0].pixelFormat = MTLPixelFormatRGBA8Unorm; + id pipeline = [device newRenderPipelineStateWithDescriptor:pipelineDesc error:&error]; + require(pipeline != nil, error.localizedDescription.UTF8String); + + // 129 additive red fragments, each contributing exactly one 8-bit step. + // A hardcoded 32-fragment limit fails the 8/64/128 cases. + struct Pixel { uint32_t color; float depth; uint32_t seq, next; } pixels[129]; + for (unsigned i = 0; i < 129; ++i) + pixels[i] = { 0x01000000, i / 129.f, 0, i == 128 ? UINT32_MAX : i + 1 }; + uint32_t head = 0; + int32_t poly[2] { (1 << 29) | (1 << 26), -1 }; // ONE + ONE + struct alignas(16) Uniforms { + uint32_t width = 1, height = 1, count = 129; + float shade = 1; + float dither[4] { 1, 1, 1, 1 }; + uint32_t applyDither = 0; + } uniforms; + static_assert(sizeof(Uniforms) == 48); + id pixelBuffer = [device newBufferWithBytes:pixels length:sizeof(pixels) options:MTLResourceStorageModeShared]; + id headBuffer = [device newBufferWithBytes:&head length:sizeof(head) options:MTLResourceStorageModeShared]; + id polyBuffer = [device newBufferWithBytes:poly length:sizeof(poly) options:MTLResourceStorageModeShared]; + MTLTextureDescriptor *textureDesc = [MTLTextureDescriptor texture2DDescriptorWithPixelFormat:MTLPixelFormatRGBA8Unorm width:1 height:1 mipmapped:NO]; + textureDesc.storageMode = MTLStorageModeManaged; + textureDesc.usage = MTLTextureUsageShaderRead | MTLTextureUsageRenderTarget; + id background = [device newTextureWithDescriptor:textureDesc]; + id output = [device newTextureWithDescriptor:textureDesc]; + uint32_t black = 0; + [background replaceRegion:MTLRegionMake2D(0, 0, 1, 1) mipmapLevel:0 withBytes:&black bytesPerRow:4]; + MTLRenderPassDescriptor *pass = [MTLRenderPassDescriptor renderPassDescriptor]; + pass.colorAttachments[0].texture = output; + pass.colorAttachments[0].loadAction = MTLLoadActionDontCare; + pass.colorAttachments[0].storeAction = MTLStoreActionStore; + id commands = [queue commandBuffer]; + id encoder = [commands renderCommandEncoderWithDescriptor:pass]; + [encoder setRenderPipelineState:pipeline]; + [encoder setFragmentBuffer:pixelBuffer offset:0 atIndex:1]; + [encoder setFragmentBuffer:headBuffer offset:0 atIndex:2]; + [encoder setFragmentBytes:&uniforms length:sizeof(uniforms) atIndex:3]; + [encoder setFragmentBuffer:polyBuffer offset:0 atIndex:4]; + [encoder setFragmentTexture:background atIndex:0]; + [encoder drawPrimitives:MTLPrimitiveTypeTriangle vertexStart:0 vertexCount:3]; + [encoder endEncoding]; + id blit = [commands blitCommandEncoder]; + [blit synchronizeResource:output]; + [blit endEncoding]; + [commands commit]; + [commands waitUntilCompleted]; + require(commands.status == MTLCommandBufferStatusCompleted, commands.error.localizedDescription.UTF8String); + uint8_t rgba[4]; + [output getBytes:rgba bytesPerRow:4 fromRegion:MTLRegionMake2D(0, 0, 1, 1) mipmapLevel:0]; + printf("layers=%u rasterOrder=%d red=%u\n", layers, rasterOrder, rgba[0]); + require(rgba[0] == layers && rgba[1] == 0 && rgba[2] == 0, "Incorrect fragment limit"); + } + } + } +} + +int main() +{ + @autoreleasepool { + NSArray> *devices = MTLCopyAllDevices(); + require(devices.count != 0, "No Metal device"); + for (id device in devices) + testDevice(device); + } +} diff --git a/tests/metal/texture_storage.mm b/tests/metal/texture_storage.mm new file mode 100644 index 0000000000..677350f1bb --- /dev/null +++ b/tests/metal/texture_storage.mm @@ -0,0 +1,62 @@ +// clang++ -std=c++17 -fobjc-arc -framework Metal -framework Foundation \ +// tests/metal/texture_storage.mm -o /tmp/texture_storage +// MTL_DEBUG_LAYER=1 /tmp/texture_storage +#include "../../core/rend/metal/metal_texture_utils.h" +#include +#include + +static void require(bool ok, const char *message) +{ + if (!ok) { + fprintf(stderr, "%s\n", message); + exit(1); + } +} + +int main() +{ + @autoreleasepool { + NSArray> *devices = MTLCopyAllDevices(); + require(devices.count != 0, "No Metal device"); + for (id device in devices) + { + MTLTextureDescriptor *desc = [MTLTextureDescriptor texture2DDescriptorWithPixelFormat:MTLPixelFormatRGBA8Unorm + width:4 height:4 mipmapped:NO]; + desc.storageMode = metalCpuTextureStorageMode(device); + desc.usage = MTLTextureUsageShaderRead; + id source = [device newTextureWithDescriptor:desc]; + desc.usage |= MTLTextureUsageRenderTarget; + id target = [device newTextureWithDescriptor:desc]; + require(source != nil && target != nil, "Texture allocation failed"); + uint32_t pixels[16]; + for (uint32_t& pixel : pixels) + pixel = 0xff332211; + [source replaceRegion:MTLRegionMake2D(0, 0, 4, 4) mipmapLevel:0 withBytes:pixels bytesPerRow:16]; + + id queue = [device newCommandQueue]; + id commands = [queue commandBuffer]; + MTLRenderPassDescriptor *pass = [MTLRenderPassDescriptor renderPassDescriptor]; + pass.colorAttachments[0].texture = target; + pass.colorAttachments[0].loadAction = MTLLoadActionClear; + pass.colorAttachments[0].storeAction = MTLStoreActionStore; + pass.colorAttachments[0].clearColor = MTLClearColorMake(0, 1, 0, 1); + id render = [commands renderCommandEncoderWithDescriptor:pass]; + [render endEncoding]; + id blit = [commands blitCommandEncoder]; + [blit copyFromTexture:source sourceSlice:0 sourceLevel:0 sourceOrigin:MTLOriginMake(0, 0, 0) + sourceSize:MTLSizeMake(4, 4, 1) toTexture:target destinationSlice:0 destinationLevel:0 + destinationOrigin:MTLOriginMake(0, 0, 0)]; + [blit endEncoding]; + metalSynchronizeTextureForCpu(commands, target); + [commands commit]; + [commands waitUntilCompleted]; + require(commands.status == MTLCommandBufferStatusCompleted, "GPU copy failed"); + uint32_t actual[16] {}; + [target getBytes:actual bytesPerRow:16 fromRegion:MTLRegionMake2D(0, 0, 4, 4) mipmapLevel:0]; + for (uint32_t pixel : actual) + require(pixel == 0xff332211, "CPU readback did not match uploaded pixels"); + printf("GPU: %s storage=%lu packed16=%d upload/render/copy/readback passed\n", + device.name.UTF8String, (unsigned long)desc.storageMode, metalSupportsPacked16BitFormats(device)); + } + } +}