Skip to content

Commit a188613

Browse files
seeddsv0lumehi
andcommitted
Add opt-in frame buffering with safe snapshot pacing and suspend
Integrate the present snapshots and frame-step work from #87 together with the encode-thread support and wait ledger from #157. Keep snapshots off by default on both platforms pending wider device validation. Offer Frame buffering in the iOS launcher for NVN builds. The existing launcher remembers the choice and preserves env.txt overrides. Pass the packer's detected graphics API to the settings generator. Wait for snapshot capacity at acquire; a present reaching a busy slot falls back to its original texture ticket. Drain snapshot commits and GPU completion during suspend even when display tickets were discarded. Regression tests cover both waits, fallback tickets and copied pixels. Validated on M4 Pro: full gfx run list, 38 snapshot lifecycle checks, 219 checks with encoding and snapshots enabled, Mac host build, 133-file iOS compile check, and eight launcher/docs/packing tests. The host unit suite cannot link t_heap_size because dm_ue_heap_owns is missing, reproduced on unchanged main cbbb600. No iPhone runtime performance claim. Co-authored-by: v0lumehi <[email protected]>
1 parent cbbb600 commit a188613

18 files changed

Lines changed: 435 additions & 36 deletions

File tree

‎README.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -174,6 +174,8 @@ With an Apple developer account you can instead build and install from Xcode: `-
174174

175175
**Settings.** A screen before the game starts offers what the game supports: frame rate, render scale, docked or handheld mode, game language, the frame-rate counter and Apple's performance HUD. Tap **Play** to start; the app remembers your choices.
176176

177+
**Frame buffering.** NVN games also offer this toggle, off by default. It may reduce stutter by buffering completed frames, at the cost of extra display latency. The app remembers your choice. `DM_PRESENT_SNAP=1` or `0` in `Documents/env.txt` overrides it; fully close and reopen the app after editing the file.
178+
177179
**Touch controls.** Tap **2D** / **3D** at the top to switch layouts; the app remembers your choice. Wonder, Engage, Dread, 13 Sentinels, Link's Awakening, Ace Attorney Investigations Collection, Unicorn Overlord, Rhythm Heaven Groove, Octopath Traveler 0, Pokémon Legends: Z-A, Cuphead, Absolum, Brain Memory Training Academy, The Great Ace Attorney Chronicles, STEINS;GATE RE:BOOT, Big Brain Academy: Brain vs. Brain, Patrick's Parabox, Celeste, Raging Loop and Mario vs. Donkey Kong start in 2D, the other games in 3D (STEINS;GATE RE:BOOT's quick save is R3, in the 3D layout). In 3D, the right stick (the camera in most games) is not drawn: swipe on the right third of the screen, starting anywhere off the buttons. In Super Mario Galaxy and Super Mario Galaxy 2, other touches outside the controls move the pointer; in Captain Toad: Treasure Tracker they touch the game's screen (touch blocks, stun enemies), and in Big Brain Academy: Brain vs. Brain too (its menus and activities).
178180
A connected game controller hides the touch controls and keeps every button.
179181

‎dm/games/01007EF00011E000/README.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,8 @@ Used at `DM_FPS_TARGET=0` and for the interval the framework keeps while the VFR
6363
- **Outdoors (2026-10-21, the user's Great Plateau save, Mac M4 Pro).** A frame had about 386 render passes and loaded and stored about 900 MB of attachments (on an iPhone at 60 fps about 55 GB/s, near the memory's bandwidth). 220 passes ended only because the game updates the first 64 bytes of a 64 KB vertex uniform block (`0x70c38c0000`) before each draw group while its shaders read up to 544 bytes of it (the terrain pixel shader `eb0afe555b86da79` indexes the whole block). Partial-cover uniform shadows (`ubp_get`, `DM_NVN_UB_PARTIAL`) and `cb_extent.tsv` keep those passes open: 386 → about 165 passes, GPU p50 about 9.3 → 6.5 ms, submit 5.7 → 4.9 ms; `DM_NVN_UBP_CHECK=1` found every shadow equal to the GPU's memory (968,000 checked). Lazy clears fold the four clear-only passes before the G-buffer into its first pass (about 30 MB less a frame at 1600x900). The frame still loads and stores about 800 MB: the NintendoWare VFX GPU particles run one compute dispatch per emitter between draws (ten 800x450 half-resolution passes and two G-buffer passes, about 190 MB a frame; the G-buffer ones read the depth being drawn), and decals sample the G-buffer right after the game sets it again. Tried and dropped: `DM_NVN_TBDR=1` (10–15% fewer stores, more CPU, red ledger lines, deferred uniform updates off), `DM_NVN_BARRIER=game` (no gain), same-target continuation outside TBDR mode.
6464
- Same-pass feedback: over a thousand draws a frame sample the G-buffer of their own pass (`4d3d5a4408c2e8d9`, `753d0169ae3ce4f0` and others on the 1600×900 G-buffer); snapshotting all of them took the Mac frame time from 16.6 to 36.6 ms, and none has shown magenta blocks on the iPhone so far. The decals that sample targets of their own pass read the stored content on the Mac; `DM_NVN_FB_SNAP=all` would snapshot them at a large cost.
6565

66+
- **Present snapshots (Mac).** The game's two swapchain textures held its CPU work to display ticks and the GPU at 444 MHz on an M2 Max ([present snapshots](../../../docs/reference/frame-rate.md#present-snapshots-the-games-swapchain-texture-free-at-once)). Judged by cost, the frame step stepped to 30 at a GPU time of 0.75 vsyncs. Zora's Domain from a Cemu save (120 Hz), frames on screen longer than 1/60 s by a quarter: 64 of 8,684 with neither, 41 with the GPU filler alone, 4 of 10,800 with snapshots alone (no step to 30 in 3 minutes, at 444 MHz throughout).
67+
6668
## Rendering
6769

6870
- **Resolved: the 3D scene black, only particles and the HUD drawn.** The engine binds almost every texture with `nvnCommandBufferBindTexturesDeferred` (`main+0xec2e64`, one handle, the pointer being the handle field inside the texture-sampler object): the GPU reads the handle when the command executes, and the game records its command blocks once and writes the handles afterwards. The host copied them at recording, mostly zeros, so the deferred-lighting composite read the dummy texture 0. The bind record keeps the source address and replay refreshes the handles first (`bh_fresh`). Found with a data-flow table from `DM_NVN_PASSDUMP_ALL`: the composite's `B` lines were all `tid=0 dummy` (without `_ALL` only the first draw of each pass is listed).

‎dm/games/settings.py‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,7 @@ def shown(cond, n):
3737
if cond == 'always': return True
3838
if cond == 'languages>1': return len(langs) > 1
3939
if cond.startswith('fixups:'): return cond[7:] in keys
40+
if cond.startswith('gfxapi:'): return os.environ.get('GFXAPI', '') == cond[7:]
4041
m = re.fullmatch(r'(DM_GAME_\w+)(!=|==)(.*)', cond)
4142
if m: return (macro(m[1], n) == m[3]) == (m[2] == '==')
4243
sys.exit(f'settings.tsv:{n}: unknown condition {cond}')

‎dm/games/settings.tsv‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,10 +4,11 @@
44
# variable the environment variable the setting sets
55
# kind choice: values value=label,... (languages: the game's own, from its control data); range: values low:high:step, shown as a percentage; toggle: 1 / 0, values -
66
# default a value; DM_GAME_<NAME>: the host's own default from the game profile (game_profile.h, game.py); build:<VAR>: the IPA build's setting (build_ipa.sh)
7-
# shown always; DM_GAME_<NAME>!=<value> or ==<value>; fixups:<KEY>: main's rewriter table has that key (a stub in the game's build, patch_nso.py); languages>1
7+
# shown always; DM_GAME_<NAME>!=<value> or ==<value>; fixups:<KEY>: main's rewriter table has that key (a stub in the game's build, patch_nso.py); languages>1; gfxapi:<API>: the packer's GFXAPI
88
# label, note the setting's name and the line under it (the note may be empty)
99
DM_FPS_TARGET choice 30=30 fps,60=60 fps DM_GAME_FPS_TARGET DM_GAME_FPS_TARGET!=0 Frame rate
1010
DM_RENDER_SCALE range 0.5:1.0:0.05 1.0 fixups:RENDER_SCALE Render scale
11+
DM_PRESENT_SNAP toggle - 0 gfxapi:nvn Frame buffering May reduce stutter; adds display latency.
1112
DM_OPMODE choice 1=Docked,0=Handheld DM_GAME_OPMODE always Console mode
1213
DM_LANG choice languages build:DM_LANG languages>1 Game language
1314
DM_SHOW_FPS toggle - build:DM_SHOW_FPS always Frame-rate counter

‎dm/gfx/nvn/hle_nvn.c‎

Lines changed: 26 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -635,11 +635,14 @@ NVN(nvnQueueWaitSync, NVNboolean, NVNqueue *q, const NVNsync *s) { (void)q; stat
635635
// ZCull data: the host does no ZCull, so there is nothing to save / restore
636636
NVN(nvnCommandBufferRestoreZCullData, void, NVNcommandBuffer *c, NVNbufferAddress a, size_t n) { (void)c; (void)a; (void)n; }
637637
NVN(nvnCommandBufferSaveZCullData, void, NVNcommandBuffer *c, NVNbufferAddress a, size_t n) { (void)c; (void)a; (void)n; }
638+
static _Atomic uint64_t g_sync_ns;
638639
NVN(nvnSyncWait, NVNsyncWaitResult, const NVNsync *s, uint64_t timeout) {
639640
const sync_t *o = (const sync_t *)s;
640641
if (!o->fenced) return NVN_SYNC_WAIT_RESULT_TIMEOUT_EXPIRED;
641-
if (mtl_wait(o->fence, 0)) return NVN_SYNC_WAIT_RESULT_ALREADY_SIGNALED;
642-
return mtl_wait(o->fence, timeout) ? NVN_SYNC_WAIT_RESULT_CONDITION_SATISFIED : NVN_SYNC_WAIT_RESULT_TIMEOUT_EXPIRED;
642+
int (*w)(uint64_t, uint64_t) = o->fenced == 2 ? mtl_wait_acq : mtl_wait;
643+
if (w(o->fence, 0)) return NVN_SYNC_WAIT_RESULT_ALREADY_SIGNALED;
644+
uint64_t t0 = now_ns(); int ok = w(o->fence, timeout); atomic_fetch_add(&g_sync_ns, now_ns() - t0); // the frame's blocked SyncWait time (@sync_ms)
645+
return ok ? NVN_SYNC_WAIT_RESULT_CONDITION_SATISFIED : NVN_SYNC_WAIT_RESULT_TIMEOUT_EXPIRED;
643646
}
644647
NVN(nvnEventBuilderSetDefaults, void, NVNeventBuilder *b) { memset(b, 0, sizeof(ev_builder_t)); }
645648
NVN(nvnEventBuilderSetStorage, void, NVNeventBuilder *b, const NVNmemoryPool *p, int64_t off) { *(ev_builder_t *)b = (ev_builder_t){(const pool_t *)p, off}; }
@@ -1263,8 +1266,11 @@ NVN(nvnWindowAcquireTexture, NVNwindowAcquireTextureResult, NVNwindow *w, NVNsyn
12631266
static uint64_t rt_period; uint64_t period = present_period(o), rtp = rt_period_ns(o, period);
12641267
if (rtp && rt_period != rtp) { rt_period = rtp; set_time_constraint(rtp); }
12651268
rt_comp_tick(rtp);
1266-
uint64_t p0 = now_ns();
1267-
if (mtl_link_active()) { if (!mtl_link_wait_tick(present_itv(o), period ? 2 * period : 33333333ull) && wait) sleep_until_ns(at); } // DM_PRESENT_LINK: pacing fully follows the display link (wait for the present interval's display-link ticks when running fast, go immediately when behind); our own 60 Hz clock is only the fallback when no display-link tick arrives
1269+
uint64_t p0 = now_ns(); int snap = mtl_snap_on();
1270+
if (snap && mtl_link_active()) { if (wait && mtl_link_stalled()) sleep_until_ns(at); } // present snapshots (nvn_mtl.m): the acquire's wait for a free ring slot below paces it.
1271+
// While the display link is silent (the window in the background or covered) frames are dropped as fast as they come and
1272+
// nothing frees a slot later, so the texture's slot time paces the game as without snapshots: unpaced, Breath of the Wild ran 3 to 4.5 times real time there
1273+
else if (mtl_link_active()) { if (!mtl_link_wait_tick(present_itv(o), period ? 2 * period : 33333333ull) && wait) sleep_until_ns(at); } // DM_PRESENT_LINK: pacing fully follows the display link (wait for the present interval's display-link ticks when running fast, go immediately when behind); our own 60 Hz clock is only the fallback when no display-link tick arrives
12681274
else if (wait) sleep_until_ns(at);
12691275
pace_ns = now_ns() - p0;
12701276
} else { // DM_DETCLOCK_PACE=1 (used by the screenshot gate): while the guest clock advances per frame, each frame's wall clock is no shorter than one step -- frame count and in-game time are deterministic, and the background loading thread has at least one step of wall clock available per frame;
@@ -1273,11 +1279,12 @@ NVN(nvnWindowAcquireTexture, NVNwindowAcquireTextureResult, NVNwindow *w, NVNsyn
12731279
if (pace < 0) { const char *e = getenv("DM_DETCLOCK_PACE"), *d = getenv("DM_DETCLOCK"); step = d ? strtoull(d, 0, 0) : 0; pace = e && atoi(e) && step; }
12741280
if (pace) { if (last && now_ns() < last + step) sleep_until_ns(last + step); last = now_ns(); }
12751281
}
1282+
pace_ns += mtl_snap_acquire_wait(); // ring capacity is waited for at acquire, where the game does not hold its present lock
12761283
g_acq_wait_ns += wait; trow(g_frame, "@late_ms", wait ? (now_ns() - at) / 1e6 : 0);
12771284
// The previous present of this texture has not yet been processed by the present thread (display cannot keep up, a whole swapchain round behind): wait for it to be returned, then hand it to the game to draw
12781285
uint64_t tk = *idx < 4 ? o->ticket[*idx] : 0;
12791286
if (tk) { uint64_t w0 = now_ns(); mtl_present_wait(tk); g_pq_wait_ns += now_ns() - w0; }
1280-
if (s) { ((sync_t *)s)->fenced = 1; ((sync_t *)s)->fence = mtl_last_fence(); } // The swapchain texture becomes available once the commits before this point have completed
1287+
if (s) { ((sync_t *)s)->fenced = 2; ((sync_t *)s)->fence = mtl_last_fence(); } // The swapchain texture becomes available once the commits before this point have completed (fenced 2: an acquire sync, for the wait ledger)
12811288
if (!g_fs_start) { g_fs_start = now_ns(); g_fs_wait = pace_ns; } // the frame starts when the first acquire after a present returns: on a display-link tick when on time
12821289
return NVN_WINDOW_ACQUIRE_TEXTURE_RESULT_SUCCESS;
12831290
}
@@ -1609,6 +1616,19 @@ static void fstep_tick(const win_t *o) {
16091616
// refresh more than its hold: a cheap 50 ms frame shows 54.5 ms at 165 Hz, which counted as late kept the hold at 20 fps for good
16101617
int hz = front_screen_max_fps(); g_fs.shown_slack = hz > 60 && hz % 60 && mtl_link_active() ? 60.0 / hz : 0;
16111618
int cslow = fstep_cpu_slowed(o->presents), gslow = nvn_fstep_gpu_slowed(&g_fg, gpu, k0 ? k0 : kmin, kmin, probe0) && dm_thermal_now() <= 1 && !dm_low_power_now(); // same gates as the CPU's
1619+
// Present snapshots (nvn_mtl.m snap_take): the game runs up to a frame ahead of the screen, so a frame whose work runs long is absorbed instead of shown late, and its cost is
1620+
// no evidence against the hold (Breath of the Wild in Zora's Domain stepped to 30 at a GPU time of 0.75 vsyncs: the frame's CPU time held its waits on its own GPU work).
1621+
// Lateness is then what the screen shows: the on-screen interval of the frame 8 presents back against its hold (pres_expect_ms), late by a quarter or dropped
1622+
// A game that is slower than its hold frame after frame (not a few long frames: 12 of the last 16 started late) is late too, though the screen misses only every few frames:
1623+
// 18.9 ms frames at hold 1 missed one refresh in 7, never three in a row, and ran at a jittering 53 fps with a payback every few frames instead of a steady 30
1624+
if (mtl_snap_on() && mtl_link_active() && !mtl_link_stalled() && o->presents > 9) { // (frames the stall fallback drops say nothing about the game: judged by cost then)
1625+
uint64_t pn = o->presents - 8; double a = mtl_presented_time(pn), b = mtl_presented_time(pn - 1);
1626+
if (a < 0) g_fs.screen = 2; else if (a > 0 && b > 0) g_fs.screen = (a - b) * 1e3 > 1.25 * pres_expect_ms(pn) ? 2 : 1;
1627+
static uint16_t slow_bits; static int slow_k; int k = g_fs.k ? g_fs.k : kmin;
1628+
if (k != slow_k) { slow_k = k; slow_bits = 0; } // judged against the hold in force, not the frames before a step
1629+
slow_bits = (uint16_t)(slow_bits << 1 | (shown > k + FSTEP_LATE));
1630+
if (__builtin_popcount(slow_bits) >= 12) g_fs.screen = 2;
1631+
}
16121632
int n = nvn_fstep_next(&g_fs, shown, cost, kmin, kmax, fixed, cslow || gslow);
16131633
__atomic_store_n((uint32_t *)(dm_fps_state + 0x20), (uint32_t)n, __ATOMIC_RELAXED); atomic_store(&g_fs_k, g_fs.k);
16141634
held[g_fs.k]++; if (fixed) fixed_sum += (uint64_t)n; // the stubs count only the host's steps
@@ -1684,7 +1704,7 @@ NVN(nvnQueuePresentTexture, void, NVNqueue *q, NVNwindow *w, int idx) {
16841704
if (prev_in) {
16851705
double fr = (t0 - prev_in) / 1e6, wk = (t0 - prev_out) / 1e6, nv = atomic_exchange(&g_nvn_ns, 0) / 1e6;
16861706
tpush(0, fr); tpush(1, wk); tpush(2, nv);
1687-
trow(f, "@frame_ms", fr); trow(f, "@work_ms", wk); trow(f, "@nvn_ms", nv); trow(f, "@itv", (double)present_itv(o));
1707+
trow(f, "@frame_ms", fr); trow(f, "@work_ms", wk); trow(f, "@nvn_ms", nv); trow(f, "@sync_ms", atomic_exchange(&g_sync_ns, 0) / 1e6); trow(f, "@itv", (double)present_itv(o));
16881708
// Slow-frame attribution (taken only when DM_NVN_TSV is on): this frame's present-thread CPU time (−1 if the thread changed), CPU of all threads in the process, acquire wait accumulated per frame, present call time (same base as the GPU / on-screen present times: ms since process start)
16891709
trow(f, "@wait_ms", g_acq_wait_ns / 1e6); trow(f, "@pq_wait_ms", g_pq_wait_ns / 1e6);
16901710
if (frame_rec()) {

‎dm/gfx/nvn/nvn_fstep.h‎

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,8 @@ typedef struct {
3535
int probe, grace; // 1: the trial in progress is a probe; 2: a probe held and its run at kmin has not ended yet; frames left of the probe's grace
3636
double hold, since; // vsyncs a trial waits for after a step up; vsyncs since the last step up
3737
double shown_slack; // vsyncs a frame on time may show longer than k (set by the caller): one refresh on screens whose rate is not a multiple of 60; the cost keeps FSTEP_LATE
38+
int screen; // set by the caller before each call, then cleared: 0 = judge lateness by shown and cost; 1 = the screen showed a recent frame on time, 2 = late. With present
39+
// snapshots (nvn_mtl.m) the game runs ahead of the screen and a frame that runs long is absorbed, so only what the screen shows counts
3840
double run, crun, cref; // vsyncs at kmin in a row; the cost of its frames on time (running mean; not during a probe's trial, whose frames run while the clock rises);
3941
// crun when the last run of FSTEP_HOLD_MAX or more ended in a step up (0 = none yet)
4042
double ccur; int ck, cn; // the cost of the frames on time at the longer hold ck (running mean) and their count
@@ -69,16 +71,19 @@ static inline int nvn_fstep_next(nvn_fstep *s, double shown, double cost, int km
6971
if (kmin < s->kmin || s->k < kmin) s->k = kmin; // the cap rose (a movie or the game's own step ended) or fell
7072
if (s->k > kmax) s->k = kmax;
7173
s->kmin = kmin;
72-
int late = shown > held + FSTEP_LATE + s->shown_slack || cost > held + FSTEP_LATE, grace = s->grace > 0;
74+
int scr = s->screen; s->screen = 0;
75+
int late = scr ? scr == 2 : shown > held + FSTEP_LATE + s->shown_slack || cost > held + FSTEP_LATE, grace = s->grace > 0;
7376
if (grace) s->grace--;
7477
if (late) { s->late++; s->late_run = grace ? 0 : s->late_run + 1; s->fit_run = 0; } else s->late_run = 0;
7578
// The cost of the frames on time (a hitch is not what the scene costs): at kmin, and at the longer hold
7679
if (kmin != s->ckmin) { s->ckmin = kmin; s->run = s->crun = s->cref = 0; }
77-
if (held <= kmin) { s->run += shown; s->cn = 0; if (!late && s->probe != 1) s->crun = s->crun > 0 ? s->crun + (cost - s->crun) / 32 : cost; }
80+
// A frame the screen showed on time while its cost did not fit (absorbed by present snapshots) is not what the hold costs: the probes would take it for the scene that held kmin
81+
int fits = !scr || cost <= held;
82+
if (held <= kmin) { s->run += shown; s->cn = 0; if (!late && fits && s->probe != 1) s->crun = s->crun > 0 ? s->crun + (cost - s->crun) / 32 : cost; }
7883
else {
7984
s->run = 0;
8085
if (held != s->ck) { s->ck = held; s->cn = 0; }
81-
if (!late) { s->ccur = s->cn ? s->ccur + (cost - s->ccur) / 8 : cost; s->cn++; }
86+
if (!late && fits) { s->ccur = s->cn ? s->ccur + (cost - s->ccur) / 8 : cost; s->cn++; }
8287
}
8388
if (s->late_run >= 3 && s->k < kmax) { // step up to the cost, at least one vsync
8489
int want = (int)ceil(cost - 0.05);

‎dm/gfx/nvn/nvn_mtl.h‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,7 @@ uint64_t mtl_sub_commit(void);
3737

3838
uint64_t mtl_last_fence(void); // Fence value of the most recent submit (0 = never submitted)
3939
int mtl_wait(uint64_t fence, uint64_t timeout_ns); // Returns 1 when the GPU has completed up to fence, 0 on timeout
40+
int mtl_wait_acq(uint64_t fence, uint64_t timeout_ns); // the same for a sync WindowAcquireTexture handed out (its own line in the wait ledger, DM_NVN_WAITS)
4041
void mtl_finish(void); // Wait for all submitted commands to complete
4142
void mtl_drain(void); // Wait for all commands on the queue (including presents) to complete: submit an empty command buffer and wait for it
4243
void mtl_xv_window_tex(uint64_t serial); // Register a window (swapchain) texture: the cross-submit validity ledger never collects it

0 commit comments

Comments
 (0)