Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 9 additions & 3 deletions dm/games/game.py
Original file line number Diff line number Diff line change
Expand Up @@ -105,14 +105,19 @@ def by_build(main_id): # the profile whose build rows register this main build
UPSCALER_SOURCE = re.compile(r'/agl_ndsr\.pck#')


def upscaler_keys(g):
# nn::movie's enhancement networks (NDVE files, Movie/Ndve/*.dat.zs): the compute shaders the shader map found in the file's NDVE part (Ocarina of Time's 12: the colour conversion
# and the network a movie frame runs; the file's NDSR pack, the scaler to the output, is not among them). DM_MOVIE_ENHANCE=0 leaves the network out (nvn_mtl.m movie_net_dispatch)
MOVIE_NET_SOURCE = re.compile(r'#NDVE@')


def upscaler_keys(g, source=UPSCALER_SOURCE):
"""the game's own upscaler shaders, from its shader map (shader_split.py's source column): sorted 16-digit keys, none without a map"""
p = g.table('shader_map.tsv')
if not p.exists(): return []
keys = set()
for line in p.read_text(encoding='utf-8').splitlines():
c = line.split('\t')
if len(c) >= 5 and c[2] == 'compute' and UPSCALER_SOURCE.search(c[4]) and re.fullmatch(r'[0-9a-f]{16}', c[3]): keys.add(c[3])
if len(c) >= 5 and c[2] == 'compute' and source.search(c[4]) and re.fullmatch(r'[0-9a-f]{16}', c[3]): keys.add(c[3])
return sorted(keys)


Expand Down Expand Up @@ -202,7 +207,7 @@ def header_one(g):
if vcr not in ('on', 'off'): sys.exit(f'{g.id}: vconv_range must be on or off: {vcr}')
mml = g.get('mem_map_limit', 'off') # MapPhysicalMemory refused beyond the application pool, as on Horizon (hle_svc.c): on / off
if mml not in ('on', 'off'): sys.exit(f'{g.id}: mem_map_limit must be on or off: {mml}')
ups = upscaler_keys(g) # the game's own upscaler shaders, which DM_UPSCALER=metalfx (the launcher's Game's upscaler) replaces with MetalFX's spatial scaler (nvn_mtl.m up_mfx_encode)
ups, mvn = upscaler_keys(g), upscaler_keys(g, MOVIE_NET_SOURCE) # the game's own upscaler shaders, which DM_UPSCALER=metalfx (the launcher's Game's upscaler) replaces with MetalFX's spatial scaler (nvn_mtl.m up_mfx_encode)
dbr = g.get('draw_barriers', 'full') # how draw passes are ordered (nvn_mtl.m barrier_game): full = each waits for all earlier GPU work, game = by the game's own barriers, so vertex work overlaps the previous pass's fragments
if dbr not in ('full', 'game'): sys.exit(f'{g.id}: draw_barriers must be full or game: {dbr}')
om = g.get('op_mode', 'console') # the operation mode reported at start (hle_oe.c dm_opmode; DM_OPMODE overrides): console = docked, handheld = touch screen in use (Super Mario Galaxy's pointer)
Expand Down Expand Up @@ -259,6 +264,7 @@ def header_one(g):
f'#define DM_GAME_TEX_DYN_SLOTS {int(tds == "on")}',
f'#define DM_GAME_DRAW_BARRIERS_GAME {int(dbr == "game")}',
f'#define DM_GAME_UPSCALER_KEYS {q(",".join(ups))}', f'#define DM_GAME_UPSCALER_N {len(ups)}',
f'#define DM_GAME_MOVIE_NET_KEYS {q(",".join(mvn))}', f'#define DM_GAME_MOVIE_NET_N {len(mvn)}',
f'#define DM_GAME_VCONV_RANGE {int(vcr == "on")}',
*([f'#define DM_GAME_NVN_API_MAJOR {api.split(".")[0]}', f'#define DM_GAME_NVN_API_MINOR {api.split(".")[1]}'] if g.get('device_api', '') else []), # without the key: by the SDK version (hle_nvn.c nvn_api)
'']
Expand Down
1 change: 1 addition & 0 deletions dm/games/settings.tsv
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ DM_RENDER_SCALE range 0.5:1.0:0.05 1.0 fixups:RENDER_SCALE Game Render scale le
DM_OPMODE choice 1=Docked,0=Handheld DM_GAME_OPMODE always Game Console mode level=basic
DM_PRESENT_UPSCALE choice off=Standard,metalfx=MetalFX off always Game Upscaling Uses more GPU time and can increase heat.
DM_UPSCALER choice game=Game's own,metalfx=MetalFX game DM_GAME_UPSCALER_N!=0 Game Game's upscaler
DM_MOVIE_ENHANCE toggle - 1 DM_GAME_MOVIE_NET_N!=0 Game Movie enhancement The game's network that cleans up its movies. Off plays them as decoded, for slower GPUs.
DM_LANG choice languages build:DM_LANG languages>1 Game Game language level=basic
DM_FULLSCREEN choice 0=Window,1=Fullscreen 0 platform:mac Game Display mode level=basic
DM_PICTURE_FIT choice fit=Fit,fill=Fill fit platform:ios Game Picture Fill crops the game's 16:9 picture to cover the screen. Health bars, subtitles or maps near the edges can be cut off. A full-screen picture without cropping needs a patch for each game.
Expand Down
63 changes: 62 additions & 1 deletion dm/gfx/nvn/nvn_mtl.m
Original file line number Diff line number Diff line change
Expand Up @@ -851,7 +851,7 @@
while (j < g_naddr && g_addr[j].lo <= hi) { lo = MIN(lo, g_addr[j].lo); hi = MAX(hi, g_addr[j].hi); j++; }
if (i == j && g_naddr == g_addr_cap) { g_addr_cap = g_addr_cap ? g_addr_cap * 2 : 256; g_addr = realloc_or_die(g_addr, (size_t)g_addr_cap * sizeof *g_addr, "the addressed range table"); }
if (j != i + 1) memmove(g_addr + i + 1, g_addr + j, (size_t)(g_naddr - j) * sizeof *g_addr);
g_naddr += 1 - (j - i); g_addr[i].lo = lo; g_addr[i].hi = hi;

Check failure on line 854 in dm/gfx/nvn/nvn_mtl.m

View workflow job for this annotation

GitHub Actions / clang-tidy (ratchet)

Out of bound access to memory preceding the heap area [clang-analyzer-security.ArrayBound] (3 in this file, the baseline has 1)
atomic_fetch_add(&g_pool_gen, 1); // the table rebuilds before the next draw that uses it
}
pthread_mutex_unlock(&g_mu);
Expand Down Expand Up @@ -5930,6 +5930,7 @@
NSMutableDictionary *geo_mesh; // a vertex shader's mesh entries by lean kernel key (geo_mesh_fn; NSNull: none)
uint8_t up_mfx; // a compute shader that is the game's own upscaler (DM_GAME_UPSCALER_KEYS, from the shader map): 0 not decided, 1 drawn by MetalFX when DM_UPSCALER=metalfx, 2 not one or one its colour keeps (up_mfx_wanted)
uint8_t up_color; // such a shader's colour, from its code at load with DM_UPSCALER=metalfx (up_mfx_color; UP_COLOR_UNREAD otherwise)
uint8_t mv_net; // a compute shader of the game's movie enhancement network file (DM_GAME_MOVIE_NET_KEYS): 0 not decided, then one of MVN_* (movie_net_dispatch)
int gs_loc, lay_loc; char gs_comp, lay_comp; // a slice-writing geometry shader (no function: the layer comes from input gs_loc.gs_comp) / a vertex shader with layer entry points writing output lay_loc.lay_comp (dmsh_build.py gs_slice, vs_layer_entry); -1 = none
uint64_t cbs_seen; uint32_t cbs_runs; // the command buffer that listed this shader last, and how many have (cbs_note)
// The argument buffer encoded last time
Expand Down Expand Up @@ -14343,6 +14344,9 @@

static void dispatch(const p_dispatch *dp);
static int up_mfx_wanted(NvShader *cs); static int up_mfx_encode(NvShader *cs); // a game's upscaler through MetalFX (see up_mfx_encode)
static int movie_net_dispatch(NvShader *cs); // the movie enhancement network left out (DM_MOVIE_ENHANCE=0, see movie_net_dispatch)
static int movie_enh_off(void); // DM_MOVIE_ENHANCE=0 (see movie_net_dispatch)
static int ndve_resample_alone(NvShader *cs); // nvn_ndve.inc: the engine's resampler with the movie enhancement off
static int ndve_engine_dispatch(NvShader *cs, const p_dispatch *dp); // nn::ndve's movie network as the host's kernels (DM_NDVE_ENGINE=1, nvn_ndve.inc)
// ---------- Compute dispatches moved ahead of the render pass they would split (DM_NVN_CS_HOIST) ----------
// Metal cannot run a compute dispatch inside a render pass, so a dispatch between two draws of one pass ends it, and on a tile-based GPU every attachment is stored and loaded again:
Expand Down Expand Up @@ -15126,8 +15130,11 @@
if (g_nubd && ubd_conflict_cs(cs, dp->ind)) { g_ubd_conflicts++; ubd_land(); } // see ubd_conflict_cs
rp_flush(); // A full clear with no draw after it waits for the next pass on its targets, but it comes before this dispatch, which may read or write them as images: land it first, as copy_t2t does
image_prepare(prog_get(S.cprog), 0x20);
if (ndve_engine_dispatch(cs, dp)) return; // nn::ndve's movie network as the host's kernels (DM_NDVE_ENGINE=1)
// nn::ndve's movie network as the host's kernels (DM_NDVE_ENGINE=1), unless the movie enhancement is off: then the network is left out (movie_net_dispatch), as the player chose.
// The engine came first, so with Movie enhancement off Ocarina of Time's opening still ran the whole network: 26 ms of a movie frame on an M1, the movie at half speed
if (DM_GAME_MOVIE_NET_N && movie_enh_off() ? ndve_resample_alone(cs) : ndve_engine_dispatch(cs, dp)) return; // off: the engine's resampler alone, on the decoded picture
if (up_mfx_wanted(cs) && !dp->ind && up_mfx_encode(cs)) return; // the game's upscaler, drawn by MetalFX instead (DM_UPSCALER=metalfx)
if (DM_GAME_MOVIE_NET_N && !dp->ind && movie_net_dispatch(cs)) return; // a dispatch of the movie enhancement network, left out or replaced by a copy (DM_MOVIE_ENHANCE=0)
// Threadgroup memory past Metal's 32 KB, in a device buffer (dmsh_rewrite.py tg_spill): a slice for every workgroup of the grid. An indirect dispatch's grid is in GPU memory, written earlier
// in the frame: the replay waits for the GPU (as an indirect-count multi-draw does, mdi_wait) and reads it. Mario Kart World's spilled dispatches are all direct, of 1 to 3 workgroups
uint64_t tg_groups = 0;
Expand Down Expand Up @@ -16933,6 +16940,60 @@
(unsigned long)out.pixelFormat, direct ? ", straight" : srgb ? ", through RGBA16F, decoded from sRGB" : ", through RGBA16F");
return 1;
}
// ---------- The movie enhancement network left out (DM_MOVIE_ENHANCE) ----------
// nn::movie's NDVE file (Ocarina of Time's Movie/Ndve/Ndve-Nvn2-vid_seq5.dat.zs) holds the compute shaders a movie frame runs between the decoder and the screen: one converts the
// decoded picture (luma 1920x1080, chroma 960x540) to RGB, eleven dispatches of a network then enhance that picture at the same size, the last of them adding their result to it into
// an RGB10A2 image, and an NDSR shader scales it to the output. On an M1 (8-core GPU) the network took 60-70 ms a frame, so the title and opening movies (24 fps) played at about 13.
// With DM_MOVIE_ENHANCE=0 (the launcher's Movie enhancement: off) the network's dispatches (those of the file's shaders that use storage buffers) are left out and its last one (one
// texture, one image, the same size) becomes a draw of its input into its image: the decoded picture as it is, without the network's clean-up. The other shaders of the file run.
// The steps before the last are left out only while the previous frame's copy was made, so a copy refused (another size, an image that cannot be drawn into) costs no frame
enum { MVN_STAGE = 1, MVN_LAST, MVN_NONE };
static int g_mvn_ok, g_mvn_left; // the previous last step was replaced by the copy; steps left out since it
static uint64_t g_mvn_copied;
static int movie_enh_off(void) {
static int v = -1;
if (v < 0) { const char *e = getenv("DM_MOVIE_ENHANCE"); v = e && !strcmp(e, "0");
if (e && strcmp(e, "0") && strcmp(e, "1")) MLOG("[RED] DM_MOVIE_ENHANCE=%s: 1 or 0; keeping the movie enhancement", e);
if (v) MLOG("movie enhancement (DM_MOVIE_ENHANCE): off, the movie network's %d shaders are left out and the decoded picture is drawn as it is", DM_GAME_MOVIE_NET_N); }
return v;
}
static int movie_net_named(NvShader *cs) {
for (const char *k = DM_GAME_MOVIE_NET_KEYS; *k; k += k[16] == ',' ? 17 : 16) if (!strncmp(k, cs->key, 16)) return 1;
return 0;
}
static int movie_net_dispatch(NvShader *cs) {
if (cs->mv_net == MVN_NONE || !movie_enh_off()) return 0;
int nt = 0, ni = 0, nsb = 0, ti = -1, oi = -1;
for (int i = 0; i < cs->rf.nb; i++) { int k = cs->rf.b[i].kind;
if (k == NVN_RB_TEX) { nt++; ti = i; } else if (k == NVN_RB_IMG) { ni++; oi = i; } else if (k == NVN_RB_SBUFP || k == NVN_RB_SBUFU) nsb++; }
if (!cs->mv_net) {
cs->mv_net = !movie_net_named(cs) || !nsb ? MVN_NONE : nt == 1 && ni == 1 ? MVN_LAST : MVN_STAGE; // without storage buffers: the colour conversion, which runs
if (cs->mv_net != MVN_NONE) MLOG("movie network %s: %s", cs->key, cs->mv_net == MVN_LAST ? "its last step, replaced by a draw of its input" : "a step, left out");
if (cs->mv_net == MVN_NONE) return 0;
}
if (cs->mv_net == MVN_STAGE) { if (!g_mvn_ok) return 0; g_mvn_left++; return 1; }
int tin = (int)(tex_slot_h(S.tex[5], S.img[5], cs->rf.b[ti].reg) & 0xfffff), tout = cs->rf.b[oi].reg < 32 ? (int)(S.img[5][cs->rf.b[oi].reg] & 0xfffff) : 0;

Check failure on line 16975 in dm/gfx/nvn/nvn_mtl.m

View workflow job for this annotation

GitHub Actions / clang-tidy (ratchet)

Out of bound access to memory preceding 'rf.b' [clang-analyzer-security.ArrayBound] (3 in this file, the baseline has 1)

Check failure on line 16975 in dm/gfx/nvn/nvn_mtl.m

View workflow job for this annotation

GitHub Actions / clang-tidy (ratchet)

Out of bound access to memory preceding 'rf.b' [clang-analyzer-security.ArrayBound] (3 in this file, the baseline has 1)
tex_t dout = {0}; id<MTLTexture> in = nil, out = nil; uint64_t rid = 0; int real = 0;
os_unfair_lock_lock(&g_rmu);
int ok = tin > 0 && tin < g_ntreg && g_treg[tin].ok && tout > 0 && tout < g_ntreg && g_treg[tout].ok;
if (ok) { dout = g_treg[tout].t; in = tex_by_id(tin); out = img_binding(tout, &cs->rf.b[oi], &rid, &real); if (!real) out = nil; }
os_unfair_lock_unlock(&g_rmu);
ok = in && out && in != out && in.textureType == MTLTextureType2D && out.textureType == MTLTextureType2D && in.width == out.width && in.height == out.height &&
!fmt_int_or_ds(in.pixelFormat) && !fmt_int_or_ds(out.pixelFormat) && !mtl_fmt_block(out.pixelFormat) && (out.usage & MTLTextureUsageRenderTarget);
if (ok) {
zskip_del(dout.serial);
rp_end(); if (g_blit) { enc_b_end(g_blit); g_blit = nil; }
ubd_land_compute();
NVNcopyRegion r = {0, 0, 0, (int)in.width, (int)in.height, 1};
ok = copy_t2t_draw(in, out, 0, 0, 0, 0, &r, &r, 0, 0);
args_dirty_all();
}
if (!ok && g_mvn_left) MLOG("[RED] movie network %s: the copy was refused after %d steps were left out: this frame's picture is wrong; the network runs from now on", cs->key, g_mvn_left);
if (ok && !g_mvn_copied++) MLOG("movie network: first frame drawn without it, %lux%lu (format %lu) → format %lu; its steps are left out from the next frame", (unsigned long)in.width, (unsigned long)in.height, (unsigned long)in.pixelFormat, (unsigned long)out.pixelFormat);
if (!ok) cs->mv_net = MVN_NONE; // the network runs from now on: its earlier steps are no longer skipped either once g_mvn_ok is 0
g_mvn_ok = ok; g_mvn_left = 0;
return ok;
}
// The present pass: src's valid rectangle drawn into dst (the drawable, or a screenshot's texture) as present_encode draws it, through MetalFX first where fx_encode takes it
// (fx: the scaler state to use, nil = bilinear). uvb: the pass's crop constants (one buffer per present allocator, written by the CPU)
static int present_encode_m4(id<MTL4CommandBuffer> cb, id<MTLTexture> src, id<MTLTexture> dst, const int crop[4], id<MTLBuffer> uvb, fx_state *fx) {
Expand Down
12 changes: 12 additions & 0 deletions dm/gfx/nvn/nvn_ndve.inc
Original file line number Diff line number Diff line change
Expand Up @@ -203,6 +203,18 @@ static void ndve_compare(id<MTLTexture> a, id<MTLTexture> b, int slot) {
slot ? "resampler" : "network", (unsigned long long)*n, c[2 * slot], (unsigned long)a.width, (unsigned long)a.height, c[2 * slot + 1]);
}
}
// With the movie enhancement off (DM_MOVIE_ENHANCE=0) the network is left out (nvn_mtl.m movie_net_dispatch), but the resampler 4f41ccf2 still runs, on the picture as decoded:
// the game's translated one took 24 ms of an M1's movie frame (8-core GPU), so the movie fell to 30 pictures a second, half its speed. The engine's resampler takes it then
static int ndve_resample_alone(NvShader *cs) {
if (!ndve_mode() || ndve_check() || g_nd.off || ndve_index(cs, NDVE_N - 1) != NDVE_N - 1) return 0;
if (g_nd.state == 0) ndve_build();
if (g_nd.state != 2) return 0;
const p_bind_buf *w = &S.ssbo[5][2]; void *wb = NULL; uint64_t wo = 0;
if (!w->addr || w->size < 0x3000 || !mtl_gpu_addr(w->addr, 0x3000, &wb, &wo, &g_nd.wrs)) { static int once; if (!once++) MLOG("NDVE engine: the resampler's weights are not bound; the game's resampler runs"); return 0; }
if (!ndve_resample(cs, nil)) return 0;
if (!g_nd.rs_frames++) MLOG("NDVE engine: first movie frame resampled by the engine (the movie enhancement off)");
return 1;
}
// 1 when the dispatch was taken (skipped or replaced by the engine), 0 to run it
static int ndve_engine_dispatch(NvShader *cs, const p_dispatch *dp) {
const int chk = ndve_check();
Expand Down
13 changes: 13 additions & 0 deletions dm/tools/tests/test_game_profile.py
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,19 @@ def test_from_shader_map(self):
self.assertEqual(macros(MAP), ['#define DM_GAME_UPSCALER_KEYS "7629d857a0a93833,c56db3d5a0f1b5af"', '#define DM_GAME_UPSCALER_N 2'])


class MovieNetKeys(unittest.TestCase):
def test_from_shader_map(self): # nn::movie's NDVE part (Ocarina of Time's Movie/Ndve file): its compute shaders, not the file's NDSR pack
mv = ('cs_other.bin\t8\tcompute\tba079f68ae288dba\t/Movie/Ndve/Ndve-Nvn2-vid_seq5.dat.zs#NDVE@0x1423e8\n'
'cs_other.bin\t9\tcompute\t4f41ccf24f163e0d\t/Movie/Ndve/Ndve-Nvn2-vid_seq5.dat.zs#NDSR@0x104fe0\n')
with tempfile.TemporaryDirectory() as d:
Path(d, ID).mkdir()
(Path(d, ID) / 'game.tsv').write_text(TSV)
(Path(d, ID) / 'shader_map.tsv').write_text(MAP.split('cs_other.bin')[0] + mv)
subprocess.run([sys.executable, str(GAME), 'header', ID, str(Path(d, ID) / 'game.h')], env={**os.environ, 'DM_GAMES_DIR': d}, check=True, capture_output=True)
got = [l for l in (Path(d, ID) / 'game.h').read_text().splitlines() if 'MOVIE_NET' in l]
self.assertEqual(got, ['#define DM_GAME_MOVIE_NET_KEYS "ba079f68ae288dba"', '#define DM_GAME_MOVIE_NET_N 1'])


if __name__ == '__main__':
unittest.main()

Expand Down
1 change: 1 addition & 0 deletions docs/env_switches.tsv
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,7 @@ DM_MOTION_AXES switch `=<map>` such as `x,-z,y`: maps Apple's controller axes to
DM_MOTION_GAIN switch `=<gain>`: how fast the orientation is pulled toward the measured gravity, in rad/s per unit error (default 0.5; `0` integrates the gyro alone)
DM_MOTION_HID switch On the Mac, `0` disables the passive Switch Pro Controller HID motion fallback (`motion_pro_mac.h`); enabled by default when exactly one physical Pro and one GameController Pro can use the same player slot; usable GameController motion takes priority
DM_MOTION_LOG diagnostic `=1` logs player 1's mapped motion sample once a second per source (phone / GameController / controller HID; acceleration in G, gyro in revolutions/s), for checking the axes: flat and still reads acc 0 0 -1
DM_MOVIE_ENHANCE player `0` leaves out the movie enhancement network of nn::movie's NDVE file (Ocarina of Time's Movie/Ndve, 60-70 ms a movie frame on an M1) and draws the decoded picture into its output; `1` (the default) runs it (`nvn_mtl.m` `movie_net_dispatch`). The launcher's Movie enhancement
DM_MOVIE_TRACE diagnostic When set, the movie decoder logs every call with its thread and decoder (by default the first 12 calls, then every 2^k-th)
DM_MSL_DIR path Parent folder of the shader libraries: NVN loads from `b-<chain version>/` or the one file `b-<chain version>.img` beneath it, Vulkan from `vk/`, GL from `gl/`; the app and the Mac launcher set it
DM_NDVE_ENGINE switch `0` runs nn::ndve's movie network (Ocarina of Time's title and opening movies) as the game's 12 translated dispatches after its colour conversion instead of the host's kernels (dm/gfx/msl/ndve_engine.metal, on by default: the same output, about half the frame's GPU time on an M4 Pro); `ab` alternates with DM_AB; `check` runs the game's dispatches and the host's network beside them and logs every 300 frames how many texels of the two differ. The host's kernels take only the model they were written for, bound by its shaders' keys and its weights' layout (docs/reference/shaders.md, The NDVE movie network by the host)
Expand Down
Loading
Loading