128 lines
5.2 KiB
Python
128 lines
5.2 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():
|
|
for name in ("glslc", "glslangValidator"):
|
|
p = shutil.which(name)
|
|
if p:
|
|
return name, 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"):
|
|
p = os.path.join(cand, sub)
|
|
if os.path.exists(p):
|
|
return os.path.basename(p), p
|
|
return None, None
|
|
|
|
|
|
def compile_one(compiler, path, compiler_path, spv_out):
|
|
if compiler == "glslc":
|
|
cmd = [compiler_path,
|
|
"-I", SHADER_DIR, # чтобы #include "common.glsl" работал
|
|
"-O", # оптимизация SPIR-V
|
|
"--target-env=vulkan1.1",
|
|
"-o", spv_out, path]
|
|
else:
|
|
# glslangValidator не умеет -I напрямую в старых версиях: используем -I<dir>
|
|
cmd = [compiler_path,
|
|
"-I" + SHADER_DIR,
|
|
"-V", # Vulkan SPIR-V
|
|
"-o", spv_out, path]
|
|
r = subprocess.run(cmd, capture_output=True, text=True)
|
|
return r.returncode, (r.stdout or "") + (r.stderr or "")
|
|
|
|
|
|
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 в xenith/backend/shaders/", file=sys.stderr)
|
|
return 1
|
|
|
|
blobs = []
|
|
failed = 0
|
|
for src in sources:
|
|
name = src[:-5] # без .comp
|
|
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
|
|
# SPIR-V — массив uint32; проверяем кратность 4
|
|
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/build_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}] = {{")
|
|
# по 12 uint32 в строке для читаемости
|
|
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())
|