mirror of
https://github.com/seedds/nxnative.git
synced 2026-11-23 11:39:42 -10:00
vulkan/tools: detect loader-only games and translate DXC shaders
Use the sole reflected SPIR-V entry point, handle DXC push-constant type names after SPIRV-Cross sanitizes them, and only build dual-source variants for matching color outputs at locations 0 and 1. Keep the one-row 2D lowering for Vulkan 1D textures. Recognize vkGetInstanceProcAddr as Vulkan evidence when the RomFS carries SPIR-V and the imports exclude EGL and NVN. On Re:ZERO 1.0.2 (0100D800117F4000), 2 of 41 modules translated before and 26 compiled for Mac Metal with this change. Seven stages are skipped and eight modules still need argument buffers. Hades generated identical MSL for all 74 shaders on the Apple M6. Synthetic tests and the Python lint and docs checks cover the shared tooling. Consolidates PR #1370 and the named Vulkan entry-point change from PR #2546. Co-authored-by: Lennart Kotzur <[email protected]> Co-authored-by: HenWorks <[email protected]>
This commit is contained in:
1 parent
2149d856d2
commit
8007591199
7 files changed
+203
-20
No files matched your search
@@ -266,9 +266,8 @@ def modules_supplying(exefs, want, modules, hooks=None): # the modules left ou
|
||||
|
||||
# ---- Shader sources: decided from the game files at every build, not kept in the profile (scripts/build_ipa_from_nsp.py; shader_split.py reads what those steps write) ----
|
||||
def shader_sources(imports, glsl_src, glslc_mods, spirv, unreal_paks, trinity_packs=0, legacy_paks=0, gl_names=0, gl_src=0, gl_files=0, oodle_pkz=0, nro_imports=frozenset(), oodle_gfpak=0, oodle_ue3=0, frostbite=False, romfs_glsl=0, oodle_ttdat=0, gl_fixed_calls=False):
|
||||
"""{name: (value, reason)}: graphics (vulkan when main imports Vulkan functions and not nvnBootstrapLoader; gl when it imports eglCreateWindowSurface and names glShaderSource, so it compiles
|
||||
GLSL through OpenGL (gl_names: how often main has that name; Absolum imports the same EGL functions for SDL3 but renders with NVN and names no GL function); else nvn; vkGetInstanceProcAddr
|
||||
alone is SDL's Vulkan loader, which Balatro's LÖVE links and never uses), vk_capture (a Vulkan game without SPIR-V files generates its shaders at run time), gl_capture (an OpenGL game with no
|
||||
"""{name: (value, reason)}: graphics (vulkan when main imports Vulkan functions and no nvnBootstrapLoader, including loader-only games with SPIR-V and no EGL or NVN NROs;
|
||||
gl when main imports eglCreateWindowSurface and has GLSL or fixed-function evidence; else nvn), vk_capture (a Vulkan game without SPIR-V files generates its shaders at run time), gl_capture (an OpenGL game with no
|
||||
GLSL source where gl_shaders.py looks, gl_src strings in main and gl_files files in the RomFS: it puts its shaders together at run time, LÖVE from its Lua), glslc_capture (main holds GLSL sources and calls glslcCompile in a module the game loads: it compiles some shaders at run time), ue_decode (prepare shared Unreal shader code
|
||||
archives for the split), oodle_packs (Trinity packs, oodle_pkz PlatinumGames PKZ archives, oodle_gfpak Game Freak GFPAK archives with Oodle Kraken entries, oodle_ue3 Unreal Engine 3 packages with Oodle chunks
|
||||
or frostbite Frostbite superbundles, whose cas files are Oodle Leviathan, or oodle_ttdat TT Games CC4 DAT archives:
|
||||
@@ -280,8 +279,11 @@ def shader_sources(imports, glsl_src, glslc_mods, spirv, unreal_paks, trinity_pa
|
||||
extracted; Hades and both Galaxies import 99 or 100 Vulkan functions, Balatro only vkGetInstanceProcAddr), Balatro alone composing its GLSL.
|
||||
nro_imports: what the NROs the game loads at run time import. Portal's main is SDL with its EGL backend (it names glShaderSource for SDL's GL renderer) and renders nothing: its Source engine
|
||||
NROs draw with NVN (materialsystem.nro and video_nx.nro import nvnBootstrapLoader) and call glslcCompile; the GLSLC outputs it ships (nxcontent/nvsb in game.zip) are read by the split"""
|
||||
vk = sum(1 for s in imports if re.match(r'vk[A-Z]', s) and s != 'vkGetInstanceProcAddr'); vulkan = bool(vk) and 'nvnBootstrapLoader' not in imports
|
||||
nro_nvn = 'nvnBootstrapLoader' in nro_imports
|
||||
vk = sum(1 for s in imports if re.match(r'vk[A-Z]', s) and s != 'vkGetInstanceProcAddr')
|
||||
# Re:ZERO loads Vulkan through this function and ships SPIR-V. Balatro imports the same loader through SDL and draws through EGL.
|
||||
vk_loader = 'vkGetInstanceProcAddr' in imports and bool(spirv) and 'eglCreateWindowSurface' not in imports and not nro_nvn
|
||||
vulkan = bool(vk or vk_loader) and 'nvnBootstrapLoader' not in imports
|
||||
# A main that imports nvnBootstrapLoader and compiles its own GLSL with GLSLC draws with NVN even when it also imports EGL and names glShaderSource: Rayman 30th Anniversary
|
||||
# Edition (Digital Eclipse, SDK 20) links both paths, never calls EGL on the Mac, and compiles the GLSL in its .shader files with subsdk2's glslcCompile; taken for OpenGL, it
|
||||
# got no GLSLC capture and drew nothing (black screen, sound and input working)
|
||||
@@ -292,7 +294,9 @@ def shader_sources(imports, glsl_src, glslc_mods, spirv, unreal_paks, trinity_pa
|
||||
gl_fixed = legacy_gl and not shader_gl
|
||||
gl = gl_fixed or (egl and shader_gl and not own_glslc)
|
||||
nro_glslc = not vulkan and not gl and 'glslcCompile' in nro_imports and bool(glslc_mods)
|
||||
return {'graphics': ('vulkan', f'main imports {vk} Vulkan functions and not nvnBootstrapLoader: the host\'s Vulkan layer (dm/gfx/vk/hle_vk.m)') if vulkan else
|
||||
vk_reason = (f'main imports {vk} Vulkan functions' if vk else
|
||||
f'main imports only vkGetInstanceProcAddr, no EGL or NVN loader, and the RomFS holds {spirv} SPIR-V files')
|
||||
return {'graphics': ('vulkan', vk_reason + ": the host's Vulkan layer (dm/gfx/vk/hle_vk.m)") if vulkan else
|
||||
('gl', 'main imports EGL and names OpenGL fixed-function calls, with no GLSL found') if gl_fixed else
|
||||
('gl', 'EGL and GLSL evidence select the host\'s OpenGL shader path (dm/gfx/gl/hle_gl.m)') if gl else
|
||||
('nvn', 'the NROs the game loads import nvnBootstrapLoader' if nro_nvn and 'nvnBootstrapLoader' not in imports else
|
||||
|
||||
+22
-11
@@ -12,7 +12,7 @@
|
||||
# · a push-constant block gets the buffer slot after the descriptor buffers (spirv-cross puts it at buffer(0), where the first uniform buffer goes), listed as p:0.0=slot;
|
||||
# the host sets the pushed bytes there (Super Mario Galaxy: 54 of its 56 built-in shaders have one)
|
||||
# · stages other than vertex and fragment are skipped and counted: Metal has no geometry shaders (Super Mario Galaxy has 2)
|
||||
# · a fragment shader with an output at location 1 also gets a variant vk_<key>_d where that output is [[color(0), index(1)]]: Super Mario Galaxy's GX shaders write
|
||||
# · a fragment shader with only outputs 0 and 1 of the same type gets a variant vk_<key>_d with [[color(0), index(1)]]: Super Mario Galaxy's GX shaders write
|
||||
# the second blend source at location 1 (no Index decoration), which NVIDIA's hardware feeds to dual-source blending; the host picks the variant for pipelines
|
||||
# whose blend factors read source 1
|
||||
# Super Mario Galaxy generates its GX shaders at run time; they come from a capture folder (the Mac host's DM_VK_CAPTURE), read like a RomFS: every input folder is
|
||||
@@ -22,6 +22,7 @@
|
||||
# p push constants)
|
||||
# Usage: vk_shaders.py <SPIR-V dir>... <out dir> [--ios <dir>] (SPIR-V dirs: the RomFS, capture folders)
|
||||
import concurrent.futures as cf, hashlib, json, os, re, struct, subprocess, sys, tempfile
|
||||
from typing import NoReturn
|
||||
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '../../tools'))
|
||||
from romfs import os, open
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
@@ -39,7 +40,7 @@ SLOT_CLASS = {'u': 'buffer', 'b': 'buffer', 't': 'texture', 's': 'sampler', 'c':
|
||||
# that the fill light (from the camera's left) faces came out white (GitHub issue 72)
|
||||
PRECISE = re.compile(r'\bfast::(min|max|clamp)\(')
|
||||
|
||||
def red(msg): sys.exit('[RED] ' + msg)
|
||||
def red(msg: str) -> NoReturn: sys.exit('[RED] ' + msg)
|
||||
|
||||
def spirv_files(root):
|
||||
for d, _, fs in os.walk(root):
|
||||
@@ -80,6 +81,12 @@ def fix_strides(words):
|
||||
if not add: return words
|
||||
return words[:at] + [w for t, s in add.items() for w in ((4 << 16) | OP_DECORATE, t, DEC_ARRAY_STRIDE, s)] + words[at:]
|
||||
|
||||
def entry_args(src, key, path):
|
||||
"""Find the translated entry point with its argument list in group 1."""
|
||||
m = re.search(r'\bvk_' + key + r'\((.*?)\)\s*\{', src, re.S)
|
||||
if not m: red(f'{path}: entry point vk_{key} not found in the translated MSL')
|
||||
return m
|
||||
|
||||
def one(path, tmp, root):
|
||||
data = open(path, 'rb').read()
|
||||
if len(data) % 4: red(f'{path}: SPIR-V length {len(data)} is not a multiple of 4')
|
||||
@@ -120,29 +127,33 @@ def one(path, tmp, root):
|
||||
open(spv, 'wb').write(struct.pack(f'<{len(words)}I', *words))
|
||||
# --msl-texture-1d-as-2d: a 1D image is a one-row 2D texture in the host (hle_vk.m vkCreateImage), since Metal's 1D texture cannot be drawn into, mipmapped or depth; spirv-cross samples it at
|
||||
# the row's centre (float2(x, 0.5)) and reads it at (x, 0)
|
||||
cmd = [SPIRV_CROSS, spv, '--msl', '--msl-version', '20300', '--msl-decoration-binding', '--msl-texture-1d-as-2d', '--rename-entry-point', 'main', f'vk_{key}', stage, '--output', msl]
|
||||
cmd = [SPIRV_CROSS, spv, '--msl', '--msl-version', '20300', '--msl-decoration-binding', '--msl-texture-1d-as-2d',
|
||||
'--rename-entry-point', eps[0]['name'], f'vk_{key}', stage, '--output', msl]
|
||||
if stage == 'vert': cmd.append('--flip-vert-y')
|
||||
r = subprocess.run(cmd, capture_output=True, text=True)
|
||||
if r.returncode: red(f'{path}: spirv-cross failed: {r.stderr.strip()[:300]}')
|
||||
# The reflection lists every declared resource; the Metal entry point only takes the ones the shader uses (Hades' ShadowMap.frag declares a buffer it never reads,
|
||||
# which the game's own pipeline layout leaves out): keep the rows whose slot is an argument of the entry point, so the host only binds, and only reports, real ones
|
||||
src = open(msl).read(); m = re.search(r'\bvk_' + key + r'\((.*?)\)\s*\{', src, re.S)
|
||||
if not m: red(f'{path}: entry point vk_{key} not found in the translated MSL')
|
||||
src = open(msl).read(); m = entry_args(src, key, path)
|
||||
if pcs: # the push-constant argument is `constant <block type>& name [[buffer(0)]]`: move it to its own slot
|
||||
tname = refl['types'][pcs[0]['type']]['name']
|
||||
# SPIRV-Cross sanitizes DXC names such as type.PushConstant.RootConstants on output.
|
||||
tname = re.sub(r'[^A-Za-z0-9_]', '_', refl['types'][pcs[0]['type']]['name'])
|
||||
a = re.search(r'constant\s+' + re.escape(tname) + r'&\s+\w+\s+\[\[buffer\((\d+)\)\]\]', m.group(1))
|
||||
if a:
|
||||
s0, s1 = m.start(1) + a.start(1), m.start(1) + a.end(1)
|
||||
src = src[:s0] + str(pc_slot) + src[s1:]; open(msl, 'w').write(src)
|
||||
m = re.search(r'\bvk_' + key + r'\((.*?)\)\s*\{', src, re.S)
|
||||
src = src[:s0] + str(pc_slot) + src[s1:]
|
||||
m = entry_args(src, key, path)
|
||||
res.append(f'p:0.0={pc_slot}')
|
||||
used = {(c, int(n)) for c, n in re.findall(r'\[\[(buffer|texture|sampler)\((\d+)\)\]\]', m.group(1))}
|
||||
res = [x for x in res if (SLOT_CLASS[x[0]], int(x.rsplit('=', 1)[1].split('*')[0])) in used]
|
||||
src = PRECISE.sub(r'precise::\1(', src); open(msl, 'w').write(src)
|
||||
msls = [msl]
|
||||
if stage == 'frag' and '[[color(1)]]' in src: # dual-source variant vk_<key>_d: the output at location 1 becomes the second blend source of attachment 0
|
||||
msl_d = os.path.join(tmp, key + '_d.metal'); msls.append(msl_d)
|
||||
open(msl_d, 'w').write(src.replace(f'vk_{key}', f'vk_{key}_d').replace('[[color(1)]]', '[[color(0), index(1)]]'))
|
||||
if stage == 'frag':
|
||||
# Metal requires two outputs of the same type for the dual-source variant.
|
||||
outs = {int(i): t for t, i in re.findall(r'(\w+)\s+\w+\s+\[\[color\((\d+)\)\]\]', src)}
|
||||
if outs.keys() == {0, 1} and outs[0] == outs[1]:
|
||||
msl_d = os.path.join(tmp, key + '_d.metal'); msls.append(msl_d)
|
||||
open(msl_d, 'w').write(src.replace(f'vk_{key}', f'vk_{key}_d').replace('[[color(1)]]', '[[color(0), index(1)]]'))
|
||||
return key, stage, res, msls, '/' + os.path.relpath(path, root)
|
||||
|
||||
def metallib(msls, out, sdk, extra):
|
||||
|
||||
@@ -59,8 +59,6 @@ pyright dm/gfx/tools/unityfs.py reportOperatorIssue 2 Operator "<=" not supporte
|
||||
pyright dm/gfx/tools/unityfs.py reportSelfClsParameterName 4 Instance methods should take a "self" parameter
|
||||
pyright dm/gfx/tools/vk_shaders.py reportArgumentType 1 Argument of type "list[str]" cannot be assigned to parameter "iterable" of type "Iterable[LiteralString]" in function "join" "list[str]" is not assignable to "Iterable[LiteralString]" Type parameter "_T_co@Iterable" is covariant, but "str" is not a subtype of "LiteralString" "str" is not assignable to "LiteralString"
|
||||
pyright dm/gfx/tools/vk_shaders.py reportCallIssue 1 No overloads for "join" match the provided arguments
|
||||
pyright dm/gfx/tools/vk_shaders.py reportOptionalMemberAccess 2 "group" is not a known attribute of "None"
|
||||
pyright dm/gfx/tools/vk_shaders.py reportOptionalMemberAccess 2 "start" is not a known attribute of "None"
|
||||
pyright dm/ios/tools/pack_ipa.py reportCallIssue 1 Expected 4 positional arguments
|
||||
pyright dm/ios/tools/xcode_projects.py reportArgumentType 1 Argument of type "Element[str] | None" cannot be assigned to parameter "parent" of type "Element[Any]" in function "SubElement" Type "Element[str] | None" is not assignable to type "Element[Any]" "None" is not assignable to "Element[Any]"
|
||||
pyright dm/ios/tools/xcode_projects.py reportOptionalMemberAccess 1 "findall" is not a known attribute of "None"
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 2 and column 73.
|
@@ -44,6 +44,22 @@ class NroGraphics(unittest.TestCase):
|
||||
self.assertEqual(s['graphics'][0], 'nvn')
|
||||
self.assertFalse(s['glslc_capture'][0])
|
||||
|
||||
def test_loader_only_vulkan_with_spirv(self): # Re:ZERO - The Prophecy of the Throne: every Vulkan function through vkGetInstanceProcAddr, SPIR-V files in the RomFS
|
||||
s = pg.shader_sources({'vkGetInstanceProcAddr'}, 0, [], 41, 0)
|
||||
self.assertEqual(s['graphics'][0], 'vulkan')
|
||||
self.assertFalse(s['vk_capture'][0])
|
||||
|
||||
def test_loader_only_beside_egl_stays_gl(self): # Balatro: SDL's loader beside its EGL backend, which draws with GL, whatever SPIR-V files the RomFS holds
|
||||
self.assertEqual(pg.shader_sources({'vkGetInstanceProcAddr'} | SDL_MAIN, 0, [], 3, 0, gl_names=1)['graphics'][0], 'gl')
|
||||
|
||||
def test_loader_only_without_spirv_is_not_vulkan(self): # a bare loader import proves nothing without the shaders a Vulkan game ships
|
||||
self.assertEqual(pg.shader_sources({'vkGetInstanceProcAddr'}, 0, [], 0, 0)['graphics'][0], 'nvn')
|
||||
|
||||
def test_loader_only_with_nvn_nros_stays_nvn(self): # SDK's loader in main, NROs that draw with NVN, SPIR-V files in the RomFS: NVN
|
||||
s = pg.shader_sources({'vkGetInstanceProcAddr'}, 0, [], 41, 0, nro_imports=frozenset({'nvnBootstrapLoader'}))
|
||||
self.assertEqual(s['graphics'][0], 'nvn')
|
||||
self.assertFalse(s['vk_capture'][0])
|
||||
|
||||
def test_load_order(self):
|
||||
self.assertEqual(sorted(['sdk', 'subsdk2', 'main', 'subsdk0', 'subsdk10'], key=pg.load_order), ['main', 'subsdk0', 'subsdk2', 'subsdk10', 'sdk'])
|
||||
|
||||
|
||||
@@ -0,0 +1,145 @@
|
||||
"""vk_shaders.py on synthetic SPIR-V fragment shaders assembled here with spirv-as (the committed spirv-cross translates them; no Metal compile, no game files): an entry point
|
||||
named as HLSL compilers name it, a push-constant block under DXC's type name, and the dual-source variant only for outputs 0 and 1 of one type.
|
||||
Requires spirv-as on PATH (the tool-tests job installs spirv-tools for spirv-val)."""
|
||||
import hashlib
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
import warnings
|
||||
|
||||
REPO = Path(__file__).resolve().parents[3]
|
||||
sys.path.insert(0, str(REPO / 'dm/gfx/tools')); import vk_shaders as vs
|
||||
|
||||
|
||||
def fragment(entry='main', pc_type=None, ubo=False, outs=('v4float',)):
|
||||
"""Assembly of a fragment shader that writes one constant per output location (the locations in `outs` order, each of the type named); with `ubo` it multiplies
|
||||
output 0 by a vec4 of a uniform buffer (set 0, binding 0), with `pc_type` by a vec4 of a push-constant block whose type carries that name (OpName)."""
|
||||
asm = f'''OpCapability Shader
|
||||
OpMemoryModel Logical GLSL450
|
||||
OpEntryPoint Fragment %main "{entry}" {" ".join(f"%out{i}" for i in range(len(outs)))}
|
||||
OpExecutionMode %main OriginUpperLeft
|
||||
OpName %main "{entry}"
|
||||
'''
|
||||
if pc_type: asm += f'OpName %PCT "{pc_type}"\nOpMemberName %PCT 0 "tint"\nOpName %pc "pc"\n'
|
||||
if ubo: asm += 'OpName %UBT "type.ubo"\nOpMemberName %UBT 0 "scale"\nOpName %ub "ub"\n'
|
||||
for i in range(len(outs)): asm += f'OpDecorate %out{i} Location {i}\n'
|
||||
if pc_type: asm += 'OpDecorate %PCT Block\nOpMemberDecorate %PCT 0 Offset 0\n'
|
||||
if ubo: asm += 'OpDecorate %UBT Block\nOpMemberDecorate %UBT 0 Offset 0\nOpDecorate %ub DescriptorSet 0\nOpDecorate %ub Binding 0\n'
|
||||
asm += '''%void = OpTypeVoid
|
||||
%fn = OpTypeFunction %void
|
||||
%float = OpTypeFloat 32
|
||||
%v2float = OpTypeVector %float 2
|
||||
%v4float = OpTypeVector %float 4
|
||||
%int = OpTypeInt 32 1
|
||||
%int0 = OpConstant %int 0
|
||||
%half = OpConstant %float 0.5
|
||||
%c2 = OpConstantComposite %v2float %half %half
|
||||
%c4 = OpConstantComposite %v4float %half %half %half %half
|
||||
%o_v2 = OpTypePointer Output %v2float
|
||||
%o_v4 = OpTypePointer Output %v4float
|
||||
'''
|
||||
if pc_type: asm += '%PCT = OpTypeStruct %v4float\n%pc_p = OpTypePointer PushConstant %PCT\n%pc_m = OpTypePointer PushConstant %v4float\n%pc = OpVariable %pc_p PushConstant\n'
|
||||
if ubo: asm += '%UBT = OpTypeStruct %v4float\n%ub_p = OpTypePointer Uniform %UBT\n%ub_m = OpTypePointer Uniform %v4float\n%ub = OpVariable %ub_p Uniform\n'
|
||||
for i, t in enumerate(outs): asm += f'%out{i} = OpVariable %o_{t[:2]} Output\n'
|
||||
asm += '%main = OpFunction %void None %fn\n%entry = OpLabel\n%v0 = OpCopyObject %v4float %c4\n'
|
||||
if pc_type: asm += '%pa = OpAccessChain %pc_m %pc %int0\n%pv = OpLoad %v4float %pa\n%v0b = OpFMul %v4float %v0 %pv\n'
|
||||
else: asm += '%v0b = OpCopyObject %v4float %v0\n'
|
||||
if ubo: asm += '%ua = OpAccessChain %ub_m %ub %int0\n%uv = OpLoad %v4float %ua\n%v0c = OpFMul %v4float %v0b %uv\n'
|
||||
else: asm += '%v0c = OpCopyObject %v4float %v0b\n'
|
||||
for i, t in enumerate(outs): asm += f'OpStore %out{i} ' + ('%v0c' if i == 0 and t == 'v4float' else '%c2' if t == 'v2float' else '%c4') + '\n'
|
||||
return asm + 'OpReturn\nOpFunctionEnd\n'
|
||||
|
||||
|
||||
class VkShaders(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.assertIsNotNone(shutil.which('spirv-as'), 'spirv-as required to assemble the test shaders')
|
||||
self.tmp = Path(tempfile.mkdtemp()); self.addCleanup(shutil.rmtree, self.tmp)
|
||||
|
||||
def translate(self, asm):
|
||||
"""vk_shaders.one() on the assembled shader: (key, stage, resource rows, [MSL text of each variant])"""
|
||||
spv = self.tmp / 'shader.spv'
|
||||
subprocess.run(['spirv-as', '--target-env', 'vulkan1.1', '-o', str(spv), '-'], input=asm, text=True, check=True)
|
||||
subprocess.run(['spirv-val', '--target-env', 'vulkan1.1', str(spv)], check=True)
|
||||
out = self.tmp / 'out'; out.mkdir(exist_ok=True)
|
||||
with warnings.catch_warnings():
|
||||
warnings.simplefilter('ignore', ResourceWarning) # the tool leaves its files to be closed at collection
|
||||
key, stage, res, msls, _ = vs.one(str(spv), str(out), str(self.tmp))
|
||||
self.assertEqual(key, hashlib.sha256(spv.read_bytes()).hexdigest()[:16])
|
||||
return key, stage, res, [Path(m).read_text() for m in msls]
|
||||
|
||||
def test_entry_point_of_an_hlsl_shader(self): # DXC names it PSMain (or ps_*), spirv-cross renames that one to vk_<key>
|
||||
key, stage, _, srcs = self.translate(fragment(entry='PSMain'))
|
||||
self.assertEqual(stage, 'frag')
|
||||
self.assertEqual(len(srcs), 1)
|
||||
self.assertIn('fragment ', srcs[0]); self.assertIn(f'vk_{key}(', srcs[0])
|
||||
self.assertNotIn('PSMain', srcs[0])
|
||||
|
||||
def test_entry_point_named_main(self): # GLSL's name keeps working
|
||||
key, _, _, srcs = self.translate(fragment())
|
||||
self.assertIn(f'vk_{key}(', srcs[0])
|
||||
|
||||
def test_named_entry_point_preserves_1d_lowering(self):
|
||||
_, _, res, srcs = self.translate('''OpCapability Shader
|
||||
OpCapability Sampled1D
|
||||
OpMemoryModel Logical GLSL450
|
||||
OpEntryPoint Fragment %main "PSMain" %color
|
||||
OpExecutionMode %main OriginUpperLeft
|
||||
OpDecorate %color Location 0
|
||||
OpDecorate %tex DescriptorSet 0
|
||||
OpDecorate %tex Binding 0
|
||||
%void = OpTypeVoid
|
||||
%fn = OpTypeFunction %void
|
||||
%float = OpTypeFloat 32
|
||||
%rgba = OpTypeVector %float 4
|
||||
%x = OpConstant %float 0.25
|
||||
%out = OpTypePointer Output %rgba
|
||||
%image = OpTypeImage %float 1D 0 0 0 1 Unknown
|
||||
%sampled = OpTypeSampledImage %image
|
||||
%uniform = OpTypePointer UniformConstant %sampled
|
||||
%color = OpVariable %out Output
|
||||
%tex = OpVariable %uniform UniformConstant
|
||||
%main = OpFunction %void None %fn
|
||||
%body = OpLabel
|
||||
%sampler = OpLoad %sampled %tex
|
||||
%value = OpImageSampleImplicitLod %rgba %sampler %x
|
||||
OpStore %color %value
|
||||
OpReturn
|
||||
OpFunctionEnd
|
||||
''')
|
||||
self.assertEqual(res, ['c:0.0=0'])
|
||||
self.assertIn('texture2d<float>', srcs[0])
|
||||
self.assertIn('float2(0.25, 0.5)', srcs[0])
|
||||
|
||||
def test_push_constant_under_dxcs_type_name(self): # type.PushConstant.RootConstants: spirv-cross writes it type_PushConstant_RootConstants
|
||||
_, _, res, srcs = self.translate(fragment(pc_type='type.PushConstant.RootConstants', ubo=True))
|
||||
self.assertEqual(res, ['u:0.0=0', 'p:0.0=1']) # the push constants take the buffer slot after the uniform buffer, where spirv-cross put them at 0
|
||||
self.assertIn('constant type_PushConstant_RootConstants& pc [[buffer(1)]]', srcs[0])
|
||||
|
||||
def test_push_constant_under_a_plain_type_name(self): # GLSL: the type's name is already an identifier
|
||||
_, _, res, srcs = self.translate(fragment(pc_type='PushBlock', ubo=True))
|
||||
self.assertEqual(res, ['u:0.0=0', 'p:0.0=1'])
|
||||
self.assertIn('constant PushBlock& pc [[buffer(1)]]', srcs[0])
|
||||
|
||||
def test_dual_source_variant_for_outputs_of_one_type(self): # Super Mario Galaxy's GX shaders: two vec4 outputs, the second the blend source
|
||||
key, _, _, srcs = self.translate(fragment(outs=('v4float', 'v4float')))
|
||||
self.assertEqual(len(srcs), 2)
|
||||
self.assertIn(f'vk_{key}_d(', srcs[1]); self.assertIn('[[color(0), index(1)]]', srcs[1])
|
||||
self.assertNotIn('index(1)', srcs[0])
|
||||
|
||||
def test_no_dual_source_variant_for_a_second_target_of_another_type(self): # a float2 output beside the float4 colour is a real attachment: Metal refuses the variant
|
||||
_, _, _, srcs = self.translate(fragment(outs=('v4float', 'v2float')))
|
||||
self.assertEqual(len(srcs), 1)
|
||||
self.assertIn('[[color(1)]]', srcs[0])
|
||||
|
||||
def test_no_dual_source_variant_for_a_single_output(self):
|
||||
self.assertEqual(len(self.translate(fragment())[3]), 1)
|
||||
|
||||
def test_no_dual_source_variant_past_two_outputs(self): # three targets of one type are three targets
|
||||
self.assertEqual(len(self.translate(fragment(outs=('v4float', 'v4float', 'v4float')))[3]), 1)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -1117,6 +1117,7 @@ One line per symptom in the [subsystem references](../reference/): what you see
|
||||
- the 3D world black, the HUD drawn over it; the scene's own colour target, read back, holds the whole scene. → [Attachments opened with `LOAD_OP_DONT_CARE`](../reference/rendering.md#attachments-opened-with-load_op_dont_care)
|
||||
- under Metal's API validation (on when Xcode's Run starts the app, or `MTL_DEBUG_LAYER=1`), a Vulkan game stops on a validation assertion when it draws or clears into a one-dimensional image, or creates a mipmapped or depth one; without validation it goes on, with undefined results. → [1D images drawn into](../reference/rendering.md#1d-images-drawn-into)
|
||||
- GX points and lines drawn as one-pixel points and lines. → [Not translated in the Vulkan layer: geometry shaders](../reference/rendering.md#not-translated-in-the-vulkan-layer-geometry-shaders)
|
||||
- `vk_shaders.py` stops with `spirv-cross failed: SPIRV-Cross threw an exception: Entry point does not exist.` A shader with push constants has no `p:` row. Metal rejects a generated dual-source variant of a shader with ordinary render targets. → [SPIR-V compiled by DXC](../reference/rendering.md#spir-v-compiled-by-dxc)
|
||||
- `gl_shaders.py` rejects a fragment shader with `a buffer or sampler slot above 15`; removing the check lets some compile, while others fail Metal compilation with `'sampler' attribute parameter is out of bounds: must be between 0 and 15`. → [GL resources exceed the direct Metal sampler table](../reference/rendering.md#gl-resources-exceed-the-direct-metal-sampler-table)
|
||||
- the survey reports no graphics API and the host drops OpenGL draws that have no shader program. → [OpenGL 1.x fixed function](../reference/rendering.md#opengl-1x-fixed-function)
|
||||
- `UNIMPL eglGetDisplay`, then `Break` right after `nv::InitializeGraphics` and `vi::OpenDefaultDisplay` (`main+0x5ed9d0`). → [Games that render with desktop OpenGL through EGL](../reference/rendering.md#games-that-render-with-desktop-opengl-through-egl)
|
||||
|
||||
@@ -1950,7 +1950,7 @@ The Vulkan layer (`dm/gfx/vk/hle_vk.m`) was written for Hades; Super Mario Galax
|
||||
|
||||
- **Symptom:** Metal refuses the pipeline: "Fragment shader does not write to render target color(0), index(1)".
|
||||
- **Cause:** the GX shaders write the second blend source as an ordinary output at location 1 (no `Index` decoration), and pipelines blend with `SRC1` factors; NVIDIA's hardware feeds MRT 1 to source 1.
|
||||
- **Fix:** `vk_shaders.py` builds a variant `vk_<key>_d` with that output at `[[color(0), index(1)]]`, which the host takes for pipelines whose blend reads source 1.
|
||||
- **Fix:** `vk_shaders.py` builds a variant `vk_<key>_d` with that output at `[[color(0), index(1)]]`, which the host takes for pipelines whose blend reads source 1. Only for outputs 0 and 1 of the same type and none at location 2 or more ([SPIR-V compiled by DXC](#spir-v-compiled-by-dxc)).
|
||||
- **Found on:** [Super Mario Galaxy](../../dm/games/010099C022B96000/README.md).
|
||||
|
||||
### Scaled and three-component vertex formats
|
||||
@@ -2090,6 +2090,14 @@ The Vulkan layer (`dm/gfx/vk/hle_vk.m`) was written for Hades; Super Mario Galax
|
||||
- **Cause:** two geometry shaders (GX points and lines expanded to quads) are not translated (Metal has no geometry stage).
|
||||
- **Found on:** [Super Mario Galaxy](../../dm/games/010099C022B96000/README.md).
|
||||
|
||||
### SPIR-V compiled by DXC
|
||||
|
||||
- **Symptom:** `vk_shaders.py` stops with `spirv-cross failed: SPIRV-Cross threw an exception: Entry point does not exist.` A shader with push constants has no `p:` row. Metal rejects a generated dual-source variant of a shader with ordinary render targets.
|
||||
- **Cause:** DXC uses entry-point names such as `PSMain`. The tool always tried to rename `main`. SPIRV-Cross changes the dots in `type.PushConstant.<name>` to underscores in MSL, so looking for the reflected type name misses the push-constant argument. A second color output can be a separate render target, such as Re:ZERO's `float2` beside a `float4`.
|
||||
- **Fix:** Rename the sole entry point reported by reflection and look up the push-constant argument under the sanitized MSL type name. Generate the dual-source variant only when the only color outputs are locations 0 and 1 with the same type.
|
||||
- **Found on:** Re:ZERO -Starting Life in Another World- The Prophecy of the Throne (`0100D800117F4000`, The Forge renderer on Vulkan, SDK 9.5.0).
|
||||
- **Check:** `test_vk_shaders.py` translates synthetic SPIR-V for named entry points, 1D sampling, push constants beside a uniform buffer, and dual-source and ordinary color outputs.
|
||||
|
||||
## OpenGL layer
|
||||
|
||||
Digimon Story Cyber Sleuth: Complete Edition (Media.Vision's MVGL engine, SDK 6.4.0) and Balatro (LÖVE 11.4, "love-nx", with SDL and LuaJIT) render with **NVIDIA's desktop OpenGL 4.5 core profile through EGL**, not NVN. The host implements GL itself on Metal (`dm/gfx/gl/hle_gl.m`), as it does Vulkan for Hades; NVIDIA's GL driver (`subsdk0`) is not loaded. Balatro's graphics module is LÖVE's own OpenGL backend, so its choices follow what the context reports.
|
||||
@@ -2221,7 +2229,7 @@ Digimon Story Cyber Sleuth: Complete Edition (Media.Vision's MVGL engine, SDK 6.
|
||||
|
||||
- **Symptom:** the NSP script's provisional profile said Vulkan, and the capture boot crashed in the GL layer.
|
||||
- **Cause:** `main` imports `vkGetInstanceProcAddr` for SDL's Vulkan loader, which nothing uses; the game draws with EGL and GL.
|
||||
- **Fix:** `profile_guess.py` decides `graphics gl` when `main` imports `eglCreateWindowSurface` and names `glShaderSource`, and now leaves `vkGetInstanceProcAddr` out of its Vulkan count.
|
||||
- **Fix:** `profile_guess.py` picks GL when `main` imports `eglCreateWindowSurface` and names `glShaderSource`. It treats `vkGetInstanceProcAddr` as Vulkan evidence on its own when the RomFS contains SPIR-V, `main` has no EGL window or NVN loader import, and no loaded NRO imports the NVN loader. Re:ZERO resolves every Vulkan entry point through this loader.
|
||||
- **Found on:** [Digimon Story Cyber Sleuth: Complete Edition](../../dm/games/010014E00DB56000/README.md): `main` imports `nvnBootstrapLoader` and 13 EGL functions. Its graphics setup (`main+0x5ed8f0`) makes an NVN device first, which only a helper beside the movie player uses (`main+0x528000`–`+0x52c400`: a memory pool and four textures next to the movie's GL textures). Then `eglGetDisplay`, `eglBindAPI(EGL_OPENGL_API)`, a 4.5 core context, a window surface on `vi::CreateLayer(w, h)` and a glad loader (`main+0x52c460`). Of the 22 games extracted here (at the time), only Digimon matches the rule. [Balatro](../../dm/games/0100CD801CE5E000/README.md) (SDK 18.3.2, LÖVE 11.4 on OpenGL with SDL and LuaJIT; one boot): `main` imports the EGL functions and `vkGetInstanceProcAddr`, SDL's Vulkan loader, which nothing calls (`subsdk1` is NVIDIA's Vulkan driver); Hades and both Galaxies import 99 or 100 Vulkan functions, `vkCreateInstance` among them.
|
||||
- **Note:** [Absolum](../../dm/games/0100A83022A22000/README.md) imports the same EGL functions (SDL3) but renders with NVN and names no GL function.
|
||||
|
||||
|
||||
Reference in new issue
Block a user