diff options
| author | ItsNotRexed <300290919+ItsNotRexed@users.noreply.github.com> | 2026-11-22 23:08:41 -0500 |
|---|---|---|
| committer | ItsNotRexed <300290919+ItsNotRexed@users.noreply.github.com> | 2026-11-22 23:08:41 -0500 |
| commit | 8f4e2d4834dd1dcc15cd1ea5ef3f31f3de36d053 (patch) | |
| tree | 6e09a3018d038f3443329d9f35c10ffd05429f98 | |
| parent | 79313d10dc6d045ad9219b3d83b4491f52fe9141 (diff) | |
| parent | 760638c8fdfd8a2415b82982d2d487b5eeaac882 (diff) | |
Merge pull request #3829 from kotorvr
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
| -rw-r--r-- | tests/test_ttpf_assets.py | 123 | ||||
| -rw-r--r-- | tools/ttpf_assets.py | 75 |
2 files changed, 197 insertions, 1 deletions
diff --git a/tests/test_ttpf_assets.py b/tests/test_ttpf_assets.py index 74ee539bb..27a099d5a 100644 --- a/tests/test_ttpf_assets.py +++ b/tests/test_ttpf_assets.py | |||
| @@ -1,5 +1,7 @@ | |||
| 1 | """Exercise the assets stage, existing C# catalogs and downstream texture lookup.""" | 1 | """Exercise the assets stage, existing C# catalogs and downstream texture lookup.""" |
| 2 | import contextlib | ||
| 2 | from contextlib import ExitStack | 3 | from contextlib import ExitStack |
| 4 | import io | ||
| 3 | import json | 5 | import json |
| 4 | import os | 6 | import os |
| 5 | from pathlib import Path | 7 | from pathlib import Path |
| @@ -72,9 +74,130 @@ class TextureAssets(unittest.TestCase): | |||
| 72 | self.assertEqual((row["Mips"], row["BaseMipLevel"]), (5, 0)) | 74 | self.assertEqual((row["Mips"], row["BaseMipLevel"]), (5, 0)) |
| 73 | self.assertEqual(path.read_bytes()[148:], b"".join(linear.values())) | 75 | self.assertEqual(path.read_bytes()[148:], b"".join(linear.values())) |
| 74 | self.assertEqual(world_build.index_ttpf_textures(self.work / "assets")[row["AssetKey"]], str(path)) | 76 | self.assertEqual(world_build.index_ttpf_textures(self.work / "assets")[row["AssetKey"]], str(path)) |
| 77 | # The lower-mip file the row named is gone once the manifest names the full chain: it was kept through | ||
| 78 | # the failed run above, and it is not stored a second time after the successful one. | ||
| 79 | self.assertFalse(partial.exists()) | ||
| 80 | self.assertEqual(sorted(p.name for p in self.folder.iterdir()), sorted([row["File"], "manifest.json"])) | ||
| 75 | with mock.patch.object(ttpf_assets.ttpf, "Pool", side_effect=AssertionError("unexpected reopen")): | 81 | with mock.patch.object(ttpf_assets.ttpf, "Pool", side_effect=AssertionError("unexpected reopen")): |
| 76 | self.build() | 82 | self.build() |
| 77 | 83 | ||
| 84 | def upgrade(self, other_rows=(), file="partial.dds"): | ||
| 85 | """A pool whose one BCPack texture has a lower-mip export in `file`; returns that file's path.""" | ||
| 86 | build_bc1_bcpack_pool(self.pool) | ||
| 87 | first = self.row | dict(File=file, BaseMipLevel=2, Mips=3, Limitation=None) | ||
| 88 | self.catalog.write_text(json.dumps({"Count": 1 + len(other_rows), "Textures": [first, *other_rows]}), | ||
| 89 | encoding="utf-8") | ||
| 90 | old = self.folder / file | ||
| 91 | old.write_bytes(b"previous mip chain") | ||
| 92 | return old | ||
| 93 | |||
| 94 | def test_superseded_file_another_row_names_is_kept(self): | ||
| 95 | # Not a block-compressed format, so the pass leaves this row alone; it names the same file. | ||
| 96 | other = dict(Index=1, AssetKey="0123456789ABCDEF", SourceMips=1, BaseMipLevel=0, Mips=1, | ||
| 97 | File="partial.dds", DxgiFormat=28, Limitation=None) | ||
| 98 | old = self.upgrade(other_rows=[other]) | ||
| 99 | self.build() | ||
| 100 | rows = json.loads(self.catalog.read_bytes())["Textures"] | ||
| 101 | self.assertTrue(rows[0]["File"].startswith("000000_bcpack_")) | ||
| 102 | self.assertEqual(rows[1]["File"], "partial.dds") | ||
| 103 | self.assertEqual(old.read_bytes(), b"previous mip chain") | ||
| 104 | |||
| 105 | def test_superseded_file_that_cannot_be_removed_does_not_fail_the_export(self): | ||
| 106 | old = self.upgrade() | ||
| 107 | unlink = Path.unlink | ||
| 108 | |||
| 109 | def in_use(path, *args, **kwargs): | ||
| 110 | if path.name == "partial.dds": | ||
| 111 | raise PermissionError(13, "The process cannot access the file because it is being used") | ||
| 112 | return unlink(path, *args, **kwargs) | ||
| 113 | |||
| 114 | stderr = io.StringIO() | ||
| 115 | with mock.patch.object(Path, "unlink", in_use), contextlib.redirect_stderr(stderr): | ||
| 116 | self.build() | ||
| 117 | self.assertTrue(self.row_after_export()["File"].startswith("000000_bcpack_")) | ||
| 118 | self.assertTrue(old.exists()) | ||
| 119 | # Not hidden: a folder that stays double-sized has its reason on screen. | ||
| 120 | self.assertIn("pool: 1 replaced DDS file(s) could not be removed", stderr.getvalue()) | ||
| 121 | # And not forever: the manifest lists it, so the next build removes it once nothing holds it, although | ||
| 122 | # that build finds the pass stamped and writes nothing else. | ||
| 123 | self.assertEqual(json.loads(self.catalog.read_bytes())[ttpf_assets.PENDING], ["partial.dds"]) | ||
| 124 | with mock.patch.object(ttpf_assets.ttpf, "Pool", side_effect=AssertionError("unexpected reopen")): | ||
| 125 | self.build() | ||
| 126 | self.assertFalse(old.exists()) | ||
| 127 | self.assertNotIn(ttpf_assets.PENDING, json.loads(self.catalog.read_bytes())) | ||
| 128 | self.build() # nothing left to do: no further write, no error | ||
| 129 | self.assertTrue(self.row_after_export()["File"].startswith("000000_bcpack_")) | ||
| 130 | |||
| 131 | def test_a_run_stopped_after_the_switch_is_finished_by_the_next(self): | ||
| 132 | # The manifest that switches the rows already lists the file to remove, so a build stopped between that | ||
| 133 | # write and the removal leaves nothing behind for good. | ||
| 134 | old = self.upgrade() | ||
| 135 | with mock.patch.object(ttpf_assets, "finish_replaced"): | ||
| 136 | self.build() | ||
| 137 | self.assertTrue(old.exists()) | ||
| 138 | self.assertEqual(json.loads(self.catalog.read_bytes())[ttpf_assets.PENDING], ["partial.dds"]) | ||
| 139 | self.build() | ||
| 140 | self.assertFalse(old.exists()) | ||
| 141 | self.assertNotIn(ttpf_assets.PENDING, json.loads(self.catalog.read_bytes())) | ||
| 142 | |||
| 143 | def complete_with_row_file(self, file): | ||
| 144 | """Run the pass on a manifest whose row names `file`; returns the folder's file names afterwards.""" | ||
| 145 | self.upgrade() | ||
| 146 | manifest = json.loads(self.catalog.read_bytes()) | ||
| 147 | manifest["Textures"][0]["File"] = file | ||
| 148 | self.assertEqual(ttpf_assets.complete_pool(self.pool, self.folder, manifest, ("v1-strict", None)), (1, 0)) | ||
| 149 | return sorted(p.name for p in self.folder.iterdir()) | ||
| 150 | |||
| 151 | def test_a_row_that_named_the_new_file_in_other_letter_case_keeps_it(self): | ||
| 152 | # On Windows and macOS that name is the file the pass has just published; removing it removed the export. | ||
| 153 | names = self.complete_with_row_file("000000_BCPACK_V1-STRICT.DDS") | ||
| 154 | row = self.row_after_export() | ||
| 155 | self.assertEqual(row["File"], "000000_bcpack_v1-strict.dds") | ||
| 156 | self.assertTrue((self.folder / row["File"]).is_file(), names) | ||
| 157 | self.assertGreater((self.folder / row["File"]).stat().st_size, 148) | ||
| 158 | |||
| 159 | def test_a_row_that_named_the_manifest_does_not_remove_it(self): | ||
| 160 | names = self.complete_with_row_file("manifest.json") | ||
| 161 | self.assertIn("manifest.json", names) | ||
| 162 | self.assertTrue(self.row_after_export()["File"].startswith("000000_bcpack_")) | ||
| 163 | |||
| 164 | def test_only_dds_files_are_removed(self): | ||
| 165 | (self.folder / "notes.txt").write_text("mine", encoding="utf-8") | ||
| 166 | names = self.complete_with_row_file("notes.txt") | ||
| 167 | self.assertIn("notes.txt", names) | ||
| 168 | |||
| 169 | def test_removal_looks_at_each_file_once_not_once_per_pair(self): | ||
| 170 | # 50 rows and 50 replaced files: 100 files to look at, not 2,500 pairs. A pool completes most of its | ||
| 171 | # textures in one pass, so a per-pair check takes minutes to hours on a real one. | ||
| 172 | rows = [dict(File=f"{i:06d}_bcpack_v1-strict.dds") for i in range(50)] | ||
| 173 | replaced = {f"{i:06d}.dds" for i in range(50)} | ||
| 174 | for name in [row["File"] for row in rows] + sorted(replaced): | ||
| 175 | (self.folder / name).write_bytes(b"dds") | ||
| 176 | stat, calls = os.stat, [] | ||
| 177 | |||
| 178 | def counted(path, *args, **kwargs): | ||
| 179 | calls.append(path) | ||
| 180 | return stat(path, *args, **kwargs) | ||
| 181 | |||
| 182 | with mock.patch.object(ttpf_assets.os, "stat", counted), \ | ||
| 183 | mock.patch.object(ttpf_assets.os.path, "samefile", side_effect=AssertionError("per-pair check")): | ||
| 184 | self.assertEqual(ttpf_assets.remove_replaced(self.folder, replaced, rows), []) | ||
| 185 | self.assertLessEqual(len(calls), 100, len(calls)) | ||
| 186 | # The replaced files are gone and the rows' files stay. | ||
| 187 | self.assertEqual(sorted(p.name for p in self.folder.iterdir()), sorted(row["File"] for row in rows)) | ||
| 188 | |||
| 189 | def test_only_a_file_in_the_pool_folder_is_removed(self): | ||
| 190 | # A row is trusted for a file name, not for a path: nothing outside the pool's folder is touched. | ||
| 191 | outside = self.folder.parent / "outside.dds" | ||
| 192 | outside.write_bytes(b"not this pool's") | ||
| 193 | self.upgrade() | ||
| 194 | manifest = json.loads(self.catalog.read_bytes()) | ||
| 195 | manifest["Textures"][0]["File"] = "../outside.dds" | ||
| 196 | written, blocked = ttpf_assets.complete_pool(self.pool, self.folder, manifest, ("v1-strict", None)) | ||
| 197 | self.assertEqual((written, blocked), (1, 0)) | ||
| 198 | self.assertTrue(self.row_after_export()["File"].startswith("000000_bcpack_")) | ||
| 199 | self.assertEqual(outside.read_bytes(), b"not this pool's") | ||
| 200 | |||
| 78 | def test_profile_added_after_strict_rejection(self): | 201 | def test_profile_added_after_strict_rejection(self): |
| 79 | build_bc1_bcpack_pool(self.pool, ref_dists=[250] + [0] * 1023) | 202 | build_bc1_bcpack_pool(self.pool, ref_dists=[250] + [0] * 1023) |
| 80 | self.legacy() | 203 | self.legacy() |
diff --git a/tools/ttpf_assets.py b/tools/ttpf_assets.py index 3cb96d1c6..f34c9b62a 100644 --- a/tools/ttpf_assets.py +++ b/tools/ttpf_assets.py | |||
| @@ -47,6 +47,67 @@ def publish(path, data): | |||
| 47 | tmp.unlink(missing_ok=True) | 47 | tmp.unlink(missing_ok=True) |
| 48 | 48 | ||
| 49 | 49 | ||
| 50 | def file_identity(path): | ||
| 51 | """(device, inode) of an existing file, or None: two names with one identity are one file on disk.""" | ||
| 52 | try: | ||
| 53 | st = os.stat(path) | ||
| 54 | except OSError: | ||
| 55 | return None | ||
| 56 | return (st.st_dev, st.st_ino) if st.st_ino else None | ||
| 57 | |||
| 58 | |||
| 59 | def remove_replaced(directory, replaced, rows): | ||
| 60 | """Remove the files of `replaced` (names the rows had before they were switched) from `directory`; returns | ||
| 61 | the names that could not be removed (in use), sorted. | ||
| 62 | |||
| 63 | Only a .dds file by its bare name in this folder is removed, never manifest.json, and never a file a row still | ||
| 64 | names: by the same name, by a name that differs in letter case only, or by any other spelling of the same file | ||
| 65 | on disk (on Windows and macOS that can be the file the pass has just published). Each file is looked at once: | ||
| 66 | one stat per named row and one per replaced name, not one per pair.""" | ||
| 67 | names = [row["File"] for row in rows if isinstance(row.get("File"), str)] | ||
| 68 | named = {os.path.normcase(name) for name in names} | ||
| 69 | on_disk = {file_identity(directory / name) for name in names} - {None} | ||
| 70 | left = [] | ||
| 71 | for name in sorted(replaced): | ||
| 72 | if Path(name).name != name or not name.lower().endswith(".dds") or os.path.normcase(name) in named: | ||
| 73 | continue | ||
| 74 | if file_identity(directory / name) in on_disk: | ||
| 75 | continue | ||
| 76 | try: | ||
| 77 | (directory / name).unlink(missing_ok=True) | ||
| 78 | except OSError: | ||
| 79 | left.append(name) | ||
| 80 | return left | ||
| 81 | |||
| 82 | |||
| 83 | # The manifest key that lists replaced files still to be removed. It is written with the manifest that switches the | ||
| 84 | # rows, so a removal that fails (a file in use) or a run stopped right after the switch is finished by a later run, | ||
| 85 | # even though that run finds the pass stamped and writes nothing else. | ||
| 86 | PENDING = "BCPackReplaced" | ||
| 87 | |||
| 88 | |||
| 89 | def finish_replaced(directory, manifest): | ||
| 90 | """Remove the files the manifest lists under PENDING, and publish it again with what is left.""" | ||
| 91 | pending = manifest.get(PENDING) | ||
| 92 | if not isinstance(pending, list) or not pending: | ||
| 93 | return | ||
| 94 | left = remove_replaced(directory, {name for name in pending if isinstance(name, str)}, manifest["Textures"]) | ||
| 95 | if left: | ||
| 96 | manifest[PENDING] = left | ||
| 97 | else: | ||
| 98 | manifest.pop(PENDING) | ||
| 99 | if left != pending: | ||
| 100 | try: | ||
| 101 | publish(directory / "manifest.json", json.dumps(manifest, indent=2).encode("utf-8")) | ||
| 102 | except OSError as exc: | ||
| 103 | # The files are gone; the list on disk still names them, and a later run drops them (missing is fine). | ||
| 104 | print(f"assets: {directory.name}: could not update manifest.json after removing replaced DDS files: " | ||
| 105 | f"{exc.strerror or exc}", file=sys.stderr) | ||
| 106 | if left: | ||
| 107 | print(f"assets: {directory.name}: {len(left)} replaced DDS file(s) could not be removed (in use?) and stay " | ||
| 108 | "next to the full-chain files; the next build tries again", file=sys.stderr) | ||
| 109 | |||
| 110 | |||
| 50 | def candidate(row, profile): | 111 | def candidate(row, profile): |
| 51 | if row.get("DxgiFormat") not in ttpf.BC_FORMATS: | 112 | if row.get("DxgiFormat") not in ttpf.BC_FORMATS: |
| 52 | return False | 113 | return False |
| @@ -59,13 +120,15 @@ def candidate(row, profile): | |||
| 59 | def complete_pool(source, directory, manifest, settings): | 120 | def complete_pool(source, directory, manifest, settings): |
| 60 | """Publish full chains next to ordinary DDS files, then switch the catalog to them.""" | 121 | """Publish full chains next to ordinary DDS files, then switch the catalog to them.""" |
| 61 | stamp, profile = settings | 122 | stamp, profile = settings |
| 123 | directory = Path(directory) | ||
| 62 | if manifest.get("BCPackPass") == stamp: | 124 | if manifest.get("BCPackPass") == stamp: |
| 125 | finish_replaced(directory, manifest) | ||
| 63 | return 0, 0 | 126 | return 0, 0 |
| 64 | rows = [row for row in manifest["Textures"] if candidate(row, profile)] | 127 | rows = [row for row in manifest["Textures"] if candidate(row, profile)] |
| 65 | if not rows: | 128 | if not rows: |
| 66 | return 0, 0 | 129 | return 0, 0 |
| 67 | directory = Path(directory) | ||
| 68 | written = blocked = 0 | 130 | written = blocked = 0 |
| 131 | superseded = set() # the files the rows named before they were switched to a full chain | ||
| 69 | with closing(ttpf.Pool(source)) as pool: | 132 | with closing(ttpf.Pool(source)) as pool: |
| 70 | decoder = None | 133 | decoder = None |
| 71 | if profile is not None: | 134 | if profile is not None: |
| @@ -99,6 +162,8 @@ def complete_pool(source, directory, manifest, settings): | |||
| 99 | # A distinct name keeps an existing lower-mip DDS usable until the manifest switches. | 162 | # A distinct name keeps an existing lower-mip DDS usable until the manifest switches. |
| 100 | name = f"{index:06d}_bcpack_{method[:19]}.dds" | 163 | name = f"{index:06d}_bcpack_{method[:19]}.dds" |
| 101 | publish(directory / name, blob) | 164 | publish(directory / name, blob) |
| 165 | if isinstance(row.get("File"), str) and row["File"] != name: | ||
| 166 | superseded.add(row["File"]) | ||
| 102 | row.update(File=name, Mips=desc["mips"], BaseMipLevel=0, Limitation=None, BCPackDecoder=method) | 167 | row.update(File=name, Mips=desc["mips"], BaseMipLevel=0, Limitation=None, BCPackDecoder=method) |
| 103 | row.pop("BCPackLimitation", None) | 168 | row.pop("BCPackLimitation", None) |
| 104 | written += 1 | 169 | written += 1 |
| @@ -106,5 +171,13 @@ def complete_pool(source, directory, manifest, settings): | |||
| 106 | if decoder: | 171 | if decoder: |
| 107 | decoder.read_chunk.cache_clear() | 172 | decoder.read_chunk.cache_clear() |
| 108 | manifest["BCPackPass"] = stamp | 173 | manifest["BCPackPass"] = stamp |
| 174 | # The files the switched rows named before would otherwise stay in the folder, named by no row, so every | ||
| 175 | # completed texture would be stored twice. They are listed in the manifest that switches the rows and removed | ||
| 176 | # only after it is published: a file another row still names is kept, and one that can't be removed (in use) | ||
| 177 | # stays listed for the next build. The export is complete either way. | ||
| 178 | pending = {name for name in manifest.get(PENDING) or [] if isinstance(name, str)} | superseded | ||
| 179 | if pending: | ||
| 180 | manifest[PENDING] = sorted(pending) | ||
| 109 | publish(directory / "manifest.json", json.dumps(manifest, indent=2).encode("utf-8")) | 181 | publish(directory / "manifest.json", json.dumps(manifest, indent=2).encode("utf-8")) |
| 182 | finish_replaced(directory, manifest) | ||
| 110 | return written, blocked | 183 | return written, blocked |