Files
Xenith/tools/build_shaders.py
2026-10-15 11:14:14 +07:00

162 lines
6.9 KiB
Python

import os
import re
import shutil
import subprocess
import sys
HERE = os.path.dirname(os.path.abspath(__file__))
ROOT = os.path.normpath(os.path.join(HERE, ".."))
SHADER_DIR = os.path.join(ROOT, "xenith", "backend", "shaders")
OUT_HEADER = os.path.join(ROOT, "xenith", "backend", "shaders_bin.h")
def find_compiler():
script_dir = os.path.dirname(os.path.abspath(__file__))
local_tool = os.path.join(script_dir, "glslangValidator.exe")
if os.path.exists(local_tool):
return "glslangValidator", local_tool
p = shutil.which("glslangValidator")
if p:
return "glslangValidator", p
p = shutil.which("glslc")
if p:
return "glslc", p
for cand in (os.environ.get("VULKAN_SDK"), "/usr/local/vulkan", os.path.expanduser("~/VulkanSDK")):
if not cand:
continue
for sub in ("bin/glslc", "bin/glslangValidator"):
full_path = os.path.join(cand, sub)
if os.path.exists(full_path):
return os.path.basename(full_path), full_path
return None, None
def compile_one(compiler, path, compiler_path, spv_out):
if compiler == "glslc":
cmd = [compiler_path,
"-I", SHADER_DIR,
"-O",
"--target-env=vulkan1.1",
"-o", spv_out, path]
r = subprocess.run(cmd, capture_output=True, text=True)
return r.returncode, (r.stdout or "") + (r.stderr or "")
else:
import tempfile
with open(path, 'r', encoding='utf-8') as f:
lines = f.readlines()
# Ищем строку с #version
version_line_idx = -1
for i, line in enumerate(lines):
stripped = line.strip()
if stripped.startswith('#version'):
version_line_idx = i
break
modified_lines = list(lines)
# Если нашли #version, вставляем extension СРАЗУ ПОСЛЕ неё
if version_line_idx >= 0:
ext_directive = '#extension GL_GOOGLE_include_directive : enable\n'
# Проверяем, нет ли уже такой директивы
has_ext = any('GL_GOOGLE_include_directive' in l for l in lines)
if not has_ext:
modified_lines.insert(version_line_idx + 1, ext_directive)
else:
# Если #version нет (не должно быть для Vulkan), добавляем в начало
# Но лучше просто добавить extension в начало, если version отсутствует
ext_directive = '#extension GL_GOOGLE_include_directive : enable\n'
has_ext = any('GL_GOOGLE_include_directive' in l for l in lines)
if not has_ext:
modified_lines.insert(0, ext_directive)
# Пишем во временный файл
with tempfile.NamedTemporaryFile(mode='w', suffix='.comp',
delete=False, encoding='utf-8') as tmp:
tmp.writelines(modified_lines)
tmp_path = tmp.name
try:
cmd = [compiler_path,
f"-I{SHADER_DIR}",
"-V",
"--target-env", "vulkan1.1",
"-o", spv_out,
tmp_path]
r = subprocess.run(cmd, capture_output=True, text=True)
return r.returncode, (r.stdout or "") + (r.stderr or "")
finally:
os.unlink(tmp_path)
def main():
compiler, cpath = find_compiler()
if not compiler:
print("ОШИБКА: не найден ни glslc, ни glslangValidator.", file=sys.stderr)
print("Установи Vulkan SDK (https://vulkan.lunarg.com) или пакет shaderc/glslang,", file=sys.stderr)
print("либо собери проект без Vulkan: cmake -DXENITH_VULKAN=OFF", file=sys.stderr)
return 1
print(f"компилятор: {compiler} ({cpath})")
print(f"каталог : {SHADER_DIR}")
sources = sorted(f for f in os.listdir(SHADER_DIR) if f.endswith(".comp"))
if not sources:
print("нет ни одного .comp — сначала запусти tools/gen_shaders.py", file=sys.stderr)
return 1
blobs = []
failed = 0
for src in sources:
name = src[:-5]
spv = os.path.join(SHADER_DIR, name + ".spv")
rc, log = compile_one(compiler, os.path.join(SHADER_DIR, src), cpath, spv)
if rc != 0 or not os.path.exists(spv):
print(f" ✗ {src}\n{log}")
failed += 1
continue
with open(spv, "rb") as f:
data = f.read()
if len(data) < 20 or data[:4] not in (b"\x03\x02\x23\x07", b"\x07\x23\x02\x03"):
print(f" ✗ {src}: файл не похож на SPIR-V (магия {data[:4].hex()})")
failed += 1
continue
if len(data) % 4:
data = data[: len(data) - (len(data) % 4)]
blobs.append((name, data))
print(f"[OK] {src:22} > {len(data):7d} байт ({len(data)//4} слов)")
if failed:
print(f"\n{failed} шейдеров не собрались — заголовок НЕ перезаписан", file=sys.stderr)
return 1
lines = []
lines.append("// shaders_bin.h — SPIR-V шейдеры, упакованные в бинарник.")
lines.append("// СГЕНЕРИРОВАН АВТОМАТИЧЕСКИ: tools/build_shaders.py — руками не править.")
lines.append("// Исходники: xenith/backend/shaders/*.comp (генерирует tools/gen_shaders.py)")
lines.append("#ifndef XENITH_SHADERS_BIN_H")
lines.append("#define XENITH_SHADERS_BIN_H")
lines.append("#include <cstdint>")
lines.append("#include <cstddef>")
lines.append("")
for name, data in blobs:
words = len(data) // 4
lines.append(f"// {name}.comp — {words} слов")
lines.append(f"static const uint32_t xenith_spv_{name}[{words}] = {{")
row = []
for i in range(0, len(data), 4):
w = int.from_bytes(data[i:i+4], "little")
row.append(f"0x{w:08x}u")
if len(row) == 12:
lines.append(" " + ",".join(row) + ",")
row = []
if row:
lines.append(" " + ",".join(row))
lines.append("};")
lines.append(f"static const size_t xenith_spv_{name}_len = {words};")
lines.append("")
lines.append("#endif // XENITH_SHADERS_BIN_H")
with open(OUT_HEADER, "w", encoding="utf-8") as f:
f.write("\n".join(lines) + "\n")
total = sum(len(d) for _, d in blobs)
print(f"\nзаписано {OUT_HEADER}")
print(f" шейдеров: {len(blobs)}, суммарно {total} байт SPIR-V "
f"({total/1024:.1f} КиБ, в заголовке ~{os.path.getsize(OUT_HEADER)/1024:.0f} КиБ)")
return 0
if __name__ == "__main__":
sys.exit(main())