Add dlss to the game build on Windows + NVIDIA RTX with the SDK
build / mod (push) Failing after 29s

tools/airdef.py game always built with --features mods, so an RTX user had
to run the manual cargo line from docs/DLSS-TESTING.md. The feature string
now comes from dlss_build_features(): dlss is added only when the OS is
Windows, a Win32_VideoController name has both NVIDIA and RTX, the DLSS SDK
has include/nvngx*.h and lib/Windows_x86_64/x64 (DLSS_SDK, a repo DLSS/ dir
or %ProgramFiles%\NVIDIA\DLSS), and VULKAN_SDK has Include/vulkan/vulkan.h
(dlss_wgpu's build script needs both SDKs). Otherwise the build stays
mods-only; on Windows + RTX without the SDK it prints how to get v310.9.1
instead of failing. GPU/SDK probe errors mean "no DLSS" and never abort the
build; the HORIZON_DLSS runtime switch is untouched.

Tests: tools/test_airdef_build.py covers non-Windows, no RTX, missing DLSS
SDK, missing Vulkan SDK, the full toolchain, a failed GPU probe, the SDK
layout check and the feature string reaching cargo. python3 tools/airdef.py
game still builds mods-only on macOS (fresh target dir: 3m11s, exit 0).

Co-Authored-By: Kimi Code <noreply@moonshot.ai>
This commit is contained in:
2026-11-21 14:17:38 +03:00
parent d8d9913770
commit 11238c4a03
3 changed files with 169 additions and 3 deletions
+2
View File
@@ -54,6 +54,8 @@ DLSS Super Resolution: [1280, 720] -> [1920, 1080]
Нужны Visual Studio Build Tools с C++, Rust, clang, Vulkan SDK и NVIDIA DLSS SDK v310.9.1. Ветка — `kimi-work`.
`python3 tools/airdef.py game` сам добавляет `dlss` к features на Windows с NVIDIA RTX, если заданы `DLSS_SDK` и `VULKAN_SDK`; без них он предупреждает и собирает только `mods`. Ручная сборка ниже делает то же самое явно.
```powershell
git clone --branch kimi-work https://gitea.maoniao.team/chexit/airdef.git
cd airdef
+94 -3
View File
@@ -2,7 +2,7 @@
"""AirDef: сборка, установка и запуск на Windows, macOS и Linux. Только стандартная библиотека Python.
python3 tools/airdef.py fork # инициализировать закреплённый сабмодуль Horizon (horizon/)
python3 tools/airdef.py game # собрать игру (форк) — нужен Rust
python3 tools/airdef.py game # собрать игру (форк) — нужен Rust; на Windows + NVIDIA RTX с DLSS SDK добавляет feature dlss
python3 tools/airdef.py mod # собрать мод airdef.hmod — нужен Rust с wasm32
python3 tools/airdef.py install # положить мод в папку игры и включить
python3 tools/airdef.py play [аргументы игры] # запустить форк на папке игры
@@ -12,7 +12,8 @@
python3 tools/airdef.py test-budgets # тяжёлый WASM budget сценарий + JSON provenance
Переменные окружения: HORIZON_HOME (папка игры), HORIZON_RESOURCES (подготовленные ресурсы
Minecraft 26.3), AIRDEF_GAME (готовый horizon-client вместо собранного).
Minecraft 26.3), AIRDEF_GAME (готовый horizon-client вместо собранного), DLSS_SDK и VULKAN_SDK
(сборка game с feature dlss на Windows + NVIDIA RTX).
"""
import glob
import hashlib
@@ -101,9 +102,99 @@ def fork():
sys.exit(f"horizon/: ожидался {expected}, получен {current}")
DLSS_SDK_URL = "https://github.com/NVIDIA/DLSS/tree/v310.9.1"
VULKAN_SDK_URL = "https://vulkan.lunarg.com/sdk/home"
def gpu_names():
"""Имена видеоадаптеров Windows. Сбой опроса — пустой список (это «нет DLSS», а не ошибка сборки)."""
if platform.system() != "Windows":
return []
flags = getattr(subprocess, "CREATE_NO_WINDOW", 0)
for cmd in (["powershell", "-NoProfile", "-Command", "(Get-CimInstance Win32_VideoController).Name"],
["wmic", "path", "win32_VideoController", "get", "name"]):
try:
out = subprocess.run(cmd, capture_output=True, text=True, timeout=30,
creationflags=flags, errors="replace")
except (OSError, ValueError, subprocess.SubprocessError):
continue
if out.returncode != 0:
continue
# У wmic первая строка — заголовок Name.
names = [line.strip() for line in out.stdout.splitlines()
if line.strip() and line.strip().lower() != "name"]
if names:
return names
return []
def rtx_gpu(names) -> bool:
"""NVIDIA RTX среди адаптеров: в имени есть и NVIDIA, и RTX."""
return any("nvidia" in name.lower() and "rtx" in name.lower() for name in names)
def valid_dlss_sdk(path) -> bool:
"""Каталоги, без которых dlss_wgpu не соберётся: include/nvngx*.h и lib/Windows_x86_64/x64."""
return bool(path) and (path / "include").is_dir() and list((path / "include").glob("nvngx*.h")) \
and (path / "lib" / "Windows_x86_64" / "x64").is_dir()
def dlss_sdk_path():
"""Корень NVIDIA DLSS SDK v310.9.1 или None."""
candidates = []
if os.environ.get("DLSS_SDK"):
candidates.append(Path(os.environ["DLSS_SDK"]))
candidates += [ROOT / "DLSS", ROOT / "dlss-sdk"]
for env in ("ProgramFiles", "ProgramFiles(x86)"):
if os.environ.get(env):
candidates += sorted((Path(os.environ[env]) / "NVIDIA" / "DLSS").glob("*"), reverse=True)
for path in candidates:
if valid_dlss_sdk(path):
return path
return None
def dlss_build_features(system=None, gpus=None, sdk=None) -> str:
"""Features сборки клиента: 'mods,dlss' только на Windows + RTX при готовом SDK, иначе 'mods'.
Нет SDK на Windows + RTX — предупреждение с инструкцией и обычная сборка без DLSS.
"""
system = platform.system() if system is None else system
if system != "Windows":
return "mods"
names = gpu_names() if gpus is None else gpus
if not rtx_gpu(names):
return "mods"
if sdk is None:
sdk_root = dlss_sdk_path()
else:
candidate = Path(sdk)
sdk_root = candidate if valid_dlss_sdk(candidate) else None
vulkan = os.environ.get("VULKAN_SDK")
# dlss_wgpu ищет заголовки Vulkan в Include (Windows) или include.
vulkan_ok = bool(vulkan) and any((Path(vulkan) / part).is_file() for part in
("Include/vulkan/vulkan.h", "include/vulkan/vulkan.h"))
missing = []
if sdk_root is None:
missing.append(f"NVIDIA DLSS SDK v310.9.1 (переменная DLSS_SDK, {DLSS_SDK_URL})")
if not vulkan_ok:
missing.append(f"Vulkan SDK (переменная VULKAN_SDK, {VULKAN_SDK_URL})")
if missing:
print("Внимание: NVIDIA RTX найден, но DLSS-сборка пропущена — нет " + " и ".join(missing) + ".",
flush=True)
print(" DLSS SDK: скачай v310.9.1 и задай DLSS_SDK на корень SDK (include/ и lib/).", flush=True)
print(" Vulkan SDK: установи и задай VULKAN_SDK на корень SDK.", flush=True)
print(" Собираю --features mods: DLSS выключен, native TAAU остаётся.", flush=True)
return "mods"
print(f"DLSS: NVIDIA RTX, SDK {sdk_root}; собираю --features mods,dlss", flush=True)
print(" nvngx_dlss.dll положи рядом с horizon-client.exe; backend включает HORIZON_DLSS=1.", flush=True)
return "mods,dlss"
def game():
fork()
run([cargo(), "build", "--profile", "fast", "-p", "horizon-client", "--features", "mods"], cwd=FORK)
run([cargo(), "build", "--profile", "fast", "-p", "horizon-client", "--features", dlss_build_features()],
cwd=FORK)
def built_game() -> Path:
+73
View File
@@ -1,5 +1,7 @@
"""Real Git migration regression; no network, user settings or player data."""
import contextlib
import importlib.util
import io
import os
from pathlib import Path
import subprocess
@@ -59,5 +61,76 @@ class ForkMigrationTests(unittest.TestCase):
self.assertEqual(git(child, "remote", "get-url", "origin"), str(canonical))
class DlssBuildFeatureTests(unittest.TestCase):
"""Feature-строку решает детект Windows + RTX + SDK; на Mac и при сбоях — просто mods."""
def setUp(self):
self.tmp = tempfile.TemporaryDirectory(prefix="airdef-dlss-test-")
self.root = Path(self.tmp.name)
self.sdk = self.root / "DLSS"
(self.sdk / "include").mkdir(parents=True)
(self.sdk / "include" / "nvngx_dlss.h").write_text("")
(self.sdk / "lib" / "Windows_x86_64" / "x64").mkdir(parents=True)
self.vulkan = self.root / "VulkanSDK"
(self.vulkan / "Include" / "vulkan").mkdir(parents=True)
(self.vulkan / "Include" / "vulkan" / "vulkan.h").write_text("")
def tearDown(self):
self.tmp.cleanup()
def features(self, **kwargs):
out = io.StringIO()
with patch.dict(os.environ, {"VULKAN_SDK": str(self.vulkan)}), contextlib.redirect_stdout(out):
return airdef.dlss_build_features(**kwargs), out.getvalue()
def test_non_windows_is_mods_even_with_rtx_and_sdk(self):
features, output = self.features(system="Darwin", gpus=["NVIDIA GeForce RTX 3060"], sdk=self.sdk)
self.assertEqual(features, "mods")
self.assertEqual(output, "")
def test_windows_without_rtx_is_mods_silently(self):
features, output = self.features(system="Windows", gpus=["Intel(R) UHD Graphics 770"], sdk=self.sdk)
self.assertEqual(features, "mods")
self.assertEqual(output, "")
def test_windows_rtx_without_sdk_warns_and_builds_mods(self):
features, output = self.features(system="Windows", gpus=["NVIDIA GeForce RTX 3060"],
sdk=self.root / "missing")
self.assertEqual(features, "mods")
self.assertIn("DLSS_SDK", output)
self.assertIn("RTX", output)
def test_windows_rtx_without_vulkan_sdk_warns_and_builds_mods(self):
with patch.dict(os.environ, {"VULKAN_SDK": str(self.root / "missing")}), contextlib.redirect_stdout(io.StringIO()):
features = airdef.dlss_build_features(system="Windows", gpus=["NVIDIA GeForce RTX 3060"], sdk=self.sdk)
self.assertEqual(features, "mods")
def test_windows_rtx_with_full_toolchain_enables_dlss(self):
features, output = self.features(system="Windows", gpus=["NVIDIA GeForce RTX 3060", "Intel(R) UHD"],
sdk=self.sdk)
self.assertEqual(features, "mods,dlss")
self.assertIn("mods,dlss", output)
def test_gpu_query_failure_means_no_dlss(self):
with patch.object(airdef.platform, "system", return_value="Windows"), \
patch.object(airdef.subprocess, "run", side_effect=OSError("no powershell")):
self.assertEqual(airdef.gpu_names(), [])
self.assertEqual(airdef.dlss_build_features(system="Windows", gpus=[]), "mods")
def test_sdk_path_requires_the_layout_dlss_wgpu_builds_with(self):
with patch.dict(os.environ, {"DLSS_SDK": str(self.sdk)}):
self.assertEqual(airdef.dlss_sdk_path(), self.sdk)
with patch.dict(os.environ, {"DLSS_SDK": str(self.root / "missing")}):
self.assertIsNone(airdef.dlss_sdk_path())
def test_game_builds_with_the_detected_feature_string(self):
commands = []
with patch.object(airdef, "fork"), patch.object(airdef, "cargo", return_value="cargo"), \
patch.object(airdef, "run", side_effect=lambda cmd, cwd=None, env=None: commands.append(cmd)), \
patch.object(airdef, "dlss_build_features", return_value="mods,dlss"):
airdef.game()
self.assertEqual(commands[-1][-1], "mods,dlss")
if __name__ == "__main__":
unittest.main()