mirror of
https://github.com/seedds/nxnative.git
synced 2026-11-23 11:39:42 -10:00
A shader build leaves a few files instead of one per shader output: finished shaders wait in cas.db and the image is written from there, so Octopath Traveler 0's build holds at most 328 files while it runs and about 65 when stopped, not 68,230 (chain c8849b34b7b0)
dmsh_build.py wrote each shader's outputs into b-<chain>/ and packed them into the image only at the end, restored every cache hit into that folder before translating anything, and had the translator write every missed shader's working files into one temporary folder that went only on a normal exit, so a stopped build kept them and every later build made another beside it. Now a finished shader's files go into the compile cache under stage/<output folder>/ and leave the disk (commit); reads of another shader's outputs (vs_pad's paired pixel MSL, the mesh step) take them from there (output); at the end publish_library writes the image from the staged outputs (with a partial build's image under it, less the keys it built) through shader_lib.write, which now takes a function per file, and the folder and the stage go. When the image cannot be written the staged outputs go back into the folder. Cache hits are restored when their shader is finished. Shaders are translated and finished in batches of 4 x J, the next batch translated while this one is finished, and a shader's working files go as soon as it is done. Each working folder holds its build's process ID; a later build removes one whose process is gone (sweep_work). The NSP script's progress comes from a file the build rewrites (DMSH_PROGRESS) instead of counting its files; the NSP script, regress.py and bug_report.py read the image where they read the folder; shader_cache.Store gains delete_prefix. The outputs are unchanged: Minecraft Dungeons II's 61,655 library files and Octopath Traveler 0's 41,880 are byte for byte those of chain cfcc3a82c78b (reflection without its chain field), apart from _b_cas.txt. Measured on an M4 Pro, every shader translated again: Octopath Traveler 0, at most 328 files under shader/ and tmp/ (12 outside a build), the step 2:38; stopped with SIGKILL, 40 files in b-<chain>/ and 7 in tmp/, which the next run cleared before writing the same library in 59 s. A partial build for the Mac and the iPhone leaves one image each. Shader, NSP, regress and docs tests and the Python lint pass; no game run (the host is unchanged by this commit).
This commit is contained in:
1 parent
51cc8bce3e
commit
9c2fb0c967
16 files changed
+324
-114
No files matched your search
@@ -87,6 +87,7 @@ General host changes first needed here; each applies to every game (or every Unr
|
||||
- **Rewriter:** byte tables far from their `br` (`jump_bytes_far`): [Byte tables whose add is far from the br](../../../docs/reference/rewriter.md#byte-tables-whose-add-is-far-from-the-br). Not first found here but met here: long functions analysed in pieces (`pieces`, [Long functions analysed in pieces](../../../docs/reference/rewriter.md#long-functions-analysed-in-pieces)) and spin waits that store (`patch_nso.py` "Spin waits", [development.md, Power](../../../docs/development.md#power)).
|
||||
- **Undefined weak imports bound to 0** (`loader.c`), **`vi::GetLatestFrameNumber`** (`hle_vi.c`), **`fs::GetSaveDataSizeMax`** (`hle_fs.c`), **NVN pool getters and `nvnCommandBufferFenceSync`** (`OP_FENCE_SYNC`), **the guest clock left running behind the software keyboard** (`hle_swkbd.c`, `front_ios.m`, `guest_clock_freeze_for`): [Undefined weak imports bind to 0](../../../docs/reference/services.md#undefined-weak-imports-bind-to-0), [Layer frame numbers](../../../docs/reference/services.md#layer-frame-numbers), [Save data size queries](../../../docs/reference/services.md#save-data-size-queries), [Pool size getters, texture address and command memory size](../../../docs/reference/nvn-objects.md#pool-size-getters-texture-address-and-command-memory-size), [Fence syncs recorded in command buffers](../../../docs/reference/nvn-objects.md#fence-syncs-recorded-in-command-buffers), [The software keyboard blocks only its caller](../../../docs/reference/services.md#the-software-keyboard-blocks-only-its-caller).
|
||||
- **`DM_ALIAS_WINDOWS`**, the alias-region window census: [05, Memory growth](../../../docs/agents/05-debugging.md#memory-growth).
|
||||
- **The shader build leaves a few files, not one per output** (`dmsh_build.py` stages finished shaders in `cas.db`, batches its translator's working files; first measured on this game's stopped build, 68,230 files): [A shader build leaves a file per shader output while it runs or after a stop](../../../docs/reference/packing.md#a-shader-build-leaves-a-file-per-shader-output-while-it-runs-or-after-a-stop).
|
||||
|
||||
## Open
|
||||
|
||||
|
||||
@@ -35,6 +35,7 @@ No host or rewriter rule is specific to this game.
|
||||
- [Layer frame history](../../../docs/reference/services.md#layer-frame-history)
|
||||
- [The offline pages of a sparse base game stop the build as a damaged NSP](../../../docs/reference/packing.md#the-offline-pages-of-a-sparse-base-game-stop-the-build-as-a-damaged-nsp)
|
||||
- [The survey's build ID lookup stops on the base game alone with a hash error](../../../docs/reference/packing.md#the-surveys-build-id-lookup-stops-on-the-base-game-alone-with-a-hash-error)
|
||||
- [A shader build leaves a file per shader output while it runs or after a stop](../../../docs/reference/packing.md#a-shader-build-leaves-a-file-per-shader-output-while-it-runs-or-after-a-stop): measured here, its 61,655 library files the same under the new chain
|
||||
|
||||
## Open
|
||||
|
||||
|
||||
@@ -1,3 +1,3 @@
|
||||
// Generated file (dm/gfx/tools/dmsh_chain.py --header): the B shader library translation chain version this source tree expects (default options), one for every game;
|
||||
// the host loads only <library dir>/b-<V>/. Run dmsh_chain.py --header after changing the chain's tools and commit this file with the change
|
||||
#define DMSH_CHAIN "23a1ea1db092"
|
||||
#define DMSH_CHAIN "c8849b34b7b0"
|
||||
+195
-47
@@ -2,14 +2,17 @@
|
||||
# Route B offline build: original Switch shaders → SPIR-V (dmsh_xlate, the Ryujinx translator) → spirv-cross MSL → metallib + replay reflection JSON.
|
||||
# No translation at runtime (iOS has no JIT): build output goes into the shader cache directory, file name = Switch control segment key (dm_ctl_sha16, same as column 4 of shader_map.tsv) + "_b".
|
||||
# Source of query answers: the answer table in the game profile, dm/games/<id>/shader_facts.tsv (dmsh_facts.py) - texture types, vertex attribute / fragment output component types, compute thread group size and shared memory.
|
||||
# Usage: dmsh_build.py <Switch package dir> <output cache dir> [key...] (no keys = all); build output is actually written to <output cache dir>/b-<chain version>/ (same for IOSOUT), for the chain version see dmsh_chain.py.
|
||||
# Usage: dmsh_build.py <Switch package dir> <output cache dir> [key...] (no keys = all); build output is the image <output cache dir>/b-<chain version>.img (same for IOSOUT; dm/tools/shader_lib.py), for the chain version see dmsh_chain.py.
|
||||
# The folder b-<chain version>/ beside it holds only the shaders in flight: a finished shader's files go into the shader cache (cas.db, under stage/), and the image is written from there
|
||||
# at the end (publish_library), so a build, stopped or not, leaves a few files and not one per shader output (Octopath Traveler 0, stopped in its compile: 68,230 files). The translator's
|
||||
# working files go into a folder per batch of shaders, removed when the batch is done; a working folder whose build is gone is removed at the next start (sweep_work).
|
||||
# A full build (no keys) also stamps both directories with the game and the digest of its profile inputs (inputs.tsv) and writes the profile's c1_full.tsv and cb_extent.tsv (c1_guard.py, cb_extent.py)
|
||||
# from its Mac outputs. One output directory per game: the chain version is the same for every game Environment: DM_GAME=game profile (required, dm/games/<id>), XLATE=path to the translation tool (default the in-repo dmsh_xlate_bin), DMSH_CAS=the compile cache, one file (shader_cache.py; default <output cache dir>/cas.db), DMSH_PREFILL=Mac library root[=iOS library root] (separated by :, their b-*/ go into the MSL-keyed compile cache first; sibling b-*/ always do), J=concurrency
|
||||
# Build output: <key>_b.metallib, <key>_b.json (replay reflection, including drv_reads, the runtime read offsets into driver segments c0 / c2), <key>_b.metal (MSL)
|
||||
# Environment IOSOUT=dir: the same MSL also goes through dm/ios/tools/ios_metal.compile to produce an iphoneos metallib + reflection (chain_metal records the iOS compile convention)
|
||||
# Final summary: success / failure counts and the distribution of reasons; distribution of driver segment read offsets (those outside the range the replay layer can fill are listed separately);
|
||||
# a [RED] line per shader that built but lost something (shader_regressions.report_losses), which does not change the exit status
|
||||
import atexit, inspect, os, re, sys, json, mmap, struct, hashlib, shutil, subprocess, tempfile, collections, threading, concurrent.futures as cf
|
||||
import atexit, inspect, os, re, sys, json, mmap, struct, hashlib, shutil, subprocess, tempfile, time, collections, threading, concurrent.futures as cf
|
||||
import dmsh_geometry, dmsh_atomic, dmsh_wide, dmsh_meshstage, dmsh_abi as abi # abi: the driver segment layout and the binding kinds the host shares (dm/gfx/nvn/dmsh_abi.h)
|
||||
DM_ROOT = os.environ.get('DM_ROOT') or os.path.expanduser('~/dm-work') # Workspace root (game files, build outputs and run artifacts are all under it)
|
||||
HOME = os.path.expanduser('~')
|
||||
@@ -37,8 +40,9 @@ IOS_PULL = os.environ.get('DMSH_IOS_PULL') != '0' # DMSH_IOS_PULL=0: no iOS pu
|
||||
if IOSOUT:
|
||||
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '../../ios/tools')); import ios_metal
|
||||
IOSOUT = os.path.join(IOSOUT, 'b-' + CHAIN); os.makedirs(IOSOUT, exist_ok=True)
|
||||
import shader_lib, romfs # dm/tools (on the path shader_regressions puts it): the library's image, which this build writes (publish_library)
|
||||
for _d in [out] + ([IOSOUT] if IOSOUT else []): # one chain version serves every game, so b-<V>/ alone does not keep two games' libraries apart
|
||||
_g = dmsh_chain.read_stamp(_d).get('game')
|
||||
_g = shader_lib.read_stamp(_d).get('game')
|
||||
if _g and _g != GAME.id: sys.exit(f'[RED] {_d} holds the shader libraries of game {_g}, not {GAME.id}: give each game its own output directory')
|
||||
MAP = str(GAME.table('shader_map.tsv'))
|
||||
BF_WANT_FILE = str(GAME.table('bf_want.tsv'))
|
||||
@@ -391,6 +395,63 @@ def cache_meta_path(key): return f'index/{key}.json'
|
||||
def cache_path(digest): return f'shader/{digest}'
|
||||
CAS_USED = '_b_cas.txt' # in the Mac library directory b-<V>/: the cache_path digests of its last full build, one per line
|
||||
|
||||
# A finished shader's outputs are staged in the cache, under a name of this output folder's, and leave the disk (commit); the image is written from them at the end (publish_library).
|
||||
# A stopped build leaves them there, and the next build of this folder clears them first: its shaders come back from the cache entries publish_cache wrote
|
||||
STAGE = 'stage/' + hashlib.sha256(os.path.realpath(out).encode()).hexdigest()[:16]
|
||||
def label_dir(label) -> str: return out if label == 'mac' else IOSOUT or '' # '' when this build makes no iPhone libraries
|
||||
|
||||
def output(label, name):
|
||||
"""An output file's bytes: on disk while its shader is in flight, else staged; for a partial build, a shader it does not build is read from the image it builds on. None when there is none"""
|
||||
try:
|
||||
if label_dir(label):
|
||||
with open(os.path.join(label_dir(label), name), 'rb') as f: return f.read()
|
||||
except FileNotFoundError: pass
|
||||
data = STORE.get(f'{STAGE}/{label}/{name}') # put before its file is removed (commit), so a file gone meanwhile is found here
|
||||
if data is not None or not want: return data
|
||||
m = OUT_KEY.match(name); old = OLD_IMAGE.get(label)
|
||||
if old is None or not m or m.group(1) in want: return None # a key this build makes has no older outputs: the start removed them
|
||||
try: return (old / name).read_bytes()
|
||||
except OSError: return None
|
||||
|
||||
def output_of(label, name) -> bytes: # an output its shader has just written or restored: there is one
|
||||
data = output(label, name)
|
||||
if data is None: raise FileNotFoundError(f'{label}/{name}: no such output')
|
||||
return data
|
||||
|
||||
def commit(key='', names=None):
|
||||
"""A finished shader's files (<key>_*, or the names given) into the cache's stage and off the disk. A file the cache could not take (a full drive) stays on disk, where publish_library finds it too"""
|
||||
with STORE.batch():
|
||||
for label in ('mac', 'ios'):
|
||||
d = label_dir(label)
|
||||
if not d: continue
|
||||
for n in (names if names is not None else [n for n in os.listdir(d) if n.startswith(key + '_')]):
|
||||
p = os.path.join(d, n)
|
||||
if n.startswith('.') or '.tmp' in n or not os.path.isfile(p): continue
|
||||
STORE.put_file(f'{STAGE}/{label}/{n}', p)
|
||||
if not STORE.full: os.unlink(p)
|
||||
|
||||
def publish_library(label):
|
||||
"""The library's image <dir>.img from the staged outputs and the files left on disk (these win), and for a partial build the image it builds on, less the outputs of the keys it built
|
||||
(and its stamp, when the profile's inputs changed). Then the folder and the staged entries go. When the image cannot be written, the staged outputs go back into the folder, which works as it is"""
|
||||
d = label_dir(label); image = shader_lib.image_of(d); prefix = f'{STAGE}/{label}/'
|
||||
files = {}
|
||||
old = OLD_IMAGE.get(label)
|
||||
if old is not None:
|
||||
for p in old.iterdir():
|
||||
m = OUT_KEY.match(p.name)
|
||||
if (m and m.group(1) in want) or (p.name == dmsh_chain.STAMP and STAMP_BEFORE != INPUTS): continue
|
||||
files[p.name] = str(p)
|
||||
for n in STORE.names(prefix): files[n[len(prefix):]] = (lambda n=n: STORE.get(n))
|
||||
for n in os.listdir(d):
|
||||
if not n.startswith('.') and '.tmp' not in n and os.path.isfile(os.path.join(d, n)): files[n] = os.path.join(d, n)
|
||||
try: shader_lib.write(files, image)
|
||||
except (OSError, ValueError) as e:
|
||||
print(f'[RED] could not write {image}, the library stays the folder {d}: {e}', flush=True)
|
||||
for n in STORE.names(prefix): STORE.to_file(n, os.path.join(d, n[len(prefix):]))
|
||||
return
|
||||
STORE.delete_prefix(prefix)
|
||||
shutil.rmtree(d, ignore_errors=True)
|
||||
|
||||
def cache_outputs(key, digest, cached=False):
|
||||
root = cache_path(digest); files = {}
|
||||
for label, directory in (('mac', out), ('ios', IOSOUT)):
|
||||
@@ -423,10 +484,10 @@ def restore_cache(key, digest):
|
||||
elif not STORE.to_file(src, dst): return False
|
||||
return True
|
||||
|
||||
def cache_lookup(key, digest, rule_fp, code_fp):
|
||||
def cache_lookup(key, digest, rule_fp, code_fp): # whether the cache holds the shader's outputs; they are restored when the shader is finished (fin), so they are on disk only while it is in flight
|
||||
with CAS_LOCKS_GUARD: lock = CAS_LOCKS.setdefault(('shader', key), threading.Lock())
|
||||
with lock:
|
||||
if restore_cache(key, digest): PRE_STATS['hit'] += 1; return True, 'hit'
|
||||
if cache_outputs(key, digest, cached=True): PRE_STATS['hit'] += 1; return True, 'hit'
|
||||
old = json.loads(STORE.get(cache_meta_path(key)) or b'null')
|
||||
if old and old.get('code_fp') != code_fp: reason = 'code fingerprint changed: all rebuilt'
|
||||
elif old and old.get('rule_fp') != rule_fp: reason = 'rule changed'
|
||||
@@ -435,7 +496,7 @@ def cache_lookup(key, digest, rule_fp, code_fp):
|
||||
|
||||
def publish_cache(key, digest, rule_fp, code_fp):
|
||||
# Paired pixel MSL is an input to vs_pad; a diagnostic build without it must not cache an incomplete vertex shader under a complete dependency key.
|
||||
if any(not os.path.isfile(os.path.join(out, ps + '_b.metal')) for ps in PAIRS.get(key, ())): return
|
||||
if any(output('mac', ps + '_b.metal') is None for ps in PAIRS.get(key, ())): return
|
||||
found = cache_outputs(key, digest)
|
||||
if not found: return
|
||||
root, files = found
|
||||
@@ -1125,9 +1186,8 @@ def vs_pad(key, src):
|
||||
(over 10,000 "Fragment input(s) user(locnN) ... not written by vertex shader" in one iPhone session after the opening course). Returns (new source, padded locations); pairs whose pixel MSL cannot be read are skipped."""
|
||||
want = set()
|
||||
for ps in PAIRS.get(key, ()):
|
||||
fn = os.path.join(out, ps + '_b.metal')
|
||||
if os.path.exists(fn):
|
||||
with open(fn) as f: want |= {int(x) for x in re.findall(r'\[\[user\(locn(\d+)\)', f.read())}
|
||||
data = output('mac', ps + '_b.metal') # finished before this vertex shader (fin's phases), so staged in the cache by now
|
||||
if data is not None: want |= {int(x) for x in re.findall(r'\[\[user\(locn(\d+)\)', data.decode())}
|
||||
miss = sorted(want - {int(x) for x in re.findall(r'\[\[user\(locn(\d+)\)', src)})
|
||||
i = src.find('struct main0_out\n{\n'); j = src.find('\n};', i); k = src.find('main0_out out = {};')
|
||||
if not miss or i < 0 or j < 0 or k < 0: return src, []
|
||||
@@ -1568,31 +1628,75 @@ def finish(key, w, j, c1):
|
||||
keys = build_keys(want, loc, PAIRS)
|
||||
if want: want = set(keys) # dependency outputs are cleaned too, so a failed pixel build cannot leave old MSL for padding
|
||||
NJ = int(os.environ.get('J', '8'))
|
||||
os.makedirs(out, exist_ok=True)
|
||||
BATCH = 4 * NJ # shaders translated and finished together: the next batch is translated while this one is finished, and a shader's working files go when it is (fin).
|
||||
# Minecraft Dungeons II, 15,826 shaders: at most 3,279 files under the build folder with batches of 256 removed whole, 68,230 before batches (Octopath Traveler 0's stopped build)
|
||||
# A full build starts from no shader outputs, a partial one from none of the keys it builds, so what a run leaves is what it built: every output is restored from the cache anyway.
|
||||
# The chain version is the same whatever the profile's tables, so a key that left the map, a shader that no longer builds or a variant no longer made would keep an old library.
|
||||
# The stamp goes too, and a full build writes it at the end; a partial build keeps it only while it names the profile's current inputs
|
||||
# The stamp goes too, and a full build writes it at the end; a partial build keeps it only while it names the profile's current inputs.
|
||||
# A full build also removes the image (as the NSP script does before it): a stopped build leaves no library, rather than one with old shaders for those it had not reached. A partial build
|
||||
# builds on the image (OLD_IMAGE), less the outputs of the keys it builds, which publish_library leaves out
|
||||
OUT_KEY = re.compile(r'([0-9a-f]{16})_b')
|
||||
STAMP_BEFORE = dmsh_chain.read_stamp(out).get('inputs')
|
||||
for _d in [out] + ([IOSOUT] if IOSOUT else []):
|
||||
for _n in os.listdir(_d):
|
||||
STAMP_BEFORE = shader_lib.read_stamp(out).get('inputs')
|
||||
OLD_IMAGE = {}
|
||||
for _label, _d in (('mac', out), ('ios', IOSOUT)):
|
||||
if not _d: continue
|
||||
if not want:
|
||||
shutil.rmtree(_d, ignore_errors=True); shader_lib.remove_image(_d)
|
||||
elif os.path.isfile(shader_lib.image_of(_d)): OLD_IMAGE[_label] = romfs.Path(shader_lib.image_of(_d))
|
||||
os.makedirs(_d, exist_ok=True)
|
||||
for _n in os.listdir(_d): # a partial build over a folder (an older chain's, or one a stopped build left)
|
||||
_m = OUT_KEY.match(_n)
|
||||
if _m and (not want or _m.group(1) in want): os.unlink(os.path.join(_d, _n))
|
||||
if (not want or STAMP_BEFORE != INPUTS) and os.path.exists(os.path.join(_d, dmsh_chain.STAMP)): os.unlink(os.path.join(_d, dmsh_chain.STAMP))
|
||||
if not want and os.path.exists(os.path.join(_d, CAS_USED)): os.unlink(os.path.join(_d, CAS_USED)) # written again at the end, with the stamp
|
||||
w = tempfile.mkdtemp(prefix='dmsh_', dir=os.environ.get('WORK'))
|
||||
if _m and _m.group(1) in want: os.unlink(os.path.join(_d, _n))
|
||||
if STAMP_BEFORE != INPUTS and os.path.exists(os.path.join(_d, dmsh_chain.STAMP)): os.unlink(os.path.join(_d, dmsh_chain.STAMP))
|
||||
STORE.delete_prefix(STAGE + '/') # what a stopped build of this folder staged
|
||||
|
||||
def sweep_work(root):
|
||||
"""The working folders (dmsh_*) a build left that is no longer running: each holds the process ID of its build (pid), one from before that is taken after a day.
|
||||
Octopath Traveler 0's build, stopped in its compile, left 38,376 files there, and every later build made another folder beside it"""
|
||||
for d in (os.path.join(root, n) for n in os.listdir(root) if n.startswith('dmsh_')) if os.path.isdir(root) else ():
|
||||
try:
|
||||
with open(os.path.join(d, 'pid')) as f: pid = int(f.read())
|
||||
try: os.kill(pid, 0); continue # its build runs
|
||||
except ProcessLookupError: pass
|
||||
except PermissionError: continue
|
||||
except (OSError, ValueError):
|
||||
try:
|
||||
if time.time() - os.stat(d).st_mtime < 86400: continue
|
||||
except OSError: continue
|
||||
shutil.rmtree(d, ignore_errors=True)
|
||||
_work = os.environ.get('WORK') or tempfile.gettempdir()
|
||||
sweep_work(_work)
|
||||
w = tempfile.mkdtemp(prefix='dmsh_', dir=_work)
|
||||
with open(os.path.join(w, 'pid'), 'w') as _f: _f.write(str(os.getpid()))
|
||||
MTL = dmsh_mtlcache.Cache(STORE, {'mac': ('macosx', MAC_RECORD, mac_compile), **({'ios': ('iphoneos', ios_metal.RECORD, ios_metal.compile)} if IOSOUT else {})}, w)
|
||||
# first take the libraries earlier chain versions left on disk: the b-*/ beside the output (iOS: the folder of the same name) and the roots DMSH_PREFILL lists
|
||||
# first take the libraries earlier chain versions left on disk: the b-*/ and b-*.img beside the output (iOS: the folder of the same name) and the roots DMSH_PREFILL lists
|
||||
for _spec in [cache_root + ('=' + os.path.dirname(IOSOUT) if IOSOUT else '')] + [x for x in os.environ.get('DMSH_PREFILL', '').split(os.pathsep) if x]:
|
||||
_mac, _, _ios = _spec.partition('=')
|
||||
for _b in sorted(os.listdir(_mac)) if os.path.isdir(_mac) else []:
|
||||
if _b.startswith('b-') and os.path.realpath(os.path.join(_mac, _b)) != os.path.realpath(out):
|
||||
if _b.startswith('b-') and os.path.realpath(shader_lib.folder_of(os.path.join(_mac, _b))) != os.path.realpath(out):
|
||||
for _ln in MTL.fill(os.path.join(_mac, _b), os.path.join(_ios, _b) if _ios else None, targets=TARGETS): print(_ln, flush=True)
|
||||
|
||||
# Progress for the NSP script (DMSH_PROGRESS: a small JSON file it reads, build_ipa_from_nsp.py ShaderWatch), written at most every half second
|
||||
PROGRESS = os.environ.get('DMSH_PROGRESS')
|
||||
_prog = {'t': 0.0, 'lock': threading.Lock()}
|
||||
def progress(step, done, total, force=False, **extra):
|
||||
if not PROGRESS: return
|
||||
with _prog['lock']:
|
||||
now = time.time()
|
||||
if not force and now - _prog['t'] < 0.5: return
|
||||
_prog['t'] = now
|
||||
try:
|
||||
with open(PROGRESS + '.tmp', 'w') as f: json.dump({'step': step, 'done': done, 'total': total, **extra}, f)
|
||||
os.replace(PROGRESS + '.tmp', PROGRESS)
|
||||
except OSError: pass
|
||||
|
||||
packs, jobs, c1s = {}, {}, {}
|
||||
packs_lock = threading.Lock()
|
||||
digests, rule_fps, cache_reasons, cache_hits = {}, {}, {}, set()
|
||||
def rec_of(key): # → (package name, the shader's record), read from the package each time and not kept (see record_index)
|
||||
name, k = loc[key]
|
||||
if name not in packs: packs[name] = record_index(os.path.join(dm_dir, name))
|
||||
with packs_lock:
|
||||
if name not in packs: packs[name] = record_index(os.path.join(dm_dir, name))
|
||||
fd, offs = packs[name]
|
||||
return name, os.pread(fd, offs[k + 1] - offs[k], offs[k])
|
||||
for key in keys: digests[key] = shader_key(key, *rec_of(key))
|
||||
@@ -1601,45 +1705,78 @@ def plain_digest(k): # a paired pixel shader's key, also when it is not built
|
||||
return shader_key(k, *rec_of(k)) if k in loc else 'missing'
|
||||
for key in keys:
|
||||
if PAIRS.get(key): digests[key] = pair_keyed(digests[key], [plain_digest(p) for p in sorted(PAIRS[key])])
|
||||
for key in keys:
|
||||
for i, key in enumerate(keys):
|
||||
name = loc[key][0]
|
||||
rule_fps[key] = hashlib.sha256(shader_rule_source(name) + ','.join(sorted(PAIRS.get(key, ()))).encode()).hexdigest() # the vertex shader must be rebuilt when its pairs change (vs_pad)
|
||||
hit, cache_reasons[key] = cache_lookup(key, digests[key], rule_fps[key], CODE_FP)
|
||||
if hit: cache_hits.add(key)
|
||||
else: jobs[key], c1s[key] = job_for(key, name, rec_of(key)[1], w)
|
||||
misses = [key for key in keys if key not in cache_hits]
|
||||
chunks = [misses[i::NJ] for i in range(NJ)]
|
||||
def xl(ch):
|
||||
jp = os.path.join(w, f'job_{abs(hash(ch[0]))}.json'); json.dump([jobs[k] for k in ch], open(jp, 'w'))
|
||||
return subprocess.run([XLATE, jp, w], capture_output=True, text=True)
|
||||
with cf.ThreadPoolExecutor(NJ) as ex: xr = list(ex.map(xl, [c for c in chunks if c]))
|
||||
progress('cache check', i + 1, len(keys), cached=len(cache_hits))
|
||||
NMISS = sum(1 for k in keys if k not in cache_hits)
|
||||
xerr = {}
|
||||
for r in xr:
|
||||
def xlate_errors(r):
|
||||
for ln in r.stderr.splitlines():
|
||||
m = re.match(r'\[RED\] (\w+): (.*)', ln)
|
||||
if m: xerr[m.group(1)] = m.group(2)[:160]
|
||||
def fin(key):
|
||||
if key in cache_hits:
|
||||
refl = json.load(open(os.path.join(out, key + '_b.json')))
|
||||
src = open(os.path.join(out, key + '_b.metal')).read() if refl['stage'] in ('ps', 'vs') else ''
|
||||
if refl['stage'] == 'vs': write_refl(key, pull_finish(key, src, vin_finish(key, src, refl)))
|
||||
if refl['stage'] == 'ps': refl.update(ps_libraries(key, os.path.join(out, key + '_b.metal'), src))
|
||||
return key, 'ok', '', fetch_finish(key, src, refl)
|
||||
if key in xerr or not os.path.exists(os.path.join(w, key + '.spv')): return key, 'translation failed', xerr.get(key, 'no spv'), None
|
||||
result = (key,) + finish(key, w, jobs[key], c1s[key])
|
||||
if result[1] == 'ok': publish_cache(key, digests[key], rule_fps[key], CODE_FP)
|
||||
return result
|
||||
with cf.ThreadPoolExecutor(NJ) as ex: # two phases: paired vertex shaders read their pixel shaders' MSL (vs_pad), so they go last
|
||||
res = list(ex.map(fin, [k for k in keys if k not in PAIRS])) + list(ex.map(fin, [k for k in keys if k in PAIRS]))
|
||||
def translate(batch):
|
||||
"""A batch's misses translated into a working folder of its own (removed once the batch is finished) → that folder"""
|
||||
wb = tempfile.mkdtemp(prefix='batch_', dir=w)
|
||||
miss = [k for k in batch if k not in cache_hits]
|
||||
for k in miss: jobs[k], c1s[k] = job_for(k, loc[k][0], rec_of(k)[1], wb)
|
||||
def xl(ch):
|
||||
jp = os.path.join(wb, f'job_{abs(hash(ch[0]))}.json'); json.dump([jobs[k] for k in ch], open(jp, 'w'))
|
||||
return subprocess.run([XLATE, jp, wb], capture_output=True, text=True)
|
||||
with cf.ThreadPoolExecutor(NJ) as ex:
|
||||
for r in ex.map(xl, [c for c in (miss[i::NJ] for i in range(NJ)) if c]): xlate_errors(r)
|
||||
return wb
|
||||
def restored(key, wb):
|
||||
"""A cache hit's outputs back on disk while it is finished. When another build pruned them since the look (cache_lookup), the shader is translated now, in the batch's folder: False"""
|
||||
if restore_cache(key, digests[key]): return True
|
||||
PRE_STATS['hit'] -= 1; PRE_STATS['miss'] += 1; PRE_STATS['pruned meanwhile'] += 1
|
||||
jobs[key], c1s[key] = job_for(key, loc[key][0], rec_of(key)[1], wb)
|
||||
jp = os.path.join(wb, f'job1_{key}.json'); json.dump([jobs[key]], open(jp, 'w'))
|
||||
xlate_errors(subprocess.run([XLATE, jp, wb], capture_output=True, text=True))
|
||||
return False
|
||||
DONE = collections.Counter()
|
||||
def fin(key, wb):
|
||||
try:
|
||||
if key in cache_hits and restored(key, wb):
|
||||
refl = json.loads(output_of('mac', key + '_b.json'))
|
||||
src = output_of('mac', key + '_b.metal').decode() if refl['stage'] in ('ps', 'vs') else ''
|
||||
if refl['stage'] == 'vs': write_refl(key, pull_finish(key, src, vin_finish(key, src, refl)))
|
||||
if refl['stage'] == 'ps': refl.update(ps_libraries(key, os.path.join(out, key + '_b.metal'), src))
|
||||
return key, 'ok', '', fetch_finish(key, src, refl)
|
||||
if key in xerr or not os.path.exists(os.path.join(wb, key + '.spv')): return key, 'translation failed', xerr.get(key, 'no spv'), None
|
||||
result = (key,) + finish(key, wb, jobs[key], c1s[key])
|
||||
if result[1] == 'ok': publish_cache(key, digests[key], rule_fps[key], CODE_FP)
|
||||
return result
|
||||
finally:
|
||||
commit(key)
|
||||
with os.scandir(wb) as it: # its working files (<key>.bin / .spv / .res.json / .metal, the geometry variants' <key>_g<n>.*, job1_<key>.json)
|
||||
for e in it:
|
||||
if e.name.startswith((key, 'job1_' + key)) and e.is_file(): os.unlink(e.path)
|
||||
with _prog['lock']: DONE['n'] += 1; n = DONE['n']
|
||||
progress('compiling', n, len(keys), cached=len(cache_hits), misses=NMISS)
|
||||
# Two phases: paired vertex shaders read their pixel shaders' MSL (vs_pad), so they go last, in batches of their own. The next batch is translated while this one is finished
|
||||
batches = [b[i:i + BATCH] for b in ([k for k in keys if k not in PAIRS], [k for k in keys if k in PAIRS]) for i in range(0, len(b), BATCH)]
|
||||
res = []
|
||||
with cf.ThreadPoolExecutor(1) as tx, cf.ThreadPoolExecutor(NJ) as ex:
|
||||
nxt = tx.submit(translate, batches[0]) if batches else None
|
||||
for i, batch in enumerate(batches):
|
||||
assert nxt is not None
|
||||
wb = nxt.result()
|
||||
nxt = tx.submit(translate, batches[i + 1]) if i + 1 < len(batches) else None
|
||||
res += list(ex.map(lambda k, wb=wb: fin(k, wb), batch))
|
||||
shutil.rmtree(wb, ignore_errors=True)
|
||||
# Passthrough geometry as mesh shaders (dmsh_mesh.py): <vertex key>_<geometry key>_m3 for each pair in the profile's geo_mesh.tsv whose two libraries exist; the host
|
||||
# draws a lean triangle-list geometry draw with it when its pair has one, and through the compute path otherwise (nvn_geometry.inc geo_mesh_draw)
|
||||
MESH_STATS = collections.Counter()
|
||||
def mesh_finish(pair):
|
||||
vk, gk = pair
|
||||
srcs = [os.path.join(out, n) for n in (vk + '_b.metal', gk + '_bl3.metal', gk + '_bl3.json')]
|
||||
libs = [os.path.join(out, f'{vk}_{gk}_m3.metallib')] + ([os.path.join(IOSOUT, f'{vk}_{gk}_m3.metallib')] if IOSOUT else [])
|
||||
if not all(os.path.exists(p) for p in srcs): MESH_STATS['missing a library'] += 1; return
|
||||
try: msl = dmsh_mesh.compose(open(srcs[0]).read(), open(srcs[1]).read(), json.load(open(srcs[2]))['geometry']['capture_reads'])
|
||||
vs, gs, gj = (output('mac', n) for n in (vk + '_b.metal', gk + '_bl3.metal', gk + '_bl3.json')) # staged by now
|
||||
name = f'{vk}_{gk}_m3.metallib'
|
||||
libs = [os.path.join(out, name)] + ([os.path.join(IOSOUT, name)] if IOSOUT else [])
|
||||
if vs is None or gs is None or gj is None: MESH_STATS['missing a library'] += 1; return
|
||||
try: msl = dmsh_mesh.compose(vs.decode(), gs.decode(), json.loads(gj)['geometry']['capture_reads'])
|
||||
except ValueError as e: MESH_STATS['not composed'] += 1; print(f'[RED] mesh {vk} {gk}: {e}', flush=True); return
|
||||
path = os.path.join(w, f'{vk}_{gk}_m3.metal'); open(path, 'w').write(msl)
|
||||
try:
|
||||
@@ -1647,6 +1784,10 @@ def mesh_finish(pair):
|
||||
if IOSOUT: MTL.compile('ios', path, libs[1])
|
||||
MESH_STATS['built'] += 1
|
||||
except subprocess.CalledProcessError as e: MESH_STATS['failed to compile'] += 1; print(f'[RED] mesh {vk} {gk}: does not compile ({str(e)[:120]})', flush=True)
|
||||
finally:
|
||||
try: os.unlink(path)
|
||||
except FileNotFoundError: pass
|
||||
commit(names=[name])
|
||||
_mesh = GAME.table('geo_mesh.tsv')
|
||||
if _mesh.exists():
|
||||
with cf.ThreadPoolExecutor(NJ) as ex: list(ex.map(mesh_finish, [tuple(ln.split()[:2]) for ln in _mesh.read_text().splitlines() if ln.strip() and not ln.startswith('#')]))
|
||||
@@ -1691,6 +1832,13 @@ if not want: # a full build: the stamp, then the c1 guard and uniform read ext
|
||||
os.replace(os.path.join(out, CAS_USED + '.tmp'), os.path.join(out, CAS_USED))
|
||||
for _d in [out] + ([IOSOUT] if IOSOUT else []): dmsh_chain.write_stamp(_d, GAME.id, INPUTS)
|
||||
print(f'library stamp: game {GAME.id}, inputs {INPUTS}', flush=True)
|
||||
# The libraries' images, from what this build staged (and for a partial build the images it builds on): the folders go, and what reads a library from here on reads the image
|
||||
for _label in ('mac', 'ios'):
|
||||
if label_dir(_label): publish_library(_label)
|
||||
if PROGRESS:
|
||||
try: os.unlink(PROGRESS)
|
||||
except FileNotFoundError: pass
|
||||
if not want:
|
||||
for _tool, _table in (('c1_guard.py', 'c1_full.tsv'), ('cb_extent.py', 'cb_extent.tsv')):
|
||||
_r = subprocess.run([sys.executable, os.path.join(os.path.dirname(os.path.abspath(__file__)), _tool), out, str(GAME.table(_table))], capture_output=True, text=True)
|
||||
if _r.returncode: sys.exit(f'[RED] {_tool} failed ({_r.returncode}): {_r.stderr.strip()[-500:]}')
|
||||
|
||||
@@ -14,7 +14,6 @@ pyright dm/gfx/tools/dmsh_build.py reportCallIssue 1 No overloads for "open" mat
|
||||
pyright dm/gfx/tools/dmsh_build.py reportCallIssue 2 No overloads for "join" match the provided arguments
|
||||
pyright dm/gfx/tools/dmsh_build.py reportGeneralTypeIssues 2 "None" is not iterable "__iter__" method not defined
|
||||
pyright dm/gfx/tools/dmsh_build.py reportOptionalMemberAccess 3 "group" is not a known attribute of "None"
|
||||
pyright dm/gfx/tools/dmsh_build.py reportOptionalSubscript 13 Object of type "None" is not subscriptable
|
||||
pyright dm/gfx/tools/gl_shaders.py reportArgumentType 1 Argument of type "list[str]" cannot be assigned to parameter "iterable" of type "Iterable[LiteralString]" in function "join" "list[str]" is not assignable to "Iterable[LiteralString]" Type parameter "_T_co@Iterable" is covariant, but "str" is not a subtype of "LiteralString" "str" is not assignable to "LiteralString"
|
||||
pyright dm/gfx/tools/gl_shaders.py reportCallIssue 1 No overloads for "join" match the provided arguments
|
||||
pyright dm/gfx/tools/shader_split.py reportArgumentType 1 Argument of type "Literal['m_Name']" cannot be assigned to parameter "s" of type "slice[SupportsIndex | None, SupportsIndex | None, SupportsIndex | None]" in function "__getitem__" "Literal['m_Name']" is not assignable to "slice[SupportsIndex | None, SupportsIndex | None, SupportsIndex | None]"
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 2 and column 73.
|
@@ -116,6 +116,17 @@ class Store:
|
||||
self._run('PRAGMA incremental_vacuum')
|
||||
return len(gone), sum(size.get(d, 0) for d in gone)
|
||||
|
||||
def delete_prefix(self, prefix):
|
||||
"""Remove every entry whose name starts with prefix, and the bytes nothing names any more, giving their pages back (dmsh_build.py's staged outputs once its image is written)"""
|
||||
with self.lock:
|
||||
try:
|
||||
with self.batch():
|
||||
self.db.execute('DELETE FROM entry WHERE name>=? AND name<?', (prefix, prefix + '\U0010ffff'))
|
||||
self.db.execute('DELETE FROM blob WHERE id NOT IN (SELECT blob FROM entry)')
|
||||
except sqlite3.DatabaseError as e:
|
||||
if not self._damage(e): raise
|
||||
self._run('PRAGMA incremental_vacuum')
|
||||
|
||||
def close(self): # also folds the write-ahead log into the file, so that one file is left
|
||||
with self.lock, contextlib.suppress(sqlite3.Error): self.db.close()
|
||||
|
||||
|
||||
@@ -11,7 +11,8 @@
|
||||
# (a full drive) is one [RED] line, not an error: the build is done, and the folder works.
|
||||
# An iPhone library may leave out the pulling vertex libraries when nothing will read them (pack's leave_out), which the marker PULLING_LEFT_OUT inside it says: the build that needs them compiles them,
|
||||
# and pack_ipa.py refuses to pack such an image for an app that needs them, which would fail only on the device.
|
||||
# Not part of the translation chain: it decides no output (dmsh_chain.py), and dmsh_build.py still writes a folder.
|
||||
# Not part of the translation chain: it decides no output (dmsh_chain.py). dmsh_build.py writes the image itself (write, from the outputs it staged in the shader cache), and its folder holds
|
||||
# only the shaders in flight; pack is for a folder an older chain's dmsh_build.py wrote (regress.py builds old revisions) or a build stopped before that.
|
||||
# Usage: shader_lib.py pack <lib> the folder into the image
|
||||
# shader_lib.py expand <lib> the image back into a folder, only for a host from before this change
|
||||
# shader_lib.py path <lib> what to read: the folder or the image
|
||||
@@ -71,7 +72,8 @@ def _names(folder):
|
||||
|
||||
|
||||
def write(files, dst):
|
||||
"""files: {name: path to read (a romfs path may name a file inside an image) or the bytes} → the image dst, by way of dst.part. A stopped write leaves only the .part, and an image is whole or absent"""
|
||||
"""files: {name: path to read (a romfs path may name a file inside an image), the bytes, or a function returning them (read only when its file is written: dmsh_build.py's outputs staged in the
|
||||
shader cache, so that no library is held in memory whole)} → the image dst, by way of dst.part. A stopped write leaves only the .part, and an image is whole or absent"""
|
||||
part = dst + '.part'
|
||||
names = sorted((n.encode() for n in files))
|
||||
ents, off = [], romfs.HEAD.size
|
||||
@@ -81,7 +83,10 @@ def write(files, dst):
|
||||
off += -off % ALIGN
|
||||
out.seek(off)
|
||||
n, source = 0, files[name.decode()]
|
||||
if callable(source): source = source()
|
||||
if source is None: raise OSError(f'{name.decode()}: no bytes to write')
|
||||
if isinstance(source, bytes): out.write(source); n = len(source)
|
||||
elif not isinstance(source, (str, os.PathLike)): raise TypeError(f'{name.decode()}: {type(source).__name__} is not a path, bytes or a function')
|
||||
else:
|
||||
with romfs.open(source, 'rb') as f:
|
||||
while b := f.read(8 << 20): out.write(b); n += len(b)
|
||||
|
||||
@@ -319,12 +319,15 @@ class Nvn(Base):
|
||||
self.build(True); self.assertEqual(len(self.ran), 1)
|
||||
self.build(True); self.assertEqual(self.ran, [])
|
||||
|
||||
def test_shader_watch_finishes_extra_pairs_last(self):
|
||||
(self.tmp / 'shader_map.tsv').write_text('p.bin\t0\tvs\ta\tsrc\np.bin\t1\tps\tb\tsrc\np.bin\t2\tvs\tc\tsrc\n')
|
||||
(self.tmp / 'shader_pairs.tsv').write_text('c\tb\n')
|
||||
pso = self.tmp / 'pso_pairs.tsv'; pso.write_text('a\tb\n')
|
||||
watch = nsp.ShaderWatch(self.g, self.tmp, self.tmp, pso)
|
||||
self.assertEqual(list(watch.pos), ['b', 'a', 'c'])
|
||||
def test_shader_watch_reads_the_progress_file(self): # dmsh_build.py DMSH_PROGRESS
|
||||
p = self.tmp / 'progress.json'; watch = nsp.ShaderWatch(p)
|
||||
self.assertIsNone(watch()) # not written yet
|
||||
p.write_text('{"step": "cache check", "done": 3, "total": 10, "cached": 2}')
|
||||
self.assertEqual(watch(), {'step': 'cache check', 'done': 3, 'total': 10, 'unit': 'shaders', 'note': '2 cached'})
|
||||
p.write_text('{"step": "compiling", "done": 7, "total": 10, "cached": 6, "misses": 4}')
|
||||
self.assertEqual(watch(), {'step': 'compiling', 'done': 7, 'total': 10, 'unit': 'shaders', 'note': '4 not cached'})
|
||||
p.write_text('{"step": "comp') # half written: no progress this time, not an error
|
||||
self.assertIsNone(watch())
|
||||
|
||||
|
||||
class EnvFile(Base):
|
||||
|
||||
@@ -34,6 +34,14 @@ class Entries(Base):
|
||||
for n in ('shader/a/mac/x', 'shader/a/ios/x', 'shader/ab/mac/x', 'shader0'): self.store.put(n, b'1')
|
||||
self.assertEqual(self.store.names('shader/a/'), {'shader/a/mac/x', 'shader/a/ios/x'})
|
||||
|
||||
def test_delete_prefix_takes_only_its_names_and_bytes_shared_stay(self): # dmsh_build.py's staged outputs, once its image is written
|
||||
self.store.put('stage/x/mac/k_b.metallib', b'shared'); self.store.put('stage/x/mac/k_b.json', b'staged only')
|
||||
self.store.put('shader/d/mac/k_b.metallib', b'shared'); self.store.put('stage/xy', b'another stage')
|
||||
self.store.delete_prefix('stage/x/')
|
||||
self.assertEqual(self.store.names('stage/'), {'stage/xy'})
|
||||
self.assertEqual(self.store.get('shader/d/mac/k_b.metallib'), b'shared')
|
||||
self.assertEqual(self.blobs(), 2) # 'staged only' gave its bytes back; 'shared' is still named
|
||||
|
||||
def test_the_same_bytes_are_stored_once(self): # a library under its MSL's digest and its shader's digest was one APFS clone
|
||||
self.store.put('metallib/mac/d.metallib', b'L' * 100000); self.store.put('shader/d/mac/k_b.metallib', b'L' * 100000)
|
||||
self.assertEqual(self.blobs(), 1)
|
||||
|
||||
@@ -26,6 +26,9 @@ sys.path.insert(0, str(TOOLS))
|
||||
import dmsh_chain # noqa: E402
|
||||
import dmsh_mtlcache # noqa: E402
|
||||
import shader_cache # noqa: E402
|
||||
sys.path.insert(0, str(REPO / 'dm/tools'))
|
||||
import romfs # noqa: E402
|
||||
import shader_lib # noqa: E402
|
||||
|
||||
spec = importlib.util.spec_from_file_location('nsp_toolchain_cache', REPO / 'scripts/build_ipa_from_nsp.py')
|
||||
assert spec and spec.loader
|
||||
@@ -42,10 +45,12 @@ class ShaderCache(unittest.TestCase):
|
||||
ios_metal=types.SimpleNamespace(RECORD='ios flags'), METAL_FP='tested Metal and SDK',
|
||||
FACTS={}, MAP_ROWS={}, MAP_CONFLICT_ROWS={}, CODE_FP='source', PROFILE_ROWS=b'', PAIRS={},
|
||||
DUAL_WANT=set(), BF_WANT=set(), BF_STATS=collections.Counter(), STORE=shader_cache.Store(root / 'cas.db'), out=str(root / 'out'),
|
||||
CHAIN='test-chain', clone=shutil.copyfile, shader_rule_source=lambda name: b'')
|
||||
CHAIN='test-chain', clone=shutil.copyfile, shader_rule_source=lambda name: b'',
|
||||
STAGE='stage/test', want=set(), OUT_KEY=re.compile(r'([0-9a-f]{16})_b'), OLD_IMAGE={}, shader_lib=shader_lib, romfs=romfs, shutil=shutil,
|
||||
STAMP_BEFORE=None, INPUTS='inputs')
|
||||
(root / 'out').mkdir()
|
||||
names = {'tool_fingerprint', 'shader_key', 'cache_path', 'cache_outputs', 'restore_cache', 'publish_cache', 'atomic_json', 'cache_meta_path',
|
||||
'bf_digest', 'bf_cache_root', 'bf_cache_restore', 'vs_pad'}
|
||||
'bf_digest', 'bf_cache_root', 'bf_cache_restore', 'vs_pad', 'label_dir', 'output', 'commit', 'publish_library'}
|
||||
tree = ast.parse((TOOLS / 'dmsh_build.py').read_text())
|
||||
self.tree = tree
|
||||
nodes: list[ast.stmt] = [n for n in tree.body if isinstance(n, ast.FunctionDef) and n.name in names]
|
||||
@@ -204,7 +209,7 @@ class ShaderCache(unittest.TestCase):
|
||||
(out / (pixel + '_bf.metallib')).write_bytes(b'stale dependency variant')
|
||||
# Execute the real selection and cleanup block, stopping before temporary jobs or tools start.
|
||||
start = next(i for i, n in enumerate(self.tree.body) if isinstance(n, ast.Assign) and any(isinstance(t, ast.Name) and t.id == 'keys' for t in n.targets))
|
||||
end = next(i for i, n in enumerate(self.tree.body) if i > start and isinstance(n, ast.Assign) and any(isinstance(t, ast.Name) and t.id == 'w' for t in n.targets))
|
||||
end = next(i for i, n in enumerate(self.tree.body) if i > start and isinstance(n, ast.FunctionDef) and n.name == 'sweep_work') # not the sweep of the working folders
|
||||
self.ns.update(want={vertex}, loc=locations, PAIRS=pairs, INPUTS='inputs')
|
||||
exec(compile(ast.Module(body=self.tree.body[start:end], type_ignores=[]), str(TOOLS / 'dmsh_build.py'), 'exec'), self.ns)
|
||||
self.assertEqual(self.ns['want'], {vertex, pixel})
|
||||
@@ -247,10 +252,13 @@ class ShaderCache(unittest.TestCase):
|
||||
self.ns['publish_cache'](key, key + '-digest', 'rule', 'source')
|
||||
return key, 'ok', '', refl
|
||||
|
||||
phase = next(n for n in self.tree.body if isinstance(n, ast.With) and any(
|
||||
isinstance(s, ast.Assign) and any(isinstance(t, ast.Name) and t.id == 'res' for t in s.targets) for s in n.body))
|
||||
self.ns.update(cf=cf, NJ=1, keys=keys, fin=finish_key)
|
||||
exec(compile(ast.Module(body=[phase], type_ignores=[]), str(TOOLS / 'dmsh_build.py'), 'exec'), self.ns)
|
||||
# the batches, then the loop that translates and finishes them (the translator and fin substituted)
|
||||
start = next(i for i, n in enumerate(self.tree.body) if isinstance(n, ast.Assign) and any(isinstance(t, ast.Name) and t.id == 'batches' for t in n.targets))
|
||||
end = next(i for i, n in enumerate(self.tree.body) if i > start and isinstance(n, ast.With)) + 1
|
||||
work = Path(self.tmp.name) / 'work'
|
||||
def translate(batch): work.mkdir(exist_ok=True); return str(work)
|
||||
self.ns.update(cf=cf, NJ=1, BATCH=1, keys=keys, fin=lambda key, wb: finish_key(key), translate=translate)
|
||||
exec(compile(ast.Module(body=self.tree.body[start:end], type_ignores=[]), str(TOOLS / 'dmsh_build.py'), 'exec'), self.ns)
|
||||
self.assertEqual(built, [pixel, vertex])
|
||||
self.assertIn('dm_pad7 [[user(locn7)]]', (out / (vertex + '_b.metal')).read_text())
|
||||
expected = {p.name: json.loads(p.read_text()) if p.suffix == '.json' else p.read_bytes() for p in out.iterdir()}
|
||||
@@ -262,6 +270,46 @@ class ShaderCache(unittest.TestCase):
|
||||
self.assertEqual(json.loads((out / (vertex + '_b.json')).read_text())['vs_pad'], [7])
|
||||
|
||||
|
||||
def test_finished_shaders_leave_the_disk_and_the_image_holds_them(self):
|
||||
# commit moves a finished shader's files into the cache's stage; output reads them back; publish_library writes the image and removes the folder and the stage
|
||||
out, a, b = Path(self.ns['out']), '1' * 16, '2' * 16
|
||||
for key in (a, b):
|
||||
(out / (key + '_b.metal')).write_text(key + ' source'); (out / (key + '_b.metallib')).write_bytes(key.encode())
|
||||
(out / (a + '_b.metal.tmp-1-2')).write_text('a write in progress') # not a finished file: stays
|
||||
self.ns['commit'](a)
|
||||
self.assertEqual(sorted(p.name for p in out.iterdir()), sorted([a + '_b.metal.tmp-1-2', b + '_b.metal', b + '_b.metallib']))
|
||||
self.assertEqual(self.ns['output']('mac', a + '_b.metal'), (a + ' source').encode()) # from the stage
|
||||
self.assertEqual(self.ns['output']('mac', b + '_b.metal'), (b + ' source').encode()) # still on disk
|
||||
self.assertIsNone(self.ns['output']('mac', '3' * 16 + '_b.metal'))
|
||||
(out / 'inputs.tsv').write_text('game\tid\ninputs\tinputs\n')
|
||||
self.ns['publish_library']('mac')
|
||||
self.assertFalse(out.exists())
|
||||
self.assertEqual(self.ns['STORE'].names('stage/'), set())
|
||||
img = shader_lib.view(out)
|
||||
self.assertEqual(sorted(p.name for p in img.iterdir()), sorted([a + '_b.metal', a + '_b.metallib', b + '_b.metal', b + '_b.metallib', 'inputs.tsv']))
|
||||
self.assertEqual((img / (a + '_b.metallib')).read_bytes(), a.encode())
|
||||
|
||||
def test_partial_build_keeps_the_image_less_the_keys_it_builds(self):
|
||||
out, built, kept = Path(self.ns['out']), '1' * 16, '2' * 16
|
||||
shader_lib.write({built + '_b.metal': b'old', built + '_bf.metallib': b'old variant', kept + '_b.metal': b'kept', 'inputs.tsv': b'game\tid\ninputs\told\n'},
|
||||
shader_lib.image_of(str(out)))
|
||||
self.ns.update(want={built}, OLD_IMAGE={'mac': romfs.Path(shader_lib.image_of(str(out)))}, STAMP_BEFORE='old', INPUTS='new')
|
||||
self.assertIsNone(self.ns['output']('mac', built + '_b.metal'), 'a key this build makes has no older outputs')
|
||||
self.assertEqual(self.ns['output']('mac', kept + '_b.metal'), b'kept')
|
||||
(out / (built + '_b.metal')).write_text('new'); self.ns['commit'](built)
|
||||
self.ns['publish_library']('mac')
|
||||
img = shader_lib.view(out)
|
||||
self.assertEqual({p.name: p.read_bytes() for p in img.iterdir()}, {built + '_b.metal': b'new', kept + '_b.metal': b'kept'}) # the old variant and the stale stamp are gone
|
||||
|
||||
def test_an_image_that_cannot_be_written_leaves_a_whole_folder(self):
|
||||
out, key = Path(self.ns['out']), '1' * 16
|
||||
(out / (key + '_b.metal')).write_text('source'); self.ns['commit'](key)
|
||||
self.ns['shader_lib'] = types.SimpleNamespace(image_of=shader_lib.image_of, write=mock.Mock(side_effect=OSError('No space left on device')))
|
||||
self.ns['publish_library']('mac')
|
||||
self.assertEqual((out / (key + '_b.metal')).read_text(), 'source')
|
||||
self.assertFalse(os.path.exists(shader_lib.image_of(str(out))))
|
||||
|
||||
|
||||
class TargetSelection(unittest.TestCase):
|
||||
def test_mesh_compiles_only_requested_targets(self):
|
||||
tree = ast.parse((TOOLS / 'dmsh_build.py').read_text())
|
||||
@@ -275,14 +323,19 @@ class TargetSelection(unittest.TestCase):
|
||||
with self.subTest(targets=targets):
|
||||
compile_target = mock.Mock()
|
||||
compose = mock.Mock(return_value='mesh source')
|
||||
def output(label, name, td=td):
|
||||
p = Path(td) / name
|
||||
return p.read_bytes() if p.is_file() else None
|
||||
ns: dict[str, Any] = dict(os=os, json=json, subprocess=subprocess, out=td, w=td, TARGETS=targets,
|
||||
IOSOUT=str(ios) if 'ios' in targets else None, MESH_STATS=collections.Counter(),
|
||||
MTL=types.SimpleNamespace(compile=compile_target), dmsh_mesh=types.SimpleNamespace(compose=compose))
|
||||
MTL=types.SimpleNamespace(compile=compile_target), dmsh_mesh=types.SimpleNamespace(compose=compose),
|
||||
output=output, commit=mock.Mock())
|
||||
exec(compile(ast.Module(body=[function], type_ignores=[]), '<mesh targets>', 'exec'), ns)
|
||||
ns['mesh_finish'](('vertex', 'geometry'))
|
||||
compose.assert_called_once_with('vertex source', 'geometry source', [36])
|
||||
self.assertEqual([call.args[0] for call in compile_target.call_args_list], [t for t in ('mac', 'ios') if t in targets])
|
||||
self.assertEqual(ns['MESH_STATS']['built'], 1)
|
||||
ns['commit'].assert_called_once_with(names=['vertex_geometry_m3.metallib']) # its library staged as a shader's outputs are
|
||||
|
||||
def selection(self, env):
|
||||
tree = ast.parse((TOOLS / 'dmsh_build.py').read_text())
|
||||
|
||||
@@ -23,6 +23,7 @@ One line per symptom in the [subsystem references](../reference/): what you see
|
||||
- a game's `<id>_build` folder is slow to count, copy or delete: Metroid Dread's held 160,331 files in 48,782 folders, 84,541 of them in the compile cache. → [A build folder holds hundreds of thousands of small files](../reference/packing.md#a-build-folder-holds-hundreds-of-thousands-of-small-files)
|
||||
- a build that runs the shader step writes the compile cache's files back and removes them again, on Skyward Sword HD 24,131 files and 10,150 folders each time, Tears of the Kingdom over 900,000 entries. Removing old entries took up to half an hour on an external drive. → [The compile cache was unpacked for each build](../reference/packing.md#the-compile-cache-was-unpacked-for-each-build)
|
||||
- a game's shader libraries are slow to copy or delete: Skyward Sword HD's `b-<chain>/` held 12,064 files for 2,470 shaders, a third of its build folder's files, and each `regress.py` chain build held another set. A tar would not do: the host reads these files at every run. → [Shader libraries take a file per shader variant](../reference/packing.md#shader-libraries-take-a-file-per-shader-variant)
|
||||
- a game's build folder holds tens of thousands of small files while its shaders build, and keeps them when the build stops: Octopath Traveler 0's `_build`, stopped in its compile, held 68,230 files (38,376 in `tmp/dmsh_*`, 29,757 in `shader/cache/b-<chain>/`), against 105 once a build finished. Every later build made another `tmp/dmsh_*` beside the old one. → [A shader build leaves a file per shader output while it runs or after a stop](../reference/packing.md#a-shader-build-leaves-a-file-per-shader-output-while-it-runs-or-after-a-stop)
|
||||
- a game's `<id>-work` folder is too slow to count: Tears of the Kingdom's held 8,893,028 files and 509 GB, and its count ran past ten minutes. → [A work folder holds millions of small files](../reference/packing.md#a-work-folder-holds-millions-of-small-files)
|
||||
- the NSP script stops at the shader split of a registered profile with `[RED] 13744 file(s) could not be read, their shaders are left out (first: AI/FileEntry/FileEntry.Product.100.byml.zs: CalledProcessError: Command ['zstd', '-d', '-c', '-q', '…/extract/v0/RomFS.img/AI/…'] returned non-zero exit status 1.)`. → [The zstd command given a path inside the image](../reference/packing.md#the-zstd-command-given-a-path-inside-the-image)
|
||||
- a game's DLC works only when packed inside its IPA, although its base RomFS can be deployed separately. After pushing a smaller DLC set, removed indices can remain reported as owned and mounted. → [DLC in Documents is ignored or removed DLC remains installed](../reference/packing.md#dlc-in-documents-is-ignored-or-removed-dlc-remains-installed)
|
||||
|
||||
+2
-2
@@ -429,7 +429,7 @@ What the script does:
|
||||
|
||||
A repeat build skips work whose inputs have not changed. The extraction is kept (`extract/`). The DLC, the rewrite, the shader split and the iOS (or Vulkan) shaders each write a key beside their output: a sha256 of their inputs (the game files, the tools, the profile, Xcode's version and the in-repo spirv-cross; for the DLC, the DLC NSPs' names, sizes and times and nx_extract's sources). When the key matches, the stage line says `reused (inputs unchanged)` and the step does not run. Any change to a tool or the profile runs the step again; deleting the `.key` file forces it. The rewrite's key covers the patch files that name one of the modules' builds, the selected game's own, and always `dm/tools/sdk_patches.py`, whose SDK-wide `MATCH_CUTS` apply to builds it does not name (a new reviewed implementation was left out of a reused rewrite of Pokémon Legends: Arceus before). The iOS shaders' inputs are the shader package's content and only the tools `dmsh_build.py` loads (the modules it imports, at any depth): a split that runs again because a reader for another engine changed (a pull that touches `shader_split.py` or `unityfs.py`) writes the same package, and the iOS shaders stay reused.
|
||||
|
||||
The shader libraries are one file, `shader/cache/b-<chain>.img` for the Mac and `shader/ios/b-<chain>.img` for the iPhone, which the host and the tools read in place and which is never unpacked (`dm/tools/shader_lib.py`, [Shader libraries take a file per shader variant](reference/packing.md#shader-libraries-take-a-file-per-shader-variant)). A build writes the folder `b-<chain>/` and packs it at the end. To look inside: `shader_lib.py cat <lib> <name>`, or `romfs.Path` in Python.
|
||||
The shader libraries are one file, `shader/cache/b-<chain>.img` for the Mac and `shader/ios/b-<chain>.img` for the iPhone, which the host and the tools read in place and which is never unpacked (`dm/tools/shader_lib.py`, [Shader libraries take a file per shader variant](reference/packing.md#shader-libraries-take-a-file-per-shader-variant)). `dmsh_build.py` writes the image itself: the folder `b-<chain>/` beside it holds only the shaders in flight, a finished shader's files wait in `cas.db`, and the translator's working files go when their shader is done, so a build holds a few hundred files at most and a stopped one leaves a few dozen, which the next run clears ([A shader build leaves a file per shader output](reference/packing.md#a-shader-build-leaves-a-file-per-shader-output-while-it-runs-or-after-a-stop)). A folder from an older chain is packed at the end of the step. To look inside: `shader_lib.py cat <lib> <name>`, or `romfs.Path` in Python.
|
||||
|
||||
The compile cache is one file too, `shader/cache/cas.db` (`dm/tools/shader_cache.py`), which a build reads and writes in place, and into which a `cas/` or `cas.tar` from before it moves by itself ([The compile cache was unpacked for each build](reference/packing.md#the-compile-cache-was-unpacked-for-each-build)). Xcode's derived data, which Xcode wants as a folder, is one uncompressed file between builds, `ipa/build/ios/pkg/dd.tar` (`dm/tools/tree_tar.py`): the step that runs unpacks it first and packs it at the end, and a reused step does not touch it ([Build folders of many small files](reference/packing.md#a-build-folder-holds-hundreds-of-thousands-of-small-files)).
|
||||
|
||||
@@ -465,7 +465,7 @@ Haptic engines are created on demand, after the game has activated its audio ses
|
||||
|
||||
The Mac is the development host. To test or debug a game on the Mac, `--platform mac` (`PLATFORM = 'mac'` in Spyder) builds only what running it in the Mac host needs, from the same NSP folder:
|
||||
- the same steps up to the shaders: extraction, rewrite, run-time shader captures and decodes, a provisional profile's heap check and the shader split;
|
||||
- the Mac shader libraries only: `dmsh_build.py` without `IOSOUT` into `<id>_build/shader/cache/b-<chain>/` (one file, `b-<chain>.img`, at the end of the step), which a full build stamps with the profile's inputs (`inputs.tsv`) and from which it makes the profile's `c1_full.tsv` and `cb_extent.tsv`, or a Vulkan or GL game's library without `--ios` into `<id>_build/shader/vk/` or `gl/`;
|
||||
- the Mac shader libraries only: `dmsh_build.py` without `IOSOUT` into `<id>_build/shader/cache/b-<chain>.img` (one file), which a full build stamps with the profile's inputs (`inputs.tsv`) and from which it makes the profile's `c1_full.tsv` and `cb_extent.tsv`, or a Vulkan or GL game's library without `--ios` into `<id>_build/shader/vk/` or `gl/`;
|
||||
- the Mac host for the profile into `<id>_build/tools/dmhost`: the compile line of `make -C dm/host GAME=<id> dmhost`, with a provisional or derived profile through `DM_GAMES_DIR` / `DM_GAMES_FIRST` as for the script's other host builds. It is reused while its sources (the chain header `dm/gfx/nvn/dmsh_chain.h` among them), the generated profile header, libvpx and the compiler are unchanged;
|
||||
- the button-icon font (`make_ext_font.py`) into `<id>_build/font/`.
|
||||
|
||||
|
||||
@@ -144,6 +144,14 @@
|
||||
- **Measured** on Skyward Sword HD, on an external drive, warm cache: 10,017 files to one: copy 3.72 s to 0.18 s, delete 0.40 s to 0.02 s, 150 MB to 131 MB on disk. Reading all 2,470 shaders' reflection and libraries 100 ms to 28 ms. The map must be `MAP_SHARED`: on a file this size a private mapping costs about 80 µs, against 0.9 µs. A cold read has not been measured, as the cache cannot be emptied without an administrator.
|
||||
- **Found on:** [Skyward Sword HD](../../dm/games/01002DA013484000/README.md#found-on-this-game).
|
||||
|
||||
### A shader build leaves a file per shader output while it runs or after a stop
|
||||
|
||||
- **Symptom:** a game's build folder holds tens of thousands of small files while its shaders build, and keeps them when the build stops: Octopath Traveler 0's `_build`, stopped in its compile, held 68,230 files (38,376 in `tmp/dmsh_*`, 29,757 in `shader/cache/b-<chain>/`), against 105 once a build finished. Every later build made another `tmp/dmsh_*` beside the old one.
|
||||
- **Cause:** `dmsh_build.py` wrote each shader's outputs into `b-<chain>/` and packed them into the image only at the end ([the entry above](#shader-libraries-take-a-file-per-shader-variant)); its cache check restored every cache hit into that folder before anything was translated; the translator wrote every missed shader's working files (`.bin`, `.spv`, `.res.json`, `.metal`) into one temporary folder before any was finished; and that folder went only when the build ended normally.
|
||||
- **Fix:** `dm/gfx/tools/dmsh_build.py`. A finished shader's files go into the compile cache (`cas.db`, under `stage/<output folder>/`) and leave the disk (`commit`); reads of another shader's outputs (a vertex shader's paired pixel MSL for `vs_pad`, the mesh step) take them from there (`output`). At the end the image is written from the staged outputs (`publish_library`, through `shader_lib.write`), with a partial build's image under it less the keys it built, and the folder and the staged entries go; when the image cannot be written, the staged outputs go back into the folder. Cache hits are restored when their shader is finished, not at the look. The shaders are translated and finished in batches of 4 × `J` (the next batch is translated while this one is finished), each in a folder of its own, and a shader's working files go as soon as it is finished. Each build's working folder holds its process ID; a later build removes a `dmsh_*` folder whose process is gone (one without the ID after a day). The NSP script's progress comes from a small file the build rewrites (`DMSH_PROGRESS`), no longer from counting its files. The outputs are the same: chain `cfcc3a82c78b` against the new one, Minecraft Dungeons II's 61,655 library files and Octopath Traveler 0's 41,880 are byte for byte the same (reflection without its `chain` field), apart from `_b_cas.txt`, which lists the new chain's cache digests.
|
||||
- **Measured** on an M4 Pro, every shader translated again (the chain changed), the Metal libraries from the cache: Octopath Traveler 0, 10,324 shaders, at most 405 files under `shader/` and `tmp/` (12 outside a build), 2:48 for the step (2:55 with batches of 4 × 128); Minecraft Dungeons II, 15,826 shaders, at most 3,279 with batches of 256 removed whole. Stopped with SIGKILL near the end of a compile: 40 files in `b-<chain>/` and 7 in `tmp/dmsh_*`; the next run cleared them and wrote the same library from the cache in 59 s. A partial build of 42 shaders for the Mac and the iPhone leaves one image each, also when run again over them.
|
||||
- **Found on:** [Minecraft Dungeons II](../../dm/games/0100A7C01B792000/README.md#found-on-this-game) and [Octopath Traveler 0](../../dm/games/01005270232F2000/README.md#found-on-this-game) builds, reported by the user.
|
||||
|
||||
### A work folder holds millions of small files
|
||||
|
||||
- **Symptom:** a game's `<id>-work` folder is too slow to count: Tears of the Kingdom's held 8,893,028 files and 509 GB, and its count ran past ten minutes.
|
||||
|
||||
@@ -136,14 +136,14 @@ def chain_version():
|
||||
|
||||
|
||||
def shader_dirs(app, build):
|
||||
"""Available library folder names only; a build may retain several old chains, so none establishes the chain the player ran."""
|
||||
"""Available library names only (a folder b-<chain>/ or its image b-<chain>.img, which dmsh_build.py writes); a build may retain several old chains, so none establishes the chain the player ran."""
|
||||
root = app if app else build
|
||||
dirs = [app / 'Contents/Resources/msl'] if app else [build / s for s in ('shader', 'shader/cache', 'shader/ios')] if build else []
|
||||
found = []
|
||||
for d in dirs:
|
||||
if d.is_symlink() or not d.is_dir(): continue
|
||||
found.extend(p.relative_to(root).as_posix() for p in d.iterdir()
|
||||
if not p.is_symlink() and p.is_dir() and re.fullmatch(r'b-[0-9a-f]+', p.name))
|
||||
if not p.is_symlink() and ((p.is_dir() and re.fullmatch(r'b-[0-9a-f]+', p.name)) or (p.is_file() and re.fullmatch(r'b-[0-9a-f]+\.img', p.name))))
|
||||
return sorted(found)
|
||||
|
||||
|
||||
|
||||
@@ -2253,46 +2253,17 @@ def seen_keys(g, sh, logs):
|
||||
|
||||
|
||||
class ShaderWatch:
|
||||
"""Progress of dmsh_build.py, read from the files it writes (it prints nothing until it ends). It works in three phases:
|
||||
the cache check (a hit restores <key>_b.json into the library directory b-<chain>/: the iOS one, or the Mac's for a Mac-only build; a miss writes <key>.bin into its temporary folder dmsh_* under WORK),
|
||||
the translation of the misses (<key>.spv in the temporary folder), and the compile, which takes the keys in a fixed order (sorted, the vertex shaders with pixel pairs last)
|
||||
and writes <key>_b.json again for every miss and every pixel shader: the furthest key written so far tells how far it got"""
|
||||
def __init__(self, g, out, tmp, pso_pairs=None, seen=None): # out: the library directory b-<chain>/ (the iOS one, or the Mac's for a Mac-only build); seen: the keys of a partial build
|
||||
keys = set(seen) if seen else shader_keys(g)
|
||||
pairs = set()
|
||||
for path in (g.table('shader_pairs.tsv'), pso_pairs):
|
||||
if path and path.is_file():
|
||||
pairs |= {ln.split()[0] for ln in path.read_text(errors='replace').splitlines() if ln.strip() and not ln.startswith('#')}
|
||||
order = sorted(keys - pairs) + sorted(keys & pairs)
|
||||
self.pos, self.n = {k: i for i, k in enumerate(order)}, len(order)
|
||||
self.out, self.tmp, self.t0, self.t1, self.w = out, tmp, time.time(), None, None
|
||||
self.hits, self.fin, self.top = set(), set(), -1
|
||||
|
||||
def written(self, keys, since): # those of keys whose <key>_b.json in the output was written after since
|
||||
found = set()
|
||||
try:
|
||||
with os.scandir(self.out) as it:
|
||||
for e in it:
|
||||
if e.name.endswith('_b.json') and e.name[:-7] in keys and e.stat().st_mtime > since: found.add(e.name[:-7])
|
||||
except OSError: pass
|
||||
return found
|
||||
"""Progress of dmsh_build.py, from the small JSON file it rewrites at most every half second (DMSH_PROGRESS): the cache check over every key, then the compile, which finishes the keys
|
||||
in batches (cache hits and misses alike) and counts them. It used to be read from the files dmsh_build.py wrote, one per shader output, which it no longer leaves on disk"""
|
||||
def __init__(self, path): self.path = path
|
||||
|
||||
def __call__(self):
|
||||
if not self.w: # dmsh_build.py's temporary folder: the dmsh_* under WORK made since it started
|
||||
self.w = max((d for d in self.tmp.glob('dmsh_*') if d.stat().st_birthtime >= self.t0 - 2), key=lambda d: d.stat().st_birthtime, default=None)
|
||||
try: ext = collections.Counter(os.path.splitext(x)[1] for x in os.listdir(self.w)) if self.w else collections.Counter()
|
||||
except OSError: ext = collections.Counter()
|
||||
if self.t1 is None:
|
||||
self.hits |= self.written(self.pos.keys() - self.hits, self.t0 - 2)
|
||||
if len(self.hits) + ext['.bin'] < self.n and not ext['.spv'] and not ext['.metal']:
|
||||
return {'step': 'cache check', 'done': len(self.hits) + ext['.bin'], 'total': self.n, 'unit': 'shaders', 'note': f'{len(self.hits):,} cached'}
|
||||
self.t1 = time.time() # the cache check is over: from now on a <key>_b.json is written by the compile
|
||||
if ext['.bin'] and not ext['.metal'] and ext['.spv'] < ext['.bin']:
|
||||
return {'step': 'translating', 'done': ext['.spv'], 'total': ext['.bin'], 'unit': 'shaders'}
|
||||
new = self.written(self.pos.keys() - self.fin, self.t1)
|
||||
self.fin |= new; self.top = max([self.top] + [self.pos[k] for k in new])
|
||||
return {'step': 'compiling' if ext['.bin'] else 'finishing', 'done': max(len(self.fin), self.top + 1), 'total': self.n, 'unit': 'shaders',
|
||||
'note': f'{ext[".bin"]:,} not cached' if ext['.bin'] else ''}
|
||||
try: p = json.loads(self.path.read_text())
|
||||
except (OSError, ValueError): return None
|
||||
cached, misses = p.get('cached', 0), p.get('misses')
|
||||
if p.get('step') == 'cache check':
|
||||
return {'step': 'cache check', 'done': p['done'], 'total': p['total'], 'unit': 'shaders', 'note': f'{cached:,} cached'}
|
||||
return {'step': 'compiling', 'done': p.get('done', 0), 'total': p.get('total', 0), 'unit': 'shaders', 'note': f'{misses:,} not cached' if misses else ''}
|
||||
|
||||
|
||||
def spirv_cross(repo, env=None): # resolve the same selection the shader tools run, including an executable name on PATH
|
||||
@@ -2424,8 +2395,6 @@ def build_shaders(py, repo, sh, xlate, env, logs, g, pkg_key=None, mac=False, se
|
||||
rmtree(kmac)
|
||||
if not mac: rmtree(kf)
|
||||
if seen: rmtree(out) # what a run leaves is what it built; its keys are in partial-keys.txt
|
||||
try: PROG.watch(ShaderWatch(g, libs, Path(env['WORK']), pso_pairs, seen))
|
||||
except Exception: pass # progress never stops the build (a missing table is dmsh_build.py's to report)
|
||||
# The Metal work follows from what the build produces: an iPhone build needs only the iOS libraries (the macOS
|
||||
# metallibs are about half of the compile and never enter the IPA), a Mac build only the Mac's, and a build that
|
||||
# wants both compiles both. The Mac sources and reflection are written either way (c1_full / cb_extent come from them).
|
||||
@@ -2439,6 +2408,9 @@ def build_shaders(py, repo, sh, xlate, env, logs, g, pkg_key=None, mac=False, se
|
||||
if mac: del benv['IOSOUT'] # dmsh_build.py builds the iOS libraries only with IOSOUT
|
||||
elif pull is False: benv['DMSH_IOS_PULL'] = '0' # nothing in this app reads them
|
||||
if seen: benv['DMSH_CAS'] = str(cas)
|
||||
prog = sh / 'progress.json'; rmtree(prog); benv['DMSH_PROGRESS'] = str(prog) # dmsh_build.py's progress (ShaderWatch)
|
||||
try: PROG.watch(ShaderWatch(prog))
|
||||
except Exception: pass # progress never stops the build
|
||||
try: stale = None if seen else stale_shaders(py, repo, env, [sh / 'cache'] if mac else [sh / 'cache', ios] if keep_mac else [ios], chain, g)
|
||||
except Exception: stale = None # a note never stops the build
|
||||
if stale:
|
||||
@@ -2455,10 +2427,10 @@ def build_shaders(py, repo, sh, xlate, env, logs, g, pkg_key=None, mac=False, se
|
||||
PROG.watch(None)
|
||||
if not seen and not chain_tables(py, repo, sh, env, logs, g, chain): raise BuildError(f'no stamped Mac shader outputs in {sh / "cache" / f"b-{chain}"} (inputs.tsv): dmsh_build.py did not finish a full build')
|
||||
what = 'Mac' if mac else 'iOS'
|
||||
n = sum(1 for _ in libs.glob('*_b.metallib')) if libs.is_dir() else 0
|
||||
n = sum(1 for _ in shader_lib.view(libs).glob('*_b.metallib')) if shader_lib.exists(libs) else 0 # the image dmsh_build.py writes (a folder from an older chain)
|
||||
if n == 0: raise BuildError(f'no {what} shader libraries in {libs}')
|
||||
say(f'{n} {what} shader libraries ({libs})')
|
||||
if keep_mac: say(f'{sum(1 for _ in (sh / "cache" / f"b-{chain}").glob("*_b.metallib"))} Mac shader libraries kept for the Mac run command ({sh / "cache" / f"b-{chain}"})')
|
||||
if keep_mac: say(f'{sum(1 for _ in shader_lib.view(sh / "cache" / f"b-{chain}").glob("*_b.metallib"))} Mac shader libraries kept for the Mac run command ({sh / "cache" / f"b-{chain}"})')
|
||||
t = log.read_text(errors='replace')
|
||||
if own := re.search(r'^note: (built with this Mac\'s compilers.*)$', t, re.M): say(own.group(1))
|
||||
if lost := re.search(r'^\[RED\] lost without failing: .*$', t, re.M): say(f'{lost.group(0)}; each is named in {log}, and the build goes on: a shader the game never reaches costs nothing')
|
||||
@@ -2493,7 +2465,7 @@ def shader_regressions(py, repo, lib_dir, chain, logs):
|
||||
"""dm/gfx/tools/shader_regressions.py on the Mac libraries (dmsh_build.py writes its build report there in an iOS build too): shaders that translated in this game's previous build
|
||||
and fail with this chain stop the build, unless ALLOW_SHADER_REGRESSIONS. The chain is one for every game, so a change can break a game its author never ran (GitHub issue #272)"""
|
||||
log = logs / 'shader_regressions.log'
|
||||
if not (lib_dir / f'b-{chain}' / '_b_build.json').is_file(): return # a full dmsh_build.py run always writes it
|
||||
if not (shader_lib.view(lib_dir / f'b-{chain}') / '_b_build.json').is_file(): return # a full dmsh_build.py run always writes it
|
||||
r = subprocess.run([py, str(repo / 'dm/gfx/tools/shader_regressions.py'), str(lib_dir), chain], capture_output=True, text=True, errors='replace')
|
||||
log.write_text(r.stdout + r.stderr)
|
||||
if r.returncode == 0: return
|
||||
|
||||
+2
-2
@@ -463,14 +463,14 @@ def chain_build_locked(tree, g, a, v, inp, key, out):
|
||||
say(f' {g.id}: chain {v} (inputs {inp}) of {tree.id}: translating the shaders ({jobs} workers) → {out}')
|
||||
if cas.suffix != '.db': tree_tar.unpack(cas, say)
|
||||
rc, paused = run_heavy([sys.executable, entry, g.build / 'shader/pkg', out], log, tree.path, env, a, f'{g.id} shader build'); t0 += paused
|
||||
if rc or not (lib / '_b_build.json').is_file():
|
||||
if rc or not (shader_lib.view(lib) / '_b_build.json').is_file(): # a folder (an older revision's dmsh_build.py) or the image a newer one writes
|
||||
raise HarnessError(f'{g.id}: dmsh_build.py of {tree.id} failed (exit {rc}); last lines of {log}:\n' + ''.join(collections.deque(open(log, errors='replace'), maxlen=8)))
|
||||
prof = out / 'profile'; prof.mkdir(exist_ok=True) # the tables the host reads beside the shader map, as this build made them
|
||||
for src in g.profile_dir(tree).glob('*.tsv'): shutil.copyfile(src, prof / src.name)
|
||||
(out / 'built.ok').write_text(f'{tree.id}\n')
|
||||
if cas.suffix != '.db': tree_tar.pack(cas, say)
|
||||
say(f' {g.id}: hashing the outputs of chain {v}')
|
||||
shaders = nvn_manifest(lib, jobs)
|
||||
shaders = nvn_manifest(shader_lib.view(lib), jobs)
|
||||
else:
|
||||
say(f' {g.id}: vk_shaders.py {v} of {tree.id} → {out}')
|
||||
msl = out / 'msl'; shutil.rmtree(msl, ignore_errors=True); msl.mkdir()
|
||||
|
||||
Reference in new issue
Block a user