Skip to content

Add Metal Renderer and native macOS/iOS support for TIC-80 - #2973

Merged
nesbox merged 2 commits into
nesbox:mainfrom
Wang-Yue:pr/apple-metal-backend
Sep 19, 2026
Merged

nesbox merged 2 commits into
nesbox:mainfrom
Wang-Yue:pr/apple-metal-backend

Conversation

@Wang-Yue

Copy link
Copy Markdown
Contributor

This commit introduces native macOS and iOS support using Metal, AVAudioEngine, GCController.

@joshgoebel

Copy link
Copy Markdown
Collaborator

Can you elaborate a bit more on what this supports... does it support zoom factors, background border, etc? Haven't had a change to compile it yet for a look-see.

What is the big advantage over SDL (on Mac OS)? Are you hoping to revive the iOS port?

Comment thread src/studio/system.h Resolved
rightChannel?[writeIdx + i] = sampleR
}
} else {
for i in 0..<samplesToCopy {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Think we could use memset here, yes?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Mentioned in the above comment that this is not the main bottleneck

Comment on lines +51 to +57
for i in 0..<samplesToCopy {
let sampleL = Float(samplesBuffer[(self.bufferReadIdx + i) * 2]) / 32768.0
let sampleR = Float(samplesBuffer[(self.bufferReadIdx + i) * 2 + 1]) / 32768.0

leftChannel[writeIdx + i] = sampleL
rightChannel?[writeIdx + i] = sampleR
}

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

AI suggestion:

I’d also consider replacing the per-sample copy loop (lines 51–57) with an interleaved→planar bulk conversion (e.g., vDSP) later,

Do you understand the suggestion? I did imagine there would be a more optimize way to do this transfer, and sounds like there is.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I am specialized in audio programming (see for instance my previous project https://github.com/Wang-Yue/cdsp). vDSP is only tremendously better when doing bulk conversion for thousands of samples. In this paticular case if we pull every frame, we only get 44100/60 = 735 samples. vDSP performs badly when you have small chunk size, as there are cost calling vDSP functions --- they are not inline functions. Also the code here and below is not the major concern unless we

  1. solve the main bottleneck, which is the software renderer.
  2. add api to start/stop audio, as currently we are still draining battery when there's nothing playing.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Makes sense. I'll take your word for it. :-)

as currently we are still draining battery when there's nothing playing.

Sounds like something worth investigating one day in a future PR maybe. (after other things as you mention)

Comment thread src/system/apple/AudioEngine.swift Resolved
Comment thread src/system/apple/GamepadManager.swift Resolved
Comment thread src/system/apple/MetalRenderer.swift Resolved
Comment thread README.md Resolved
Comment thread README.md Resolved
Comment thread src/system/apple/main.swift Resolved
Comment thread src/system/apple/main.swift Resolved
}

func windowWillClose(_ notification: Notification) {
NSApp.terminate(nil)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this a final notice or something we could interact with? Remember sometimes we might have editor changes we need to save.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No. SDL backend also don't check this. I just tried, no final notice or anything.
I also don't think TIC-80 expose functions that let us check if editor have changes.

@joshgoebel

Copy link
Copy Markdown
Collaborator

I did my best to review this a bit. Looks pretty awesome though overall (the functionality - getting this back in core)...

@joshgoebel

Copy link
Copy Markdown
Collaborator

how does loading/saving cartridges on IOS work? Do you use Files top drop source/carts into a folder TIC-80 can access or?

@Wang-Yue

Copy link
Copy Markdown
Contributor Author

I did my best to review this a bit. Looks pretty awesome though overall (the functionality - getting this back in core)...

Thank you for the detailed review!

how does loading/saving cartridges on IOS work? Do you use Files top drop source/carts into a folder TIC-80 can access or?

as mentioned above, there are still many functionalities I have not implemented/tested, and while I was playing on iPads myself, I already found a few bugs. mac app feels far more ready than iOS, btw. so I am constantly fixing them in my main branch. Once the PR is accepted I will send those incremental fixes to here. I also believe when the users test this on their apple device they will notice bugs I didn't notice, as they may have a different usage pattern compared to mine.

So I can address bugs/missing features in later PRs for incremental fixes whenever I have time. Or other interested party may contribute their PRs. It's impossible for me to get to close to 100% ready in the first PR. The good thing is we now have the full app running on iPhone and iPad, and playing games work end to end. so iterative improvements become possible now.

@Wang-Yue

Wang-Yue commented Jul 28, 2026 •

Copy link
Copy Markdown
Contributor Author

Can you elaborate a bit more on what this supports... does it support zoom factors, background border, etc? Haven't had a change to compile it yet for a look-see.

zoom --- yes.
background border --- yes.

On a mac I think we support almost everything SDL supports. iOS is less ready than Mac. iOS window cannot be set with fixed aspect ratio, so I do have commits to draw the background border as well (https://github.com/Wang-Yue/TIC-80/commit/c7027c2f9510587a93ba102f865025e795ae939b) when it's rendered in a window. I can send those incremental improvements later when this PR is merged.

What is the big advantage over SDL (on Mac OS)?

Higher performance for both audio and graphics. Cleaner callbacks.

Here's TIC-80 running the supernova game (60fps 3D car race) profile:

SDL:
Screenshot 2026-07-28 at 12 02 28

Metal:
Screenshot 2026-07-28 at 12 03 18

You can see in the SDL case only 70% of the run time is leaving for TIC-80's studio_tick (user program and software rendering), while for the metal case, it's > 85%. If you do the math, you'll find Metal + AVAudioEngine is half of the overhead compared to SDL (30/15*85/70 = 2.4x faster).

For close to static screens, things are even more extraordinary. This is TIC-80's music editor when music is not playing:

Screenshot 2026-07-28 at 12 20 48

You see SDL is very busy and takes 55% of the run time

Screenshot 2026-07-28 at 12 26 57

with the help of the draw cache, our new backend spend most time doing _platform_memcmp, then find all of them hit the cache, and all the rendering functions become no-op. CPU is almost idle in this case. This is super crucial for mobile and low powered devices.

I also want to add that the biggest _platform_memcmp on the right (around 23% of the running time) can be eliminated once TIC-80 decide to accept my draw cache patch. This PR is written with even draw cache not being accepted in mind, so we still compare final buffer every single frame when shipping rendered buffer to GPU. With Draw Cache PR accepted, we will know without memcmp if the buffer is dirty or not, and fully eliminate the 23% memcmp time, saving even more CPU cycles.

Are you hoping to revive the iOS port?

Yes. Before working on this port I spent a long time to fix the SDL port for iOS, but even after a lot of work, it's still almost not usable --- Existing user interface is very buggy, and it is running very slow. At this stage, I believe starting from scratch is much easier than fixing that port. So I did it.

@joshgoebel

Copy link
Copy Markdown
Collaborator

@nesbox I'm not sure how you want to merge/release this, but this looks pretty awesome to me. Obviously would be room for you to make an official iOS release in the app store in the future as well if you were so interested... this looks like a pretty solid foundation for that.

@Wang-Yue

Wang-Yue commented Sep 18, 2026 •

Copy link
Copy Markdown
Contributor Author

Merged pr/skip-clean-screen-blit and pr/draw-cache here, as they provide API to indicate if the buffer is updated or not, which is used to skip rendering for metal backend, instead of using memcmp.

NOTE: #2974 is not merged in this as that is an independent change. To test performance please also merge that which will benefit CPU utilization in code mode.

@nesbox

nesbox commented Sep 19, 2026

Copy link
Copy Markdown
Owner

Thanks for folding the two branches in — that makes this the single thread for the mechanism, and #3003 and #2975 are now closed into it.

On the cache itself: all three points raised on #2975 are addressed here, which I checked in the tree rather than the description — has_scn/has_bdr replace the source-text strstr, the skip only runs when the cart defines neither callback, and the cache has an off switch.

On the Apple backend, the direction is: no iOS plans, and it stays a build-it-yourself path rather than a platform we ship. Three things before this can merge:

  • a rebase, the branch conflicts with main;
  • -DBUILD_APPLE=ON added to one of the macOS jobs already in the matrix (macos-arm64 on macos-14, or macos on macos-15-intel). No new runner is needed — CI cannot run the shell, only compile it, and compiling is what catches it rotting under later changes to core.c;
  • build instructions in the repository, so someone can reproduce the build.

And the rendering optimisation wants to sit behind one build flag. Merging this must not change behaviour for anyone: the default build stays exactly as it is today, and whoever wants the optimisation builds it in.

  • BUILD_RENDER_CACHE, a CMake option, off by default;
  • with it off, nothing of the optimisation is compiled in — no draw cache, no skip;
  • with -DBUILD_RENDER_CACHE=ON, all of it arrives together.

Today only half of it is gated, and that is the part to fix: drawCache is a runtime config option that ships as true and covers only the API-hook side, while the vram memcmp check in tic_core_blit_ex runs unconditionally.

- Add native Apple Metal backend for macOS with Swift, Metal, AppKit, AVFoundation, and GameController
- Gate draw cache and clean screen skip rendering optimizations behind CMake option BUILD_RENDER_CACHE (OFF by default)
- Add -DBUILD_APPLE=ON compile check to macOS CI matrix in build.yml
- Add macOS Metal build instructions to README.md
- Optimize mouse cursor stationary CPU usage in Studio
@Wang-Yue
Wang-Yue force-pushed the pr/apple-metal-backend branch from 302057b to 68be9ca Compare September 19, 2026 12:29
@Wang-Yue

Copy link
Copy Markdown
Contributor Author

Thanks, PTAL.

@nesbox nesbox left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Requesting changes. The gating of the optimisation itself is complete and correct — config field, menu entry, the blit skip, all eight bindings — so the flag work is done properly. Three things, though, changed the default build with both flags off, and those have to come back behind the flags first: the condition is that merging changes behaviour for nobody.

Default path — before merge

  • studio.c:1467, :2323-2332, :2410-2413 — the cursor reordering is not under #if defined(BUILD_RENDER_CACHE), so it lands on every platform. Two consequences: vram.vars.cursor now lags a frame, because the tick runs before the sync where it used to run after; and the write goes through VBANK(tic, 0) while blitCursor reads the active bank, so a cart that leaves vbank(1) selected loses the studio cursor (bank 1 is {sprite=0, system=false} and blitCursor returns early). Dropping the VBANK wrapper and writing to the same ram->vram that blitCursor reads is the small fix.
  • cmake/core.cmake:48-50, CMakeLists.txt:7-9 — enable_language(OBJC) and fft.c as Objective-C are gated on APPLE, not on BUILD_APPLE. Every macOS build compiles src/ext/fft.c as ObjC, and since only CMAKE_C_FLAGS_RELEASE is set, the OBJC language misses the -O2 -flto its C siblings get. Nothing needs it: there is no .m/.mm in the tree, and Swift takes the bridging header through -import-objc-header.
  • sdl/main.c:560-562 — SDL_SetHint(SDL_HINT_RENDER_DRIVER, "metal") under __APPLE__ overrides the "opengl" hint set at :2090, switching shipped macOS SDL builds to Metal. The Apple backend does not compile this file at all, so the line buys this PR nothing.

The cache, with the flag on

  • A false "clean" freezes the screen: the cache verdict (core.c:673) returns before the vram memcmp (core.c:679), so a mutation through an API that is not hooked is invisible — function TIC() mset(1,1,t%16) map(0,0,30,17) end draws frame 1 forever.
  • cache_api_pix returns 0 to the cartridge on a cache hit (draw_cache.c:529) — cls(3) print(pix(0,0),0,0,12) prints 3 once and then zeroes.
  • map() with a remap function: unchecked malloc and a truncated size (draw_cache.c:749-782) overflow the buffer on map(0,0,100000,100000,0,0,nil,nil,1,function(t) return t end).
  • has_scn/has_bdr are never set by the wren, miniscript and forth bindings, so scanline/border effects can disappear for those languages.
  • The replay truncates print/font text at 511 characters (draw_cache.c:341-354).

Apple backend

  • main.swift:127-128 subtracts the letterbox a second time, so mouse() is off by (−16,−8) and the cursor cannot reach the left 8 / top 4 pixels.
  • AudioEngine.swift:42-53 copies the samples after releasing the lock; SDL holds its mutex across the whole copy.
  • The documented build (README:350, build.yml:712) omits -DBUILD_STATIC=ON, which is off by default on macOS — as written it links no script runtimes, so the binary cannot load a cartridge.

What would make this mergeable

  • the three default-path items fixed, or moved under the same flags;
  • -DBUILD_RENDER_CACHE=ON and -DBUILD_STATIC=ON added to the Apple CI step, so this code compiles somewhere — nothing in CI builds draw_cache.c today, which is why all of the above is green;
  • the cache defects above, at least the ones that produce a wrong picture rather than a slow one.

@Wang-Yue

Copy link
Copy Markdown
Contributor Author

Thank you so much @nesbox for the detail review! I made a commit to address your review comments. All requested changes have been addressed across the default path, render cache, and Apple backend. lemme know how to further improve this.

1. Default Path (Zero Behavioral Changes with Flags OFF)

  • Studio Cursor (studio.c): Restored direct synchronous writes to tic->ram->vram.vars.cursor inside setCursor() and processMouseStates(), eliminating the 1-frame cursor lag and avoiding VBANK(tic, 0) active-bank mismatches. Cursor tracking for cache invalidation is now isolated strictly within #if defined(BUILD_RENDER_CACHE).
  • ObjC Language & Compiler Flags (CMakeLists.txt, cmake/core.cmake): Removed enable_language(OBJC) and the fft.c Objective-C language property so standard C compiler flags (-O2 -flto) apply uniformly.
  • Metal Driver Hint (src/system/sdl/main.c): Removed SDL_SetHint(SDL_HINT_RENDER_DRIVER, "metal").
  • Clean Separation: When -DBUILD_RENDER_CACHE=OFF, draw_cache.h is excluded and all cache/dirty APIs (studio_is_dirty, tic_core_is_dirty, etc.) are eliminated from the build path.

2. Cache Optimization Fixes (-DBUILD_RENDER_CACHE=ON)

  • False "Clean" Screen Fix (core.c, draw_cache.c): tic_core_blit_ex() now ensures blits are not skipped if VRAM was mutated. In addition, tic_core_draw_cache_end() checks RAM/VRAM mutations against the start-of-frame state, invalidating and replaying draw calls immediately if unhooked mutations (such as mset() or direct poke()) occurred during TIC().
  • cache_api_pix Getter (draw_cache.c): Fixed cache hit logic when get == true to read and return the actual pixel from VRAM instead of 0.
  • map() Remap Buffer Safety (draw_cache.c): Added 64-bit overflow and boundary checks on map dimensions, checked allocation failures, and enforced capacity bounds in remapInterceptor.
  • Hook Detection for has_scn/has_bdr: Implemented scanline/border callback detection in wren.c, miniscript.cpp, and forth.c.
  • Replay Text Length (draw_cache.c): Dynamically allocates text buffers in DRAW_CALL_PRINT and DRAW_CALL_FONT replay to support text longer than 511 characters.

3. Apple Backend

  • Mouse Coordinate Mapping (main.swift): Removed duplicate margin subtraction in mapMouseToFullCoords().
  • Audio Mutex Scope (AudioEngine.swift): audioLock is now held continuously across the entire sample buffer generation and copy loop, matching SDL's audioCallback.
  • Build Instructions & CI (README.md, .github/workflows/build.yml): Added -DBUILD_STATIC=ON and -DBUILD_RENDER_CACHE=ON to both the documentation and the macOS CI matrix step.

Verification

All configurations have been built and tested locally on macOS:

  1. Default SDL (-DBUILD_RENDER_CACHE=OFF): Compiles and runs cleanly.
  2. Render Cache SDL (-DBUILD_RENDER_CACHE=ON): Compiles and runs cleanly.
  3. Apple Metal (-DBUILD_APPLE=ON -DBUILD_STATIC=ON -DBUILD_RENDER_CACHE=OFF): Compiles and runs cleanly.
  4. Apple Metal (-DBUILD_APPLE=ON -DBUILD_STATIC=ON -DBUILD_RENDER_CACHE=ON): Compiles and runs cleanly.
  5. Regression Tests:
    • tests/fft.c & tests/vqt.c regression test suites pass.
    • Multi-language cartridges (luamark, wrenmark, forthmark, miniscriptmark, jsmark, pythonmark, rubymark, janetmark, schememark, squirrelmark, wasmmark, benchmark, fire, tetris) load and run cleanly under both cache modes.
    • Specific edge-case regression tests (cls(3); pix(0,0), long strings > 511 chars, and large map() calls) verified.

@nesbox
nesbox merged commit 2672714 into nesbox:main Sep 19, 2026
10 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants