Follow-up to116a70e(C++ shadergen FS-side PGXP_DEPTH routing) which brought D3D11 / D3D12 / OpenGL on. This commit parallels it on the Vulkan path: collapses the PGXP_DEPTH SPIR-V-structural axis from all 5 batch FS templates (untextured + nearest + bilinear + jinc2 + xbr), making gl_FragDepth always written with a runtime branch on u_pgxp_depth. Vulkan FS templates each had PGXP_DEPTH as one of their four structural axes (3 interp x 2 persp x 2 dual x 2 pgxp = 24 blobs per template, 120 total batch FS blobs). After this commit each template has 3 x 2 x 2 = 12 blobs, 60 total. Routing for each template follows the same shape: GLSL UBO grows by u_pgxp_depth at offset 52. For the filter family (bilinear / jinc2 / xbr) the UBO previously declared the first 6 fields and stopped at offset 32; this commit adds a `layout(offset = 52) uint u_pgxp_depth;` trailing field to skip past the spec-const-handled intermediate slots (u_resolution_scale through u_interlacing). For Nearest the UBO already had u_uv_limits at offset 56; u_pgxp_depth slots in before it at offset 52. For the untextured template the UBO previously declared only the first 6 fields; same trailing layout(offset=52) treatment. GLSL FS body: drop the #if !defined(PGXP_DEPTH) gl_FragDepth = oalpha * gl_FragCoord.z; #endif block, replace with the unconditional gl_FragDepth = (u_pgxp_depth != 0u) ? gl_FragCoord.z : (oalpha * gl_FragCoord.z); Same expression shape as the C++ shadergen routing in116a70ebut using Vulkan's gl_FragCoord.z (rasterizer- interpolated depth) instead of HLSL's v_pos.z. Regen tool: drop pgxp_axes from each of the three variant-generator helpers (_batch_fs_untextured_variants, _batch_fs_textured_nearest_variants, _batch_fs_textured_filter_variants - the last shared by bilinear / jinc2 / xbr). Filename suffix shortens from `_<interp>_<persp>_<dual>_<pgxp>` to `_<interp>_<persp>_<dual>`. embedded_spirv/: 120 obsolete files deleted (60 _pgxpoff + 60 _pgxpon, 24 per template), 60 new files added (12 per template) carrying the runtime-branch SPIR-V. Total .inc count: 151 -> 91. embedded_shaders.{h,cpp}: 5 FS blob tables drop from [24] to [12]. 5 helper functions (GetBatch{Untextured,TexturedNearest,TexturedBilinear, TexturedJINC2,TexturedXBR}FragmentShaderBlob) drop the bool pgxp_depth parameter. Index encoding becomes index = interp*4 + persp*2 + dual (0..11) (was: interp*8 + persp*4 + dual*2 + pgxp). 60 #include lines collapse to 60 (renamed, no count change for that block, just filename change). gpu_hw_vulkan.cpp: 5 FS lookup call sites (GetBatchUntexturedFragmentShaderBlob and the four textured filter variants in the switch on `filter`) drop their sixth argument (m_pgxp_depth_buffer). What does NOT change in this commit: - The Vulkan batch VS still uses PGXP_DEPTH as a spec constant (id=3, declared in batch.vert.glsl, set via vs_spec.AddBool(3, m_pgxp_depth_buffer) at pipeline build). The C++ shadergen VS was routed to u_pgxp_depth in49c0f82but the Vulkan VS still has spec const PGXP_DEPTH. A separate small follow-up can route the VS GLSL through u_pgxp_depth too; the cost matters less on Vulkan because spec consts don't fork SPIR-V (one VS blob, two pipelines per PGXP value), only PSO assembly, and Vulkan already has depth_test as a PSO matrix dim that swaps the depth comparison func at draw time without rebuild. - The non-batch FS spec const id=3 PGXP_DEPTH sites (gpu_hw_vulkan.cpp lines 2477, 2523, 2581 - the vram_fill, vram_copy, vram_write_* paths) are unrelated to the batch FS arc. Those shaders genuinely declare PGXP_DEPTH as a spec const (data/shaders/vulkan/vram_fill.frag.glsl:80 etc.) and have their own pre-bake plans. - m_pgxp_depth_buffer STAYS in shader_source_changed across all backends. The Vulkan FS bytecode is now invariant under it but the C++ shadergen FS still has PSO-state dependency (gpu_hw_d3d12.cpp:1317-1319 picks LESS_EQUAL vs GREATER_EQUAL based on m_pgxp_depth_buffer at PSO build time), so PSO rebuild on flip is still required for D3D11 / D3D12 / OpenGL. Vulkan handles the depth-comp swap via its depth_test PSO matrix dim (depth_test=1 GREATER_OR_EQUAL, depth_test=2 LESS_OR_EQUAL - see gpu_hw_vulkan.cpp:2233's depth_test_values array) so Vulkan doesn't actually need a rebuild on flip post-this-commit. Decoupling the cross-backend rebuild trigger from Vulkan's no-longer-needing-it is a separate cleanup. Variant-count delta: Per-template Vulkan FS: 24 -> 12 SPIR-V blobs. Across 5 templates: 120 -> 60 SPIR-V blobs. Pipeline cache footprint drops by 60 FS pipelines per (filter, render, texture) cell - actual PSO count depends on how many of those cells get exercised in practice but the savings are proportional. Disk SPIR-V footprint: Before: 151 .inc files, ~11.3 MiB. After: 91 .inc files, ~7.5 MiB. (-60 files, ~3.8 MiB. The new files are slightly larger than the old _pgxpoff ones - they always emit the gl_FragDepth write and the runtime branch - but smaller than two old files combined, so net footprint drops.) Cost matrix delta (Vulkan): Per-session m_pgxp_depth_buffer flip: Pre-commit: 60 batch FS pipelines per (filter, render, texture) cell rebuilt to swap from _pgxpoff -> _pgxpon. Tens of ms on cold pipeline cache, ~0 with warm cache. Post-commit: 0 FS pipeline rebuilds. The u_pgxp_depth UBO write picks up at next FlushRender; the FS bytecode is invariant across the flip. The PSO depth-comp swap is handled by Vulkan's depth_test matrix axis (and the C++ side passes the right depth_test index based on m_pgxp_depth_buffer at draw time). Cold launch precompile pass on Vulkan: 60 fewer batch FS pipelines to enumerate / create. Steady-state runtime cost (Vulkan batch FS): + 4-byte UBO read on every fragment. + One uniform branch on u_pgxp_depth (cbuffer scalar, uniform across the warp) - resolves to a predicated select on modern hardware. + The early-Z TEST trade discussed in 116a70e's commit message applies: pre-commit, the _pgxpon variants on Vulkan retained early-Z TEST (no FS depth write); post-commit those variants always write gl_FragDepth so early-Z TEST is disabled. For PSX content on modern GPUs the cost is sub-noise (low overdraw, cheap FS, painter's-sorted geometry, depth values that are essentially random and Hi-Z can't compress). Test: - Build: tools/regen_vulkan_spirv.py runs cleanly, producing 91 blobs. Embedded_shaders.cpp compiles against the smaller tables. gpu_hw_vulkan.cpp links clean. - Boot any PSX title on Vulkan with PGXP-depth off: u_pgxp_depth=0, the FS ternary picks oalpha * gl_FragCoord.z. Output identical to pre-commit. - Toggle PGXP-depth on: u_pgxp_depth flips to 1 via the existing UpdateHWSettings cbuffer push. The depth_test index passed to the PSO lookup also changes to select the LESS_OR_EQUAL pipeline. FS picks the gl_FragCoord.z pass-through path. No pipeline rebuild fired on Vulkan. Output identical to pre-commit PGXP-on state. - Mask-bit-heavy titles (Crash 1/2/3, Final Fantasy combat backgrounds, Silent Hill 1 fog plane): visual sanity check that the mask-bit-depth-encode path still works at all 5 filters (Nearest baseline, Bilinear, JINC2, xBR, BilinearBinAlpha). - PGXP-corrected titles (Tekken 3, Tomb Raider 1/2, Soul Blade): visual sanity that the pass-through write is value-equivalent to the omit-gl_FragDepth-declaration pre-routing behaviour. Watch for z-fighting on co-planar stage geometry. Next: - Optionally route the Vulkan VS PGXP_DEPTH spec const through u_pgxp_depth for parity (small follow-up; cuts one spec const per VS pipeline build). - per_sample / dcp collapse decisions. - Pre-bake the resulting D3D12 FS matrix.
301 lines
11 KiB
Python
Executable file
301 lines
11 KiB
Python
Executable file
#!/usr/bin/env python3
|
|
# Regenerate embedded Vulkan SPIR-V blobs from GLSL sources.
|
|
#
|
|
# This script is NOT invoked by the core build. It is run by contributors who
|
|
# edit shader sources under data/shaders/vulkan/. The build itself only sees
|
|
# the resulting .inc files (checked into src/common/vulkan/embedded_spirv/),
|
|
# so the libretro core has zero glslangValidator dependency.
|
|
#
|
|
# Usage:
|
|
# python3 tools/regen_vulkan_spirv.py [--glslang PATH]
|
|
#
|
|
# Requires glslangValidator from the Vulkan SDK or the `glslang-tools`
|
|
# package on Debian / Ubuntu.
|
|
|
|
import argparse
|
|
import os
|
|
import re
|
|
import struct
|
|
import subprocess
|
|
import sys
|
|
from pathlib import Path
|
|
|
|
REPO_ROOT = Path(__file__).resolve().parent.parent
|
|
GLSL_DIR = REPO_ROOT / "data" / "shaders" / "vulkan"
|
|
INC_DIR = REPO_ROOT / "src" / "common" / "vulkan" / "embedded_spirv"
|
|
|
|
# Map glsl file suffix to glslangValidator stage flag. Anything not in this
|
|
# table is skipped with a warning.
|
|
STAGE_FROM_SUFFIX = {
|
|
".vert.glsl": ("vert", "vs"),
|
|
".frag.glsl": ("frag", "fs"),
|
|
".comp.glsl": ("comp", "cs"),
|
|
".geom.glsl": ("geom", "gs"),
|
|
}
|
|
|
|
|
|
# Templates: shader sources that produce more than one .inc output, each
|
|
# with a different combination of -D preprocessor defines. Index ordering
|
|
# below MUST match the helper in src/common/vulkan/embedded_shaders.cpp
|
|
# that picks the right blob at runtime - if you add a variant here, add
|
|
# the matching entry there too.
|
|
#
|
|
# For each entry: filename -> [(variant_suffix, [-D defines]), ...]
|
|
def _batch_vs_variants():
|
|
out = []
|
|
# Attribute layout: untextured / textured (the latter always with
|
|
# UV limits since the UV_LIMITS-routing commit lifted the axis to
|
|
# the FS-side u_uv_limits cbuffer scalar). 2 layouts now.
|
|
attr_axes = [
|
|
("untextured", []),
|
|
("textured", ["TEXTURED"]),
|
|
]
|
|
# Output interpolation: standard / centroid (MSAA) / sample (SSAA).
|
|
interp_axes = [
|
|
("none", []),
|
|
("centroid", ["INTERP_CENTROID"]),
|
|
("sample", ["INTERP_SAMPLE"]),
|
|
]
|
|
# Color perspective: standard / noperspective.
|
|
persp_axes = [
|
|
("persp", []),
|
|
("noperp", ["NOPERSP"]),
|
|
]
|
|
for a_name, a_defs in attr_axes:
|
|
for i_name, i_defs in interp_axes:
|
|
for p_name, p_defs in persp_axes:
|
|
suffix = f"{a_name}_{i_name}_{p_name}"
|
|
out.append((suffix, a_defs + i_defs + p_defs))
|
|
return out
|
|
|
|
|
|
def _batch_fs_untextured_variants():
|
|
out = []
|
|
# Output interpolation: standard / centroid (MSAA) / sample (SSAA).
|
|
# MUST match the batch VS chosen by the C++ side.
|
|
interp_axes = [
|
|
("none", []),
|
|
("centroid", ["INTERP_CENTROID"]),
|
|
("sample", ["INTERP_SAMPLE"]),
|
|
]
|
|
# Color perspective: standard / noperspective. MUST match batch VS.
|
|
persp_axes = [
|
|
("persp", []),
|
|
("noperp", ["NOPERSP"]),
|
|
]
|
|
# Dual-source colour output: 1 attachment vs 2 (location 0
|
|
# index 0/1). Pipeline blend state references SRC1_* or it does
|
|
# not - per-call decision driven by transparency_mode AND
|
|
# m_supports_dual_source_blend.
|
|
dual_axes = [
|
|
("nodual", []),
|
|
("dual", ["DUAL_SOURCE"]),
|
|
]
|
|
# PGXP_DEPTH used to be a fourth axis (gating gl_FragDepth
|
|
# declaration) - collapsed to a runtime branch on the u_pgxp_depth
|
|
# cbuffer scalar so the FS body unconditionally writes
|
|
# gl_FragDepth with a ternary on u_pgxp_depth.
|
|
for i_name, i_defs in interp_axes:
|
|
for p_name, p_defs in persp_axes:
|
|
for d_name, d_defs in dual_axes:
|
|
suffix = f"{i_name}_{p_name}_{d_name}"
|
|
out.append((suffix, i_defs + p_defs + d_defs))
|
|
return out
|
|
|
|
|
|
def _batch_fs_textured_nearest_variants():
|
|
out = []
|
|
interp_axes = [
|
|
("none", []),
|
|
("centroid", ["INTERP_CENTROID"]),
|
|
("sample", ["INTERP_SAMPLE"]),
|
|
]
|
|
persp_axes = [("persp", []), ("noperp", ["NOPERSP"])]
|
|
dual_axes = [("nodual", []), ("dual", ["DUAL_SOURCE"])]
|
|
# UV_LIMITS used to be a fifth axis here, PGXP_DEPTH a fourth.
|
|
# Both have been collapsed to runtime branches on the
|
|
# u_uv_limits / u_pgxp_depth cbuffer scalars - v_uv_limits is
|
|
# always declared (the batch VS always emits it when textured)
|
|
# and gl_FragDepth is always written. Brings the Nearest FS cube
|
|
# into parity shape with the Bilinear / JINC2 / xBR families.
|
|
for i_name, i_defs in interp_axes:
|
|
for p_name, p_defs in persp_axes:
|
|
for d_name, d_defs in dual_axes:
|
|
suffix = f"{i_name}_{p_name}_{d_name}"
|
|
out.append((suffix, i_defs + p_defs + d_defs))
|
|
return out
|
|
|
|
|
|
def _batch_fs_textured_filter_variants():
|
|
"""Shared structural cube for non-Nearest filter templates.
|
|
|
|
UV_LIMITS is implicit (ShouldUseUVLimits() forces it true for any
|
|
non-Nearest filter); PGXP_DEPTH used to be a fourth axis but has
|
|
been collapsed to a runtime branch on u_pgxp_depth. Cube
|
|
collapses to 3 x 2 x 2 = 12 blobs.
|
|
"""
|
|
out = []
|
|
interp_axes = [
|
|
("none", []),
|
|
("centroid", ["INTERP_CENTROID"]),
|
|
("sample", ["INTERP_SAMPLE"]),
|
|
]
|
|
persp_axes = [("persp", []), ("noperp", ["NOPERSP"])]
|
|
dual_axes = [("nodual", []), ("dual", ["DUAL_SOURCE"])]
|
|
for i_name, i_defs in interp_axes:
|
|
for p_name, p_defs in persp_axes:
|
|
for d_name, d_defs in dual_axes:
|
|
suffix = f"{i_name}_{p_name}_{d_name}"
|
|
out.append((suffix, i_defs + p_defs + d_defs))
|
|
return out
|
|
|
|
|
|
TEMPLATE_VARIANTS = {
|
|
"batch.vert.glsl": _batch_vs_variants(),
|
|
"batch_untextured.frag.glsl": _batch_fs_untextured_variants(),
|
|
"batch_textured_nearest.frag.glsl": _batch_fs_textured_nearest_variants(),
|
|
"batch_textured_bilinear.frag.glsl": _batch_fs_textured_filter_variants(),
|
|
"batch_textured_jinc2.frag.glsl": _batch_fs_textured_filter_variants(),
|
|
"batch_textured_xbr.frag.glsl": _batch_fs_textured_filter_variants(),
|
|
}
|
|
|
|
|
|
def find_glslang(explicit):
|
|
if explicit:
|
|
return explicit
|
|
for name in ("glslangValidator", "glslangValidator.exe"):
|
|
from shutil import which
|
|
path = which(name)
|
|
if path:
|
|
return path
|
|
sys.stderr.write(
|
|
"error: glslangValidator not found on PATH. Install the Vulkan SDK\n"
|
|
" or the glslang-tools package, or pass --glslang PATH.\n")
|
|
sys.exit(1)
|
|
|
|
|
|
def sanitize_identifier(stem):
|
|
# Map "screen_quad.vert" -> "screen_quad_vs"; only [A-Za-z0-9_] survive.
|
|
name = re.sub(r"[^A-Za-z0-9_]", "_", stem)
|
|
return name
|
|
|
|
|
|
def compile_one(glslang, glsl_path, stage_flag, defines=None):
|
|
# Write SPIR-V to a temp file under INC_DIR so we don't pollute /tmp on
|
|
# restricted-filesystem hosts.
|
|
spv_path = INC_DIR / (glsl_path.stem + ".spv.tmp")
|
|
cmd = [
|
|
glslang,
|
|
"--target-env", "vulkan1.0",
|
|
"-S", stage_flag,
|
|
"-V", str(glsl_path),
|
|
"-o", str(spv_path),
|
|
]
|
|
for d in defines or ():
|
|
cmd.append(f"-D{d}")
|
|
result = subprocess.run(cmd, capture_output=True, text=True)
|
|
if result.returncode != 0:
|
|
sys.stderr.write(f"glslangValidator failed for {glsl_path.name}:\n")
|
|
sys.stderr.write(result.stdout)
|
|
sys.stderr.write(result.stderr)
|
|
if spv_path.exists():
|
|
spv_path.unlink()
|
|
sys.exit(1)
|
|
data = spv_path.read_bytes()
|
|
spv_path.unlink()
|
|
if len(data) % 4 != 0:
|
|
sys.stderr.write(
|
|
f"error: {glsl_path.name} produced {len(data)} bytes "
|
|
f"of SPIR-V (not a multiple of 4)\n")
|
|
sys.exit(1)
|
|
words = struct.unpack(f"<{len(data) // 4}I", data)
|
|
if not words or words[0] != 0x07230203:
|
|
sys.stderr.write(
|
|
f"error: {glsl_path.name} produced invalid SPIR-V (bad magic)\n")
|
|
sys.exit(1)
|
|
return words
|
|
|
|
|
|
def emit_inc(identifier, glsl_name, words, out_path):
|
|
# 8 words per line keeps the file diff-friendly without being too tall.
|
|
PER_LINE = 8
|
|
lines = []
|
|
lines.append(
|
|
f"// Autogenerated from data/shaders/vulkan/{glsl_name}.\n"
|
|
f"// DO NOT EDIT. Regenerate with tools/regen_vulkan_spirv.py.\n"
|
|
f"// glslangValidator --target-env vulkan1.0\n"
|
|
f"//\n"
|
|
f"// Included inside namespace Vulkan::EmbeddedShaders in\n"
|
|
f"// embedded_shaders.cpp. The matching extern declaration lives in\n"
|
|
f"// embedded_shaders.h.\n"
|
|
f"\n"
|
|
f"const uint32_t k_{identifier}[] = {{\n")
|
|
for i in range(0, len(words), PER_LINE):
|
|
chunk = ", ".join(f"0x{w:08x}u" for w in words[i:i + PER_LINE])
|
|
lines.append(f" {chunk},\n")
|
|
lines.append(f"}};\n"
|
|
f"const size_t k_{identifier}_size_bytes = "
|
|
f"sizeof(k_{identifier});\n")
|
|
out_path.write_text("".join(lines))
|
|
|
|
|
|
def main():
|
|
ap = argparse.ArgumentParser()
|
|
ap.add_argument("--glslang", help="path to glslangValidator binary")
|
|
args = ap.parse_args()
|
|
glslang = find_glslang(args.glslang)
|
|
INC_DIR.mkdir(parents=True, exist_ok=True)
|
|
|
|
glsl_files = sorted(GLSL_DIR.glob("*.glsl"))
|
|
if not glsl_files:
|
|
sys.stderr.write(f"warning: no .glsl files under {GLSL_DIR}\n")
|
|
return
|
|
|
|
total = 0
|
|
for glsl_path in glsl_files:
|
|
# glsl_path.name looks like "screen_quad.vert.glsl".
|
|
suffix = None
|
|
for k in STAGE_FROM_SUFFIX:
|
|
if glsl_path.name.endswith(k):
|
|
suffix = k
|
|
break
|
|
if suffix is None:
|
|
sys.stderr.write(
|
|
f"warning: {glsl_path.name} has no recognised stage suffix; "
|
|
f"skipping\n")
|
|
continue
|
|
stage_flag, ident_suffix = STAGE_FROM_SUFFIX[suffix]
|
|
|
|
# "screen_quad.vert.glsl" -> stem "screen_quad.vert" -> "screen_quad"
|
|
base = glsl_path.name[:-len(suffix)]
|
|
|
|
variants = TEMPLATE_VARIANTS.get(glsl_path.name)
|
|
if variants is None:
|
|
# Single-variant shader: one .inc, no -D flags.
|
|
identifier = sanitize_identifier(base) + "_" + ident_suffix
|
|
out_path = INC_DIR / (identifier + ".inc")
|
|
words = compile_one(glslang, glsl_path, stage_flag)
|
|
emit_inc(identifier, glsl_path.name, words, out_path)
|
|
size_kb = (len(words) * 4) / 1024.0
|
|
print(f" {glsl_path.name:<40} -> {out_path.name} "
|
|
f"({len(words)} words, {size_kb:.1f} KiB)")
|
|
total += 1
|
|
else:
|
|
# Template: emit one .inc per variant, named with a suffix
|
|
# appended after the stage identifier.
|
|
for variant_suffix, defines in variants:
|
|
identifier = (sanitize_identifier(base) + "_" + ident_suffix +
|
|
"_" + variant_suffix)
|
|
out_path = INC_DIR / (identifier + ".inc")
|
|
words = compile_one(glslang, glsl_path, stage_flag, defines)
|
|
emit_inc(identifier, glsl_path.name, words, out_path)
|
|
size_kb = (len(words) * 4) / 1024.0
|
|
print(f" {glsl_path.name:<40} -> {out_path.name} "
|
|
f"({len(words)} words, {size_kb:.1f} KiB)")
|
|
total += 1
|
|
|
|
print(f"regenerated {total} SPIR-V blob(s) in {INC_DIR}")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|