Skip to content

Commit 2d1396b

Browse files
committed
Load selected offline non-point variants on iOS Metal 3
1 parent d61574f commit 2d1396b

3 files changed

Lines changed: 131 additions & 0 deletions

File tree

‎dm/gfx/nvn/nvn_mtl_legacy.inc‎

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4708,6 +4708,39 @@ static NSDictionary *nonpoint_sources_manifest(void) {
47084708
});
47094709
return manifest;
47104710
}
4711+
4712+
// Optional Metal 3 libraries built from the exact, effective non-point source.
4713+
// Keep the ordinary compiler fallback for missing files and incompatible GPUs.
4714+
static id<MTLFunction> nonpoint_offline_function(NvShader *vs, NSString *key,
4715+
NSString *src, NSDictionary *record) {
4716+
if (DM_GAME_PROGRAM_ID != 0x0400C3F00006E000ull) return nil;
4717+
NSString *root = [g_msl_dir stringByAppendingPathComponent:@"nonpoint-metal3-v1"];
4718+
static NSDictionary *manifest; static dispatch_once_t once;
4719+
dispatch_once(&once, ^{
4720+
NSData *data = [NSData dataWithContentsOfFile:[root stringByAppendingPathComponent:@"manifest.json"]];
4721+
id decoded = data ? [NSJSONSerialization JSONObjectWithData:data options:0 error:nil] : nil;
4722+
if ([decoded isKindOfClass:[NSDictionary class]]) manifest = decoded;
4723+
});
4724+
if (![manifest[@"schema"] isEqual:@1] || ![manifest[@"chain"] isEqual:@(TONTON_SHADER_CHAIN)]) return nil;
4725+
id entries = manifest[@"shaders"];
4726+
if (![entries isKindOfClass:[NSDictionary class]]) return nil;
4727+
id row = entries[key];
4728+
if (![row isKindOfClass:[NSDictionary class]] ||
4729+
![row[@"source_sha256"] isEqual:record[@"source_sha256"]] ||
4730+
![row[@"library_sha256"] isEqual:record[@"library_sha256"]] ||
4731+
![row[@"effective_source_sha256"] isEqual:nonpoint_digest([src dataUsingEncoding:NSUTF8StringEncoding])]) return nil;
4732+
NSString *path = [root stringByAppendingPathComponent:[key stringByAppendingString:@".metallib"]];
4733+
NSData *data = [NSData dataWithContentsOfFile:path options:NSDataReadingMappedIfSafe error:nil];
4734+
if (!data || ![row[@"offline_sha256"] isEqual:nonpoint_digest(data)]) return nil;
4735+
id<MTLLibrary> lib = [g_dev newLibraryWithURL:[NSURL fileURLWithPath:path] error:nil];
4736+
if (!lib) return nil;
4737+
id<MTLFunction> fn = vs->specialized ?
4738+
[lib newFunctionWithName:vs->fn.name constantValues:[MTLFunctionConstantValues new] error:nil] :
4739+
[lib newFunctionWithName:vs->fn.name];
4740+
if (!fn || (vs->rf.nb && [fn newArgumentEncoderWithBufferIndex:vs->rf.abi].encodedLength != vs->arg_len)) return nil;
4741+
vs->nonpoint_lib = lib;
4742+
return fn;
4743+
}
47114744
static id<MTLFunction> nonpoint_vertex(NvShader *vs, NSError **error) {
47124745
@synchronized (vs) {
47134746
if (!vs->nonpoint_tried) {
@@ -4734,6 +4767,12 @@ static id<MTLFunction> nonpoint_vertex(NvShader *vs, NSError **error) {
47344767
[NSString stringWithFormat:@"Missing or mismatched non-point source for %@ (chain %s)", key, DMSH_CHAIN]}];
47354768
} else {
47364769
src = [src stringByReplacingOccurrencesOfString:@"[[point_size]]" withString:@"[[user(dm_unused_point_size)]]"];
4770+
vs->nonpoint_fn = nonpoint_offline_function(vs, key, src, record);
4771+
if (vs->nonpoint_fn) {
4772+
MLOG("Non-point vertex variant %s loaded precompiled Metal 3; original point/TF entry retained", vs->key);
4773+
dispatch_semaphore_signal(compile_slots);
4774+
return vs->nonpoint_fn;
4775+
}
47374776
MTLCompileOptions *options = [MTLCompileOptions new];
47384777
options.languageVersion = MTLLanguageVersion3_0;
47394778
options.preserveInvariance = YES;
Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
#!/usr/bin/env python3
2+
"""Build selected hash-bound non-point vertex variants for the iOS Metal 3 fallback."""
3+
4+
import argparse
5+
import hashlib
6+
import json
7+
from pathlib import Path
8+
import re
9+
import subprocess
10+
from tempfile import TemporaryDirectory
11+
12+
13+
def digest(data: bytes) -> str:
14+
return hashlib.sha256(data).hexdigest()
15+
16+
17+
def build(sources: Path, manifest: Path, libraries: Path, keys: Path, output: Path) -> int:
18+
doc = json.loads(manifest.read_text())
19+
chain = doc["chain"]
20+
if doc["schema"] != 1 or not re.fullmatch(r"[0-9a-f]{12}", chain):
21+
raise ValueError("Invalid source manifest version or chain")
22+
if libraries.name != f"b-{chain}" or output.exists() or output.is_symlink():
23+
raise ValueError("Use the exact base library chain and a new output directory")
24+
selected = sorted(set(keys.read_text().split()))
25+
if not selected or any(not re.fullmatch(r"[0-9a-f]{16}_b", key) for key in selected):
26+
raise ValueError("Expected a nonempty list of vertex shader keys")
27+
28+
flags = ["-target", "air64-apple-ios16.1", "-std=metal3.0", "-fno-fast-math",
29+
"-fpreserve-invariance"]
30+
records = {}
31+
with TemporaryDirectory(prefix=".nonpoint-metal3-", dir=output.parent) as directory:
32+
tmp = Path(directory)
33+
stage = tmp / "published"
34+
stage.mkdir()
35+
for key in selected:
36+
record = doc["shaders"][key]
37+
source = (sources / (key + ".metal")).read_bytes()
38+
base = (libraries / (key + ".metallib")).read_bytes()
39+
if digest(source) != record["source_sha256"] or digest(base) != record["library_sha256"]:
40+
raise ValueError(f"Source or base library hash mismatch for {key}")
41+
needle = b"[[point_size]]"
42+
if needle not in source:
43+
raise ValueError(f"No point-size output for {key}")
44+
effective = source.replace(needle, b"[[user(dm_unused_point_size)]]")
45+
msl, air, lib = tmp / (key + ".metal"), tmp / (key + ".air"), stage / (key + ".metallib")
46+
msl.write_bytes(effective)
47+
subprocess.run(["xcrun", "-sdk", "iphoneos", "metal", *flags,
48+
f"-fmodules-cache-path={tmp / 'modules'}", "-c", msl, "-o", air], check=True)
49+
subprocess.run(["xcrun", "-sdk", "iphoneos", "metallib", air, "-o", lib], check=True)
50+
data = lib.read_bytes()
51+
if not data.startswith(b"MTLB"):
52+
raise ValueError(f"Invalid metallib for {key}")
53+
records[key] = {**record, "effective_source_sha256": digest(effective),
54+
"offline_sha256": digest(data)}
55+
msl.unlink()
56+
air.unlink()
57+
(stage / "manifest.json").write_text(
58+
json.dumps({"schema": 1, "chain": chain, "shaders": records}, sort_keys=True) + "\n"
59+
)
60+
stage.rename(output)
61+
return len(records)
62+
63+
64+
if __name__ == "__main__":
65+
parser = argparse.ArgumentParser(description=__doc__)
66+
parser.add_argument("--sources", type=Path, required=True, help="Exported non-point source directory")
67+
parser.add_argument("--manifest", type=Path, help="Defaults to the source directory's manifest.json")
68+
parser.add_argument("--libraries", type=Path, required=True, help="Exact b-<chain> directory")
69+
parser.add_argument("--keys", type=Path, required=True, help="Whitespace-separated vertex shader keys")
70+
parser.add_argument("--output", type=Path, required=True, help="New nonpoint-metal3-v1 directory")
71+
args = parser.parse_args()
72+
try:
73+
count = build(args.sources, args.manifest or args.sources / "manifest.json",
74+
args.libraries, args.keys, args.output)
75+
except (ValueError, OSError, KeyError, subprocess.CalledProcessError) as error:
76+
parser.exit(1, f"{error}\n")
77+
print(f"Built {count} Metal 3 non-point variants")

‎docs/reference/shaders.md‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1410,3 +1410,18 @@ handle used guest uniform slot 4, byte 40; its texture was separate slot 128, no
14101410
combined slot 1. An R16Uint pass separately rejected a float fragment output.
14111411
Synthetic production-parser, production-descriptor and GPU readback tests pass;
14121412
matching-chain full resources and device picture verification remain required.
1413+
1414+
### Offline non-point vertex variants on iOS Metal 3
1415+
1416+
The legacy Mario Kart World renderer can load selected non-point vertex
1417+
variants from `nonpoint-metal3-v1` under the game's MSL resource directory.
1418+
`dm/ios/tools/build_nonpoint_metal3.py` builds keys from the on-device
1419+
compile log against the exact companion source manifest and base libraries.
1420+
The loader checks the chain, source and library hashes, and argument buffer
1421+
length before using the variant. Missing or incompatible variants keep using
1422+
the existing compiler path. The original point and transform-feedback entry
1423+
stays in use for those draws.
1424+
1425+
On M2 with iPadOS 16.1 the legacy renderer loaded the packaged variants.
1426+
The title sequence still showed long frames with new pipeline compilation
1427+
and texture uploads; a cache hit does not establish gameplay frame rate.

0 commit comments

Comments
 (0)