Repository navigation
Metal renderer for macOS - #2563
Conversation
Based on Isaac Marovitz's Metal backend draft, flyinghead#1787. Adds the RenderType::Metal renderer type and the USE_METAL build option (on by default for macOS, forced off for iOS and libretro), creates the Metal graphics context from initRenderApi with an OpenGL fallback, and adds a Metal choice to the video settings. The duplicate frames option and the About page also handle Metal. The switcher is compiled as Objective-C++ when Metal is enabled because the Metal context header uses Objective-C types. The SDL display metrics use SDL_Metal_GetDrawableSize for Metal windows. mainui maps renderer types to graphics APIs with a helper so that switching to or from Metal recreates the graphics context. Adds the Dear ImGui Metal backend. It is the upstream v1.92.8 file without the platform_io DrawCallback_* registrations, which the vendored imgui 1.92.6 does not have. The USE_METAL compile definition and the Metal sources are added with the renderer in the next commit; until then this code is compiled out. Also fixes two problems that kept the standalone macOS app from building with a non-Xcode generator: - ZLIB_LIBRARY is set to "-lz" for the Xcode generator. With Ninja the ZLIB::ZLIB imported target then lists "-lz" as a file dependency of the final link, which fails with "no known rule to make it". Only set it for the Xcode generator. - Syphon declares its prefix header with target_precompile_headers PUBLIC, so it propagates to flycast. flycast then gets a C++-only precompiled header, and every .mm file fails with "Objective-C was disabled in precompiled file". Clear Syphon's interface precompiled headers; the prefix header is only meant for Syphon's own sources. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Native Metal renderer for the macOS SDL build, selectable as "Metal" in the video settings. It follows the Vulkan renderer's structure: a Metal graphics context that presents through the SDL window's CAMetalLayer, screen and render-to-texture drawers, a pipeline and depth/stencil state cache, a texture cache, and the Dear ImGui Metal backend for the UI. Shaders are MSL compiled at runtime and specialised with function constants, like the Vulkan shader variants. Framebuffer emulation and render-to-texture readback write back to VRAM. With threaded rendering, Render() waits for the GPU before returning, so the SH4 thread is not released on RENDER_DONE while the frame is still being drawn. GPU waits are bounded (200ms) so a missing completion signal drops a frame instead of hanging the render and SH4 threads. Only a wait that actually timed out quarantines the frame; the command buffer status switches to Completed slightly after the shared event fires, so checking it after a successful wait would quarantine most render-to-texture frames. macOS specifics: constant buffer offsets are 256-byte aligned, the packed 16-bit texture formats are expanded to RGBA8 on GPUs that don't support them (anything that isn't an Apple GPU), and the context refuses to start before macOS 12 (MTLSharedEvent timed waits), so initRenderApi falls back to OpenGL there. Apple's MacTypes.h and QuickDraw headers declare global Rect and RGBColor types that clash with flycast's. metal_apple.h imports the Apple frameworks with those names renamed and is included first by every Metal header. Resource lifetime: buffers and textures are released by dropping the last reference. Command buffers retain what they reference, so memory is freed once the GPU is done with it; resources are not set to MTLPurgeableStateEmpty first, which the Metal validation layer rejects while a command buffer still uses them. ImGui setup reads the attachment pixel format from a 1x1 texture instead of holding one of the layer's drawables, and the swap chain color space reference is released. Not implemented yet: video routing (Syphon). The VMU and crosshair overlay is added in a later commit. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Port of the Vulkan OIT renderer, selected with Metal + Per Pixel
transparent sorting (RenderType::Metal_OIT). Translucent fragments are
appended to per-pixel linked lists in a collect pass, then sorted and
blended over the opaque background in a resolve pass. Translucent
modifier volumes and two-volume polygons are supported.
The TA parser treats Metal_OIT as per-pixel, like the other OIT
renderers, so translucent polygons are not sorted per triangle.
The opaque background is copied to a texture between the collect and
resolve encoders instead of being read with [[color(0)]] framebuffer
fetch, which not every Metal implementation supports. The collect and
resolve passes use separate render encoders because Metal does not
order device-memory atomics against later draws in the same encoder.
The OIT frame is waited on before presenting: the renderer's command
pool and the context's present path use different command queues, which
Metal does not order, and without the wait the present could sample the
color attachment before the resolve finished.
Collect fragments are depth-tested in the shader before they are
appended. fs_main writes [[depth(any)]], so the hardware depth test runs
after the fragment function, when the a-buffer append (device atomics)
has already happened; relying on it let translucent geometry behind
opaque surfaces be collected and blended on top. As in the Vulkan OIT
shaders ("Manual depth testing"), the collect discards fragments that
fail GEqual against the opaque depth:
- On Apple GPUs (MTLGPUFamilyApple2 or later: programmable blending and
memoryless render targets), the OIT pass has a second colour
attachment, R32Float and memoryless, that the OP/PT pipelines write
their fragment depth to; the collect reads it with [[color(1)]]
framebuffer fetch. Every pipeline in that encoder declares the
attachment (writeMask None where it must not write) and the resolve
encoder detaches it. Passes after the first seed it with a full-screen
draw from a depth copy blitted before the encoder opens.
- Elsewhere (Intel/AMD Macs), the encoder is ended after the OP/PT
draws, the depth attachment is blitted to a sampled copy, and the
collect reads that copy.
Two-volume translucent collects (stencil areas 1/2) use an
[[early_fragment_tests]] entry point with a depth-Always,
stencil-area-test state, so the stencil test runs before the append;
depth is still tested in the shader.
The translucent modifier volume marks, their inclusion/exclusion sums
and the resolve run in one render encoder and access the shaded pixel's
a-buffer list. Where Vulkan uses two by-region fragment-to-fragment
barriers, the shaders put the pixel buffer and head pointers in raster
order group 0 when the GPU supports raster order groups. Otherwise the
encoder uses a fragment memory barrier on Intel/AMD GPUs, where it is
valid, or is ended and reopened at each ordering point.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Port of VulkanOverlay. The overlay is drawn by the Metal context after the frame and before ImGui, so both Metal renderers get it. A VMU texture is recreated when its screen changes rather than updated in place, since a frame still in flight may be sampling it. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
With rend.EmulateFramebuffer on, Present() shows the frame read back from VRAM (presentFramebuffer), but MetalOITScreenDrawer::EndFrame never wrote the rendered frame there, so the per-pixel renderer presented black frames. The regular Metal renderer was fine. Do what Vulkan's OITScreenDrawer::EndFrame does: when emulating the framebuffer, call scaleAndWriteFramebuffer on the attachment just rendered, before the ping-pong index advances. scaleAndWriteFramebuffer and its cached readback textures move from MetalScreenDrawer to MetalBaseDrawer (Vulkan keeps it on BaseDrawer) so both screen drawers share it. The copies are now also bounded by the source texture, since the OIT attachments are sized from the drawer viewport rather than globClip. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
OITMetalRenderer::Render never called resize(), so the OIT screen drawer kept BaseMetalRenderer's 640x480 default viewport. Per-pixel mode ignored rend.Resolution, and under EmulateFramebuffer a PVR framebuffer that isn't 640x480 was rendered into 640x480. Port OITVulkanRenderer::resize: Render() resizes to framebufferWidth/Height, and the override grows the a-buffer (one head pointer per pixel) and re-inits the screen drawer. The screen drawer's attachments only ever grew, but it presents and reads back the whole color attachment, so a smaller viewport now drops them and MakeBuffers reallocates them at the exact size. MakeBuffers grows the shared OIT buffers before its early return, like Vulkan OITDrawer::MakeBuffers, and the first-frame head-pointer clear covers the whole buffer instead of the current pass's w*h. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Publish the presented image to Syphon with the Metal renderers, like the OpenGL and Vulkan renderers do on macOS. MetalContext::EndFrame hands the drawable texture, after the frame, the overlays and the UI are drawn, to os_VideoRoutingPublishFrameTexture() on the frame's command buffer. The macOS shell implements it with a SyphonMetalServer, shared with the Vulkan renderer, and recreates the server if the Metal device changes. The image is published flipped, which gives clients the same orientation as the OpenGL renderer. "Scale down before sending" renders the image into a texture of the requested size with linear filtering before publishing it, as the OpenGL renderer does with glBlitFramebuffer. The server is stopped when the option is turned off and when the renderer or the context is terminated. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Add a CMake option, USE_METALFX (off by default), that builds the Metal renderer with MetalFX spatial upscaling, and a setting, rend.MetalFXUpscale (off by default), that turns it on. It upscales the rendered frame to its on-screen size with the MetalFX spatial scaler instead of the bilinear/nearest present, and is meant to be used with a low internal resolution. The scaler runs in MetalContext::PresentFrame, in the frame's command buffer before the present render pass, so it covers the per-triangle and per-pixel renderers and the framebuffer path. Render-to-texture passes are not affected. The output size is the aspect-fitted frame rectangle in whole pixels (swapped when the frame is rotated) and the result is drawn 1:1. The scaler is recreated when the input format, input size or output size changes, which covers window resizes and internal resolution changes. Duplicated frames and PresentLastFrame reuse the last upscaled texture. Screenshots and savestate thumbnails still use the original frame. MetalFX needs macOS 13 and a supported GPU (MTLFXSpatialScalerDescriptor supportsDevice:). The framework is weak linked and every use is behind @available, so the renderer still runs on macOS 12. When MetalFX is unsupported, the scaler can't be created, the frame is tiny (such as the 1x1 border color frame shown when video output is disabled) or the output isn't larger than the input, the frame is presented as before. The setting is shown in the video settings when the Metal API is selected. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2df4c2e to
667999a
Compare
I’d prefer to move MetalFX upscaling into a separate PR and keep this one focused on the Metal renderer. I’ve been testing different internal resolutions and still haven’t found a setting where I’d want MetalFX enabled. In my previous test, an M1 Max Mac Studio ran Flycast smoothly at 7200p (15×) with the widescreen cheat, and only started dropping frames at 8640p (18×). So for desktop class Apple Silicon, I’d just render at a higher resolution. There may be more value on iOS? There’s also a real chance upscaling gets rejected upstream. @flyinghead removed xBR texture upscaling because users enabled it for 3D games, adding a lot of processing for little benefit when it was better suited to 2D artwork. MetalFX could raise a similar concern if users enable it assuming it always improves the image. A separate PR would give us room to establish useful settings and measurable benefits. Temporal antialiasing and upscaling would also be worth exploring there, though I understand that’s considerably more work. |
|
@vkedwardli this is S-Tier review, thanks a ton! The issues on macOS aren't so suprising, I've tested the heck out of this across iOS and tvOS chips but less so on mac, especially the Intel chips. I have a few legacy systems around so I'll send jobs over to validate these issues. I agree, metalfx should be pulled out and up to @flyinghead if wanting to keep. In my limited experience, it does a bit more than just upscaling, like the BIOS boot alone has a crisper more modern look. Purists will hate that obviously, and usually I would too, but something about the DC rendering, the look and feel was really ahead of it's time and some of these games actually look realllllly nice with MetalFX on, even if already upscaled to 1080p. Maybe an "advanced" user option as I have it in iFly alphas. I may have to wait a bit to get to these fixes since I have to fix my Intel machines after not booting them for a while and not having the required tooling installed. |
Retire each upload through the command pool and share the presentation queue. Fix teardown ordering, Naomi 2 buffer strides and modifier-volume uniforms, RTT source selection, framebuffer scaling and delayed OIT renders. Honor custom textures, integer scaling, video shift and the OIT layer limit; initialize a valid viewport depth range and report driver version information. macOS arm64 build links. The Metal validation regression test resolves exactly 8/32/64/128 fragments under both ordering variants on an M2 Max; the original shader fails the 8-layer case. Intel runtime validation remains pending. Co-Authored-By: Codex <codex@openai.com>
Keep the renderer PR focused on Metal rendering. Preserve integer scaling and video shift; retain MetalFX separately for follow-up evaluation. Co-Authored-By: Codex <codex@openai.com>
Use managed CPU-visible textures on Mac GPU families that reject shared textures, and synchronize RTT writes before CPU readback. Keep shared storage on Apple GPUs and choose packed-format support at runtime. Keep the Intel macOS maximum page size constant even when Mach headers define PAGE_SIZE as vm_page_size. Exercise every detected GPU in the OIT layer-limit test and add upload/render/copy/readback coverage. Validated with Metal API validation on Intel UHD 630 and Radeon Pro 5600M: OIT limits 8/32/64/128 with both ordering specializations, texture readback, and eight BIOS boot/reload/capture/shutdown runs across regular, per-strip, OIT and framebuffer-emulation configurations. Apple M2 Max storage and OIT regressions also pass. Hardware runtime checks used macOS 26.5.2, not 12. Co-Authored-By: Codex <noreply@openai.com>
MSL rounds FragmentShaderUniforms to 96 bytes because its float4 members require 16-byte alignment. The CPU struct was only 88 bytes, so a final packed uniform block could end eight bytes before the shader argument. Metal validation aborts when entering THPS2's Hangar on Radeon Pro 5600M. Align the shared CPU uniform struct to 16 bytes and assert its size. This fixes both regular and per-pixel uploads without changing field offsets. Validated THPS2 Hangar gameplay, shadows and RTT-to-VRAM copying with Metal API validation on Intel UHD 630 and Radeon Pro 5600M, in regular and per-pixel modes on macOS 26.7.2. Co-Authored-By: Codex <noreply@openai.com>
Unthreaded Maple input polls SDL events from the emulation call stack. Opening a file there unloads the active game and starts asynchronous loading while the old DMA code is still running. This can corrupt DMA state and crash across game changes with both OpenGL and Metal. Keep the first pending file path and consume it in mainui_rend_frame after input polling. Apply this to drop events and native file-open requests, and discard pending paths when the SDL input subsystem shuts down. Tested native x86_64 game switching between SA2, THPS2 and Beach Spikers with Metal API validation and an OpenGL regression run. Co-Authored-By: Codex <noreply@openai.com>
|
Following up on the MetalFX scope comment: removed MetalFX from this PR in a74c562. The implementation is preserved for a separate follow-up; no separate PR has been opened yet. This submission now focuses on the native Metal renderer. Any later upscaling proposal will need its own image-quality/performance evidence and discussion of useful settings. |
|
Following up on the Intel/macOS, Syphon and About report:
Hardware results: Intel UHD 630 and Radeon Pro 5600M. Eight BIOS smoke runs passed on macOS 26.5.2; subsequent game tests used 26.7.2, all with Those runs found two additional bugs, now fixed: the CPU fragment-uniform block was 88 bytes but the MSL argument requires 96 bytes; the CPU struct now has 16-byte alignment and a size assertion (07ab5b9), and unthreaded SDL game loading could reset state from inside Maple DMA (5ca6f58). Five short SA2 → THPS2 → Beach Spikers → SA2 lifecycle sequences now pass, covering Intel/AMD Metal, an OpenGL regression, threaded/unthreaded rendering, and native file-open requests. All 20 CI checks pass at 5ca6f58. macOS 12 and Radeon Pro 5500M remain untested here; these results do not establish compatibility with the original older-driver combination. Specific pending checks are listed in the PR description and individual thread replies. |
|
I will get to this shortly. Sorry for the delay. I'm in the process of releasing iCube and iFly and grinding on dozens of tickets there. Need the mental bandwidth to properly do this one. Maybe next weekend. |
Every drawer owned a MetalShaders for the framebuffer-emulation scaler, and its constructor compiles all the shader libraries: two extra sets in regular mode and four in per-pixel mode, even with framebuffer emulation off, and the RTT drawers never scale. The screen drawers already receive the renderer's shader manager in Init(); the scaler uses that one. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Both geometry uploaders use GetMainBuffer() and quads use setVertexBytes, so MetalRingBuffer, MetalBufferPacker::uploadToBuffer() and MetalQuadBuffer have no callers. The ring constructor also allocated with the unaligned slice size while stepping by the aligned one. The regular screen drawer always rendered to image 0 of single-element vectors. It now holds one color attachment and one pair of pass descriptors, and releases its attachments in one place. The texture drawer's framebuffer vector was never used. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
MakeBuffers() created two color and two depth textures at the internal resolution for both per-pixel drawers. The screen drawer only renders to and presents slot 0, and the RTT drawer renders into the texture's own color image and its own depth attachment, so it used neither pair. The screen drawer now owns a single color/depth pair and the RTT drawer allocates none. The shared a-buffer and resolve background are unchanged. The framebuffer index and its toggle are gone with the second slot. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
With threaded rendering and framebuffer emulation off, Render() left the screen encoder open until Present(). If the game rendered again before presenting (DelayFrameSwapping), the next Process() did its texture work on the same command buffer, and mipmap generation opens a blit encoder there while the render encoder is still active, which Metal forbids. Render() now always ends the pass. A repeated screen render starts a new pass that loads the color attachment, as the threaded path already did. The per-pixel renderer already ends its frame in Render(). Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Same change as 3a5267a for Vulkan and DirectX 11: the quad pipeline blended alpha with SourceAlpha, so the VMU and crosshair overlays left alpha below 1 in the frame sent to Syphon. Source alpha factor One keeps an opaque target opaque. Color blending is unchanged. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This reverts commit 5ca6f58. The change affects game loading on every SDL frontend regardless of the renderer, so it is submitted on its own. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
vkedwardli
left a comment
There was a problem hiding this comment.
@flyinghead Green light from me. This is ready to merge.
Thanks Joe, all of the second-round comments are addressed. Tested on macOS 12.7.6 with a Radeon Pro 5500M under MTL_DEBUG_LAYER=1: per-triangle and per-pixel, framebuffer emulation, unthreaded with Delay Frame Swapping, and render-to-texture in per-pixel mode all work, with no validation errors.


A native Metal renderer for the macOS SDL build, with per-triangle/per-strip sorting (
RenderType::Metal, rend=7) and per-pixel OIT (RenderType::Metal_OIT, rend=8). It picks up Isaac Marovitz's draft #1787 and targetsdev.Metal requires macOS 12. Older macOS versions show an explanation and fall back to OpenGL. CMake keeps Metal disabled for iOS and libretro in this submission. VMU screens, lightgun crosshairs, framebuffer emulation, resolution changes and Syphon output are included.
MetalFX has been removed from this PR and preserved for a separate follow-up.
Review fixes
GetMainBuffer(). Each upload gets exclusive storage, including multiple uploads in one command buffer. The command pool returns it only after completion; timed-out slots stay quarantined. Shutdown retains the existing bounded-wait policy and deliberately leaks still-busy holders rather than recycling their storage.ThreadedRendering. The regular screen drawer uses one persistent target instead of allocating three while always selecting slot zero. Quad vertices usesetVertexBytes, so subsequent quads cannot overwrite an earlier draw's vertices.clearFramebuffer. Each new OIT encoder invalidates its scissor cache.getWindowboxDimensions()andgetVideoShift().PerPixelLayerscontrols the resolve and translucent modifier-volume shader limits, clamped to 8–128. Changing it rebuilds the affected OIT library and pipelines.Intel/AMD hardware follow-up
PAGE_SIZEasvm_page_size. The maximum page size used by static layout checks is now constant on Intel macOS.Validation of the review revision
BIOS/storage/OIT regression baseline:
12e7e9d1399c917a396dbeae483f2fb9b21c94eb.MTL_DEBUG_LAYER=1: Intel UHD 630 and AMD Radeon Pro 5600M, each using per-triangle, per-strip with framebuffer emulation, OIT at 128 layers, and OIT with framebuffer emulation at 8 layers. Every run boots the BIOS twice, captures a nonblank frame throughGetLastFrame(), and exits cleanly. Threaded rendering is off in the triangle/128-layer cases and on in the framebuffer cases. A test-only library selects the GPU and requests boot/reload/capture/quit; renderer source is unchanged by the harness.tests/metal/texture_storage.mmpasses upload/render/copy/readback on Intel UHD 630 and Radeon Pro 5600M with managed storage, and on Apple M2 Max with shared storage.tests/metal/oit_layer_limit.mmpasses on Intel UHD 630, Radeon Pro 5600M and Apple M2 Max withMTL_DEBUG_LAYER=1. A 129-fragment linked list resolves exactly 8, 32, 64 and 128 contributions, with raster-order groups both disabled and enabled. The original shader fails the 8-layer test, returning 32.Game-content follow-up
Revision:
07ab5b955c12ad0005ac95b5009a2c8414cf088b. Native x86_64 standalone on macOS 26.7.2, Intel UHD 630 and Radeon Pro 5600M, withMTL_DEBUG_LAYER=1.Entering THPS2's Hangar exposed an additional validation abort: the CPU fragment-uniform block was 88 bytes, while MSL requires 96 bytes due to its float4 alignment. The shared CPU struct now has 16-byte alignment and a compile-time size assertion. The failing scene passes after the fix.
Game-switch follow-up
Actual-game switching exposed a separate SDL lifecycle bug that also reproduces with OpenGL: in unthreaded mode, Maple DMA polls SDL input, and handling a file drop there unloaded the game and started loading the next one while the old DMA call stack was still active.
That fix is no longer part of this PR. It changes game loading for every SDL frontend, so it was reverted here (
e5efd6321) and submitted separately as #2649. Until #2649 is merged, switching games by file drop or native file-open with threaded rendering off can still crash on this branch, with any renderer, as it does ondev.The switching runs below were made at
5ca6f58c2, with the SDL fix still included:Second review round
Revision:
e5efd632142d374d32c54cf94f9f7c65b4fd82a0.d8956ef4a).MetalRingBuffer,MetalBufferPacker::uploadToBuffer()andMetalQuadBufferare removed. The regular screen drawer holds a single target instead of single-element vectors (96854524d).f49b2c149).Render()always ends the screen render pass, so no render encoder is open when the nextProcess()generates mipmaps on the same command buffer (344f34c42).One, keeping routed (Syphon) frames opaque under overlays, as in Fix dark Spout/Syphon video output by keeping routed frames opaque #2606 (9d826d8a0).249693009).Checked on Apple M2 Max, arm64 standalone build, with
MTL_DEBUG_LAYER=1: Crazy Taxi for 40–45 seconds in regular and per-pixel mode, threaded and unthreaded, with and without framebuffer emulation, and with Delay Frame Swapping on in the unthreaded runs. No validation errors; the frame was inspected in the two unthreaded runs without framebuffer emulation. That scene is mostly 2D with no RTT. The open-encoder case was fixed from the code path and not reproduced first, and the alpha change was not checked against a Syphon receiver. The Intel/AMD runs above have not been repeated on this revision.Earlier Apple-silicon framebuffer/resolution/Syphon checks have not been repeated for this revision. The reviewer confirmed Syphon reception in OBS on an earlier revision.
Pending validation
Original implementation prepared with Claude Code; review corrections prepared with Codex.