Merge pull request #1385: restbl_cache = 1 serves the mods' merged resource size table from the last start when totk.exe, the RomFS image and every mod file are the same (about 0.9 s off a start with The Second Quest); off by default (itaskaev2)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Valiantsin DzerakhandClaude Opus 5.5 committed 2026-11-23 18:51:57 +03:00
commit 1dad1ef60b
5 files changed
+215 -6

No files matched your search

+1
View File
@@ -115,6 +115,7 @@ Many rows below are developer tools that only act together with another setting
| `mods_without_code` (default `0`) | `1` uses every mod without its code part, as if `mods_no_code` named them all. | See `mods_no_code`. | Caution |
| `pipeline_cache` | Path of the Vulkan pipeline cache file (default `pipeline-cache.bin` beside `totk.exe`). | Moves the cache; a new path starts empty and pipelines are built again. | Caution |
| `profile_dir` | Folder of the game profile, which holds the user account id that save data is named after; the default is a `profile` folder beside `totk.exe`, else the build-time path. | Another folder means a different set of saves. | Save risk |
| `restbl_cache` (default `0`) | `1`: with player mods, the resource size table merged at the last start is served again when nothing it was built from changed: every mod file and shipped table (path, size, write time, file id), the mod list and its order, the RomFS image and `totk.exe` itself. `<profile>/mods/` keeps the table and its `.key`. `0` builds it at every start. | Saves the merge at start: the pass over every mod file and the mods' packs (about 0.9 s with The Second Quest, 3,300 files; more with a texture pack). A changed, added or removed mod file, another order, a new build or game version builds the table again; a damaged kept table or key is built again too. A tool that rewrites a mod file with the same size and write time is not seen. | Caution |
| `romfs` | Folder of the game's RomFS (with `romfs.bin`); a relative path is relative to `totk.exe`'s folder. | Without it, a `romfs` folder next to `totk.exe` is used, else the build-time path; a missing image stops the start with a message. | Save risk |
| `romfs_index` | Path of `romfs-index.bin`, which `tools/romfs_index.py` wrote; the default is beside `totk.exe`. | The index is checked against the image by SHA-256 and size; a mismatch stops the start. | Caution |
| `romfs_mmap` | `1` maps the RomFS image into memory instead of reading it with positional reads. | Changes how the image is read; the log reports when the mapped path is on. | Caution |
+1 -1
View File
@@ -61,7 +61,7 @@ static const char *const known[] = {
"PREWARM_XLATE", "PROBE_MOVIE", "PROBE_MOVIE_BENCH", "PROBE_MOVIE_SHOT", "PROFILE", "PROFILE_CHAINS", "PROFILE_DIR", "PROFILE_FRAMES",
"PROFILE_MAIN", "PROFILE_RENDER", "PROMPTS", "PUSH_SKIP", "PUSH_STAGE", "QUICKLOAD_KEY", "QUICKSAVE", "QUICKSAVE_KEY", "RDOC", "RDOC_DIR", "RDOC_DLL", "REALTIME", "REC_ASYNC", "REC_END", "REC_SPIN_US", "REEXEC", "REFLEX",
"RENDER_SCALE", "REPLAY_ASYNC", "REPLAY_CHUNKS", "REPLAY_CHUNK_DRAWS", "REPLAY_SKEW_US", "REPLAY_STATE_CHECK", "REPLAY_WORKERS",
"REPLAY_CHECK", "REPORT_GUARD", "RESOLVE_CHECK", "RESTART_WAIT", "ROMFS", "ROMFS_INDEX", "ROMFS_MMAP", "ROMFS_MODS", "ROMFS_PATCHES",
"REPLAY_CHECK", "REPORT_GUARD", "RESOLVE_CHECK", "RESTART_WAIT", "RESTBL_CACHE", "ROMFS", "ROMFS_INDEX", "ROMFS_MMAP", "ROMFS_MODS", "ROMFS_PATCHES",
"ROMFS_PROOF_DIR", "ROMFS_VERIFY", "RSTICK_DEADZONE", "RUMBLE", "RUMBLE_CURVE", "RUMBLE_STRENGTH", "RUMBLE_TRIGGERS", "SCENE_UPSCALER", "SHADER_CACHE",
"SHADER_MEMO", "SHADOW", "SHADOW_DEFER", "SHADOW_RANGE", "SHADOW_RES", "SHADOW_SCALE", "SHADOW_SNAP", "SHARED_FONTS", "SHARPNESS", "SHOTS", "SHOTS_DIR", "SHUTTER_FIX",
"SHOTS_FULL", "SPEED_PROBE", "SPIN", "SPIN_HANDOFF_US", "SPLIT_DRAWS", "SPLIT_US", "STICK_DEADZONE", "STICK_SENS",
+135 -2
View File
@@ -25,7 +25,8 @@
//
// The resource size table: with a player mod enabled, the game's table is rebuilt at start with the tables the mods
// ship merged in and the entries of the mods' files raised to what they need (restbl_overlay), the members of their
// packs too (restbl_packs), and served from <profile>/mods/ in place of the game's or a mod's table.
// packs too (restbl_packs), and served from <profile>/mods/ in place of the game's or a mod's table. TOTK_RESTBL_CACHE=1
// serves the table of the last start instead when every input of the build is the same (restbl_cache_key).
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
@@ -761,6 +762,127 @@ static int restbl_packs(Restbl *out, const Restbl *base, int *packs, int *lines)
return raised;
}
// ---- the merged table across starts (TOTK_RESTBL_CACHE=1, off by default). Building it opens every mod file and
// unpacks the mods' packs. A start whose inputs are the same as the last one's serves the table that start wrote.
// The key is a SHA-256 over every input restbl_overlay reads:
// - the running totk.exe's path and identity: a new build may merge differently, and it carries the port version, the
// game version and the RomFS index's SHA-256 (romfs_config.h);
// - the RomFS image's path and identity and the game table's index entry: the base table, the game's copies of the
// mods' packs and Pack/ZsDic.pack.zs come from the image;
// - every shipped table (restbl_collect, mod_walk_cb; also the ones overlay_contest drops) with its owner and identity;
// - every overlay overlay_contest kept (player mods, the TOTK_ROMFS_MODS manifest, the port's folders) with its RomFS
// path, file path, place in the order (index, prio, mod) and identity.
// Identity is the volume, file id, size, last write and creation time. A file's bytes are not hashed: identity is
// what the overlay layer already trusts (romfs_open stops the game on a file whose identity changed after the start
// check), and hashing a texture pack would cost more than the merge does. <profile>/mods/<table>.key holds the key,
// what the build gave (a table or none) and the SHA-256 of the table it wrote; it is replaced atomically after the
// table is written. A key file of another size, magic or version, another key, or a table of another SHA-256 is a
// miss: the table is built again and both files are replaced, so the cache stays two files.
#define RESTBL_CACHE_VERSION 3
typedef struct { char magic[8]; uint32_t version, outcome; uint8_t key[32], table[32]; } RestblCache;
enum { RESTBL_NONE = 1, RESTBL_TABLE = 2 };
static void restbl_cache_paths(char *key, size_t key_cap, char *table, size_t table_cap) {
const char *leaf = strrchr(restbl_rel, '/') ? strrchr(restbl_rel, '/') + 1 : restbl_rel;
need(snprintf(table, table_cap, "%s/mods/%s", rt_config()->profile, leaf) < (int)table_cap, "table path");
need(snprintf(key, key_cap, "%s.key", table) < (int)key_cap, "table key path");
}
static void hash_identity(Sha256 *h, const char *path, const Identity *id) {
sha256_update(h, path, strlen(path) + 1);
sha256_update(h, id, sizeof *id);
}
// 0 when path cannot be opened.
static int hash_file_id(Sha256 *h, const char *path) {
PlatFile *f = open_read(path);
Identity id = {0};
if (f) id = identity_of(f), plat_file_close(f);
hash_identity(h, path, &id);
return f != NULL;
}
// The key of this start's inputs into out; 0 when the running exe cannot be opened (no key: the table is built).
static int restbl_cache_key(uint64_t gi, uint8_t out[32]) {
char exe[2100];
Sha256 h;
sha256_init(&h);
static const char tag[] = "totk restbl cache";
uint32_t v = RESTBL_CACHE_VERSION;
sha256_update(&h, tag, sizeof tag);
sha256_update(&h, &v, sizeof v);
sha256_update(&h, rt_port_version, strlen(rt_port_version) + 1);
if (!plat_exe_path(exe, sizeof exe) || !hash_file_id(&h, exe)) return 0;
Identity img = identity_of(image);
hash_identity(&h, image_file, &img);
Entry ge = entry(gi);
sha256_update(&h, &ge, sizeof ge);
uint64_t n = nshipped;
sha256_update(&h, &n, sizeof n);
for (size_t s = 0; s < nshipped; s++) {
int32_t m[2] = {shipped[s].mod, shipped[s].other};
sha256_update(&h, m, sizeof m);
hash_file_id(&h, shipped[s].file);
}
n = noverlay;
sha256_update(&h, &n, sizeof n);
for (size_t k = 0; k < noverlay; k++) {
const Overlay *o = &overlays[k];
int64_t place[3] = {o->index == ADDED ? -1 : (int64_t)o->index, o->prio, o->mod};
sha256_update(&h, o->name, strlen(o->name) + 1);
sha256_update(&h, place, sizeof place);
hash_identity(&h, o->path, &o->id);
}
sha256_final(&h, out);
return 1;
}
// Records the build's result for key: RESTBL_NONE, or RESTBL_TABLE with the SHA-256 of the table it wrote.
static void restbl_cache_store(const uint8_t key[32], int outcome, const uint8_t table[32]) {
char kp[2300], tp[2300];
restbl_cache_paths(kp, sizeof kp, tp, sizeof tp);
RestblCache c = {.magic = {'T', 'O', 'T', 'K', 'R', 'S', 'Z', 'C'}, .version = RESTBL_CACHE_VERSION,
.outcome = (uint32_t)outcome};
memcpy(c.key, key, 32);
if (table) memcpy(c.table, table, 32);
if (!plat_file_write_atomic(kp, &c, sizeof c))
rt_log("RomFS: cannot write %s; the resource size table is built at every start", kp);
}
// 1 when the last start's result fits: its table is served again (or none, as then). A miss logs why.
static int restbl_cache_use(const uint8_t key[32], Overlay *served, const char *keeps, double t0) {
char kp[2300], tp[2300];
restbl_cache_paths(kp, sizeof kp, tp, sizeof tp);
uint64_t n = 0;
RestblCache *c = (RestblCache *)plat_file_read(kp, &n);
const char *miss = NULL;
if (!c || n != sizeof *c || memcmp(c->magic, "TOTKRSZC", 8) || c->version != RESTBL_CACHE_VERSION ||
(c->outcome != RESTBL_NONE && c->outcome != RESTBL_TABLE))
miss = "no usable key from an earlier start";
else if (memcmp(c->key, key, 32))
miss = "the mods, the game files or the build changed since the last start";
if (!miss && c->outcome == RESTBL_TABLE) {
uint64_t zn = 0;
uint8_t *z = plat_file_read(tp, &zn), sum[32];
if (z) sha256(z, (size_t)zn, sum);
if (!z || memcmp(sum, c->table, 32)) {
free(z);
miss = "the kept table is missing or damaged";
} else if (!serve_generated(restbl_rel, served, z, (size_t)zn, "mods", // frees z
"merged resource sizes, kept from the last start", keeps)) {
miss = "the kept table cannot be served";
}
}
if (miss)
rt_log("RomFS: resource size table: built again: %s", miss);
else
rt_log("RomFS: resource size table: the mods' files are the ones of the last start: %s (%.0f ms)",
c->outcome == RESTBL_TABLE ? "its merged table is used" : "they fit the game's entries",
(now_s() - t0) * 1000);
free(c);
return !miss;
}
// With a player mod (or the TOTK_ROMFS_MODS manifest) serving files: the game's table with every shipped table of this
// version merged in (an entry larger than the game's wins), the entries a mod's table for another version gives for
// that mod's files, and each served mod file's entry raised to what its size needs (restbl_grow for a file the game
@@ -773,6 +895,12 @@ static void restbl_overlay(void) {
static const char keeps[] = "mod files that grew may fail to load";
double t0 = now_s();
uint64_t gi = lower(restbl_rel);
uint8_t cache_key[32];
Overlay *served_now = NULL;
for (size_t k = 0; k < noverlay; k++)
if (overlays[k].index == gi) served_now = &overlays[k];
int cached = rt_knob("RESTBL_CACHE", "0") && restbl_cache_key(gi, cache_key);
if (cached && restbl_cache_use(cache_key, served_now, keeps, t0)) return;
Entry ge = entry(gi);
void *gz = ge.size < (64u << 20) ? malloc((size_t)ge.size) : NULL;
Restbl *base = NULL, *out = NULL;
@@ -838,6 +966,7 @@ static void restbl_overlay(void) {
if (!merged && !raised && !members && !served) {
restbl_free(out);
rt_log("RomFS: resource size table: the mods' files fit the game's entries (%.0f ms)", (now_s() - t0) * 1000);
if (cached) restbl_cache_store(cache_key, RESTBL_NONE, NULL);
return;
}
size_t rn = 0, zn = 0;
@@ -852,10 +981,14 @@ static void restbl_overlay(void) {
rt_log("RomFS: cannot pack the merged resource size table; %s", keeps);
return;
}
if (serve_generated(restbl_rel, served, z, zn, "mods", "merged resource sizes", keeps))
uint8_t sum[32];
if (cached) sha256(z, zn, sum); // before serve_generated frees z
if (serve_generated(restbl_rel, served, z, zn, "mods", "merged resource sizes", keeps)) {
rt_log("RomFS: resource size table: %d tables merged (%d entries), %d entries raised for mod files (%d "
"added files estimated), %d for members of %d mod packs, %.0f ms", tables, merged, raised, estimated,
members, packs, (now_s() - t0) * 1000);
if (cached) restbl_cache_store(cache_key, RESTBL_TABLE, sum);
}
}
// The HeapDef table a bigger game resolution or TOTK_TEX_HEAP_EXTRA_MB needs (resolution.c): its texture heaps and
+73 -3
View File
@@ -6,12 +6,15 @@ Builds a mods folder in a temp directory with files of its own bytes at real Rom
build/extracted/<version>/romfs/index.json unless --romfs says otherwise), runs `totk.exe --probe-fs` on it and reads the `mods:` lines of the log.
--probe-fs compares the bytes it reads through the RomFS with every overlay file, so a wrong winner fails it too.
A second folder checks the merged resource size table the start writes to the profile (runtime/romfs.c
restbl_overlay): a grown file's entry, an added file's, a shipped table's and another version's table's.
restbl_overlay): a grown file's entry, an added file's, a shipped table's and another version's table's. Then the
table kept across starts (restbl_cache = 1, runtime/romfs.c restbl_cache_key): served again when nothing changed, built
again after a changed mod file, an added or removed mod, another order, a new totk.exe, a damaged key or table.
Needs the extracted RomFS of the version.
"""
import argparse
import json
import os
import shutil
import struct
import subprocess
import sys
@@ -43,9 +46,10 @@ def put(root, mod, rel, data, part='romfs', times=64):
f.write_bytes(data * times)
def run(exe, mods, order, disabled=''):
def run(exe, mods, order, disabled='', cache='0'):
"""--probe-fs with a profile of its own beside mods (the merged resource size table is written there)."""
env = dict(os.environ, TOTK_MODS_DIR=str(mods), TOTK_MODS_ORDER=order, TOTK_MODS_DISABLED=disabled)
env = dict(os.environ, TOTK_MODS_DIR=str(mods), TOTK_MODS_ORDER=order, TOTK_MODS_DISABLED=disabled,
TOTK_RESTBL_CACHE=cache, TOTK_BACKGROUND_WINDOW='1', TOTK_ASSUME_FOCUS='1')
profile = Path(mods).parent / 'profile'
r = subprocess.run([str(exe), '--profile', str(profile), '--probe-fs'], env=env, capture_output=True, timeout=600)
log = (r.stdout + r.stderr).decode('utf-8', 'replace')
@@ -122,6 +126,72 @@ def restbl_case(exe, version, romfs, check, tmp):
check(merged[key(old_other)] == game[key(old_other)], 'another version\'s table leaves other files alone')
lower = [h for h, s in game.items() if merged.get(h, 0) < s]
check(not lower, f'no entry of the game\'s table is lowered ({len(lower)})')
restbl_cache_case(exe, mods, merged_file, grown, check)
HIT = 'the mods\' files are the ones of the last start'
BUILT = 'RomFS: resource size table: built again: '
def restbl_cache_case(exe, mods, table, grown, check):
"""restbl_cache = 1 across starts on the mods restbl_case made (order Grow|Ships|Old)."""
keyf = table.with_name(table.name + '.key')
order = 'Grow|Ships|Old'
def start(what, hit, why=None, order=order):
code, log = run(exe, mods, order, cache='1')
ok = code == 0 and (HIT in log) == hit and (why is None or BUILT + why in log)
check(ok, f'restbl_cache: {what}: ' + ('served from the last start' if hit else f'built again ({why})'), log)
start('first start', False, 'no usable key')
check(keyf.is_file() and keyf.stat().st_size == 80, 'restbl_cache: the key file is written beside the table')
good = table.read_bytes()
start('same mods', True)
check(table.read_bytes() == good, 'restbl_cache: the served table is the built one')
changed = 'the mods, the game files or the build changed'
f = mods / 'Grow' / 'romfs' / grown
data = f.read_bytes()
f.write_bytes(data[:-1] + bytes([data[-1] ^ 1])) # same size, new bytes and write time
start('a mod file rewritten', False, changed)
start('the rewritten file again', True)
f.write_bytes(data)
start('the file restored', False, changed)
put(mods, 'Extra', 'Pack/Actor/ModTest_Extra.pack.zs',
zstandard.ZstdCompressor(write_content_size=True).compress(bytes(40000)), times=1)
start('a mod added', False, changed, order=order + '|Extra')
shutil.rmtree(mods / 'Extra')
start('the mod removed', False, changed)
start('another order', False, changed, order='Ships|Grow|Old')
start('the first order again', False, changed)
check(table.read_bytes() == good, 'restbl_cache: the table built again equals the first one')
st = os.stat(exe)
try:
os.utime(exe, ns=(st.st_atime_ns, st.st_mtime_ns + 2_000_000_000)) # what a new build changes
start('a new totk.exe', False, changed)
finally:
os.utime(exe, ns=(st.st_atime_ns, st.st_mtime_ns))
start('the old totk.exe again', False, changed)
keyf.write_bytes(keyf.read_bytes()[:40])
start('a torn key file', False, 'no usable key')
keyf.write_bytes(os.urandom(80))
start('a key file of random bytes', False, 'no usable key')
start('after the damaged key', True)
t = bytearray(table.read_bytes())
t[len(t) // 2] ^= 0xff
table.write_bytes(bytes(t))
start('a damaged table', False, 'the kept table is missing or damaged')
check(table.read_bytes() == good, 'restbl_cache: the damaged table is replaced by the built one')
table.unlink()
start('a missing table', False, 'the kept table is missing or damaged')
key_before = keyf.read_bytes()
code, log = run(exe, mods, order)
check(code == 0 and HIT not in log and BUILT not in log and keyf.read_bytes() == key_before,
'restbl_cache = 0 (the default): the table is built, the key is neither read nor written', log)
def main():
+5
View File
@@ -571,6 +571,11 @@
# cheats and the other patch files load. Its files may expect the missing code. 0: only the mods mods_no_code names.
# Read at start. Default: 0.
# mods_without_code = 0
# 1: the resource size table merged from the mods' files at start is kept in <profile>/mods/ and served again at the
# next start when no mod file, shipped table, the mod list or order, the game files or totk.exe changed (a file counts
# as changed when its size, write time or file id did). It saves the merge at start. A tool that rewrites a mod file
# with the same size and write time is not seen: set 0 while editing mod files that way. Read at start. Default: 0.
# restbl_cache = 0
# Extra room in MiB (0 to 4096) for the heap the world's textures stream into, for HD texture packs. Packs made for
# emulators with 8 GB of DRAM grow it in their own HeapDef table (System/HeapSize/Product.Nin_NX_NVN.HeapDef.byml.zs):
# the port reads that growth at start and applies it itself (about 3339 MiB for the HDPacks 4K pack), so such a pack