mirror of
https://github.com/ProjectLeonida/mandy.git
synced 2026-12-06 13:28:35 +00:00
dstorage history: fit packed tails against decoded BCPack siblings
The predictor profile fits a history field only from a stream with a raw or zlib sibling mip. A BC7 texture whose mip 1 and packed tail share one BCPack stream has none for the tail, so history fields that only such tails use stayed unknown and the runtime refused the stream with missing-endpoint (E_DSTORAGE_DECOMPRESSION_ERROR) on every game run. fit_decoded_neighbors decodes the nearest BCPack sibling with the profile so far, also inside a stream the decoder refuses (blocks whose chains start at an unknown field are left out of the reference), and fits the streams that still reference missing fields. Only empty fields are filled, never as confirmed. On the local package the BC7 endpoint fields go from 4228 to 4406 of 6144 and the runtime decoder refuses 8 of 5167 BC7 streams instead of 60; both request shapes that failed in game runs decode. BC6H is unchanged (10 of 268). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@ -190,7 +190,16 @@ The first boot with the executable settles most of this: the dry-run report show
|
||||
256 blocks of a stream. It combines adjacent mips from the same layer with full-stream index anchor
|
||||
and shared-p-bit constraints. A shared p-bit can relate low red endpoint bits even when its sibling
|
||||
mip supplies only the leading bits. These local fits preserve the recorded precision and exact reference
|
||||
bits. A profile can still lack endpoint values or exceed the reference consistency tolerance. Such a request reports a decompression error before publication.
|
||||
bits. A packed tail whose larger mips are BCPack-coded too has no raw or zlib sibling, so a history field that
|
||||
only such tails use stayed unknown: in the game runs of 2026-11-25 two BC7 tail streams of one pool failed
|
||||
with `missing-endpoint` (alpha fields of two history entries). For the streams that still start a chain at a
|
||||
missing field, the fitter now decodes the nearest BCPack sibling with the profile so far and fits against it,
|
||||
repeating while a round adds fields. The sibling may sit in the same refused BC7 stream: every block whose
|
||||
chains start elsewhere is still determined, and the undetermined ones are left out of the reference. Those
|
||||
fields are fitted, never confirmed, and fill only what the other fits left empty. On the 1.0.2.1 package this
|
||||
raised the BC7 endpoint fields from 4,228 to 4,406 of 6,144; the runtime decoder then refuses 8 of 5,167 BC7
|
||||
streams instead of 60 (both failing requests decode), and the 268 BC6H streams are unchanged (10 refused; a
|
||||
refused BC6H sibling is not used as a reference yet). A profile can still lack endpoint values or exceed the reference consistency tolerance. Such a request reports a decompression error before publication.
|
||||
- The four swizzle modes interleave stripes from request-wide component planes into 16 KiB (mode 1) or
|
||||
32 KiB (modes 2–4) groups. The enum names give the successive stripe widths. The shipped BC4 sample
|
||||
separates its endpoint planes from indices across the inflated source. The title's compute shader does
|
||||
|
||||
@ -85,6 +85,58 @@ class RuntimeHistoryTest(unittest.TestCase):
|
||||
self.assertEqual(bc7["historyEndpointConfirmedBits"][255][field], 0)
|
||||
self.assertLessEqual(abs(bc7["historyEndpoints"][255][field] - 128), 4)
|
||||
|
||||
def test_packed_tail_fits_against_decoded_bcpack_sibling(self):
|
||||
# Mip 0 is zlib, mip 1 a self-contained BCPack stream and the packed tail (mips 2-4) starts its
|
||||
# chains at history entry 255, whose alpha no raw or zlib sibling of the tail can show.
|
||||
solid = bytes([0x40]) + bytes(15)
|
||||
secret = (0, 0, 0, 128) * 6
|
||||
tail = _encode_bc7_mode6_tiled(solid * 256, secret_entry=255, secret_ep=secret, ref_count=255)
|
||||
with tempfile.TemporaryDirectory() as name:
|
||||
pool = Path(name)/"bcpack-parent.ttpf"
|
||||
record = _pack_etpf(128, 128, 4, 1, 98, 4096)
|
||||
_write_custom_rds5_pool(pool, [record], [(7, 4096, tail), (7, 4096, _encode_bc7_mode6_tiled(solid * 256)),
|
||||
(8, 16384, zlib.compress(solid * 1024))])
|
||||
fits = {6: history.calib.Bc6hCalibrator(), 7: history.calib.Bc7Calibrator()}
|
||||
history.calib.calibrate_from_pools([str(pool)], fits)
|
||||
docs = {history.calib.CODEC_KEYS[c]: f.build_document()[0] for c, f in fits.items()}
|
||||
history.extend_missing(docs, history.fit_slices([pool]))
|
||||
bcpack = history.calib.bcpack
|
||||
with self.assertRaises(bcpack.BcpackProvisionalError):
|
||||
bcpack.decode(tail, 7, 4096, allow_provisional=True, history=docs)
|
||||
history.fit_decoded_neighbors([pool], docs)
|
||||
bc7 = docs["bc7"]
|
||||
for field in (3, 7):
|
||||
self.assertGreaterEqual(bc7["historyEndpointBits"][255][field], 4)
|
||||
self.assertEqual(bc7["historyEndpointConfirmedBits"][255][field], 0)
|
||||
self.assertLessEqual(abs(bc7["historyEndpoints"][255][field] - 128), 4)
|
||||
self.assertEqual(bcpack.decode(tail, 7, 4096, allow_provisional=True, history=docs), solid * 256)
|
||||
|
||||
def test_packed_tail_fits_against_its_own_refused_stream(self):
|
||||
# One BCPack stream holds the packed tail (blocks 0-255) and mip 1 (blocks 256-511). Chains from history
|
||||
# entry 255 stay inside the tail, so the stream is refused and no fit reaches the entry, but mip 1 is
|
||||
# determined and is the reference.
|
||||
solid = bytes([0x40]) + bytes(15)
|
||||
secret = (0, 0, 0, 128) * 6
|
||||
stream = _encode_bc7_mode6_tiled(solid * 512, secret_entry=255, secret_ep=secret, ref_count=200)
|
||||
with tempfile.TemporaryDirectory() as name:
|
||||
pool = Path(name)/"one-stream.ttpf"
|
||||
record = _pack_etpf(128, 128, 4, 1, 98, 4096)
|
||||
_write_custom_rds5_pool(pool, [record], [(7, 8192, stream), (8, 16384, zlib.compress(solid * 1024))])
|
||||
fits = {6: history.calib.Bc6hCalibrator(), 7: history.calib.Bc7Calibrator()}
|
||||
history.calib.calibrate_from_pools([str(pool)], fits)
|
||||
docs = {history.calib.CODEC_KEYS[c]: f.build_document()[0] for c, f in fits.items()}
|
||||
history.extend_missing(docs, history.fit_slices([pool]))
|
||||
bcpack = history.calib.bcpack
|
||||
with self.assertRaises(bcpack.BcpackProvisionalError):
|
||||
bcpack.decode(stream, 7, 8192, allow_provisional=True, history=docs)
|
||||
history.fit_decoded_neighbors([pool], docs)
|
||||
bc7 = docs["bc7"]
|
||||
for field in (3, 7):
|
||||
self.assertGreaterEqual(bc7["historyEndpointBits"][255][field], 4)
|
||||
self.assertEqual(bc7["historyEndpointConfirmedBits"][255][field], 0)
|
||||
self.assertLessEqual(abs(bc7["historyEndpoints"][255][field] - 128), 4)
|
||||
self.assertEqual(bcpack.decode(stream, 7, 8192, allow_provisional=True, history=docs), solid * 512)
|
||||
|
||||
def test_build_resume_and_repair(self):
|
||||
trainer = os.environ.get("LEONIDA_TEST_BCPACK_TRAINER")
|
||||
if not trainer and not shutil.which("cl" if os.name == "nt" else "c++"):
|
||||
|
||||
@ -1858,6 +1858,8 @@ class Bc7Calibrator:
|
||||
if xy is None:
|
||||
continue
|
||||
qpts = get_quads(xy[0], xy[1])
|
||||
if qpts is None: # the sibling block is undetermined itself
|
||||
continue
|
||||
spread = max(max(p[c] for p in qpts) - min(p[c] for p in qpts) for c in range(4))
|
||||
weight = 4.0 if spread <= 6.0 else (2.0 if spread <= 18.0 else 0.5)
|
||||
sm = None if ns == 1 else (p2[part] if ns == 2 else p3[part])
|
||||
|
||||
@ -93,6 +93,164 @@ def extend_missing(base, extra):
|
||||
base["bc7"][value][k][j] = extra["bc7"][value][k][j]
|
||||
|
||||
|
||||
def _field_count(docs):
|
||||
return (sum(map(bool, docs["bc6h"]["endpointClass"])) + sum(map(bool, docs["bc6h"]["indexClass"])) +
|
||||
sum(bool(v) for key in ("historyEndpointBits", "historyIndexBits") for row in docs["bc7"][key] for v in row))
|
||||
|
||||
|
||||
def _unknown_references(codec, lanes, blocks, docs, table):
|
||||
"""Whether the stream's first 256 blocks start a predictor chain at a field the profile still lacks."""
|
||||
if codec == 7:
|
||||
try:
|
||||
return bool(calib.bcpack._bc7_check(lanes, min(blocks, 256), table, set(), has_history=True))
|
||||
except calib.bcpack.BcpackError:
|
||||
return False
|
||||
l0, l1 = lanes[0], lanes[1]
|
||||
for i in range(min(blocks, 256)):
|
||||
di = calib.bcpack._inter8(l1[2*i], l1[2*i+1])
|
||||
de = (di + calib.bcpack._unzig(calib.bcpack._inter8(l0[2*i], l0[2*i+1]))) & 255
|
||||
if (de > i and not docs["bc6h"]["endpointClass"][256+i-de] or
|
||||
di > i and not docs["bc6h"]["indexClass"][256+i-di]):
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def _decode_known(pool, start, size, docs, table, cache):
|
||||
"""Tiled bytes of a range plus the byte offsets (within it) of blocks the profile cannot determine.
|
||||
|
||||
A BC7 stream that the decoder refuses for its unknown history still determines every block whose predictor
|
||||
chains start elsewhere; only the blocks rooted at an unknown field, or failing the anchor and p-bit check, are
|
||||
marked. Other BCPack streams must decode in provisional mode."""
|
||||
bcpack = calib.bcpack
|
||||
out = bytearray(size)
|
||||
unknown = set()
|
||||
for virt, csize, offset, packed, codec, _ in pool.chunks_for(start, size):
|
||||
key = (offset, packed, codec)
|
||||
if key not in cache:
|
||||
raw = pool.data[offset:offset+packed]
|
||||
bad = ()
|
||||
if codec in (0, 8):
|
||||
data = pool.read_range(virt, csize, None, bcpack_mode="off")
|
||||
elif codec == 7:
|
||||
lanes, _ = bcpack.decode_lanes(raw, 7, csize)
|
||||
blocks = csize // 16
|
||||
missing = bcpack._bc7_check(lanes, blocks, table, set(), has_history=True)
|
||||
data, status = bcpack._bc7_rebuild(lanes, blocks, table)
|
||||
ends = {k for kind, k in missing if kind == "endpoint"}
|
||||
idxs = {k for kind, k in missing if kind == "index"}
|
||||
l0, l1 = lanes[0], lanes[1]
|
||||
er, ir = [-1] * blocks, [-1] * blocks
|
||||
for i in range(blocks):
|
||||
di = bcpack._inter8(l1[2*i], l1[2*i+1])
|
||||
de = (di + bcpack._unzig(bcpack._inter8(l0[2*i], l0[2*i+1]))) & 255
|
||||
er[i] = -1 if de == 0 else (256 + i - de if de > i else er[i - de])
|
||||
ir[i] = -1 if di == 0 else (256 + i - di if di > i else ir[i - di])
|
||||
bad = {16 * i for i in range(blocks) if status[i] or er[i] in ends or ir[i] in idxs}
|
||||
else:
|
||||
data = bcpack.decode(raw, codec, csize, allow_provisional=True, history=docs)
|
||||
cache[key] = (bytes(data), bad)
|
||||
data, bad = cache[key]
|
||||
lo, hi = max(start, virt), min(start + size, virt + csize)
|
||||
out[lo - start:hi - start] = data[lo - virt:hi - virt]
|
||||
unknown.update(virt + b - start for b in bad if lo <= virt + b < hi)
|
||||
return bytes(out), unknown
|
||||
|
||||
|
||||
def _known_quads(getter, layout, ref, kind, unknown):
|
||||
"""The sibling getter, answering None where a reference block is undetermined."""
|
||||
if not unknown:
|
||||
return getter
|
||||
bw, bh = (ref["pixels_w"] + 3) // 4, (ref["pixels_h"] + 3) // 4
|
||||
def get_quads(bx, by):
|
||||
# A child's 2x2 pixels per quad lie in one block; a parent's quads cover a 2x2 block square.
|
||||
x0, y0, span = (bx // 2, by // 2, 1) if kind == "child" else (2 * bx, 2 * by, 2)
|
||||
for y in range(y0, y0 + span):
|
||||
for x in range(x0, x0 + span):
|
||||
if calib.tiled_offset(layout, ref, min(x, bw - 1), min(y, bh - 1)) in unknown:
|
||||
return None
|
||||
return getter(bx, by)
|
||||
return get_quads
|
||||
|
||||
|
||||
def fit_decoded_neighbors(pools, docs, rounds=4):
|
||||
"""Fill fields that only streams without a raw or zlib sibling reference.
|
||||
|
||||
The other fits take their reference from a raw or zlib mip. A packed tail whose larger mips are BCPack-coded
|
||||
too has none, so a field that only such streams use stays unknown and the runtime refuses them. Decode the
|
||||
nearest BCPack sibling with the profile so far and fit against it; it may lie in the same refused stream, whose
|
||||
undetermined blocks are left out of the reference. A decoded mip can be the reference of the next one, so
|
||||
repeat while a round adds fields. Only fields still missing are filled, and never as confirmed.
|
||||
"""
|
||||
table = bptc.load_bc7(docs)
|
||||
jobs = []
|
||||
for path in pools:
|
||||
with closing(ttpf.Pool(path)) as pool:
|
||||
wanted = set()
|
||||
for _, size, offset, packed, codec, _ in pool.chunks:
|
||||
if codec in (6, 7):
|
||||
blocks = min(2048, size // 16)
|
||||
lanes = calib.decode_lanes_prefix(pool.data[offset:offset+packed], codec, size, blocks*2)
|
||||
if _unknown_references(codec, lanes, blocks, docs, table):
|
||||
wanted.add(offset)
|
||||
if not wanted:
|
||||
continue
|
||||
for index in range(pool.textures):
|
||||
d = pool.descriptor(index)
|
||||
codec = next((c for c in (6, 7) if d["format"] in calib.CODEC_DXGI[c]), None)
|
||||
if not codec or d["dimension"] not in (1, 2):
|
||||
continue
|
||||
a = ttpf.analyze(pool, index)
|
||||
if not a.get("available") or a.get("blocked"):
|
||||
continue
|
||||
layout = a["layout"]
|
||||
for layer in range(d["depth"]):
|
||||
for level, mip in enumerate(layout["mips"]):
|
||||
start = (d["base"] + layout.get("data_offset", 0) + mip["offset"] +
|
||||
layer * mip.get("slice_stride", layout.get("face_size", 0)))
|
||||
if any(c[2] in wanted for c in pool.chunks_for(start, mip["region"])):
|
||||
jobs.append((path, index, codec, layer, level))
|
||||
for _ in range(rounds):
|
||||
before = _field_count(docs)
|
||||
table = bptc.load_bc7(docs)
|
||||
fits = {6: calib.Bc6hCalibrator(), 7: calib.Bc7Calibrator()}
|
||||
for path in sorted({job[0] for job in jobs}):
|
||||
with closing(ttpf.Pool(path)) as pool:
|
||||
cache = {}
|
||||
for _, index, codec, layer, level in (job for job in jobs if job[0] == path):
|
||||
d = pool.descriptor(index)
|
||||
layout = ttpf.analyze(pool, index)["layout"]
|
||||
mips = layout["mips"]
|
||||
def address(m):
|
||||
return (d["base"] + layout.get("data_offset", 0) + m["offset"] +
|
||||
layer * m.get("slice_stride", layout.get("face_size", 0)))
|
||||
mip = mips[level]
|
||||
start = address(mip)
|
||||
chunks = [(size, offset, packed, virt - start, min(2048, size // 16))
|
||||
for virt, size, offset, packed, mode, _ in pool.chunks_for(start, mip["region"])
|
||||
if mode == codec and start - virt < 2048 * 16]
|
||||
for neighbor, kind in ((level+1, "child"), (level-1, "parent")):
|
||||
if not 0 <= neighbor < len(mips) or mips[neighbor]["region"] > 1048576:
|
||||
continue
|
||||
ref = mips[neighbor]
|
||||
if codec not in pool.codecs(address(ref), ref["region"]):
|
||||
continue # a raw or zlib sibling is the other fits' reference
|
||||
try:
|
||||
tiled, unknown = _decode_known(pool, address(ref), ref["region"], docs, table, cache)
|
||||
except (calib.bcpack.BcpackError, ValueError):
|
||||
continue
|
||||
getter = _known_quads(calib._make_sibling_quads_getter(codec, layout, ref, tiled, kind,
|
||||
signed=d["format"] == 96),
|
||||
layout, ref, kind, unknown)
|
||||
inverse = calib.make_inverse_tile_lookup(layout, mip)
|
||||
for size, offset, packed, relative, blocks in chunks:
|
||||
lanes = calib.decode_lanes_prefix(pool.data[offset:offset+packed], codec, size, blocks*2)
|
||||
fits[codec].add_pool_chunk(lanes, blocks, inverse, relative, getter)
|
||||
extend_missing(docs, {calib.CODEC_KEYS[c]: f.build_document()[0] for c, f in fits.items()})
|
||||
if _field_count(docs) == before:
|
||||
break
|
||||
return docs
|
||||
|
||||
|
||||
def collect(pools, trainer, temporary):
|
||||
"""The host trainer consumes framed chunks and returns violation counts per candidate."""
|
||||
output = temporary / "constraints"
|
||||
@ -214,6 +372,7 @@ def build(game, output, trainer, base_history=None, json_out=None, if_needed=Fal
|
||||
calib.calibrate_from_pools(pools, fits)
|
||||
docs = {calib.CODEC_KEYS[c]: f.build_document()[0] for c, f in fits.items()}
|
||||
extend_missing(docs, fit_slices(pools))
|
||||
fit_decoded_neighbors(pools, docs)
|
||||
history = temp/"history.json"
|
||||
history.write_text(json.dumps(docs), encoding="utf-8", newline="\n")
|
||||
if not trainer:
|
||||
|
||||
Reference in New Issue
Block a user