TMC MacOS

tmc_macos is a native macOS port of The Minish Cap with keyboard and gamepad input, and high-quality audio mixing.

README

The Minish Cap: native macOS and iOS port

This is a fork of zeldaret/tmc, the decompilation of The Legend of Zelda: The Minish Cap. The decompilation project's own README, with the supported ROMs and its links, is README.OLD.md; setting up the repository for the GBA build is INSTALL.md.

The fork builds the decompiled game code natively for macOS (Apple silicon and Intel, macOS 12 or later): a Metal app with keyboard and gamepad input, plus a headless runner for automated testing. The same game core, renderer and sound also build as an iPhone and iPad app (iOS 16 or later; see iPhone and iPad). The GBA build in the repository root stays byte-matching: every port change is either under port/ or behind #ifdef PORT_HOSTED (hardware through port/hw.h, fixes for what only agbcc's code got right) or #ifdef PORT_LAYOUT_64 (this port's 64-bit data layout). The native build defines both, with PLATFORM_NATIVE; the DSi port (port/dsi/PLAN.md) only PORT_HOSTED.

No game data is in this repository. Building needs your own ROM of The Minish Cap (USA), and the shared app asks for one on first launch.

Setup

One-time machine setup. The native build reads the GBA build's data objects, so both toolchains are needed.

  1. Tools: Xcode Command Line Tools, CMake ≥ 3.24 and Python 3.

    brew install cmake python3
    
  2. ROM: place an original USA ROM (SHA1 b4bd50e4131b027c334547b4524e2dbbd4227130) at baserom.gba in the repository root. A symlink works and *.gba is gitignored:

    ln -s ~/tmc_usa.gba baserom.gba
    
  3. Host tools and assets: see Building below.

  4. GBA toolchain: arm-none-eabi-gcc and agbcc. agbcc is cloned next to this repository and installs into tools/agbcc; its install also leaves untracked tools/include/ and tools/lib/, which are not committed.

    brew install arm-none-eabi-gcc arm-none-eabi-binutils
    
    git clone https://github.com/pret/agbcc ../agbcc
    
    (cd ../agbcc && sh build.sh && sh install.sh ../tmc_macos)
    

    Replace ../tmc_macos with the path to this checkout if it lives elsewhere.

  5. Python packages: the GBA make needs pycparser, and the native data converter needs pyelftools and libclang. Homebrew's Python refuses global installs, so use the repository's .venv (gitignored):

    python3 -m venv .venv && .venv/bin/pip install -r port/requirements.txt
    

Building

Build the host tools and extract assets (CMake 4 needs the policy override for a bundled dependency; recent clang needs the warning relaxed):

CMAKE_POLICY_VERSION_MINIMUM=3.5 cmake -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX=tools -DCMAKE_CXX_FLAGS=-Wno-error=deprecated-literal-operator -S tools -B tools/cmake-build
cmake --build tools/cmake-build -j --target install

Build the GBA ROM. This also extracts the assets, and its objects and tmc.elf are the input to the native data converter. A matching build ends with tmc.gba: OK:

PATH="$PWD/.venv/bin:$PATH" make -j$(sysctl -n hw.ncpu)

Configure and build the native game. The first configure converts the game data (about a minute). Builds convert it again by themselves when datagen's code, hints.txt, tmc.elf or linker.ld is newer than the last conversion (so rebuild the GBA game first after changing game data); cmake --build build/native --target datagen forces a rerun:

cmake -S port -B build/native
cmake --build build/native -j

This builds three programs from the same game code:

  • build/native/The Minish Cap.app, the macOS app (see Playing).
  • build/native/tmc, the headless runner for automated runs (see below).
  • build/native/tmc-songs, the song exporter (see Exporting the music).

Build just one with --target tmc_app, --target tmc or --target tmc_songs. If the link ever breaks, cmake --build build/native --target link-report groups the unresolved symbols by where the GBA build defines them.

Development and distributable builds

The build above is a development build: the game's assets are built into the programs, so they run as they are, but they must not be shared. -DTMC_BAKE_DATA=OFF makes a distributable build without them; each program extracts them from the player's own ROM instead (see First launch). Use a separate build folder:

cmake -S port -B build/native-rom -DTMC_BAKE_DATA=OFF
cmake --build build/native-rom -j

What is left out is decided by where each byte comes from, not by whether it equals the ROM:

  • Assets are what asset extraction (tools/asset_processor, assets.json) copies out of baserom.gba into build/USA/assets, and the data sources .incbin: graphics, tilesets, palettes, maps, entity and room data blobs, sound samples and songs, text. They come from the player's ROM: 13.1 of the 13.8 MB of game data.
  • Everything written in the repository stays compiled in: the C code and its tables, data spelled out in data/*.s (.byte/.4byte lists and macros, about 670 KB), and the pointer tables datagen lays out. All of it is public in the decomp.

To find the assets' bytes, datagen assembles every data object twice more: once with each extracted asset file replaced by a file of the same size full of 0x55, once full of 0xaa. The bytes that differ are asset bytes (port/tools/datagen/provenance.py). Those become zeros plus a run each (native address, ROM offset, length), about 1,000 runs; every run is checked against tmc.gba. Building still needs the GBA build and its extracted assets. The programs are about 15 MB: the zeros take file space, because nearly every data section also holds source-written bytes. They compress to almost nothing.

To check that a program carries no asset content:

python3 port/scripts/asset_overlap.py "build/native-rom/The Minish Cap.app/Contents/MacOS/The Minish Cap" build/USA/assets

It lists every stretch of 64 bytes or more that the program shares with an extracted asset file, with the file and the program's symbol, and exits with 1 if there is one. A development build shares 12.7 MB. A distributable build shares 5 stretches, 710 bytes. These are source-written tables whose bytes also occur inside asset dumps: entity lists from data/map/entity_headers.s that the ROM holds again inside a blob, one equal to a USA-demo-only asset, and a C table in src/manager/diggingCaveEntranceManager.c.

In a development build with TMC_ROM=path set, tmc checks every run of the manifest against that ROM before it starts (built-in data: all 46923 manifest runs ... match the ROM).

Universal builds and a package to share

The programs run on macOS 12 and later (CMAKE_OSX_DEPLOYMENT_TARGET, which also sets the app's LSMinimumSystemVersion). Using anything newer than that is a build error (-Werror=unguarded-availability-new) unless it is behind an @available check. They build for this Mac's architecture unless CMAKE_OSX_ARCHITECTURES says otherwise; "arm64;x86_64" makes universal programs that also run on Intel Macs. Only Python runs during the build (datagen, the name tables), and datagen's output suits both architectures, since the native data layouts are the same.

A universal distributable app, zipped with its ad hoc signature intact and its read-me (port/dist/Read me first.txt), as build/TheMinishCap-1.2-macos-universal.zip (the version is the one in port/CMakeLists.txt):

port/scripts/package_macos.sh

By hand, without the read-me:

cmake -S port -B build/dist -DTMC_BAKE_DATA=OFF -DCMAKE_OSX_ARCHITECTURES="arm64;x86_64" -DCMAKE_BUILD_TYPE=Release
cmake --build build/dist -j4 && ditto -c -k --norsrc --noextattr --keepParent "build/dist/The Minish Cap.app" build/TMC-macos-universal.zip

Check it before sending it: lipo -archs and vtool -show-build on The Minish Cap.app/Contents/MacOS/The Minish Cap should say x86_64 arm64 and minos 12.0, and asset_overlap.py (above) the 5 known stretches.

What the person you send it to does on first launch:

  1. Unzip it and move The Minish Cap.app to Applications (or anywhere).
  2. Open it with right-click (or Control-click) → Open, then Open in the alert. It is signed ad hoc, not by an identified developer, so a double-click only says it cannot be checked. Recent macOS versions instead need System Settings → Privacy & Security → Open Anyway after the first try.
  3. Choose their own The Minish Cap (USA) ROM when asked (First launch). Its data goes to ~/Library/Application Support/tmc_macos; the app holds no game assets.

The x86_64 programs were checked under Rosetta 2 on Apple silicon: the 24000-frame playthrough's frame checksums and player trace, the Ezlo replay and the app self-test (TMC_SELFTEST) match the arm64 programs. Save states load across the two (by symbol), both ways, and carry on with the same frames. The audio mixer's samples differ in the last bit, as arm64 fuses multiply-adds and baseline x86_64 has no FMA instructions. Rosetta cannot show:

  • An Intel or AMD GPU. Under Rosetta the app draws on the Apple GPU. On those GPUs textures cannot use shared storage, so the renderer uses managed textures there and synchronizes them before reading them back. TMC_MANAGED_TEXTURES=1 takes that path on Apple silicon too, and the self-test passes with it, with the same shader buffer checksums. Drivers can still differ: the shaders (compiled at launch as Metal 2.4, the version macOS 12 has) and full-screen and display sync behaviour are untested on such a GPU.
  • macOS 12 itself. Only the compiler's availability checks stand for it.
  • Speed on an older Intel Mac, CPU or GPU.

Before 1.0 the universal app was played on a real Intel Mac with its own GPU: the Metal renderer (the GPU PPU included), the filters and the debug tools all worked as on Apple silicon. macOS 12 itself is still unchecked.

Playing
open "build/native/The Minish Cap.app"

The app runs the game at the GBA's 59.73 Hz (or, in display sync, once per display refresh: see Input latency) and shows it scaled by a whole number (or, with integer scaling off, as large as the 3:2 shape allows). Sound comes from the game's own m4a engine (see Sound). The Sound menu has Mute (⌥⌘M) and High-Quality Audio, which mixes at 48 kHz in floating point instead of the GBA's 15.7 kHz 8-bit mix; both are remembered.

KeyboardGBAGamepad
Arrow keysD-padD-pad or left stick
XAButton labelled A (Xbox A, PlayStation ✕, Nintendo A), or X
ZBButton labelled B (Xbox B, PlayStation ○, Nintendo B), or Y
A / SL / RShoulders or triggers
ReturnStartMenu
Backspace or \SelectOptions
Tab (hold)Fast-forward (4×)Right stick click

Keys are matched by position, so other keyboard layouts use the same physical keys. Any extended gamepad (Xbox, PlayStation, Switch Pro, MFi) works and can be connected or disconnected while the game runs. Settings → Controls → Gamepad A/B switches Xbox and PlayStation pads to the GBA's positions instead (right and top buttons = A, bottom and left = B); Nintendo pads already have A on the right, so they are the same either way.

Menu shortcuts: ⌘1–⌘6 pick the filter (nearest neighbour, sharp bilinear, smooth bilinear, LCD grid, CRT scanlines, soft subpixel), ⌘I toggles integer scaling, ⌃⌘F toggles full screen (Escape leaves it), ⌘P pauses, ⌘R resets (the game's own A+B+Select+Start reset). The filter and scaling choice are remembered.

Soft subpixel follows the look of Nintendo Switch Online's GBA LCD filter: its colour response and B-G-R stripes, bright pixels driven into a soft white clip so they fill out while dark ones keep their stripes, and a glow; its constants were fitted to a capture of NSO (port/src/apple/shaders.metal).

The Minish Cap → Settings… (⌘,) adjusts the filters live; values are saved and Reset to Defaults restores these:

KnobDefaultRangeEffect
LCD gap strength0.350–1How dark the gaps between pixels are
LCD gap width0.150–0.5Gap width, as a fraction of a GBA pixel
LCD subpixel strength0.350–1How strongly each RGB stripe dims the other two channels
LCD gap bloom0.000–1Bright pixels shrink their gaps (1 = no gap on white)
LCD brightness1.300.5–2Makes up for the light the gaps and stripes take
CRT scanline strength1.000–1Depth of the dark lines between scanlines
CRT bloom0.800–1How much a line's height follows its brightness (0 = all lines alike)
CRT beam width (dark)0.140.05–0.6Beam width on black, as a Gaussian sigma in scanlines
CRT beam width (bright)0.340.05–0.6Beam width on white
CRT aperture grille0.100–1RGB column mask, one screen pixel per column
CRT brightness1.350.5–2Brightness of the scanline beams
LCD response time22 ms0–40 ms10–90% time of a pixel getting brighter (with LCD response on)
LCD darkening slowdown1.301–2Getting darker takes this much longer (1.3 × 22 = 28.6 ms)
GBA colour correction0.000–1Blend towards the GBA screen's own colours (Pokefan531's gba-color matrix): less saturated and warmer
Gamma1.000.5–2Output = colour^gamma; above 1 darkens mid-tones

The LCD and CRT masks are box-filtered over each screen pixel, so they average to neutral at any scale: greys stay grey in a window, at fractional scales and in full screen. Beam and gap sizes follow one brightness value per pixel (halfway between luma and the brightest channel), the same for all three channels, so bloom adds no colour fringes. Each CRT pixel sums the beams of its own scanline and the two around it, so bright lines spread into dark ones.

View (Settings → Display → View) is "GBA (original)", the GBA's 240x160, or "Fit to display", which shows more of the world to fill the window: 160 lines and as wide as the window's shape asks (up to 432, in steps of 16), or taller on screens narrower than 3:2 (up to 224 lines). The HUD keeps the GBA layout, centred, and menus stay at 240x160 with black around them. How it works and what is not done yet: port/notes/widescreen.md.

LCD response (Settings → Display → LCD response, off by default) imitates the GBA screen's slow pixels, which some effects count on: sprites flickered on alternate frames look see-through and flashes leave a short afterglow. A compute pass keeps what the simulated LCD shows in a 240×160 float16 texture, in linear light (2.2 gamma), and for every new game frame moves each channel towards the new picture by shown = mix(new, shown, k), with k = exp(-frame / τ), frame = 1/59.73 s and τ = response time / ln 9 (so the 10–90% time is the setting). A channel getting darker uses the response time × the darkening slowdown. At the defaults k is 0.19 rising and 0.28 falling: 81% of a black-to-white step shows in the first frame, 96% in the second; a 30 Hz on/off flicker settles at 86% / 24% of full brightness (linear) instead of 100% / 0%. Whichever filter is chosen then draws that picture.

It steps once per game frame, never per display refresh, so it looks the same at 60 and 120 Hz, and it holds while paused (Step Frame steps it once). When the display misses game frames, as with fast-forward (up to 4x), one step covers all of them (k^n for n frames, using the newest): the ghost lasts the same number of game frames, so it is shorter in real time, and fast-forwarded flicker can alias. The picture starts afresh from the frame itself on the first frame, when the option is switched on, after a state load and after a reset.

The save is ~/Library/Application Support/tmc_macos/tmc.sav, an 8 KB EEPROM image (The Minish Cap menu → Show Save Folder). TMC_SAVE=path overrides it.

Save states (see Save states) are in the Game menu: Quick Save (F5) and Quick Load (F7) use one of four slots (⌥⌘1–⌥⌘4), Save State As… (⇧⌘S) and Load State… (⌘O) use any file. They live in ~/Library/Application Support/tmc_macos/states. The Debug menu (shown except in Release builds; Settings → Debug → Show Debug menu switches it) has Step Frame (F8: pauses, then advances one frame per press; ⌘P resumes), Show Frame Counter (in the window's subtitle), Load Checkpoint (the states port/scripts/checkpoints.sh wrote in this source tree) and Show State Folder. TMC_LOAD_STATE=path starts the app from a state. It also opens the graphics viewers (see Graphics debugging): Tiles (⌃⌘1), Sprites (⌃⌘2), Layers (⌃⌘3), Palettes (⌃⌘4), IO Registers (⌃⌘5) and Shader Buffers (⌃⌘6).

The window's toolbar has Save/Load (the Game menu's state items), Filter (the View menu's filters and Integer Scaling) and Settings buttons on the right, and a Debug button with the Debug menu's items when Settings → Debug → Show debug tools in toolbar is on. The buttons never take the keyboard, and View → Customize Toolbar… rearranges them. The subtitle names the room the player is in ("Hyrule Field – Lon Lon Ranch", or the area's name for rooms without one, from include/area.h and include/roomid.h via port/scripts/room_names.py), followed by a recent save or load and the frame counter: "Deepwood Shrine – Madderpillar · Saved slot 2". In full screen the toolbar hides with the menu bar.

Input latency

From a key press to the first picture that shows it takes about 105 ms in the first version of the app, measured as described below. Three things shortened it:

  • Late input. The game thread reads the keyboard and the gamepad itself, right before the game reads its input, rather than using what was last delivered to the main thread. The game thread then waits until shortly before the frame has to be ready (the time the last 32 frames took, plus a margin) and only then reads, so the input is as fresh as the pacing allows.
  • Less buffering. Two frames in flight, and no more than two frames waiting for the screen: when a third would queue behind them, that refresh is left out and the next one shows the newest game frame instead of an older one. The compositor of a windowed Metal app needs about two refreshes between a frame being committed and being on the screen; anything beyond that is just lag.
  • Display sync (below).

Settings → Timing → Frame pacing chooses how the game is paced:

ModeBehaviour
Accurate (59.73 Hz)The game's own timer runs it at the GBA's rate, independent of the display. Every ~3.7 s at 60 Hz the display shows one game frame twice.
Display sync (60 Hz, less lag)One game frame per display refresh (every other refresh on a 120 Hz display), started so that it is ready for a refresh it can still reach. The game runs 0.45% faster than a GBA, and the sound follows (the resampler is told the real rate, so nothing crackles or drifts). Used only when the display's rate is a multiple of ~60 Hz (60, 120, 180, 240: within 1.5 Hz); otherwise, and while fast-forwarding, it falls back to the timer.

It can be switched while the game runs, and the note under it says whether display sync is in use. The default is Display sync: the lag is what the mode is for, a 0.45% speed difference cannot be heard or felt, and it falls back to the accurate timer by itself where it cannot work. Pick Accurate for recordings or comparisons with hardware timing.

To measure: TMC_LATENCY_LOG=path writes a CSV with one line per input change (source,frame,event_to_latch_ms,latch_to_present_ms,total_ms, source key or `pad