mirror of
https://github.com/boykopovar/AnyPS5.git
synced 2026-12-05 17:11:09 +00:00
fix(libkernel_sys): reconcile shared-memory tests and document offset gap
This commit is contained in:
commit
79b02b3bdb
531 files changed
+18009
-1503
No files matched your search
@@ -246,6 +246,9 @@ if(BUILD_TESTING)
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/tools/check_test_registration.py --scripts)
|
||||
add_test(NAME build_eligibility COMMAND ${Python3_EXECUTABLE}
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_build_eligibility.py)
|
||||
add_test(NAME check_skips_ctest COMMAND ${Python3_EXECUTABLE}
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_check_skips_ctest.py)
|
||||
set_tests_properties(check_skips_ctest PROPERTIES TIMEOUT 30)
|
||||
add_test(NAME check_skips COMMAND ${Python3_EXECUTABLE}
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_check_skips.py)
|
||||
add_test(NAME sanitizer_report COMMAND ${Python3_EXECUTABLE}
|
||||
@@ -254,6 +257,18 @@ if(BUILD_TESTING)
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_select_tests.py)
|
||||
add_test(NAME check_main_sync COMMAND ${Python3_EXECUTABLE}
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_check_main_sync.py)
|
||||
set(select_tests_source "${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_select_tests.py")
|
||||
set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS "${select_tests_source}")
|
||||
file(STRINGS "${select_tests_source}" select_tests_classes REGEX "^class [A-Za-z0-9_]*Tests\\(")
|
||||
foreach(test_class IN LISTS select_tests_classes)
|
||||
string(REGEX REPLACE "^class ([A-Za-z0-9_]+).*" "\\1" test_class "${test_class}")
|
||||
if(test_class STREQUAL "SelectTests")
|
||||
set_tests_properties(select_tests PROPERTIES ENVIRONMENT "ANYPS5_SELECT_TEST_CLASS=SelectTests" TIMEOUT 30)
|
||||
else()
|
||||
add_test(NAME select_tests_${test_class} COMMAND ${Python3_EXECUTABLE} "${select_tests_source}" ${test_class})
|
||||
set_tests_properties(select_tests_${test_class} PROPERTIES TIMEOUT 30)
|
||||
endif()
|
||||
endforeach()
|
||||
add_test(NAME configure_seed COMMAND ${Python3_EXECUTABLE}
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_configure_seed.py ConfigureSeedTests)
|
||||
add_test(NAME configure_seed_paths COMMAND ${Python3_EXECUTABLE}
|
||||
@@ -311,6 +326,25 @@ if(BUILD_TESTING)
|
||||
add_test(NAME pad_timeline COMMAND ${Python3_EXECUTABLE}
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_pad_timeline.py)
|
||||
set_tests_properties(pad_timeline PROPERTIES TIMEOUT 20)
|
||||
function(register_check_compile_remaining_tests)
|
||||
if(TEST check_compile)
|
||||
set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_check_compile.py")
|
||||
file(STRINGS "${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_check_compile.py"
|
||||
check_compile_lines REGEX "^class CheckCompile|^ def test_")
|
||||
foreach(line IN LISTS check_compile_lines)
|
||||
if(line MATCHES "^class (CheckCompile[A-Za-z0-9_]*)")
|
||||
set(check_compile_class "${CMAKE_MATCH_1}")
|
||||
elseif(NOT check_compile_class MATCHES "^CheckCompile(Fixture|Tests|OutputTests)$")
|
||||
string(REGEX REPLACE "^ def (test_[A-Za-z0-9_]+).*" "\\1" test_case "${line}")
|
||||
add_test(NAME check_compile_${check_compile_class}_${test_case} COMMAND ${Python3_EXECUTABLE}
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_check_compile.py ${check_compile_class}.${test_case})
|
||||
set_tests_properties(check_compile_${check_compile_class}_${test_case} PROPERTIES TIMEOUT 30)
|
||||
endif()
|
||||
endforeach()
|
||||
endif()
|
||||
endfunction()
|
||||
cmake_language(DEFER CALL register_check_compile_remaining_tests)
|
||||
set(check_compile_modes_source "${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_check_compile_modes.py")
|
||||
set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS "${check_compile_modes_source}")
|
||||
file(STRINGS "${check_compile_modes_source}" check_compile_modes_cases REGEX "^ def test_")
|
||||
@@ -350,6 +384,29 @@ if(BUILD_TESTING)
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_check_conventions_agent_files.py)
|
||||
add_test(NAME conventions_alignment COMMAND ${Python3_EXECUTABLE}
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_check_conventions_alignment.py)
|
||||
add_test(NAME trace_intervals_csv COMMAND ${Python3_EXECUTABLE}
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_trace_intervals_csv.py)
|
||||
set_tests_properties(trace_intervals_csv PROPERTIES TIMEOUT 20)
|
||||
set(trace_digest_test_source "${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_trace_digest.py")
|
||||
set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS "${trace_digest_test_source}")
|
||||
file(STRINGS "${trace_digest_test_source}" trace_digest_cases REGEX "^class |^ def test_")
|
||||
set(trace_digest_first TRUE)
|
||||
foreach(test_case IN LISTS trace_digest_cases)
|
||||
if(test_case MATCHES "^class ([A-Za-z0-9_]+)")
|
||||
set(trace_digest_class "${CMAKE_MATCH_1}")
|
||||
else()
|
||||
string(REGEX REPLACE "^ def (test_[A-Za-z0-9_]+).*" "\\1" test_case "${test_case}")
|
||||
if(trace_digest_first)
|
||||
set_tests_properties(trace_digest PROPERTIES
|
||||
ENVIRONMENT "TRACE_DIGEST_TEST=${trace_digest_class}.${test_case}" TIMEOUT 20)
|
||||
set(trace_digest_first FALSE)
|
||||
else()
|
||||
add_test(NAME trace_digest_${trace_digest_class}_${test_case} COMMAND ${Python3_EXECUTABLE}
|
||||
"${trace_digest_test_source}" "${trace_digest_class}.${test_case}")
|
||||
set_tests_properties(trace_digest_${trace_digest_class}_${test_case} PROPERTIES TIMEOUT 20)
|
||||
endif()
|
||||
endif()
|
||||
endforeach()
|
||||
add_test(NAME conventions_pr_template COMMAND ${Python3_EXECUTABLE}
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_check_conventions_pr_template.py)
|
||||
add_test(NAME check_compile_preprocessor COMMAND ${Python3_EXECUTABLE}
|
||||
|
||||
+4
-2
@@ -32,9 +32,9 @@ ctest --test-dir build --output-on-failure
|
||||
|
||||
Python 3 is optional; without it some relinker tests are not registered.
|
||||
|
||||
Every push to `main`, including a merged pull request, automatically runs full Linux and Windows builds and tests and the relinker matrix on Linux, Windows and macOS, using the pushed commit without contributor checks.
|
||||
Every push to `main`, including a merged pull request, automatically runs full Linux and Windows builds and tests, which include the relinker tests, using the pushed commit without contributor checks. The relinker-only build and tests run separately on macOS, for arm64 and x86_64, and the relinker-only build with the address sanitizer runs on Linux, only when the push changes a file the relinker-only build uses.
|
||||
|
||||
For pull requests, full Linux and Windows builds and tests run only when a collaborator with write access selects Actions > Build > Run workflow on `main` and enters an open pull request number targeting `main`. A collaborator can start the same manual run from the command line, replacing `1234` with the pull request number:
|
||||
For pull requests, full Linux and Windows builds and tests run only when a collaborator with write access selects Actions > Build > Run workflow on `main` and enters up to 40 numbers of open pull requests targeting `main`, separated by spaces or commas; they are merged in that order and built together. A collaborator can start the same manual run from the command line, replacing `1234` with the pull request numbers:
|
||||
|
||||
```
|
||||
gh workflow run build.yml --repo boykopovar/AnyPS5 --ref main --field pr=1234
|
||||
@@ -44,6 +44,8 @@ This manual run also builds and tests the relinker on Linux, Windows and macOS w
|
||||
|
||||
With `--field full=false`, the manual run skips the full builds and runs only the relinker matrix on Linux, Windows and macOS, if the pull request changes a file the relinker-only build uses, such as the Python tools and their tests in `tools/`.
|
||||
|
||||
With `--field linux=false`, the manual run skips the full Linux build and adds Linux to the relinker matrix, if the pull requests change a file the relinker-only build uses. With `--field select=true`, the full builds build and run only the tests whose build inputs the pull requests change; push builds of `main` always run every test.
|
||||
|
||||
The Conventions check runs automatically for every contributor, including first-time contributors. It uses the checker from the current tip of the base branch, so rules added after a pull request was opened apply to its next run, and reads pull request Git objects without executing pull request code. The Conventions check runs on every pull request and fails when a rule on this page is broken. It accepts code comments only when the pull request also changes [technical debt](docs/dev/TechnicalDebt.md), the index or a file in `docs/dev/debt/`, and only UTF-8 text files. Run it locally before pushing:
|
||||
|
||||
```
|
||||
|
||||
@@ -11,6 +11,13 @@ function(add_bundled_opus)
|
||||
add_subdirectory(3rdparty/opus EXCLUDE_FROM_ALL)
|
||||
set_target_properties(opus PROPERTIES POSITION_INDEPENDENT_CODE ON C_VISIBILITY_PRESET hidden)
|
||||
target_compile_definitions(opus PRIVATE OPUS_EXPORT=)
|
||||
if(MINGW AND CMAKE_C_COMPILER_ID STREQUAL "GNU")
|
||||
include(CheckCCompilerFlag)
|
||||
check_c_compiler_flag("-Wa,-muse-unaligned-vector-move" ANYPS5_ASM_UNALIGNED_VECTOR_MOVE)
|
||||
if(ANYPS5_ASM_UNALIGNED_VECTOR_MOVE)
|
||||
target_compile_options(opus PRIVATE -Wa,-muse-unaligned-vector-move)
|
||||
endif()
|
||||
endif()
|
||||
if(MINGW OR CMAKE_SYSTEM_NAME STREQUAL "Linux")
|
||||
target_link_options(opus INTERFACE LINKER:--exclude-libs,libopus.a)
|
||||
endif()
|
||||
|
||||
@@ -109,7 +109,7 @@ set(LIBS_INCLUDE_DIR ${CMAKE_CURRENT_SOURCE_DIR})
|
||||
add_subdirectory(${LIBC_DIR} ${CMAKE_CURRENT_BINARY_DIR}/prx/libc)
|
||||
target_include_directories(libc PRIVATE ${CMAKE_CURRENT_SOURCE_DIR})
|
||||
if(WIN32)
|
||||
target_compile_options(libc PRIVATE "SHELL:-include ${CMAKE_CURRENT_SOURCE_DIR}/prx/libc/include/HostStandardStreams.hpp")
|
||||
target_compile_options(libc PRIVATE "SHELL:-include \"${CMAKE_CURRENT_SOURCE_DIR}/prx/libc/include/HostStandardStreams.hpp\"")
|
||||
endif()
|
||||
configure_windows_unwind(libc)
|
||||
configure_macos_unwind(libc)
|
||||
@@ -170,7 +170,7 @@ foreach(LIB_DIR ${LIBS_DIRS})
|
||||
endif()
|
||||
|
||||
if(WIN32)
|
||||
target_compile_options(${LIB_NAME} PRIVATE "SHELL:-include ${CMAKE_CURRENT_SOURCE_DIR}/prx/libc/include/HostStandardStreams.hpp")
|
||||
target_compile_options(${LIB_NAME} PRIVATE "SHELL:-include \"${CMAKE_CURRENT_SOURCE_DIR}/prx/libc/include/HostStandardStreams.hpp\"")
|
||||
endif()
|
||||
if(LIB_NAME STREQUAL "libkernel")
|
||||
target_link_libraries(${LIB_NAME} PUBLIC libc)
|
||||
@@ -288,6 +288,15 @@ if(BUILD_TESTING)
|
||||
set_tests_properties(guest_kernel_sys_console_identity PROPERTIES ENVIRONMENT_MODIFICATION
|
||||
"PATH=path_list_prepend:$<TARGET_FILE_DIR:libkernel_sys>")
|
||||
endif()
|
||||
add_test_executable(guest_kernel_sys_cpumode_tests tests/GuestKernelSysCpumode.cpp)
|
||||
target_include_directories(guest_kernel_sys_cpumode_tests PRIVATE ${CMAKE_CURRENT_SOURCE_DIR})
|
||||
target_link_libraries(guest_kernel_sys_cpumode_tests PRIVATE libkernel_sys libkernel libc)
|
||||
configure_windows_unwind(guest_kernel_sys_cpumode_tests)
|
||||
add_test(NAME guest_kernel_sys_cpumode COMMAND guest_kernel_sys_cpumode_tests)
|
||||
if(WIN32)
|
||||
set_tests_properties(guest_kernel_sys_cpumode PROPERTIES ENVIRONMENT_MODIFICATION
|
||||
"PATH=path_list_prepend:$<TARGET_FILE_DIR:libkernel_sys>")
|
||||
endif()
|
||||
add_test_executable(nid_buffer_validation_tests nid/tests/BufferValidation.cpp)
|
||||
target_include_directories(nid_buffer_validation_tests PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/nid/include)
|
||||
target_compile_features(nid_buffer_validation_tests PRIVATE cxx_std_20)
|
||||
@@ -308,7 +317,7 @@ if(BUILD_TESTING)
|
||||
add_custom_target(guest_dinkumware_fetch_libraries DEPENDS ${LIBC_PATCHED})
|
||||
add_dependencies(guest_dinkumware_fetch_tests guest_dinkumware_fetch_libraries)
|
||||
foreach(operation IN ITEMS and or xor)
|
||||
foreach(width IN ITEMS 1 2 4)
|
||||
foreach(width IN ITEMS 1 2 4 8)
|
||||
add_test(NAME guest_dinkumware_fetch_${operation}_${width} COMMAND guest_dinkumware_fetch_tests
|
||||
$<TARGET_FILE_DIR:libc> unpatched ${operation} ${width})
|
||||
add_test(NAME guest_dinkumware_fetch_${operation}_${width}_patched COMMAND guest_dinkumware_fetch_tests
|
||||
@@ -323,6 +332,18 @@ if(BUILD_TESTING)
|
||||
endif()
|
||||
endforeach()
|
||||
endforeach()
|
||||
add_test(NAME guest_dinkumware_fetch_add_8 COMMAND guest_dinkumware_fetch_tests
|
||||
$<TARGET_FILE_DIR:libc> unpatched add 8)
|
||||
add_test(NAME guest_dinkumware_fetch_add_8_patched COMMAND guest_dinkumware_fetch_tests
|
||||
${PATCHED_DIR} patched add 8)
|
||||
set_tests_properties(guest_dinkumware_fetch_add_8
|
||||
guest_dinkumware_fetch_add_8_patched PROPERTIES TIMEOUT 20)
|
||||
if(WIN32)
|
||||
set_tests_properties(guest_dinkumware_fetch_add_8 PROPERTIES ENVIRONMENT_MODIFICATION
|
||||
"PATH=path_list_prepend:$<TARGET_FILE_DIR:libc>")
|
||||
set_tests_properties(guest_dinkumware_fetch_add_8_patched PROPERTIES ENVIRONMENT_MODIFICATION
|
||||
"PATH=path_list_prepend:${PATCHED_DIR}")
|
||||
endif()
|
||||
add_test_executable(pe_import_first_tests allocator/tests/PeImportFirstTests.cpp allocator/PeImportFirst.cpp)
|
||||
target_include_directories(pe_import_first_tests PRIVATE ${CMAKE_CURRENT_SOURCE_DIR})
|
||||
target_compile_features(pe_import_first_tests PRIVATE cxx_std_20)
|
||||
@@ -474,6 +495,11 @@ if(BUILD_TESTING)
|
||||
add_test(NAME guest_kernel_sys_threads_${case} COMMAND guest_kernel_sys_threads_tests ${UNPATCHED_DIR} unpatched ${case})
|
||||
add_test(NAME guest_kernel_sys_threads_${case}_patched COMMAND guest_kernel_sys_threads_tests ${PATCHED_DIR} patched ${case})
|
||||
set_tests_properties(guest_kernel_sys_threads_${case} guest_kernel_sys_threads_${case}_patched PROPERTIES TIMEOUT 20)
|
||||
if(MINGW)
|
||||
get_filename_component(kernelSysThreadsRuntimeDirectory "${CMAKE_CXX_COMPILER}" DIRECTORY)
|
||||
set_tests_properties(guest_kernel_sys_threads_${case} guest_kernel_sys_threads_${case}_patched PROPERTIES
|
||||
ENVIRONMENT_MODIFICATION "PATH=path_list_prepend:${kernelSysThreadsRuntimeDirectory}")
|
||||
endif()
|
||||
endforeach()
|
||||
|
||||
add_test_executable(guest_gnm_neo_packets_tests tests/GuestGnmNeoPackets.cpp)
|
||||
@@ -842,6 +868,17 @@ if(BUILD_TESTING)
|
||||
"PATH=path_list_prepend:$<TARGET_FILE_DIR:libSceSsl>")
|
||||
endif()
|
||||
|
||||
add_test_executable(guest_kernel_sys_ksem_tests tests/GuestKernelSysKsem.cpp)
|
||||
target_include_directories(guest_kernel_sys_ksem_tests PRIVATE ${CMAKE_CURRENT_SOURCE_DIR})
|
||||
target_link_libraries(guest_kernel_sys_ksem_tests PRIVATE libkernel_sys libkernel libc)
|
||||
configure_windows_unwind(guest_kernel_sys_ksem_tests)
|
||||
add_test(NAME guest_kernel_sys_ksem COMMAND guest_kernel_sys_ksem_tests)
|
||||
set_tests_properties(guest_kernel_sys_ksem PROPERTIES TIMEOUT 30)
|
||||
if(WIN32)
|
||||
set_tests_properties(guest_kernel_sys_ksem PROPERTIES ENVIRONMENT_MODIFICATION
|
||||
"PATH=path_list_prepend:$<TARGET_FILE_DIR:libkernel_sys>")
|
||||
endif()
|
||||
|
||||
add_test_executable(guest_system_gesture_tests tests/GuestSystemGesture.cpp)
|
||||
target_include_directories(guest_system_gesture_tests PRIVATE ${CMAKE_CURRENT_SOURCE_DIR})
|
||||
target_link_libraries(guest_system_gesture_tests PRIVATE libSceSystemGesture libc)
|
||||
|
||||
@@ -253,12 +253,6 @@ void PeNidPatcher::PatchNids(std::vector<std::uint8_t>& pe, const std::string& l
|
||||
std::uint32_t FirstThunk;
|
||||
};
|
||||
|
||||
if (options.executable) {
|
||||
for (const auto index : {4u, 11u, 13u}) {
|
||||
const auto directory = Read<PeDataDirectory>(pe, dataDirectoryOffset + index * sizeof(PeDataDirectory));
|
||||
if (directory.VirtualAddress || directory.Size) throw std::runtime_error("signed, bound or delay-loaded PE imports are not supported in --exec mode");
|
||||
}
|
||||
}
|
||||
struct ImportUse {
|
||||
std::size_t NameOffset;
|
||||
std::size_t LookupOffset;
|
||||
@@ -315,19 +309,27 @@ void PeNidPatcher::PatchNids(std::vector<std::uint8_t>& pe, const std::string& l
|
||||
importDescOffset += sizeof(PeImportDescriptor);
|
||||
}
|
||||
const auto importMap = ResolveImportNids(importNames, excludedExports, options);
|
||||
if (!options.executable) {
|
||||
for (const auto& item : imports) {
|
||||
const auto& name = importMap.at(item.Name);
|
||||
if (name.size() > item.Name.size()) throw std::runtime_error("import NID longer than original name: " + item.Name);
|
||||
std::memcpy(pe.data() + item.NameOffset, name.c_str(), name.size() + 1);
|
||||
}
|
||||
return;
|
||||
const auto fitsInPlace = [&](const ImportUse& item) {
|
||||
return !options.executable && importMap.at(item.Name).size() <= item.Name.size();
|
||||
};
|
||||
const bool growsImports = options.executable || std::any_of(imports.begin(), imports.end(), [&](const ImportUse& item) {
|
||||
return !fitsInPlace(item) && importMap.at(item.Name) != item.Name;
|
||||
});
|
||||
for (const auto index : {4u, 11u, 13u}) {
|
||||
const auto directory = Read<PeDataDirectory>(pe, dataDirectoryOffset + index * sizeof(PeDataDirectory));
|
||||
if (growsImports && (directory.VirtualAddress || directory.Size))
|
||||
throw std::runtime_error("signed, bound or delay-loaded PE imports are not supported when import names move to a new section");
|
||||
}
|
||||
for (const auto& item : imports) {
|
||||
if (!fitsInPlace(item)) continue;
|
||||
const auto& name = importMap.at(item.Name);
|
||||
std::memcpy(pe.data() + item.NameOffset, name.c_str(), name.size() + 1);
|
||||
}
|
||||
std::vector<std::uint8_t> strings;
|
||||
std::unordered_map<std::string, std::uint32_t> stringOffsets;
|
||||
for (const auto& item : imports) {
|
||||
const auto& name = importMap.at(item.Name);
|
||||
if (name == item.Name || stringOffsets.contains(name)) continue;
|
||||
if (name == item.Name || fitsInPlace(item) || stringOffsets.contains(name)) continue;
|
||||
if (strings.size() & 1u) strings.push_back(0);
|
||||
if (strings.size() > 0xffffffffu - name.size() - 3u) throw std::runtime_error("PE import string table overflow");
|
||||
stringOffsets.emplace(name, static_cast<std::uint32_t>(strings.size()));
|
||||
@@ -372,7 +374,7 @@ void PeNidPatcher::PatchNids(std::vector<std::uint8_t>& pe, const std::string& l
|
||||
Write(pe, optionalHeaderOffset + 64u, std::uint32_t{0});
|
||||
for (const auto& item : imports) {
|
||||
const auto& name = importMap.at(item.Name);
|
||||
if (name == item.Name) continue;
|
||||
if (name == item.Name || fitsInPlace(item)) continue;
|
||||
const auto rva = section.VirtualAddress + stringOffsets.at(name);
|
||||
for (const auto offset : {item.LookupOffset, item.AddressOffset}) {
|
||||
if (magic == 0x20bu) Write(pe, offset, std::uint64_t{rva});
|
||||
|
||||
@@ -4,6 +4,7 @@ import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
|
||||
from test_macho_nids import build_dylib, exports_of, nid, PATCHER
|
||||
|
||||
@@ -441,5 +442,68 @@ class ExecutableImportTests(unittest.TestCase):
|
||||
self.assertEqual(path.read_bytes(), image)
|
||||
|
||||
|
||||
@unittest.skipUnless(PATCHER is not None and PATCHER.is_file(), "nid_patcher executable required")
|
||||
class LibraryImportTests(unittest.TestCase):
|
||||
def library(self, names):
|
||||
image = ExecutableImportTests.pe(SimpleNamespace(names=names))
|
||||
struct.pack_into("<IIHHIIIIIII", image, 0x600, 0, 0, 0, 0, 0x1446, 1, 1, 1, 0x1428, 0x142c, 0x1430)
|
||||
struct.pack_into("<IIH", image, 0x628, 0x1000, 0x1432, 0)
|
||||
image[0x632:0x643] = b"puts_nid_postfix\0"
|
||||
image[0x646:0x64e] = b"lib.dll\0"
|
||||
struct.pack_into("<II", image, 0x58 + 112, 0x1400, 80)
|
||||
return image
|
||||
|
||||
def imports(self, image, count):
|
||||
sections = [struct.unpack_from("<8sIIIIIIHHI", image, 0x58 + 240 + index * 40)
|
||||
for index in range(struct.unpack_from("<H", image, 0x46)[0])]
|
||||
result = []
|
||||
for index in range(count):
|
||||
rva = struct.unpack_from("<Q", image, 576 + index * 8)[0]
|
||||
self.assertEqual(rva, struct.unpack_from("<Q", image, 704 + index * 8)[0])
|
||||
section = next(s for s in sections if s[2] <= rva < s[2] + s[3])
|
||||
offset = section[4] + rva - section[2] + 2
|
||||
result.append((rva, image[offset:image.index(0, offset)].decode()))
|
||||
return result, len(sections)
|
||||
|
||||
def patch(self, image):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
path = Path(directory) / "library.dll"
|
||||
path.write_bytes(image)
|
||||
result = subprocess.run([str(PATCHER), "libtest", str(path)], capture_output=True, text=True, timeout=20)
|
||||
return result, path.read_bytes()
|
||||
|
||||
def test_imports_longer_as_nids_move_to_a_new_section(self):
|
||||
names = ["sceA", "sceNetRecv", "sceKernelLongerName", "plain"]
|
||||
image = self.library(names)
|
||||
before, _ = self.imports(image, len(names))
|
||||
result, patched = self.patch(image)
|
||||
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
|
||||
after, sections = self.imports(patched, len(names))
|
||||
self.assertEqual([name for _, name in after], [nid("sceA"), nid("sceNetRecv"), nid("sceKernelLongerName"), "plain"])
|
||||
self.assertEqual(sections, 2)
|
||||
self.assertEqual([rva == old for (rva, _), (old, _) in zip(after, before)], [False, False, True, True])
|
||||
|
||||
def test_imports_that_fit_keep_the_section_layout(self):
|
||||
names = ["sceKernelLongerName", "plain"]
|
||||
result, patched = self.patch(self.library(names))
|
||||
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
|
||||
after, sections = self.imports(patched, len(names))
|
||||
self.assertEqual([name for _, name in after], [nid("sceKernelLongerName"), "plain"])
|
||||
self.assertEqual(sections, 1)
|
||||
|
||||
def test_delay_loaded_imports_cannot_grow(self):
|
||||
for names, accepted in ((["sceNetRecv"], False), (["sceKernelLongerName"], True)):
|
||||
with self.subTest(names=names):
|
||||
image = self.library(names)
|
||||
struct.pack_into("<II", image, 0x58 + 112 + 13 * 8, 0x1500, 32)
|
||||
result, patched = self.patch(image)
|
||||
if accepted:
|
||||
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
|
||||
else:
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
self.assertIn("delay-loaded", result.stdout + result.stderr)
|
||||
self.assertEqual(patched, image)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,309 @@
|
||||
#pragma once
|
||||
|
||||
#include "SceTypes.hpp"
|
||||
|
||||
extern "C" {
|
||||
|
||||
int APS5_VABI __asan_addr_is_in_fake_stack();
|
||||
int APS5_VABI __asan_address_is_poisoned();
|
||||
int APS5_VABI __asan_after_dynamic_init();
|
||||
int APS5_VABI __asan_aligned_alloc();
|
||||
int APS5_VABI __asan_alloca_poison();
|
||||
int APS5_VABI __asan_allocas_unpoison();
|
||||
int APS5_VABI __asan_before_dynamic_init();
|
||||
int APS5_VABI __asan_calloc();
|
||||
int APS5_VABI __asan_current_error_report();
|
||||
int APS5_VABI __asan_current_error_report_size();
|
||||
int APS5_VABI __asan_describe_address();
|
||||
int APS5_VABI __asan_destroy_fake_stack();
|
||||
int APS5_VABI __asan_exp_load1();
|
||||
int APS5_VABI __asan_exp_load16();
|
||||
int APS5_VABI __asan_exp_load16_noabort();
|
||||
int APS5_VABI __asan_exp_load1_noabort();
|
||||
int APS5_VABI __asan_exp_load2();
|
||||
int APS5_VABI __asan_exp_load2_noabort();
|
||||
int APS5_VABI __asan_exp_load4();
|
||||
int APS5_VABI __asan_exp_load4_noabort();
|
||||
int APS5_VABI __asan_exp_load8();
|
||||
int APS5_VABI __asan_exp_load8_noabort();
|
||||
int APS5_VABI __asan_exp_loadN();
|
||||
int APS5_VABI __asan_exp_loadN_noabort();
|
||||
int APS5_VABI __asan_exp_store1();
|
||||
int APS5_VABI __asan_exp_store16();
|
||||
int APS5_VABI __asan_exp_store16_noabort();
|
||||
int APS5_VABI __asan_exp_store1_noabort();
|
||||
int APS5_VABI __asan_exp_store2();
|
||||
int APS5_VABI __asan_exp_store2_noabort();
|
||||
int APS5_VABI __asan_exp_store4();
|
||||
int APS5_VABI __asan_exp_store4_noabort();
|
||||
int APS5_VABI __asan_exp_store8();
|
||||
int APS5_VABI __asan_exp_store8_noabort();
|
||||
int APS5_VABI __asan_exp_storeN();
|
||||
int APS5_VABI __asan_exp_storeN_noabort();
|
||||
int APS5_VABI __asan_free();
|
||||
int APS5_VABI __asan_get_alloc_stack();
|
||||
int APS5_VABI __asan_get_current_fake_stack();
|
||||
int APS5_VABI __asan_get_free_stack();
|
||||
int APS5_VABI __asan_get_report_access_size();
|
||||
int APS5_VABI __asan_get_report_access_type();
|
||||
int APS5_VABI __asan_get_report_address();
|
||||
int APS5_VABI __asan_get_report_bp();
|
||||
int APS5_VABI __asan_get_report_description();
|
||||
int APS5_VABI __asan_get_report_pc();
|
||||
int APS5_VABI __asan_get_report_sp();
|
||||
int APS5_VABI __asan_get_shadow_mapping();
|
||||
int APS5_VABI __asan_handle_no_return();
|
||||
int APS5_VABI __asan_init();
|
||||
int APS5_VABI __asan_init_v5();
|
||||
int APS5_VABI __asan_load1();
|
||||
int APS5_VABI __asan_load16();
|
||||
int APS5_VABI __asan_load16_noabort();
|
||||
int APS5_VABI __asan_load1_noabort();
|
||||
int APS5_VABI __asan_load2();
|
||||
int APS5_VABI __asan_load2_noabort();
|
||||
int APS5_VABI __asan_load4();
|
||||
int APS5_VABI __asan_load4_noabort();
|
||||
int APS5_VABI __asan_load8();
|
||||
int APS5_VABI __asan_load8_noabort();
|
||||
int APS5_VABI __asan_loadN();
|
||||
int APS5_VABI __asan_loadN_noabort();
|
||||
int APS5_VABI __asan_load_cxx_array_cookie();
|
||||
int APS5_VABI __asan_locate_address();
|
||||
int APS5_VABI __asan_malloc();
|
||||
int APS5_VABI __asan_malloc_stats();
|
||||
int APS5_VABI __asan_malloc_usable_size();
|
||||
int APS5_VABI __asan_memalign();
|
||||
int APS5_VABI __asan_memcpy();
|
||||
int APS5_VABI __asan_memmove();
|
||||
int APS5_VABI __asan_memset();
|
||||
int APS5_VABI __asan_option_detect_stack_use_after_return();
|
||||
int APS5_VABI __asan_poison_cxx_array_cookie();
|
||||
int APS5_VABI __asan_poison_intra_object_redzone();
|
||||
int APS5_VABI __asan_poison_memory_region();
|
||||
int APS5_VABI __asan_poison_stack_memory();
|
||||
int APS5_VABI __asan_posix_memalign();
|
||||
int APS5_VABI __asan_print_accumulated_stats();
|
||||
int APS5_VABI __asan_realloc();
|
||||
int APS5_VABI __asan_reallocalign();
|
||||
int APS5_VABI __asan_region_is_poisoned();
|
||||
int APS5_VABI __asan_register_elf_globals();
|
||||
int APS5_VABI __asan_register_globals();
|
||||
int APS5_VABI __asan_register_image_globals();
|
||||
int APS5_VABI __asan_report_error();
|
||||
int APS5_VABI __asan_report_exp_load1();
|
||||
int APS5_VABI __asan_report_exp_load16();
|
||||
int APS5_VABI __asan_report_exp_load16_noabort();
|
||||
int APS5_VABI __asan_report_exp_load1_noabort();
|
||||
int APS5_VABI __asan_report_exp_load2();
|
||||
int APS5_VABI __asan_report_exp_load2_noabort();
|
||||
int APS5_VABI __asan_report_exp_load4();
|
||||
int APS5_VABI __asan_report_exp_load4_noabort();
|
||||
int APS5_VABI __asan_report_exp_load8();
|
||||
int APS5_VABI __asan_report_exp_load8_noabort();
|
||||
int APS5_VABI __asan_report_exp_load_n();
|
||||
int APS5_VABI __asan_report_exp_load_n_noabort();
|
||||
int APS5_VABI __asan_report_exp_store1();
|
||||
int APS5_VABI __asan_report_exp_store16();
|
||||
int APS5_VABI __asan_report_exp_store16_noabort();
|
||||
int APS5_VABI __asan_report_exp_store1_noabort();
|
||||
int APS5_VABI __asan_report_exp_store2();
|
||||
int APS5_VABI __asan_report_exp_store2_noabort();
|
||||
int APS5_VABI __asan_report_exp_store4();
|
||||
int APS5_VABI __asan_report_exp_store4_noabort();
|
||||
int APS5_VABI __asan_report_exp_store8();
|
||||
int APS5_VABI __asan_report_exp_store8_noabort();
|
||||
int APS5_VABI __asan_report_exp_store_n();
|
||||
int APS5_VABI __asan_report_exp_store_n_noabort();
|
||||
int APS5_VABI __asan_report_load1();
|
||||
int APS5_VABI __asan_report_load16();
|
||||
int APS5_VABI __asan_report_load16_noabort();
|
||||
int APS5_VABI __asan_report_load1_noabort();
|
||||
int APS5_VABI __asan_report_load2();
|
||||
int APS5_VABI __asan_report_load2_noabort();
|
||||
int APS5_VABI __asan_report_load4();
|
||||
int APS5_VABI __asan_report_load4_noabort();
|
||||
int APS5_VABI __asan_report_load8();
|
||||
int APS5_VABI __asan_report_load8_noabort();
|
||||
int APS5_VABI __asan_report_load_n();
|
||||
int APS5_VABI __asan_report_load_n_noabort();
|
||||
int APS5_VABI __asan_report_present();
|
||||
int APS5_VABI __asan_report_store1();
|
||||
int APS5_VABI __asan_report_store16();
|
||||
int APS5_VABI __asan_report_store16_noabort();
|
||||
int APS5_VABI __asan_report_store1_noabort();
|
||||
int APS5_VABI __asan_report_store2();
|
||||
int APS5_VABI __asan_report_store2_noabort();
|
||||
int APS5_VABI __asan_report_store4();
|
||||
int APS5_VABI __asan_report_store4_noabort();
|
||||
int APS5_VABI __asan_report_store8();
|
||||
int APS5_VABI __asan_report_store8_noabort();
|
||||
int APS5_VABI __asan_report_store_n();
|
||||
int APS5_VABI __asan_report_store_n_noabort();
|
||||
int APS5_VABI __asan_set_error_report_callback();
|
||||
int APS5_VABI __asan_set_shadow_00();
|
||||
int APS5_VABI __asan_set_shadow_01();
|
||||
int APS5_VABI __asan_set_shadow_02();
|
||||
int APS5_VABI __asan_set_shadow_03();
|
||||
int APS5_VABI __asan_set_shadow_04();
|
||||
int APS5_VABI __asan_set_shadow_05();
|
||||
int APS5_VABI __asan_set_shadow_06();
|
||||
int APS5_VABI __asan_set_shadow_07();
|
||||
int APS5_VABI __asan_set_shadow_f1();
|
||||
int APS5_VABI __asan_set_shadow_f2();
|
||||
int APS5_VABI __asan_set_shadow_f3();
|
||||
int APS5_VABI __asan_set_shadow_f5();
|
||||
int APS5_VABI __asan_set_shadow_f8();
|
||||
int APS5_VABI __asan_stack_free_0();
|
||||
int APS5_VABI __asan_stack_free_1();
|
||||
int APS5_VABI __asan_stack_free_10();
|
||||
int APS5_VABI __asan_stack_free_2();
|
||||
int APS5_VABI __asan_stack_free_3();
|
||||
int APS5_VABI __asan_stack_free_4();
|
||||
int APS5_VABI __asan_stack_free_5();
|
||||
int APS5_VABI __asan_stack_free_6();
|
||||
int APS5_VABI __asan_stack_free_7();
|
||||
int APS5_VABI __asan_stack_free_8();
|
||||
int APS5_VABI __asan_stack_free_9();
|
||||
int APS5_VABI __asan_stack_malloc_0();
|
||||
int APS5_VABI __asan_stack_malloc_1();
|
||||
int APS5_VABI __asan_stack_malloc_10();
|
||||
int APS5_VABI __asan_stack_malloc_2();
|
||||
int APS5_VABI __asan_stack_malloc_3();
|
||||
int APS5_VABI __asan_stack_malloc_4();
|
||||
int APS5_VABI __asan_stack_malloc_5();
|
||||
int APS5_VABI __asan_stack_malloc_6();
|
||||
int APS5_VABI __asan_stack_malloc_7();
|
||||
int APS5_VABI __asan_stack_malloc_8();
|
||||
int APS5_VABI __asan_stack_malloc_9();
|
||||
int APS5_VABI __asan_stack_malloc_always_0();
|
||||
int APS5_VABI __asan_stack_malloc_always_1();
|
||||
int APS5_VABI __asan_stack_malloc_always_10();
|
||||
int APS5_VABI __asan_stack_malloc_always_2();
|
||||
int APS5_VABI __asan_stack_malloc_always_3();
|
||||
int APS5_VABI __asan_stack_malloc_always_4();
|
||||
int APS5_VABI __asan_stack_malloc_always_5();
|
||||
int APS5_VABI __asan_stack_malloc_always_6();
|
||||
int APS5_VABI __asan_stack_malloc_always_7();
|
||||
int APS5_VABI __asan_stack_malloc_always_8();
|
||||
int APS5_VABI __asan_stack_malloc_always_9();
|
||||
int APS5_VABI __asan_store1();
|
||||
int APS5_VABI __asan_store16();
|
||||
int APS5_VABI __asan_store16_noabort();
|
||||
int APS5_VABI __asan_store1_noabort();
|
||||
int APS5_VABI __asan_store2();
|
||||
int APS5_VABI __asan_store2_noabort();
|
||||
int APS5_VABI __asan_store4();
|
||||
int APS5_VABI __asan_store4_noabort();
|
||||
int APS5_VABI __asan_store8();
|
||||
int APS5_VABI __asan_store8_noabort();
|
||||
int APS5_VABI __asan_storeN();
|
||||
int APS5_VABI __asan_storeN_noabort();
|
||||
int APS5_VABI __asan_unpoison_intra_object_redzone();
|
||||
int APS5_VABI __asan_unpoison_memory_region();
|
||||
int APS5_VABI __asan_unpoison_stack_memory();
|
||||
int APS5_VABI __asan_unregister_elf_globals();
|
||||
int APS5_VABI __asan_unregister_globals();
|
||||
int APS5_VABI __asan_unregister_image_globals();
|
||||
int APS5_VABI __asan_update_allocation_context();
|
||||
int APS5_VABI __asan_version_mismatch_check_v6();
|
||||
int APS5_VABI __asan_version_mismatch_check_v7();
|
||||
int APS5_VABI __asan_version_mismatch_check_v8();
|
||||
int APS5_VABI __sancov_default_options();
|
||||
int APS5_VABI __sanitizer_annotate_contiguous_container();
|
||||
int APS5_VABI __sanitizer_annotate_double_ended_contiguous_container();
|
||||
int APS5_VABI __sanitizer_contiguous_container_find_bad_address();
|
||||
int APS5_VABI __sanitizer_cov_dump();
|
||||
int APS5_VABI __sanitizer_cov_trace_pc_guard();
|
||||
int APS5_VABI __sanitizer_cov_trace_pc_guard_init();
|
||||
int APS5_VABI __sanitizer_double_ended_contiguous_container_find_bad_address();
|
||||
int APS5_VABI __sanitizer_dump_coverage();
|
||||
int APS5_VABI __sanitizer_dump_trace_pc_guard_coverage();
|
||||
int APS5_VABI __sanitizer_finish_switch_fiber();
|
||||
int APS5_VABI __sanitizer_free_hook();
|
||||
int APS5_VABI __sanitizer_get_allocated_begin();
|
||||
int APS5_VABI __sanitizer_get_allocated_size();
|
||||
int APS5_VABI __sanitizer_get_allocated_size_fast();
|
||||
int APS5_VABI __sanitizer_get_current_allocated_bytes();
|
||||
int APS5_VABI __sanitizer_get_estimated_allocated_size();
|
||||
int APS5_VABI __sanitizer_get_free_bytes();
|
||||
int APS5_VABI __sanitizer_get_heap_size();
|
||||
int APS5_VABI __sanitizer_get_ownership();
|
||||
int APS5_VABI __sanitizer_get_report_path();
|
||||
int APS5_VABI __sanitizer_get_unmapped_bytes();
|
||||
int APS5_VABI __sanitizer_malloc_hook();
|
||||
int APS5_VABI __sanitizer_print_stack_trace();
|
||||
int APS5_VABI __sanitizer_ptr_cmp();
|
||||
int APS5_VABI __sanitizer_ptr_sub();
|
||||
int APS5_VABI __sanitizer_purge_allocator();
|
||||
int APS5_VABI __sanitizer_sandbox_on_notify();
|
||||
int APS5_VABI __sanitizer_set_death_callback();
|
||||
int APS5_VABI __sanitizer_set_report_fd();
|
||||
int APS5_VABI __sanitizer_set_report_path();
|
||||
int APS5_VABI __sanitizer_start_switch_fiber();
|
||||
int APS5_VABI __sanitizer_symbolize_global();
|
||||
int APS5_VABI __sanitizer_symbolize_pc();
|
||||
int APS5_VABI __sanitizer_unaligned_load16();
|
||||
int APS5_VABI __sanitizer_unaligned_load32();
|
||||
int APS5_VABI __sanitizer_unaligned_load64();
|
||||
int APS5_VABI __sanitizer_unaligned_store16();
|
||||
int APS5_VABI __sanitizer_unaligned_store32();
|
||||
int APS5_VABI __sanitizer_unaligned_store64();
|
||||
int APS5_VABI __sanitizer_verify_contiguous_container();
|
||||
int APS5_VABI __sanitizer_verify_double_ended_contiguous_container();
|
||||
int APS5_VABI __ubsan_current_error_report();
|
||||
int APS5_VABI __ubsan_current_error_report_size();
|
||||
int APS5_VABI __ubsan_default_options();
|
||||
int APS5_VABI __ubsan_get_current_report_data();
|
||||
int APS5_VABI __ubsan_handle_add_overflow();
|
||||
int APS5_VABI __ubsan_handle_add_overflow_abort();
|
||||
int APS5_VABI __ubsan_handle_alignment_assumption();
|
||||
int APS5_VABI __ubsan_handle_alignment_assumption_abort();
|
||||
int APS5_VABI __ubsan_handle_builtin_unreachable();
|
||||
int APS5_VABI __ubsan_handle_divrem_overflow();
|
||||
int APS5_VABI __ubsan_handle_divrem_overflow_abort();
|
||||
int APS5_VABI __ubsan_handle_dynamic_type_cache_miss();
|
||||
int APS5_VABI __ubsan_handle_dynamic_type_cache_miss_abort();
|
||||
int APS5_VABI __ubsan_handle_float_cast_overflow();
|
||||
int APS5_VABI __ubsan_handle_float_cast_overflow_abort();
|
||||
int APS5_VABI __ubsan_handle_function_type_mismatch();
|
||||
int APS5_VABI __ubsan_handle_function_type_mismatch_abort();
|
||||
int APS5_VABI __ubsan_handle_function_type_mismatch_v1();
|
||||
int APS5_VABI __ubsan_handle_function_type_mismatch_v1_abort();
|
||||
int APS5_VABI __ubsan_handle_implicit_conversion();
|
||||
int APS5_VABI __ubsan_handle_implicit_conversion_abort();
|
||||
int APS5_VABI __ubsan_handle_invalid_builtin();
|
||||
int APS5_VABI __ubsan_handle_invalid_builtin_abort();
|
||||
int APS5_VABI __ubsan_handle_load_invalid_value();
|
||||
int APS5_VABI __ubsan_handle_load_invalid_value_abort();
|
||||
int APS5_VABI __ubsan_handle_missing_return();
|
||||
int APS5_VABI __ubsan_handle_mul_overflow();
|
||||
int APS5_VABI __ubsan_handle_mul_overflow_abort();
|
||||
int APS5_VABI __ubsan_handle_negate_overflow();
|
||||
int APS5_VABI __ubsan_handle_negate_overflow_abort();
|
||||
int APS5_VABI __ubsan_handle_nonnull_arg();
|
||||
int APS5_VABI __ubsan_handle_nonnull_arg_abort();
|
||||
int APS5_VABI __ubsan_handle_nonnull_return();
|
||||
int APS5_VABI __ubsan_handle_nonnull_return_abort();
|
||||
int APS5_VABI __ubsan_handle_nonnull_return_v1();
|
||||
int APS5_VABI __ubsan_handle_nonnull_return_v1_abort();
|
||||
int APS5_VABI __ubsan_handle_nullability_arg();
|
||||
int APS5_VABI __ubsan_handle_nullability_arg_abort();
|
||||
int APS5_VABI __ubsan_handle_nullability_return_v1();
|
||||
int APS5_VABI __ubsan_handle_nullability_return_v1_abort();
|
||||
int APS5_VABI __ubsan_handle_out_of_bounds();
|
||||
int APS5_VABI __ubsan_handle_out_of_bounds_abort();
|
||||
int APS5_VABI __ubsan_handle_pointer_overflow();
|
||||
int APS5_VABI __ubsan_handle_pointer_overflow_abort();
|
||||
int APS5_VABI __ubsan_handle_shift_out_of_bounds();
|
||||
int APS5_VABI __ubsan_handle_shift_out_of_bounds_abort();
|
||||
int APS5_VABI __ubsan_handle_sub_overflow();
|
||||
int APS5_VABI __ubsan_handle_sub_overflow_abort();
|
||||
int APS5_VABI __ubsan_handle_type_mismatch();
|
||||
int APS5_VABI __ubsan_handle_type_mismatch_abort();
|
||||
int APS5_VABI __ubsan_handle_type_mismatch_v1();
|
||||
int APS5_VABI __ubsan_handle_type_mismatch_v1_abort();
|
||||
int APS5_VABI __ubsan_handle_vla_bound_not_positive();
|
||||
int APS5_VABI __ubsan_handle_vla_bound_not_positive_abort();
|
||||
int APS5_VABI __ubsan_vptr_type_cache();
|
||||
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
#pragma once
|
||||
|
||||
#include "prx/libSceAddressSanitizer/include/Api.hpp"
|
||||
@@ -1,10 +1,12 @@
|
||||
#include "prx/libSceAgc/include/Agc.hpp"
|
||||
#include "prx/libSceAgcDriver/Resource/include/Registration.hpp"
|
||||
#include "prx/libSceAgc/Patch/include/WaitRegMem.hpp"
|
||||
#include "prx/libSceAgc/Patch/include/IndirectRegisters.hpp"
|
||||
#include "prx/libSceAgc/Patch/include/Nop.hpp"
|
||||
#include "prx/libSceAgc/Patch/include/QueueEndOfPipeAction.hpp"
|
||||
#include "prx/libSceAgc/Misc/include/Suspend.hpp"
|
||||
#include "prx/libSceAgc/Misc/include/RegisterDefaults.hpp"
|
||||
#include "prx/libSceAgc/Patch/include/Jump.hpp"
|
||||
#include "prx/libSceAgc/Misc/include/PacketInfo.hpp"
|
||||
#include "prx/libSceAgc/Misc/include/Debug.hpp"
|
||||
#include "prx/libSceAgc/DcbState/include/Workload.hpp"
|
||||
@@ -221,6 +223,24 @@ void testTagHeaders() {
|
||||
}
|
||||
}
|
||||
|
||||
void testJumpTargetPatch() {
|
||||
const auto target = [](std::uintptr_t address) { return reinterpret_cast<const volatile std::uint32_t*>(address); };
|
||||
Storage storage;
|
||||
auto* packet = sceAgcDcbJump(&storage.buffer, 1, 2, reinterpret_cast<const std::uint32_t*>(0x1000ull), 0x40);
|
||||
check(sceAgcJumpPatchSetTarget_0300(packet, 1, target(0x123456789ab0u), 0x80) == 0, "jump target patch with a cache policy failed");
|
||||
check(packet[1] == 0x56789ab0u && packet[2] == 0x1234u && packet[3] == 0x1f300080u, "jump target patch did not replace the address, size and cache policy only");
|
||||
check(sceAgcJumpPatchSetTarget(packet, target(0x2000u), 0x10) == 0, "jump target patch failed");
|
||||
check(packet[1] == 0x2000u && packet[2] == 0 && packet[3] == 0x1f300010u, "jump target patch without a cache policy changed it");
|
||||
const auto before = storage.words;
|
||||
expectFailure([&] { sceAgcJumpPatchSetTarget_0300(packet, 4, target(0x3000u), 1); });
|
||||
expectFailure([&] { sceAgcJumpPatchSetTarget_0300(packet, 0, target(0x3002u), 1); });
|
||||
expectFailure([&] { sceAgcJumpPatchSetTarget(packet, target(0x3000u), 0x100000u); });
|
||||
packet[0] = Agc::Command::Header(0x3fu, 5);
|
||||
expectFailure([&] { sceAgcJumpPatchSetTarget(packet, target(0x3000u), 1); });
|
||||
packet[0] = before[0];
|
||||
check(storage.words == before, "a refused jump target patch modified the packet");
|
||||
}
|
||||
|
||||
void testMarkers() {
|
||||
Storage dcb;
|
||||
Storage acb;
|
||||
@@ -265,6 +285,29 @@ void testMarkerSpans() {
|
||||
expectFailure([&] { sceAgcDcbPushMarkerSpan(&dcb.buffer, nullptr, 4, 0); });
|
||||
}
|
||||
|
||||
void testEndOfPipeAddressPatch() {
|
||||
const auto label = [](std::uintptr_t address) { return reinterpret_cast<const volatile Label*>(address); };
|
||||
std::array<std::uint32_t, 8> release{};
|
||||
release[0] = Agc::Command::Header(0x49u, 8);
|
||||
release[2] = 1u << 29u;
|
||||
check(sceAgcQueueEndOfPipeActionPatchAddress(release.data(), label(0x123456789abcu)) == 0 && release[3] == 0x56789abcu && release[4] == 0x1234u, "RELEASE_MEM address patch mismatch");
|
||||
release[2] = 2u << 29u;
|
||||
const auto before = release;
|
||||
expectFailure([&] { sceAgcQueueEndOfPipeActionPatchAddress(release.data(), label(0x123456789ab4u)); });
|
||||
check(release == before, "a 64-bit RELEASE_MEM accepted a label that is not 8-byte aligned");
|
||||
check(sceAgcQueueEndOfPipeActionPatchAddress(release.data(), label(0x123456789ab8u)) == 0 && release[3] == 0x56789ab8u, "64-bit RELEASE_MEM address patch mismatch");
|
||||
std::array<std::uint32_t, 6> event{};
|
||||
event[0] = Agc::Command::Header(0x47u, 6);
|
||||
event[3] = (1u << 29u) | 0x00ab0000u;
|
||||
check(sceAgcQueueEndOfPipeActionPatchAddress(event.data(), label(0x123456789abcu)) == 0 && event[2] == 0x56789abcu && event[3] == ((1u << 29u) | 0x00ab1234u), "EVENT_WRITE_EOP address patch did not keep the control bits");
|
||||
const auto eventBefore = event;
|
||||
expectFailure([&] { sceAgcQueueEndOfPipeActionPatchAddress(event.data(), label(0x1000000000000u)); });
|
||||
check(event == eventBefore, "an EVENT_WRITE_EOP accepted an address above 48 bits");
|
||||
event[0] = Agc::Command::Header(0x47u, 5);
|
||||
expectFailure([&] { sceAgcQueueEndOfPipeActionPatchAddress(event.data(), label(0x1000u)); });
|
||||
expectFailure([&] { sceAgcQueueEndOfPipeActionPatchAddress(nullptr, label(0x1000u)); });
|
||||
}
|
||||
|
||||
void testWorkloads() {
|
||||
Storage dcb;
|
||||
const std::uint32_t ids[2] = {3, 4};
|
||||
@@ -478,6 +521,44 @@ void testContextState() {
|
||||
check(invalid.buffer.cursor_up == growth.destination.words.data(), "failed reservation advanced cursor");
|
||||
}
|
||||
|
||||
void testFlowPackets() {
|
||||
const auto* target = reinterpret_cast<const std::uint32_t*>(0x123456789ab0ull);
|
||||
Storage chained;
|
||||
const auto* jump = sceAgcDcbJump(&chained.buffer, 1, 2, target, 0x40);
|
||||
const std::array<std::uint32_t, 4> chainedExpected{0xc0023f00u, 0x56789ab0u, 0x1234u, 0x2f300040u};
|
||||
check(jump == chained.words.data() && std::equal(chainedExpected.begin(), chainedExpected.end(), chained.words.begin()), "chained INDIRECT_BUFFER packet mismatch");
|
||||
Storage called;
|
||||
sceAgcDcbJump(&called.buffer, 0, 0, target, 0xfffffu);
|
||||
check(called.words[3] == 0x0f2fffffu, "unchained INDIRECT_BUFFER control word mismatch");
|
||||
Storage compute;
|
||||
sceAgcAcbJump(&compute.buffer, 1, target, 0x10);
|
||||
check(compute.words[0] == 0xc0023f00u && compute.words[3] == 0x1f300010u, "compute jumps did not chain");
|
||||
Storage rejected;
|
||||
rejected.words.fill(0xa5a5a5a5u);
|
||||
const auto rejectedWords = rejected.words;
|
||||
const auto* rejectedCursor = rejected.buffer.cursor_up;
|
||||
expectFailure([&] { sceAgcDcbJump(&rejected.buffer, 2, 0, target, 1); });
|
||||
check(rejected.words == rejectedWords && rejected.buffer.cursor_up == rejectedCursor, "a refused packet changed the command buffer");
|
||||
expectFailure([&] { sceAgcDcbJump(&rejected.buffer, 0, 4, target, 1); });
|
||||
check(rejected.words == rejectedWords && rejected.buffer.cursor_up == rejectedCursor, "a refused packet changed the command buffer");
|
||||
expectFailure([&] { sceAgcDcbJump(&rejected.buffer, 0, 0, target, 0x100000u); });
|
||||
check(rejected.words == rejectedWords && rejected.buffer.cursor_up == rejectedCursor, "a refused packet changed the command buffer");
|
||||
expectFailure([&] { sceAgcAcbJump(&rejected.buffer, 0, reinterpret_cast<const std::uint32_t*>(0x1002ull), 1); });
|
||||
check(rejected.words == rejectedWords && rejected.buffer.cursor_up == rejectedCursor, "a refused packet changed the command buffer");
|
||||
check(sceAgcDcbJumpGetSize() == 16 && sceAgcAcbJumpGetSize() == 16, "jump packet sizes");
|
||||
Storage stall;
|
||||
sceAgcDcbStallCommandBufferParser(&stall.buffer);
|
||||
check(stall.words[0] == 0xc0004200u && stall.words[1] == 0 && sceAgcDcbStallCommandBufferParserGetSize() == 8, "PFP_SYNC_ME packet mismatch");
|
||||
Storage rendering;
|
||||
sceAgcDcbWaitUntilSafeForRendering(&rendering.buffer, 7, 2);
|
||||
const std::array<std::uint32_t, 4> renderingExpected{0xc0021018u, 7, 2, 0};
|
||||
check(std::equal(renderingExpected.begin(), renderingExpected.end(), rendering.words.begin()), "rendering wait packet mismatch");
|
||||
Storage reset;
|
||||
sceAgcAcbResetQueue(&reset.buffer, 5, 9);
|
||||
check(reset.words[0] == 0xc0001024u && reset.words[1] == 5 && reset.words[2] == 0, "compute queue reset packet mismatch");
|
||||
expectFailure([&] { sceAgcAcbResetQueue(nullptr, 5, 9); });
|
||||
}
|
||||
|
||||
void testFlip() {
|
||||
Storage storage;
|
||||
storage.words.fill(0xdeadbeefu);
|
||||
@@ -530,6 +611,23 @@ void testRegisters() {
|
||||
check(storage.words == before, "invalid indirect patch modified memory");
|
||||
}
|
||||
|
||||
void testIndirectRegisterPatches() {
|
||||
using AddRegisters = int (APS5_VABI *)(std::uint32_t*, std::uint32_t);
|
||||
const std::array<ShaderRegister, 2> registers{{{0x10, 7}, {0x11, 8}}};
|
||||
const std::array<std::pair<std::uint32_t, AddRegisters>, 3> kinds{{{0x9fu, sceAgcSetCxRegIndirectPatchAddRegisters}, {0x63u, sceAgcSetShRegIndirectPatchAddRegisters}, {0x64u, sceAgcSetUcRegIndirectPatchAddRegisters}}};
|
||||
for (std::size_t i = 0; i < kinds.size(); ++i) {
|
||||
Storage storage;
|
||||
auto* packet = Agc::Command::WriteIndirectRegisters(&storage.buffer, kinds[i].first, registers.data(), 2, __func__);
|
||||
check(kinds[i].second(packet, 3) == 0 && packet[4] == 5, "indirect register patch did not add to the count");
|
||||
check(kinds[i].second(packet, 0x3fffu - 5u) == 0 && packet[4] == 0x3fffu, "indirect register patch did not reach the largest count");
|
||||
const auto before = storage.words;
|
||||
expectFailure([&] { kinds[i].second(packet, 1); });
|
||||
check(storage.words == before, "an overflowing indirect register patch modified the packet");
|
||||
expectFailure([&] { kinds[(i + 1) % kinds.size()].second(packet, 1); });
|
||||
check(storage.words == before, "an indirect register patch of another packet kind modified the packet");
|
||||
}
|
||||
}
|
||||
|
||||
void testRegisterRange() {
|
||||
Storage storage;
|
||||
storage.words.fill(0xdeadbeefu);
|
||||
@@ -963,15 +1061,19 @@ int main(int argc, char** argv) {
|
||||
testIndexedIndirectDraws();
|
||||
testTagHeaders();
|
||||
testMarkers();
|
||||
testJumpTargetPatch();
|
||||
testMarkerSpans();
|
||||
testWorkloads();
|
||||
testEndOfPipeAddressPatch();
|
||||
testWorkloadStreams();
|
||||
testIndexBuffer();
|
||||
testIndexIndirectArgs();
|
||||
testIndirectBase();
|
||||
testContextState();
|
||||
testFlowPackets();
|
||||
testFlip();
|
||||
testRegisters();
|
||||
testIndirectRegisterPatches();
|
||||
testRegisterRange();
|
||||
testPacketPayloadAddress();
|
||||
testMemory();
|
||||
|
||||
@@ -71,6 +71,26 @@ void HandBuiltUserVgprRegister() {
|
||||
catch (const std::runtime_error& error) { message = error.what(); }
|
||||
Require(message.find("GE_CNTL") != std::string::npos && message.find("0x25c") != std::string::npos);
|
||||
}
|
||||
|
||||
void UpdatedPrimitiveType() {
|
||||
using namespace ShaderRegs;
|
||||
std::array<ShaderRegister, 2> context{ShaderRegister{VGT_SHADER_STAGES_EN, 0x2412010u}, ShaderRegister{VGT_GS_OUT_PRIM_TYPE, 0xa5a5a5a0u}};
|
||||
std::array<ShaderRegister, 3> primitive{ShaderRegister{GE_CNTL, 0x100u}, ShaderRegister{GE_USER_VGPR1, 0}, ShaderRegister{VGT_PRIMITIVE_TYPE, 0x5a5a5a40u}};
|
||||
Require(sceAgcUpdatePrimState(context.data(), primitive.data(), static_cast<std::uint32_t>(PrimitiveType::LineStrip)) == 0);
|
||||
Require(context[1].value == (0xa5a5a5a0u | static_cast<std::uint32_t>(GsOutputPrimitiveType::Lines)) && primitive[2].value == (0x5a5a5a40u | 3u));
|
||||
Require(context[0].offset == VGT_SHADER_STAGES_EN && context[0].value == 0x2412010u && context[1].offset == VGT_GS_OUT_PRIM_TYPE);
|
||||
Require(primitive[0].value == 0x100u && primitive[1].value == 0 && primitive[2].offset == VGT_PRIMITIVE_TYPE);
|
||||
Require(sceAgcUpdatePrimState(context.data(), nullptr, static_cast<std::uint32_t>(PrimitiveType::RectList)) == 0);
|
||||
Require(context[1].value == (0xa5a5a5a0u | static_cast<std::uint32_t>(GsOutputPrimitiveType::Rectangle2D)) && primitive[2].value == (0x5a5a5a40u | 3u));
|
||||
Require(sceAgcUpdatePrimState(nullptr, primitive.data(), static_cast<std::uint32_t>(PrimitiveType::TriStrip)) == 0);
|
||||
Require(context[1].value == (0xa5a5a5a0u | static_cast<std::uint32_t>(GsOutputPrimitiveType::Rectangle2D)) && primitive[2].value == (0x5a5a5a40u | 6u));
|
||||
for (const auto stage : {VGT_SHADER_STAGES_GS_BIT, VGT_SHADER_STAGES_HS_BIT}) {
|
||||
context[0].value = 0x2412010u | stage;
|
||||
const auto kept = context[1].value;
|
||||
Require(sceAgcUpdatePrimState(context.data(), primitive.data(), static_cast<std::uint32_t>(PrimitiveType::PointList)) == 0);
|
||||
Require(context[1].value == kept && primitive[2].value == (0x5a5a5a40u | 1u));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extern "C" void AgcDriverResolveGraphicsStagesAbi_nid_postfix(std::span<const Shader* const> stages, std::span<const ShaderRegister> context, std::span<const ShaderRegister> primitive) {
|
||||
@@ -192,6 +212,7 @@ int main() {
|
||||
Require(preparations == 0 && mappings == 0 && links == 0);
|
||||
OptionalGeometryOutputRegister(special, vertex, hull);
|
||||
HandBuiltUserVgprRegister();
|
||||
UpdatedPrimitiveType();
|
||||
LibcRunShutdown_nid_postfix();
|
||||
std::cout << "shader helper preparation tests passed\n";
|
||||
} catch (const std::exception& error) {
|
||||
|
||||
@@ -561,6 +561,18 @@ if(BUILD_TESTING)
|
||||
"PATH=path_list_prepend:$<TARGET_FILE_DIR:libc>")
|
||||
endif()
|
||||
|
||||
if(WIN32)
|
||||
add_test_executable(agc_worker_sampler_tests tests/WorkerSampler.cpp Execution/src/WorkerSampler.cpp)
|
||||
target_include_directories(agc_worker_sampler_tests PRIVATE ${LIBS_INCLUDE_DIR})
|
||||
target_link_libraries(agc_worker_sampler_tests PRIVATE libc)
|
||||
configure_windows_unwind(agc_worker_sampler_tests)
|
||||
foreach(mode default selected unselected process)
|
||||
add_test(NAME agc_worker_sampler_${mode} COMMAND agc_worker_sampler_tests ${mode})
|
||||
set_tests_properties(agc_worker_sampler_${mode} PROPERTIES TIMEOUT 20 ENVIRONMENT_MODIFICATION
|
||||
"PATH=path_list_prepend:$<TARGET_FILE_DIR:libc>")
|
||||
endforeach()
|
||||
endif()
|
||||
|
||||
add_test_executable(agc_stack_walk_tests tests/StackWalk.cpp)
|
||||
target_include_directories(agc_stack_walk_tests PRIVATE ${LIBS_INCLUDE_DIR})
|
||||
target_link_libraries(agc_stack_walk_tests PRIVATE libc)
|
||||
@@ -880,7 +892,7 @@ if(BUILD_TESTING)
|
||||
if(WIN32)
|
||||
set_tests_properties(agc_thread_priority PROPERTIES ENVIRONMENT_MODIFICATION
|
||||
"PATH=path_list_prepend:$<TARGET_FILE_DIR:libc>")
|
||||
else()
|
||||
elseif(CMAKE_SYSTEM_NAME STREQUAL "Linux")
|
||||
foreach(mode rt high)
|
||||
add_test(NAME agc_thread_priority_refused_${mode} COMMAND agc_thread_priority_tests refused)
|
||||
set_tests_properties(agc_thread_priority_refused_${mode} PROPERTIES ENVIRONMENT
|
||||
@@ -1869,6 +1881,8 @@ if(BUILD_TESTING)
|
||||
set_tests_properties(agc_draw_snapshot_epoch PROPERTIES SKIP_RETURN_CODE 77)
|
||||
add_test(NAME agc_multisample_guest_access COMMAND agc_driver_recorder_tests --multisample-only)
|
||||
set_tests_properties(agc_multisample_guest_access PROPERTIES SKIP_RETURN_CODE 77)
|
||||
add_test(NAME agc_repeat_storage_guard COMMAND agc_driver_recorder_tests --repeat-storage-guard-only)
|
||||
set_tests_properties(agc_repeat_storage_guard PROPERTIES SKIP_RETURN_CODE 77)
|
||||
add_test(NAME agc_draw_inputs_in_place COMMAND agc_driver_recorder_tests --draw-inputs-in-place-only)
|
||||
add_test(NAME agc_pending_write_snapshot COMMAND agc_driver_recorder_tests --pending-write-snapshot-only)
|
||||
set_tests_properties(agc_pending_write_snapshot PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 30)
|
||||
@@ -1889,7 +1903,7 @@ if(BUILD_TESTING)
|
||||
add_test(NAME agc_metadata_pass COMMAND agc_driver_recorder_tests --metadata-pass-only)
|
||||
set_tests_properties(agc_metadata_pass PROPERTIES SKIP_RETURN_CODE 77)
|
||||
if(WIN32)
|
||||
set_tests_properties(agc_recorder_read_list agc_host_import_unmap agc_parked_import_unmap agc_host_import_retirement agc_sparse_run_import agc_sparse_run_import_copied agc_unit_shadow agc_driver_recorder agc_idle_publish_wait agc_descriptor_pool_recycling agc_draw_snapshot_cap agc_draw_snapshot_epoch agc_multisample_guest_access agc_draw_inputs_in_place agc_draw_inputs_copied agc_resident_present agc_slice_dirty agc_queued_write_groups agc_metadata_pass agc_tiled_resolve PROPERTIES ENVIRONMENT_MODIFICATION
|
||||
set_tests_properties(agc_recorder_read_list agc_host_import_unmap agc_parked_import_unmap agc_host_import_retirement agc_sparse_run_import agc_sparse_run_import_copied agc_unit_shadow agc_driver_recorder agc_idle_publish_wait agc_descriptor_pool_recycling agc_draw_snapshot_cap agc_draw_snapshot_epoch agc_multisample_guest_access agc_repeat_storage_guard agc_draw_inputs_in_place agc_draw_inputs_copied agc_resident_present agc_slice_dirty agc_queued_write_groups agc_metadata_pass agc_tiled_resolve PROPERTIES ENVIRONMENT_MODIFICATION
|
||||
"PATH=path_list_prepend:$<TARGET_FILE_DIR:libc>")
|
||||
add_test(NAME agc_host_import_second_mapping COMMAND agc_driver_recorder_tests --host-import-second-mapping-only)
|
||||
set_tests_properties(agc_host_import_second_mapping PROPERTIES SKIP_RETURN_CODE 77 ENVIRONMENT_MODIFICATION
|
||||
@@ -2269,6 +2283,14 @@ set_target_properties(agc_driver_mesh_tests PROPERTIES CXX_EXTENSIONS OFF)
|
||||
configure_windows_unwind(agc_driver_mesh_tests)
|
||||
|
||||
set(ANYPS5_AGC_EXECUTION_TESTS "" CACHE STRING "tests/execution sources to build, by file name without extension; the others build a stub that reports a skip. Empty builds all")
|
||||
add_executable(agc_driver_registration_prepare_budget_tests tests/RegistrationPrepareBudget.cpp)
|
||||
target_include_directories(agc_driver_registration_prepare_budget_tests PRIVATE ${LIBS_INCLUDE_DIR})
|
||||
set_target_properties(agc_driver_registration_prepare_budget_tests PROPERTIES CXX_EXTENSIONS OFF)
|
||||
if(MINGW)
|
||||
target_compile_options(agc_driver_registration_prepare_budget_tests PRIVATE -fasynchronous-unwind-tables)
|
||||
target_link_options(agc_driver_registration_prepare_budget_tests PRIVATE -static -static-libgcc -static-libstdc++)
|
||||
endif()
|
||||
|
||||
file(GLOB agcExecutionTestSources CONFIGURE_DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/tests/execution/*.cpp)
|
||||
set(agcExecutionTests)
|
||||
foreach(agcExecutionTestSource IN LISTS agcExecutionTestSources)
|
||||
@@ -2339,6 +2361,8 @@ foreach(agcExecutionTestName IN LISTS ANYPS5_AGC_EXECUTION_TESTS)
|
||||
endif()
|
||||
endforeach()
|
||||
if(BUILD_TESTING)
|
||||
add_test(NAME agc_driver_registration_prepare_budget COMMAND agc_driver_registration_prepare_budget_tests)
|
||||
set_tests_properties(agc_driver_registration_prepare_budget PROPERTIES TIMEOUT 10)
|
||||
add_test(NAME agc_driver_indirect_thread_dimensions_cpu COMMAND agc_driver_indirect_thread_dimensions_tests)
|
||||
set_tests_properties(agc_driver_indirect_thread_dimensions_cpu PROPERTIES ENVIRONMENT "APS5_NO_GPU_THREAD_DIMENSIONS=1" SKIP_RETURN_CODE 77 TIMEOUT 60)
|
||||
if(WIN32)
|
||||
@@ -2399,19 +2423,27 @@ if(BUILD_TESTING)
|
||||
endif()
|
||||
add_test(NAME agc_submit_progress COMMAND agc_driver_submit_progress_tests)
|
||||
set_tests_properties(agc_submit_progress PROPERTIES
|
||||
ENVIRONMENT "APS5_SUBMIT_PROGRESS=1;ANYPS5_REQUIRE_VULKAN=1" TIMEOUT 30 SKIP_RETURN_CODE 77 WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}")
|
||||
ENVIRONMENT "APS5_SUBMIT_PROGRESS=1" TIMEOUT 30 SKIP_RETURN_CODE 77 WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}")
|
||||
if(WIN32)
|
||||
set_tests_properties(agc_submit_progress PROPERTIES ENVIRONMENT_MODIFICATION
|
||||
"PATH=path_list_prepend:$<TARGET_FILE_DIR:libSceAgcDriver>;PATH=path_list_prepend:$<TARGET_FILE_DIR:libc>")
|
||||
endif()
|
||||
add_test(NAME agc_submit_progress_no_timeline COMMAND agc_driver_submit_progress_tests --fallback-only)
|
||||
set_tests_properties(agc_submit_progress_no_timeline PROPERTIES
|
||||
ENVIRONMENT "APS5_SUBMIT_PROGRESS=1;APS5_NO_TIMELINE=1;ANYPS5_REQUIRE_VULKAN=1"
|
||||
ENVIRONMENT "APS5_SUBMIT_PROGRESS=1;APS5_NO_TIMELINE=1"
|
||||
TIMEOUT 30 SKIP_RETURN_CODE 77 WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}")
|
||||
if(WIN32)
|
||||
set_tests_properties(agc_submit_progress_no_timeline PROPERTIES ENVIRONMENT_MODIFICATION
|
||||
"PATH=path_list_prepend:$<TARGET_FILE_DIR:libSceAgcDriver>;PATH=path_list_prepend:$<TARGET_FILE_DIR:libc>")
|
||||
endif()
|
||||
add_test(NAME agc_driver_vulkan_test_device_no_driver COMMAND agc_driver_vulkan_test_device_tests --no-driver)
|
||||
set_tests_properties(agc_driver_vulkan_test_device_no_driver PROPERTIES
|
||||
ENVIRONMENT "VK_DRIVER_FILES=${CMAKE_CURRENT_BINARY_DIR}/no-vulkan-driver.json;VK_ICD_FILENAMES=${CMAKE_CURRENT_BINARY_DIR}/no-vulkan-driver.json"
|
||||
TIMEOUT 30 SKIP_RETURN_CODE 77 WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}")
|
||||
if(WIN32)
|
||||
set_tests_properties(agc_driver_vulkan_test_device_no_driver PROPERTIES ENVIRONMENT_MODIFICATION
|
||||
"PATH=path_list_prepend:$<TARGET_FILE_DIR:libc>")
|
||||
endif()
|
||||
endif()
|
||||
|
||||
if(BUILD_TESTING)
|
||||
@@ -2718,6 +2750,21 @@ if(BUILD_TESTING)
|
||||
"PATH=path_list_prepend:$<TARGET_FILE_DIR:libc>")
|
||||
endif()
|
||||
endforeach()
|
||||
set_tests_properties(agc_driver_runtime_formatted_store PROPERTIES TIMEOUT 30)
|
||||
foreach(mode IN ITEMS x1 x2 x3 x1_d16 x2_d16 x3_d16 x4_d16)
|
||||
string(REGEX REPLACE "_d16$" "" components "${mode}")
|
||||
set(arguments "--${components}")
|
||||
if(mode MATCHES "_d16$")
|
||||
list(APPEND arguments --d16)
|
||||
endif()
|
||||
add_test(NAME agc_driver_runtime_formatted_store_${mode} COMMAND agc_driver_runtime_formatted_store_tests ${arguments})
|
||||
set_tests_properties(agc_driver_runtime_formatted_store_${mode} PROPERTIES
|
||||
ENVIRONMENT "ANYPS5_NO_SHADER_CACHE=1" SKIP_RETURN_CODE 77 TIMEOUT 30 WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}")
|
||||
if(WIN32)
|
||||
set_tests_properties(agc_driver_runtime_formatted_store_${mode} PROPERTIES ENVIRONMENT_MODIFICATION
|
||||
"PATH=path_list_prepend:$<TARGET_FILE_DIR:libc>")
|
||||
endif()
|
||||
endforeach()
|
||||
add_test(NAME agc_driver_job_manager_compute_capacity COMMAND agc_driver_job_manager_compute_tests barrier_capacity_overflow)
|
||||
set_tests_properties(agc_driver_job_manager_compute_capacity PROPERTIES
|
||||
ENVIRONMENT "ANYPS5_NO_SHADER_CACHE=1" SKIP_RETURN_CODE 77 TIMEOUT 20 WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}")
|
||||
@@ -2830,6 +2877,11 @@ if(BUILD_TESTING)
|
||||
if(WIN32)
|
||||
set_tests_properties(agc_driver_partially_resident_pending_stores PROPERTIES ENVIRONMENT_MODIFICATION "PATH=path_list_prepend:$<TARGET_FILE_DIR:libc>")
|
||||
endif()
|
||||
add_test(NAME agc_shader_disk_cache_pack_ownership COMMAND agc_shader_disk_cache_tests --prebuilt-pack-ownership)
|
||||
set_tests_properties(agc_shader_disk_cache_pack_ownership PROPERTIES TIMEOUT 30 WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}")
|
||||
if(WIN32)
|
||||
set_tests_properties(agc_shader_disk_cache_pack_ownership PROPERTIES ENVIRONMENT_MODIFICATION "PATH=path_list_prepend:$<TARGET_FILE_DIR:libc>")
|
||||
endif()
|
||||
add_test(NAME agc_shader_disk_cache_large_file COMMAND agc_shader_disk_cache_tests --large-file)
|
||||
if(Python3_Interpreter_FOUND)
|
||||
set(housekeepingModes plain)
|
||||
@@ -2944,6 +2996,7 @@ if(BUILD_TESTING)
|
||||
set_tests_properties(agc_pipeline_journal_long_paths PROPERTIES TIMEOUT 30 WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}")
|
||||
add_test(NAME agc_pipeline_library_clear_waits_for_build COMMAND agc_driver_graphics_tests --pipeline-library-clear-waits-for-build)
|
||||
add_test(NAME agc_pipeline_store_lazy_buffer_pool COMMAND agc_driver_graphics_tests --pipeline-store-lazy-buffer-pool)
|
||||
add_test(NAME agc_pipeline_store_touch COMMAND agc_driver_graphics_tests --pipeline-store-touch)
|
||||
add_test(NAME agc_pipeline_store_growth COMMAND agc_driver_graphics_tests --pipeline-store-growth)
|
||||
add_test(NAME agc_pipeline_store_fixed_bound COMMAND agc_driver_graphics_tests --pipeline-store-growth)
|
||||
add_test(NAME agc_pipeline_store_replay_growth COMMAND agc_driver_graphics_tests --pipeline-store-replay-growth)
|
||||
@@ -2951,12 +3004,12 @@ if(BUILD_TESTING)
|
||||
set_tests_properties(agc_pipeline_store_fixed_bound PROPERTIES ENVIRONMENT "APS5_PIPELINE_STORE_ENTRIES=1024")
|
||||
set_tests_properties(agc_pipeline_journal PROPERTIES TIMEOUT 30 WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}")
|
||||
set_tests_properties(agc_pipeline_library_clear_waits_for_build PROPERTIES TIMEOUT 30 WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}")
|
||||
set_tests_properties(agc_pipeline_store_lazy_buffer_pool PROPERTIES TIMEOUT 30 WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}")
|
||||
set_tests_properties(agc_pipeline_store_lazy_buffer_pool agc_pipeline_store_touch PROPERTIES TIMEOUT 30 WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}")
|
||||
if(WIN32)
|
||||
add_test(NAME agc_pipeline_journal_extended_paths COMMAND agc_driver_graphics_tests --pipeline-journal-extended-paths)
|
||||
set_tests_properties(agc_pipeline_journal_extended_paths PROPERTIES TIMEOUT 30 WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}")
|
||||
set_tests_properties(agc_pipeline_journal_long_paths agc_pipeline_journal_extended_paths PROPERTIES ENVIRONMENT_MODIFICATION "PATH=path_list_prepend:$<TARGET_FILE_DIR:libc>")
|
||||
set_tests_properties(agc_pipeline_journal agc_pipeline_library_clear_waits_for_build agc_pipeline_store_lazy_buffer_pool agc_pipeline_store_growth agc_pipeline_store_fixed_bound agc_pipeline_store_replay_growth PROPERTIES ENVIRONMENT_MODIFICATION "PATH=path_list_prepend:$<TARGET_FILE_DIR:libc>")
|
||||
set_tests_properties(agc_pipeline_journal agc_pipeline_library_clear_waits_for_build agc_pipeline_store_lazy_buffer_pool agc_pipeline_store_touch agc_pipeline_store_growth agc_pipeline_store_fixed_bound agc_pipeline_store_replay_growth PROPERTIES ENVIRONMENT_MODIFICATION "PATH=path_list_prepend:$<TARGET_FILE_DIR:libc>")
|
||||
endif()
|
||||
set_tests_properties(agc_driver_sparse_buffer_holes PROPERTIES TIMEOUT 30)
|
||||
if(WIN32)
|
||||
@@ -3263,7 +3316,7 @@ if(BUILD_TESTING)
|
||||
set_tests_properties(agc_driver_pm4_failure agc_driver_pm4_failure_inline agc_descriptor_pool_reset_failure agc_descriptor_cache agc_driver_address_space_teardown PROPERTIES ENVIRONMENT_MODIFICATION
|
||||
"PATH=path_list_prepend:$<TARGET_FILE_DIR:libc>")
|
||||
endif()
|
||||
if(NOT WIN32)
|
||||
if(CMAKE_SYSTEM_NAME STREQUAL "Linux")
|
||||
add_test(NAME agc_driver_pm4_priority_refused COMMAND agc_driver_pm4_tests priority-refused)
|
||||
set_tests_properties(agc_driver_pm4_priority_refused PROPERTIES ENVIRONMENT
|
||||
"ANYPS5_NO_SHADER_CACHE=1;APS5_THREAD_PRIORITY=high;DBUS_SYSTEM_BUS_ADDRESS=unix:path=/nonexistent/aps5-no-rtkit" SKIP_RETURN_CODE 77)
|
||||
@@ -3350,6 +3403,20 @@ if(BUILD_TESTING)
|
||||
endif()
|
||||
endforeach()
|
||||
endforeach()
|
||||
add_test(NAME agc_driver_depth_plane_cpu_write_after_page_unwatch COMMAND agc_driver_depth_plane_partial_store_tests --cpu-write-after-page-unwatch)
|
||||
set_tests_properties(agc_driver_depth_plane_cpu_write_after_page_unwatch PROPERTIES
|
||||
ENVIRONMENT "ANYPS5_NO_SHADER_CACHE=1" TIMEOUT 30 SKIP_RETURN_CODE 77 WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}")
|
||||
if(WIN32)
|
||||
set_tests_properties(agc_driver_depth_plane_cpu_write_after_page_unwatch PROPERTIES ENVIRONMENT_MODIFICATION
|
||||
"PATH=path_list_prepend:$<TARGET_FILE_DIR:libc>")
|
||||
endif()
|
||||
add_test(NAME agc_driver_depth_plane_cpu_write_after_partial_unwatch COMMAND agc_driver_depth_plane_partial_store_tests --cpu-write-after-partial-unwatch)
|
||||
set_tests_properties(agc_driver_depth_plane_cpu_write_after_partial_unwatch PROPERTIES
|
||||
ENVIRONMENT "ANYPS5_NO_SHADER_CACHE=1" TIMEOUT 30 SKIP_RETURN_CODE 77 WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}")
|
||||
if(WIN32)
|
||||
set_tests_properties(agc_driver_depth_plane_cpu_write_after_partial_unwatch PROPERTIES ENVIRONMENT_MODIFICATION
|
||||
"PATH=path_list_prepend:$<TARGET_FILE_DIR:libc>")
|
||||
endif()
|
||||
add_test(NAME agc_driver_depth_plane_cpu_write_after_memo COMMAND agc_driver_depth_plane_partial_store_tests --cpu-write-after-memo)
|
||||
set_tests_properties(agc_driver_depth_plane_cpu_write_after_memo PROPERTIES
|
||||
ENVIRONMENT "ANYPS5_NO_SHADER_CACHE=1" TIMEOUT 30 SKIP_RETURN_CODE 77 WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}")
|
||||
@@ -3374,7 +3441,7 @@ if(BUILD_TESTING)
|
||||
set_tests_properties(agc_driver_array_layer_target_cpu PROPERTIES ENVIRONMENT_MODIFICATION
|
||||
"PATH=path_list_prepend:$<TARGET_FILE_DIR:libc>")
|
||||
endif()
|
||||
foreach(preparedMode IN ITEMS indirect uncached debug debug_failure deferred deferred_undecodable registered_workgroup registered_workgroup_sync dispatch_ahead_prewarm abi_deferred_compute abi_deferred_pixel abi_deferred_stages abi_deferred_rectangle abi_deferred_undecodable_state abi_deferred_registration_failure abi_deferred_vertex_inputs abi_deferred_rectangle_pairs lazy lazy_sync)
|
||||
foreach(preparedMode IN ITEMS indirect uncached debug debug_failure deferred deferred_undecodable registered_workgroup registered_workgroup_sync dispatch_ahead_prewarm abi_deferred_compute abi_deferred_pixel abi_deferred_stages abi_deferred_rectangle abi_deferred_undecodable_state abi_deferred_registration_failure abi_deferred_vertex_inputs abi_deferred_rectangle_pairs lazy lazy_sync lazy_budget_zero)
|
||||
set(preparedTest "agc_driver_prepared_shaders_${preparedMode}")
|
||||
if(preparedMode MATCHES "^abi_deferred_")
|
||||
string(REPLACE "_" "-" preparedArgument ${preparedMode})
|
||||
@@ -3385,7 +3452,7 @@ if(BUILD_TESTING)
|
||||
add_test(NAME ${preparedTest} COMMAND agc_driver_prepared_shaders_tests --deferred)
|
||||
elseif(preparedMode STREQUAL "deferred_undecodable")
|
||||
add_test(NAME ${preparedTest} COMMAND agc_driver_prepared_shaders_tests --deferred-undecodable)
|
||||
elseif(preparedMode STREQUAL "lazy" OR preparedMode STREQUAL "lazy_sync")
|
||||
elseif(preparedMode STREQUAL "lazy" OR preparedMode STREQUAL "lazy_sync" OR preparedMode STREQUAL "lazy_budget_zero")
|
||||
add_test(NAME ${preparedTest} COMMAND agc_driver_prepared_shaders_tests --lazy)
|
||||
elseif(preparedMode STREQUAL "registered_workgroup" OR preparedMode STREQUAL "registered_workgroup_sync")
|
||||
add_test(NAME ${preparedTest} COMMAND agc_driver_prepared_shaders_tests --registered-workgroup)
|
||||
@@ -3409,6 +3476,8 @@ if(BUILD_TESTING)
|
||||
if(preparedMode STREQUAL "lazy_sync")
|
||||
set_property(TEST ${preparedTest} APPEND PROPERTY ENVIRONMENT "APS5_SYNC_SHADER_PREPARE=1")
|
||||
endif()
|
||||
elseif(preparedMode STREQUAL "lazy_budget_zero")
|
||||
set_property(TEST ${preparedTest} APPEND PROPERTY ENVIRONMENT "APS5_REGISTRATION_PREPARE_COMMIT_GB=0" "APS5_SUSPEND_DRAIN=1")
|
||||
elseif(preparedMode STREQUAL "debug" OR preparedMode STREQUAL "debug_failure")
|
||||
set_property(TEST ${preparedTest} APPEND PROPERTY ENVIRONMENT "APS5_PROFILE_DRAW=1" "APS5_NO_UNLOCKED_DEVICE=1")
|
||||
endif()
|
||||
|
||||
@@ -8,5 +8,7 @@ bool AgcDriverDeliverEopInterrupt(std::uint32_t queue);
|
||||
|
||||
extern "C" int APS5_VABI sceAgcDriverAddEqEvent(KernelEqueue eq, int id, void* udata);
|
||||
extern "C" int APS5_VABI sceAgcDriverDeleteEqEvent(KernelEqueue eq, int id);
|
||||
extern "C" int AgcDriverAddQueueEqEvent_nid_postfix(KernelEqueue eq, std::uint32_t queue, std::uintptr_t ident, void* udata);
|
||||
extern "C" int AgcDriverDeleteQueueEqEvent_nid_postfix(KernelEqueue eq, std::uintptr_t ident);
|
||||
|
||||
#endif
|
||||
@@ -18,38 +18,19 @@ constexpr int16_t EvfiltGraphicsCore = -14;
|
||||
|
||||
struct Registration {
|
||||
KernelEqueue eq;
|
||||
int id;
|
||||
std::uint32_t queue;
|
||||
std::uintptr_t ident;
|
||||
};
|
||||
|
||||
AgcDriver::Mutex g_mutex;
|
||||
std::vector<Registration> g_registrations;
|
||||
|
||||
}
|
||||
|
||||
bool AgcDriverDeliverEopInterrupt(std::uint32_t queue) {
|
||||
std::vector<Registration> registrations;
|
||||
{
|
||||
std::lock_guard lock(g_mutex);
|
||||
registrations = g_registrations;
|
||||
}
|
||||
bool delivered = false;
|
||||
for (const auto& registration : registrations) {
|
||||
if (registration.id == static_cast<int>(queue)) {
|
||||
EqueueTriggerEvent_nid_postfix(registration.eq, static_cast<uintptr_t>(registration.id), EvfiltGraphicsCore, nullptr);
|
||||
delivered = true;
|
||||
}
|
||||
}
|
||||
return delivered;
|
||||
}
|
||||
|
||||
extern "C" {
|
||||
|
||||
int APS5_VABI sceAgcDriverAddEqEvent(KernelEqueue eq, int id, void* udata) {
|
||||
int AddEvent(KernelEqueue eq, std::uint32_t queue, std::uintptr_t ident, void* udata, const char* caller) {
|
||||
if (eq == 0 || !EqueuePin_nid_postfix(eq)) {
|
||||
throw std::runtime_error(std::string(__func__) + ": invalid event queue");
|
||||
throw std::runtime_error(std::string(caller) + ": invalid event queue");
|
||||
}
|
||||
KernelEqueueEvent event{};
|
||||
event.event.ident = static_cast<uintptr_t>(id);
|
||||
event.event.ident = ident;
|
||||
event.event.filter = EvfiltGraphicsCore;
|
||||
event.event.flags = EV_ADD | EV_CLEAR;
|
||||
event.event.udata = udata;
|
||||
@@ -63,24 +44,60 @@ int APS5_VABI sceAgcDriverAddEqEvent(KernelEqueue eq, int id, void* udata) {
|
||||
};
|
||||
const int result = EqueueAddEvent_nid_postfix(eq, event);
|
||||
if (result != EQUEUE_OK) {
|
||||
throw std::runtime_error(std::string(__func__) + ": event queue rejected the event");
|
||||
throw std::runtime_error(std::string(caller) + ": event queue rejected the event");
|
||||
}
|
||||
std::lock_guard lock(g_mutex);
|
||||
if (std::none_of(g_registrations.begin(), g_registrations.end(), [&](const Registration& r) { return r.eq == eq && r.id == id; })) {
|
||||
g_registrations.push_back({eq, id});
|
||||
if (std::none_of(g_registrations.begin(), g_registrations.end(), [&](const Registration& r) { return r.eq == eq && r.ident == ident; })) {
|
||||
g_registrations.push_back({eq, queue, ident});
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
int DeleteEvent(KernelEqueue eq, std::uintptr_t ident, const char* caller) {
|
||||
{
|
||||
std::lock_guard lock(g_mutex);
|
||||
std::erase_if(g_registrations, [&](const Registration& r) { return r.eq == eq && r.ident == ident; });
|
||||
}
|
||||
if (EqueueDeleteEvent_nid_postfix(eq, ident, EvfiltGraphicsCore) != EQUEUE_OK) {
|
||||
throw std::runtime_error(std::string(caller) + ": event is not registered");
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
bool AgcDriverDeliverEopInterrupt(std::uint32_t queue) {
|
||||
std::vector<Registration> registrations;
|
||||
{
|
||||
std::lock_guard lock(g_mutex);
|
||||
registrations = g_registrations;
|
||||
}
|
||||
bool delivered = false;
|
||||
for (const auto& registration : registrations) {
|
||||
if (registration.queue == queue) {
|
||||
EqueueTriggerEvent_nid_postfix(registration.eq, registration.ident, EvfiltGraphicsCore, nullptr);
|
||||
delivered = true;
|
||||
}
|
||||
}
|
||||
return delivered;
|
||||
}
|
||||
|
||||
extern "C" {
|
||||
|
||||
int APS5_VABI sceAgcDriverAddEqEvent(KernelEqueue eq, int id, void* udata) {
|
||||
return AddEvent(eq, static_cast<std::uint32_t>(id), static_cast<std::uintptr_t>(id), udata, __func__);
|
||||
}
|
||||
|
||||
int APS5_VABI sceAgcDriverDeleteEqEvent(KernelEqueue eq, int id) {
|
||||
{
|
||||
std::lock_guard lock(g_mutex);
|
||||
std::erase_if(g_registrations, [&](const Registration& r) { return r.eq == eq && r.id == id; });
|
||||
}
|
||||
if (EqueueDeleteEvent_nid_postfix(eq, static_cast<uintptr_t>(id), EvfiltGraphicsCore) != EQUEUE_OK) {
|
||||
throw std::runtime_error(std::string(__func__) + ": event is not registered");
|
||||
}
|
||||
return 0;
|
||||
return DeleteEvent(eq, static_cast<std::uintptr_t>(id), __func__);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
extern "C" int AgcDriverAddQueueEqEvent_nid_postfix(KernelEqueue eq, std::uint32_t queue, std::uintptr_t ident, void* udata) {
|
||||
return AddEvent(eq, queue, ident, udata, __func__);
|
||||
}
|
||||
|
||||
extern "C" int AgcDriverDeleteQueueEqEvent_nid_postfix(KernelEqueue eq, std::uintptr_t ident) {
|
||||
return DeleteEvent(eq, ident, __func__);
|
||||
}
|
||||
@@ -25,6 +25,8 @@ struct DisplayBuffer {
|
||||
std::uint32_t alignment = 65536;
|
||||
};
|
||||
|
||||
inline constexpr std::uint32_t DisplayTilingGcn = 2;
|
||||
|
||||
std::size_t DisplayBufferSize(const DisplayBuffer& buffer);
|
||||
std::size_t DisplayBufferOffset(const DisplayBuffer& buffer, std::uint32_t x, std::uint32_t y);
|
||||
std::vector<std::byte> DecodeDisplayBuffer(const DisplayBuffer& buffer, std::span<const std::byte> source);
|
||||
|
||||
@@ -24,6 +24,8 @@ struct AwaitedWait {
|
||||
|
||||
extern "C" void AgcDriverPrepareCommandWrite_nid_no_patch(std::uint64_t address, std::size_t bytes);
|
||||
extern "C" void AgcDriverWaitIdle_nid_postfix();
|
||||
extern "C" void AgcDriverSubmitGraphics_nid_postfix(std::uint32_t* commands, std::uint32_t dwords);
|
||||
extern "C" void AgcDriverUseGcnShaders_nid_postfix();
|
||||
extern "C" void AgcDriverRaiseWorkerThreadPriority_nid_postfix(const char* role);
|
||||
extern "C" void AgcDriverLockVulkanLoader_nid_postfix();
|
||||
extern "C" void AgcDriverUnlockVulkanLoader_nid_postfix();
|
||||
|
||||
@@ -50,6 +50,10 @@ struct OverlayDriverCounters;
|
||||
|
||||
namespace AgcDriver::DriverDetail {
|
||||
|
||||
inline std::uint32_t ThreadDimensionGroups(std::uint32_t threads, std::uint32_t groupThreads) {
|
||||
return static_cast<std::uint32_t>((std::uint64_t{threads} + groupThreads - 1u) / groupThreads);
|
||||
}
|
||||
|
||||
struct DrawTail;
|
||||
|
||||
class Driver {
|
||||
@@ -99,6 +103,7 @@ public:
|
||||
static std::optional<Graphics::IndirectDrawPath> ClassifyIndirectDraw(const ShaderRecompiler::RecompileResult& result, const Graphics::State& graphics, const DrawProgram& frontProgram, const std::shared_ptr<VulkanDevice>& localDevice, Pm4::DrawParameters& drawParameters, bool traceIndirect);
|
||||
static void tagVariantRuns(DispatchVariant& variant, std::span<const ShaderRecompiler::MemoryRegion> regions, const ShaderRecompiler::SrtUserDataUse& use, bool eligible, std::uint32_t hiddenWords, std::span<const std::shared_ptr<const ShaderRecompiler::SrtGuestWords>> supplied = {});
|
||||
static std::string dumpRequest(std::uint64_t address, const ShaderRecompiler::RecompileRequest& request, std::string_view suffix = {});
|
||||
static void reportSkip(const char* kind, const std::string& what);
|
||||
DrawEntryCounters DrawCacheCounters();
|
||||
OverlayDriverCounters OverlayCounters();
|
||||
EntryCounters DispatchCacheCounters();
|
||||
@@ -218,7 +223,6 @@ private:
|
||||
static std::size_t& writeCursor();
|
||||
static void dumpPackets(std::span<const std::uint32_t> commands, const std::uint32_t* guest = nullptr);
|
||||
static void validate(const Submission& submission, const std::uint32_t* guest = nullptr);
|
||||
static void reportSkip(const char* kind, const std::string& what);
|
||||
static bool matchesFillKernel(std::span<const std::uint32_t> code, const std::vector<std::uint32_t>& userData, const ShaderRecompiler::ShaderComputeStageInfo& compute);
|
||||
static bool fillClearEnabled();
|
||||
static bool fillClearExactOnly();
|
||||
@@ -277,7 +281,7 @@ private:
|
||||
void noteForeignWriter(std::uint64_t begin, std::uint64_t end, std::uint32_t queue);
|
||||
void noteDrawWriters(std::span<const Graphics::CompiledShader> stages, std::uint32_t queue);
|
||||
static std::vector<std::pair<std::uint64_t, std::uint64_t>> drawWriteRanges(const Graphics::State& graphics, std::span<const Graphics::CompiledShader> stages);
|
||||
void commitDraw(std::shared_ptr<VulkanDevice> localDevice, std::uint32_t queue, const Graphics::State& graphics, const Pm4::DrawParameters& drawParameters, std::span<const Graphics::CompiledShader> stages, std::span<const Graphics::GuestMemorySnapshot> snapshots, const std::shared_ptr<const DrawRecipe>& recipe, const std::vector<std::shared_ptr<DispatchVariant>>& recipeStages, std::uint64_t drawKey, VulkanDevice::DrawTraceContext trace = {});
|
||||
void commitDraw(std::shared_ptr<VulkanDevice> localDevice, std::uint32_t queue, const Graphics::State& graphics, const Pm4::DrawParameters& drawParameters, std::span<const Graphics::CompiledShader> stages, std::span<const Graphics::GuestMemorySnapshot> snapshots, const std::shared_ptr<const DrawRecipe>& recipe, const std::vector<std::shared_ptr<DispatchVariant>>& recipeStages, std::uint64_t drawKey, VulkanDevice::DrawTraceContext trace = {}, std::uint64_t shape = 0);
|
||||
bool labelPacketQueues(std::span<const std::uint32_t> packet, std::uint32_t opcode);
|
||||
bool enqueueLabelPacket(std::span<const std::uint32_t> packet, std::uint32_t opcode, std::uint32_t queue);
|
||||
bool enqueueDmaPacket(std::span<const std::uint32_t> packet, std::uint32_t opcode, std::uint32_t queue, const QueueState& state);
|
||||
|
||||
@@ -40,6 +40,30 @@ struct PatternFillRange {
|
||||
}
|
||||
};
|
||||
|
||||
inline constexpr std::array<std::uint32_t, 18> GcnPatternFillKernel{
|
||||
0xbeeb03ffu, 0x0000000bu, 0x8f008610u, 0x4a000000u, 0xc2400d00u, 0xbf8c007fu,
|
||||
0x7d880000u, 0xbe82246au, 0x36020001u, 0xbf880007u, 0xe0002000u, 0x80010101u,
|
||||
0x7d88000au, 0xbe80246au, 0xbf8c0f70u, 0xe0102000u, 0x80020100u, 0xbf810000u
|
||||
};
|
||||
|
||||
inline bool MatchesGcnPatternFillKernel(std::span<const std::uint32_t> code, std::span<const std::uint32_t> userData, const ShaderRecompiler::ShaderComputeStageInfo& compute) {
|
||||
if (userData.size() != 16 || compute.numThreads != std::array<std::uint32_t, 3>{64, 1, 1} || !compute.groupIdEnable[0] || compute.threadIdComponentCount != 1) return false;
|
||||
if (code.size() < GcnPatternFillKernel.size() || !std::equal(GcnPatternFillKernel.begin(), GcnPatternFillKernel.end(), code.begin())) return false;
|
||||
for (const auto first : {4u, 8u}) {
|
||||
if ((userData[first + 1] & 0xbfff0000u) != 0x00040000u || (userData[first + 3] & 0xc087f000u) != 0x00024000u) return false;
|
||||
}
|
||||
return (userData[7] & 7u) == 4u && userData[6] >= 1 && userData[14] >= 1;
|
||||
}
|
||||
|
||||
inline std::optional<PatternFillRange> DecodeGcnPatternFillRange(std::span<const std::uint32_t> userData, std::span<const std::uint32_t> packet) {
|
||||
if (userData.size() != 16 || packet.size() < 5 || packet[2] != 1 || packet[3] != 1) return std::nullopt;
|
||||
const std::uint64_t invocations = (packet[4] & 0x20u) != 0 ? packet[1] : std::uint64_t{packet[1]} * 64u;
|
||||
if (invocations > (std::uint64_t{1} << 32u)) return std::nullopt;
|
||||
const auto base = [&](std::size_t word) { return userData[word] | (static_cast<std::uint64_t>(userData[word + 1] & 0xfffu) << 32u); };
|
||||
if (base(4) % 4 != 0 || base(12) % 4 != 0) return std::nullopt;
|
||||
return PatternFillRange{base(4), base(8), base(12), invocations, userData[10]};
|
||||
}
|
||||
|
||||
inline std::optional<PatternFillRange> DecodePatternFillRange(std::span<const std::uint32_t> userData, std::span<const std::uint32_t> packet) {
|
||||
if (userData.size() != 12 || packet.size() < 5 || packet[2] != 1 || packet[3] != 1) return std::nullopt;
|
||||
const std::uint64_t invocations = (packet[4] & 0x20u) != 0 ? packet[1] : std::uint64_t{packet[1]} * 64u;
|
||||
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
#ifndef CORE_LIBS_PRX_LIBSCEAGCDRIVER_EXECUTION_INCLUDE_DRIVER_SHADERS_REGISTRATIONPREPARATIONBUDGET_HPP
|
||||
#define CORE_LIBS_PRX_LIBSCEAGCDRIVER_EXECUTION_INCLUDE_DRIVER_SHADERS_REGISTRATIONPREPARATIONBUDGET_HPP
|
||||
|
||||
#include <cerrno>
|
||||
#include <cmath>
|
||||
#include <cstdlib>
|
||||
#include <cstdint>
|
||||
#include <limits>
|
||||
#include <stdexcept>
|
||||
|
||||
namespace AgcDriver::DriverDetail {
|
||||
|
||||
inline std::uint64_t RegistrationPreparationCommitBudgetBytes(const char* text, std::uint64_t defaultBudgetBytes) {
|
||||
if (text == nullptr) return defaultBudgetBytes;
|
||||
constexpr double GiB = 1024.0 * 1024.0 * 1024.0;
|
||||
char* end = nullptr;
|
||||
errno = 0;
|
||||
const auto value = std::strtod(text, &end);
|
||||
if (errno != 0 || end == text || *end != '\0' || !std::isfinite(value) || value < 0 || value >= static_cast<double>(std::numeric_limits<std::uint64_t>::max()) / GiB) {
|
||||
throw std::runtime_error("APS5_REGISTRATION_PREPARE_COMMIT_GB must be a non-negative number of GiB");
|
||||
}
|
||||
return static_cast<std::uint64_t>(value * GiB);
|
||||
}
|
||||
|
||||
constexpr bool RegistrationPreparationAllowed(std::uint64_t processPrivateBytes, std::uint64_t commitBudgetBytes) noexcept {
|
||||
return processPrivateBytes < commitBudgetBytes;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -52,6 +52,8 @@ void Write(std::uint64_t address, std::span<const std::byte> source, std::size_t
|
||||
// Stores the parts of `current` that differ from `original` (the guest bytes the GPU started from), so
|
||||
// guest writes made meanwhile to untouched bytes survive. Compares in 256-byte blocks.
|
||||
void WriteChanged(std::uint64_t address, std::span<const std::byte> current, std::span<const std::byte> original);
|
||||
void WriteChanged(std::uint64_t address, std::span<const std::byte> current, std::span<const std::byte> original, std::uint32_t byteStoreLimit);
|
||||
std::uint32_t ChangedByteStoreLimit();
|
||||
|
||||
// Write tracking. The guest arena is reserved with page write watching, so CollectWrites learns which
|
||||
// pages of a range the CPU wrote since they were last collected, stamps their 64 KiB blocks with a new
|
||||
|
||||
@@ -257,6 +257,7 @@ std::optional<std::uint64_t> ReadProcessPrivateBytes();
|
||||
std::optional<OverlayMemory> ParseCommitCharge(std::string_view meminfo);
|
||||
std::optional<OverlayMemory> ReadCommitCharge();
|
||||
std::optional<std::uint64_t> ReadPageFaults();
|
||||
std::optional<std::uint64_t> ReadPhysicalMemoryBytes();
|
||||
std::int32_t OverlayScale(VkExtent2D extent, const OverlayContent& content);
|
||||
OverlayLayout LayOutOverlay(const OverlayContent& content, VkExtent2D extent, OverlayCorner corner);
|
||||
std::array<std::array<float, 4>, OverlayColorCount> OverlayPalette(VkFormat format, VkColorSpaceKHR colorSpace);
|
||||
|
||||
@@ -13,6 +13,10 @@ inline bool WorkgroupScopeFenceUsable(VkDriverId driver) {
|
||||
return driver != VK_DRIVER_ID_AMD_PROPRIETARY;
|
||||
}
|
||||
|
||||
inline bool LdsLockFencesRequired(VkDriverId driver) {
|
||||
return driver == VK_DRIVER_ID_MOLTENVK;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -17,6 +17,7 @@
|
||||
#include <memory>
|
||||
#include <optional>
|
||||
#include <span>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
#include <utility>
|
||||
|
||||
@@ -51,6 +52,11 @@ struct DeviceQueuePlan {
|
||||
|
||||
DeviceQueuePlan PlanDeviceQueues(std::span<const VkQueueFamilyProperties> families, std::uint32_t family, bool settles, bool sparseBinding, bool presents);
|
||||
|
||||
class VulkanUnavailable final : public std::runtime_error {
|
||||
public:
|
||||
using std::runtime_error::runtime_error;
|
||||
};
|
||||
|
||||
class VulkanDevice {
|
||||
public:
|
||||
explicit VulkanDevice(const PresentationWindow* window = nullptr);
|
||||
@@ -344,7 +350,7 @@ public:
|
||||
using DrawTraceContext = Graphics::DrawTraceContext;
|
||||
// `recipe`, when given, receives the DrawRecipe a recorded, cacheable, reusable, direct draw
|
||||
// built for its draw-cache entry (design_cpu_final M8); null otherwise.
|
||||
void Draw(const Graphics::State& graphics, const Pm4::DrawParameters& draw, std::span<const Graphics::CompiledShader> shaders, std::span<const Graphics::GuestMemorySnapshot> snapshots = {}, std::shared_ptr<const DrawRecipe>* recipe = nullptr, const DrawTraceContext* trace = nullptr);
|
||||
void Draw(const Graphics::State& graphics, const Pm4::DrawParameters& draw, std::span<const Graphics::CompiledShader> shaders, std::span<const Graphics::GuestMemorySnapshot> snapshots = {}, std::shared_ptr<const DrawRecipe>* recipe = nullptr, const DrawTraceContext* trace = nullptr, std::uint64_t shape = 0);
|
||||
bool DrawInputsInPlace() const;
|
||||
std::optional<std::string> KnownDrawRejection(const Graphics::State& graphics, std::span<const Graphics::CompiledShader> shaders) const;
|
||||
void ColorMetadataPass(const Graphics::ColorMetadataPass& pass);
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
#ifndef CORE_LIBS_PRX_LIBSCEAGCDRIVER_EXECUTION_INCLUDE_WORKERSAMPLER_HPP
|
||||
#define CORE_LIBS_PRX_LIBSCEAGCDRIVER_EXECUTION_INCLUDE_WORKERSAMPLER_HPP
|
||||
|
||||
#include <cstdint>
|
||||
|
||||
namespace AgcDriver {
|
||||
|
||||
// Starts sampling the calling thread when APS5_SAMPLE_WORKER names an output file.
|
||||
void StartWorkerSampler();
|
||||
void StartWorkerSampler(std::uint32_t queue = 0);
|
||||
void StartCommitterSampler();
|
||||
void StopWorkerSampler();
|
||||
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
#include "prx/libSceAgcDriver/Execution/include/GuestMemory.hpp"
|
||||
#include "prx/libSceAgcDriver/Execution/include/PerformanceTimer.hpp"
|
||||
#include "prx/libSceAgcDriver/Execution/include/HostHdr.hpp"
|
||||
#include "prx/libSceAgcDriver/Graphics/include/ColorTargetLayout.hpp"
|
||||
#include "prx/libSceAgcDriver/Graphics/include/DccMetadata.hpp"
|
||||
#include "prx/libSceAgcDriver/Graphics/include/HalfFloatScanout.hpp"
|
||||
#include <algorithm>
|
||||
@@ -12,6 +13,7 @@
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <limits>
|
||||
#include <optional>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
|
||||
@@ -39,7 +41,19 @@ std::uint32_t tileOffset64(std::uint32_t x, std::uint32_t y) {
|
||||
return ((x << 3u) & 0x0008u) ^ ((x << 4u) & 0x0460u) ^ ((x << 5u) & 0x0300u) ^ ((x << 6u) & 0x0800u) ^ ((x << 9u) & 0x8000u) ^ ((x << 10u) & 0x2000u) ^ ((y << 4u) & 0x0010u) ^ ((y << 6u) & 0x0080u) ^ ((y << 5u) & 0x0f00u) ^ ((y << 10u) & 0x5000u);
|
||||
}
|
||||
|
||||
const Graphics::ColorTargetLayout& gcnLayout(const DisplayBuffer& buffer, std::uint32_t texelBytes) {
|
||||
thread_local std::optional<Graphics::ColorTargetLayout> layout;
|
||||
thread_local std::array<std::uint32_t, 3> key{};
|
||||
const std::array<std::uint32_t, 3> wanted{buffer.pitchInPixel, buffer.height, texelBytes};
|
||||
if (!layout || key != wanted) {
|
||||
layout.emplace(buffer.pitchInPixel, buffer.height, Graphics::ColorTileMode::GcnDisplay2D, texelBytes);
|
||||
key = wanted;
|
||||
}
|
||||
return *layout;
|
||||
}
|
||||
|
||||
std::size_t texelOffset(const DisplayBuffer& buffer, std::uint32_t x, std::uint32_t y, std::uint32_t texelBytes) {
|
||||
if (buffer.tilingMode == DisplayTilingGcn) return gcnLayout(buffer, texelBytes).Offset(x, y);
|
||||
if (buffer.tilingMode == 1) {
|
||||
const auto pitch = buffer.pitchInPixel == 0 ? buffer.width : buffer.pitchInPixel;
|
||||
return (static_cast<std::size_t>(y) * pitch + x) * texelBytes;
|
||||
@@ -130,9 +144,14 @@ std::size_t DisplayBufferSize(const DisplayBuffer& buffer) {
|
||||
throw std::runtime_error(message);
|
||||
}
|
||||
require(!halfFloat || buffer.dccAddress == 0, "VideoOut: DCC metadata on a 16-bit float display buffer is not implemented");
|
||||
require(buffer.alignment == 65536u || (buffer.alignment == 4096u && buffer.tilingMode == 1), "VideoOut: 4 KiB display buffer alignment is only supported for linear buffers");
|
||||
require(buffer.alignment == 65536u || (buffer.alignment == 4096u && (buffer.tilingMode == 1 || buffer.tilingMode == DisplayTilingGcn)), "VideoOut: 4 KiB display buffer alignment is only supported for linear and PS4 buffers");
|
||||
require(buffer.address != 0 && (buffer.address & (buffer.alignment - 1u)) == 0, buffer.alignment == 65536u ? "VideoOut: display buffer requires 64 KiB alignment" : "VideoOut: display buffer requires 4 KiB alignment");
|
||||
require(buffer.tilingMode <= 1, "VideoOut: unsupported display tiling mode");
|
||||
require(buffer.tilingMode <= 1 || buffer.tilingMode == DisplayTilingGcn, "VideoOut: unsupported display tiling mode");
|
||||
if (buffer.tilingMode == DisplayTilingGcn) {
|
||||
require(buffer.dccAddress == 0 && !DisplayHalfFloat(buffer.pixelFormat), "VideoOut: PS4 display buffers carry no DCC and no half-float texels");
|
||||
require(buffer.pitchInPixel >= buffer.width && buffer.pitchInPixel % 128u == 0, "VideoOut: PS4 tiled display pitch is not padded to 128 pixels");
|
||||
return gcnLayout(buffer, DisplayTexelBytes(buffer.pixelFormat)).Bytes();
|
||||
}
|
||||
require(buffer.tilingMode != 0 || buffer.pitchInPixel == 0, "VideoOut: tiled display pitch is unsupported");
|
||||
require(buffer.dccAddress == 0 || buffer.tilingMode == 0, "VideoOut: a linear display buffer cannot carry DCC metadata");
|
||||
require(buffer.dccAddress != 0 || buffer.dccClearColor == 0, "VideoOut: a DCC clear color needs DCC metadata");
|
||||
|
||||
@@ -458,7 +458,7 @@ void Driver::dispatch(QueueState& queue, std::span<const std::uint32_t> packet,
|
||||
|
||||
for (std::uint32_t axis = 0; axis < 3; ++axis) {
|
||||
const auto threads = std::max(readRegister(queue.shader, 0x207 + axis) & 0xffffu, 1u);
|
||||
groups[axis] = (groups[axis] + threads - 1) / threads;
|
||||
groups[axis] = ThreadDimensionGroups(groups[axis], threads);
|
||||
}
|
||||
}
|
||||
const std::uint64_t dispatchThreads = indirectArguments != 0 ? 0 : std::uint64_t{groups[0]} * groups[1] * groups[2] * compute.numThreads[0] * compute.numThreads[1] * compute.numThreads[2];
|
||||
|
||||
@@ -1245,10 +1245,10 @@ DrawVerdict Driver::finishDraw(DrawTail& tail, PerformanceTimer& timing) {
|
||||
const auto commitPacket = tail.packetOpcode;
|
||||
const auto epoch = DrawFinisher::OnFinisherThread() ? tail.epoch : DrawPipeline::EpochToken().load(std::memory_order_relaxed);
|
||||
auto reads = QueuedDrawReadRanges(drawParameters, stages);
|
||||
auto commit = [this, localDevice = std::move(localDevice), decode = std::move(decode), drawParameters, stages = std::move(stages), snapshots = std::move(snapshots), recipe = std::move(recipe), recipeStages = std::move(recipeStages), drawKey, commitQueue, commitPacket, epoch, trace = trace, writablePrograms = std::move(writablePrograms), results = std::move(results), memory = std::move(memory), linked = std::move(linked), stageCaptures = std::move(stageCaptures), matched = std::move(matched), matchedRegions = std::move(matchedRegions), fresh = std::move(fresh), decodeReads = std::move(decodeReads), shaderMemory = std::move(shaderMemory), entry = std::move(entry), dataEntry = std::move(dataEntry), compiledStages = std::move(compiledStages), stageData = std::move(stageData)]() mutable {
|
||||
auto commit = [this, localDevice = std::move(localDevice), decode = std::move(decode), drawParameters, stages = std::move(stages), snapshots = std::move(snapshots), recipe = std::move(recipe), recipeStages = std::move(recipeStages), drawKey, shape = tail.shapeKey, commitQueue, commitPacket, epoch, trace = trace, writablePrograms = std::move(writablePrograms), results = std::move(results), memory = std::move(memory), linked = std::move(linked), stageCaptures = std::move(stageCaptures), matched = std::move(matched), matchedRegions = std::move(matchedRegions), fresh = std::move(fresh), decodeReads = std::move(decodeReads), shaderMemory = std::move(shaderMemory), entry = std::move(entry), dataEntry = std::move(dataEntry), compiledStages = std::move(compiledStages), stageData = std::move(stageData)]() mutable {
|
||||
DrawPipeline::FollowEpoch(epoch);
|
||||
GuestMemory::SetCurrentPacket(commitPacket, commitQueue);
|
||||
commitDraw(localDevice, commitQueue, decode->state, drawParameters, stages, snapshots, recipe, recipeStages, drawKey, trace);
|
||||
commitDraw(localDevice, commitQueue, decode->state, drawParameters, stages, snapshots, recipe, recipeStages, drawKey, trace, shape);
|
||||
};
|
||||
auto held = std::make_shared<decltype(commit)>(std::move(commit));
|
||||
DrawPipeline::Queue0().Enqueue([held] { (*held)(); }, std::move(writes), 0, {}, std::move(reads), true);
|
||||
@@ -1270,14 +1270,14 @@ DrawVerdict Driver::finishDraw(DrawTail& tail, PerformanceTimer& timing) {
|
||||
VulkanDevice::NoteRecipe(VulkanDevice::RecipeEvent::Restart, VulkanDevice::RecipeKind::Draw);
|
||||
}
|
||||
std::shared_ptr<const DrawRecipe> built;
|
||||
localDevice->Draw(graphics, drawParameters, stages, snapshots, recipeStages.empty() ? nullptr : &built, tracePtr);
|
||||
localDevice->Draw(graphics, drawParameters, stages, snapshots, recipeStages.empty() ? nullptr : &built, tracePtr, tail.shapeKey);
|
||||
phaseTiming.Phase(DrawRowGraphics);
|
||||
if (built != nullptr) attachDrawRecipe(drawKey, recipeStages, std::move(built));
|
||||
timing.Mark("draw_and_resource_release");
|
||||
return drawn();
|
||||
}
|
||||
|
||||
void Driver::commitDraw(std::shared_ptr<VulkanDevice> localDevice, std::uint32_t queue, const Graphics::State& graphics, const Pm4::DrawParameters& drawParameters, std::span<const Graphics::CompiledShader> stages, std::span<const Graphics::GuestMemorySnapshot> snapshots, const std::shared_ptr<const DrawRecipe>& recipe, const std::vector<std::shared_ptr<DispatchVariant>>& recipeStages, std::uint64_t drawKey, VulkanDevice::DrawTraceContext trace) {
|
||||
void Driver::commitDraw(std::shared_ptr<VulkanDevice> localDevice, std::uint32_t queue, const Graphics::State& graphics, const Pm4::DrawParameters& drawParameters, std::span<const Graphics::CompiledShader> stages, std::span<const Graphics::GuestMemorySnapshot> snapshots, const std::shared_ptr<const DrawRecipe>& recipe, const std::vector<std::shared_ptr<DispatchVariant>>& recipeStages, std::uint64_t drawKey, VulkanDevice::DrawTraceContext trace, std::uint64_t shape) {
|
||||
const auto* tracePtr = trace.token != 0 ? &trace : nullptr;
|
||||
GuestMemory::TagGpuLockSite(GuestMemory::GpuLockSite::Draw);
|
||||
std::lock_guard gpuLock(GuestMemory::GpuMutex());
|
||||
@@ -1296,7 +1296,7 @@ void Driver::commitDraw(std::shared_ptr<VulkanDevice> localDevice, std::uint32_t
|
||||
VulkanDevice::NoteRecipe(VulkanDevice::RecipeEvent::Restart, VulkanDevice::RecipeKind::Draw);
|
||||
}
|
||||
std::shared_ptr<const DrawRecipe> built;
|
||||
localDevice->Draw(graphics, drawParameters, stages, snapshots, recipeStages.empty() ? nullptr : &built, tracePtr);
|
||||
localDevice->Draw(graphics, drawParameters, stages, snapshots, recipeStages.empty() ? nullptr : &built, tracePtr, shape);
|
||||
if (built != nullptr) attachDrawRecipe(drawKey, recipeStages, std::move(built));
|
||||
}
|
||||
|
||||
|
||||
@@ -117,7 +117,7 @@ void DecodeGraphicsPrograms(DrawDecode& decoded, const QueueState& queue, const
|
||||
DrawProgram result{
|
||||
{stage, address, std::span(snapshot.code).subspan(codeOffset), snapshot.headerAddress, snapshot.header},
|
||||
userDataBase,
|
||||
stage == Stage::Fragment ? 0u : 8u,
|
||||
stage == Stage::Fragment || userDataBase == 0x04cu ? 0u : 8u,
|
||||
{},
|
||||
{{{snapshot.codeAddress, std::as_bytes(std::span(snapshot.code))}, {snapshot.headerAddress, snapshot.header}}},
|
||||
program,
|
||||
@@ -167,6 +167,8 @@ void DecodeGraphicsPrograms(DrawDecode& decoded, const QueueState& queue, const
|
||||
append(0xc8, type, Stage::Mesh, 0x8b, 0x8c, Role::Main);
|
||||
InitializeMerged(queue, programs.back(), 0x82, type == 4, staticAbi);
|
||||
if (type == 4) append(0x88, 6, Stage::Mesh, 0x8b, 0x8c, Role::GeometryBack);
|
||||
} else if (graphics.stages.legacyVertex) {
|
||||
append(0x48, 2, Stage::Vertex, 0x4b, 0x4c, Role::Main);
|
||||
} else {
|
||||
append(0xc8, 2, Stage::Vertex, 0x8b, 0x8c, Role::Main);
|
||||
}
|
||||
|
||||
@@ -87,6 +87,18 @@ void Driver::lookupDraw(const Submission& submission, const std::shared_ptr<Vulk
|
||||
for (const auto word : pixel.targetMerge.descriptor) mix(word);
|
||||
mix(pixel.targetMerge.depthStencilWrites);
|
||||
mix(pixel.targetMerge.depthStencilTests);
|
||||
if (pixel.targetMerge.blend.enabled) {
|
||||
const auto& blend = pixel.targetMerge.blend;
|
||||
mix(blend.snorm);
|
||||
mix(blend.colorSource);
|
||||
mix(blend.colorDestination);
|
||||
mix(blend.colorOperation);
|
||||
mix(blend.alphaSource);
|
||||
mix(blend.alphaDestination);
|
||||
mix(blend.alphaOperation);
|
||||
mix(blend.writeMask);
|
||||
for (const auto word : blend.constants) mix(word);
|
||||
}
|
||||
mix(pixel.alphaToCoverage);
|
||||
mix(static_cast<std::uint64_t>(pixel.rasterPrimitive));
|
||||
mix(pixel.ditheredAlphaToCoverage);
|
||||
|
||||
@@ -467,7 +467,8 @@ std::uint64_t DrawPipeline::DrainRequestsByOpcode(std::uint32_t opcode) {
|
||||
}
|
||||
|
||||
bool DrawPipeline::HeldReads(std::uint64_t address, std::size_t bytes) {
|
||||
if (bytes == 0 || std::getenv("APS5_NO_QUEUED_DRAW_READ_ORDER") != nullptr) return false;
|
||||
static const bool unordered = std::getenv("APS5_NO_QUEUED_DRAW_READ_ORDER") != nullptr;
|
||||
if (bytes == 0 || unordered) return false;
|
||||
const auto end = address + bytes;
|
||||
auto& pipeline = Queue0();
|
||||
std::lock_guard lock(pipeline.mutex);
|
||||
|
||||
@@ -103,9 +103,8 @@ std::optional<DrawVerdict> Driver::precheckDraw(const QueueState& queue, const S
|
||||
const auto type = primitive == queue.userConfig.end() ? 0u : primitive->second & 0x3fu;
|
||||
const bool strip = type == 3 || type == 5 || type == 6 || type == 21;
|
||||
const bool list = type == 1 || type == 2 || type == 4;
|
||||
const auto restartDevice = device.Load();
|
||||
if (!strip && !(list && restartDevice != nullptr && restartDevice->PrimitiveListRestart())) {
|
||||
rejected = "AGC graphics: primitive restart is only supported for strips, and for lists with VK_EXT_primitive_topology_list_restart";
|
||||
if (!strip && !list) {
|
||||
rejected = "AGC graphics: primitive restart is only supported for strips and lists";
|
||||
return DrawVerdict::Rejected;
|
||||
}
|
||||
if (resetIndex == queue.context.end() || (resetIndex->second & allOnes) != allOnes) {
|
||||
|
||||
@@ -12,7 +12,7 @@ namespace AgcDriver::DriverDetail {
|
||||
namespace {
|
||||
|
||||
bool runtimeRegister(std::uint32_t offset) {
|
||||
return offset - 0x00cu < 32u || offset - 0x08cu < 32u || offset - 0x10cu < 32u || offset == 0x082u || offset == 0x083u || offset == 0x102u || offset == 0x103u;
|
||||
return offset - 0x00cu < 32u || offset - 0x04cu < 16u || offset - 0x08cu < 32u || offset - 0x10cu < 32u || offset == 0x082u || offset == 0x083u || offset == 0x102u || offset == 0x103u;
|
||||
}
|
||||
|
||||
const auto& registerMasks() {
|
||||
@@ -71,10 +71,11 @@ std::uint64_t RegisterStateKey(const QueueState& queue, bool allUserWords, bool
|
||||
mixPart(part, it->second);
|
||||
}
|
||||
};
|
||||
for (const auto base : {0x00cu, 0x08cu, 0x10cu}) {
|
||||
for (const auto base : {0x00cu, 0x04cu, 0x08cu, 0x10cu}) {
|
||||
const auto limit = base == 0x04cu ? 16u : 32u;
|
||||
const auto resources = queue.shader.find(base - 1);
|
||||
const auto count = resources == queue.shader.end() ? 0u : ((resources->second >> 1u) & 0x1fu) | (((resources->second >> 27u) & 1u) << 5u);
|
||||
words(base, allUserWords ? 32u : std::min(count, 32u), userData);
|
||||
words(base, allUserWords ? limit : std::min(count, limit), userData);
|
||||
}
|
||||
words(0x082u, 2, auxiliary);
|
||||
words(0x102u, 2, auxiliary);
|
||||
@@ -86,7 +87,7 @@ std::uint64_t RegisterStateKey(const QueueState& queue, bool allUserWords, bool
|
||||
std::uint64_t DrawShaderSetKey(const QueueState& queue, const ShaderRegistry& registry) {
|
||||
std::uint64_t key = 0xcbf29ce484222325ull;
|
||||
const auto mix = [&](std::uint64_t value) { key = (key ^ value) * 0x100000001b3ull; };
|
||||
for (const auto base : {0x008u, 0x088u, 0x0c8u, 0x108u, 0x148u}) {
|
||||
for (const auto base : {0x008u, 0x048u, 0x088u, 0x0c8u, 0x108u, 0x148u}) {
|
||||
const auto low = queue.shader.find(base);
|
||||
const auto high = queue.shader.find(base + 1);
|
||||
if (low == queue.shader.end() || high == queue.shader.end()) { mix(0); continue; }
|
||||
@@ -167,7 +168,7 @@ std::uint64_t Driver::drawRegisterKey(const QueueState& queue, const ShaderRegis
|
||||
(*components)[4] = DrawShaderSetKey(queue, registry);
|
||||
}
|
||||
mix(deviceSerial);
|
||||
for (const auto base : {0x008u, 0x088u, 0x0c8u, 0x108u, 0x148u}) {
|
||||
for (const auto base : {0x008u, 0x048u, 0x088u, 0x0c8u, 0x108u, 0x148u}) {
|
||||
const auto low = queue.shader.find(base);
|
||||
const auto high = queue.shader.find(base + 1);
|
||||
if (low == queue.shader.end() || high == queue.shader.end()) {
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
#include "prx/libkernel/Time/include/SleepWake.hpp"
|
||||
#include <algorithm>
|
||||
#include <mutex>
|
||||
#include "RdnaDecoder/RdnaInstructionDecoder.hpp"
|
||||
|
||||
namespace AgcDriver {
|
||||
|
||||
@@ -91,6 +92,15 @@ extern "C" void AgcDriverWaitIdle_nid_postfix() try {
|
||||
LibcAwaitExit_nid_postfix();
|
||||
}
|
||||
|
||||
extern "C" void AgcDriverSubmitGraphics_nid_postfix(std::uint32_t* commands, std::uint32_t dwords) {
|
||||
const Packet packet{commands, dwords, 0, {}};
|
||||
AgcDriver::Submit(&packet, 0);
|
||||
}
|
||||
|
||||
extern "C" void AgcDriverUseGcnShaders_nid_postfix() {
|
||||
ShaderRecompiler::SetGcnGuestShaders(true);
|
||||
}
|
||||
|
||||
static std::mutex& VulkanLoaderMutex() {
|
||||
static std::mutex mutex;
|
||||
return mutex;
|
||||
|
||||
@@ -165,7 +165,7 @@ bool Driver::copyBuffer(QueueState& queue, std::uint32_t queueId, std::span<cons
|
||||
if ((packet[4] & 0x20u) != 0) {
|
||||
for (std::uint32_t axis = 0; axis < 3; ++axis) {
|
||||
const auto threads = std::max(readRegister(queue.shader, 0x207 + axis) & 0xffffu, 1u);
|
||||
groups[axis] = (groups[axis] + threads - 1) / threads;
|
||||
groups[axis] = ThreadDimensionGroups(groups[axis], threads);
|
||||
}
|
||||
}
|
||||
if (groups[1] != 1 || groups[2] != 1) {
|
||||
|
||||
@@ -51,7 +51,7 @@ bool Driver::matchesFillKernel(std::span<const std::uint32_t> code, const std::v
|
||||
static const bool enabled = std::getenv("APS5_NO_FILL_HLE") == nullptr;
|
||||
static const bool patternEnabled = std::getenv("APS5_NO_PATTERN_FILL_HLE") == nullptr;
|
||||
if (!enabled || userData.size() < 8 || compute.numThreads[0] != 64 || compute.numThreads[1] != 1 || compute.numThreads[2] != 1) return false;
|
||||
if (patternEnabled && MatchesPatternFillKernel(code, userData, compute)) return true;
|
||||
if (patternEnabled && (MatchesPatternFillKernel(code, userData, compute) || MatchesGcnPatternFillKernel(code, userData, compute))) return true;
|
||||
static constexpr std::array<std::uint32_t, 9> fillKernel{0xd7460004u, 0x04010c08u, 0x7e000204u, 0x7e020205u, 0x7e040206u, 0x7e060207u, 0xe01c2000u, 0x80000004u, 0xbf810000u};
|
||||
if (!matchesBufferPatternFillKernel(code) && (code.size() < fillKernel.size() || !std::equal(fillKernel.begin(), fillKernel.end(), code.begin()))) return false;
|
||||
|
||||
@@ -275,8 +275,8 @@ bool Driver::fillBuffer(QueueState& queue, std::uint32_t queueId, std::span<cons
|
||||
std::fill(pattern.begin() + 1, pattern.end(), pattern[0]);
|
||||
base = memoryFill->address;
|
||||
bytes = memoryFill->bytes;
|
||||
} else if (MatchesPatternFillKernel(code, userData, compute)) {
|
||||
const auto range = DecodePatternFillRange(userData, packet);
|
||||
} else if (MatchesPatternFillKernel(code, userData, compute) || MatchesGcnPatternFillKernel(code, userData, compute)) {
|
||||
const auto range = MatchesGcnPatternFillKernel(code, userData, compute) ? DecodeGcnPatternFillRange(userData, packet) : DecodePatternFillRange(userData, packet);
|
||||
if (!range) return false;
|
||||
if (range->invocations == 0) return true;
|
||||
drainPendingInputWrites(queueId, {{range->control, 8}, {range->source, 4}});
|
||||
@@ -300,7 +300,7 @@ bool Driver::fillBuffer(QueueState& queue, std::uint32_t queueId, std::span<cons
|
||||
if ((packet[4] & 0x20u) != 0) {
|
||||
for (std::uint32_t axis = 0; axis < 3; ++axis) {
|
||||
const auto threads = std::max(readRegister(queue.shader, 0x207 + axis) & 0xffffu, 1u);
|
||||
groups[axis] = (groups[axis] + threads - 1) / threads;
|
||||
groups[axis] = ThreadDimensionGroups(groups[axis], threads);
|
||||
}
|
||||
}
|
||||
if (groups[1] != 1 || groups[2] != 1) return false;
|
||||
|
||||
@@ -141,7 +141,7 @@ void Driver::run(std::uint32_t id) noexcept {
|
||||
PinWorkerThread(role);
|
||||
|
||||
GuestMemory::TagGpuLockThread(id);
|
||||
if (id == 0) StartWorkerSampler();
|
||||
StartWorkerSampler(id);
|
||||
Submission submission;
|
||||
static const bool profile = std::getenv("APS5_PROFILE_DRAW") != nullptr;
|
||||
auto& costs = submissionCosts(id);
|
||||
|
||||
@@ -21,7 +21,11 @@ void Driver::reportSkip(const char* kind, const std::string& what) {
|
||||
if (!announced) {
|
||||
announced = true;
|
||||
char text[160];
|
||||
std::snprintf(text, sizeof(text), "[gpu] skip reports: one write each, RecompileRequest dumps capped at %d per reason (APS5_SKIP_REQUEST_DUMPS)\n", dumpLimit);
|
||||
if (dumpLimit < 0) {
|
||||
std::snprintf(text, sizeof(text), "[gpu] skip reports: one write each, RecompileRequest dumps uncapped (APS5_SKIP_REQUEST_DUMPS)\n");
|
||||
} else {
|
||||
std::snprintf(text, sizeof(text), "[gpu] skip reports: one write each, RecompileRequest dumps capped at %d per reason (APS5_SKIP_REQUEST_DUMPS)\n", dumpLimit);
|
||||
}
|
||||
line = text;
|
||||
}
|
||||
const std::string prefix = "[gpu] skipped " + std::string(kind);
|
||||
@@ -61,10 +65,18 @@ std::string Driver::dumpRequest(std::uint64_t address, const ShaderRecompiler::R
|
||||
try {
|
||||
const auto text = ShaderRecompiler::RequestSerializer{}.Serialize(request);
|
||||
if (std::FILE* file = std::fopen(name.c_str(), "wb")) {
|
||||
std::fwrite(text.data(), 1, text.size(), file);
|
||||
std::fclose(file);
|
||||
const auto written = std::fwrite(text.data(), 1, text.size(), file);
|
||||
const auto closed = std::fclose(file);
|
||||
if (written != text.size() || closed != 0) {
|
||||
dumped.erase(name);
|
||||
std::fprintf(stderr, "[gpu] incomplete write to dump file %s (%zu of %zu bytes, close status %d)\n", name.c_str(), written, text.size(), closed);
|
||||
}
|
||||
} else {
|
||||
dumped.erase(name);
|
||||
std::fprintf(stderr, "[gpu] could not open dump file %s for writing\n", name.c_str());
|
||||
}
|
||||
} catch (const std::exception& error) {
|
||||
dumped.erase(name);
|
||||
std::fprintf(stderr, "[gpu] could not serialize request for 0x%llx: %s\n", static_cast<unsigned long long>(address), error.what());
|
||||
}
|
||||
return name;
|
||||
|
||||
@@ -18,6 +18,8 @@
|
||||
#include <array>
|
||||
#include <atomic>
|
||||
#include <chrono>
|
||||
#include <cmath>
|
||||
#include <cerrno>
|
||||
#include <set>
|
||||
#include <condition_variable>
|
||||
#include <cstdio>
|
||||
@@ -33,6 +35,7 @@
|
||||
#include <list>
|
||||
#include <map>
|
||||
#include <mutex>
|
||||
#include <limits>
|
||||
#include <atomic>
|
||||
#include <pthread.h>
|
||||
#ifdef _WIN32
|
||||
@@ -50,6 +53,8 @@
|
||||
#include <stdexcept>
|
||||
#include <thread>
|
||||
#include "Optimization/ShaderStageInputInfo.hpp"
|
||||
#include "prx/libSceAgcDriver/Execution/include/Driver/Shaders/RegistrationPreparationBudget.hpp"
|
||||
#include "prx/libSceAgcDriver/Execution/include/PerformanceOverlay.hpp"
|
||||
#include <spirv/unified1/spirv.hpp>
|
||||
#include "RdnaDecoder/RdnaInstructionDecoder.hpp"
|
||||
|
||||
@@ -1028,7 +1033,8 @@ std::vector<ShaderRecompiler::TableCallee> ReadTableCallees(const ShaderRecompil
|
||||
}
|
||||
|
||||
ShaderRecompiler::LinkedCalls LinkUserDataCallees(const ShaderRecompiler::RecompileRequest& request) {
|
||||
if (request.shader.stage != ShaderRecompiler::ShaderStage::Compute) return {};
|
||||
const bool gcnVertex = ShaderRecompiler::GcnGuestShaders() && request.shader.stage == ShaderRecompiler::ShaderStage::Vertex;
|
||||
if (request.shader.stage != ShaderRecompiler::ShaderStage::Compute && !gcnVertex) return {};
|
||||
const auto code = request.shader.code;
|
||||
if (std::none_of(code.begin(), code.end(), [](std::uint32_t word) { return (word & 0xff80ff00u) == 0xbe802100u; })) return {};
|
||||
const auto program = ShaderRecompiler::RdnaInstructionDecoder{}.Decode(code);
|
||||
@@ -1209,7 +1215,15 @@ struct RegisteredPreparation {
|
||||
std::shared_ptr<VulkanDevice> prebuildDevice;
|
||||
};
|
||||
|
||||
bool RegistrationPrepareWithinMemoryBudget();
|
||||
void LogRegistrationPrepareDeferred();
|
||||
|
||||
std::unique_ptr<RegisteredPreparation> PlanRegistered(const ShaderSnapshot& snapshot, const VulkanDevice& device, const QueueState& state, bool registration, bool* deferred = nullptr) {
|
||||
if (registration && std::getenv("APS5_LAZY_SHADER_PREPARE") == nullptr && !RegistrationPrepareWithinMemoryBudget()) {
|
||||
if (deferred != nullptr) *deferred = true;
|
||||
LogRegistrationPrepareDeferred();
|
||||
return {};
|
||||
}
|
||||
using Stage = ShaderRecompiler::ShaderStage;
|
||||
const auto header = ReadHeader(snapshot);
|
||||
std::uint32_t programRegister;
|
||||
@@ -1705,14 +1719,39 @@ bool AsyncRegistrationPrepare() {
|
||||
return !sync;
|
||||
}
|
||||
|
||||
std::uint64_t RegistrationPrepareCommitBudgetBytes() {
|
||||
static const std::uint64_t budget = [] {
|
||||
if (const auto* text = std::getenv("APS5_REGISTRATION_PREPARE_COMMIT_GB")) {
|
||||
return RegistrationPreparationCommitBudgetBytes(text, 0);
|
||||
}
|
||||
const auto physicalBytes = ReadPhysicalMemoryBytes();
|
||||
const auto defaultBudget = physicalBytes ? *physicalBytes / 2 : std::numeric_limits<std::uint64_t>::max();
|
||||
return RegistrationPreparationCommitBudgetBytes(nullptr, defaultBudget);
|
||||
}();
|
||||
return budget;
|
||||
}
|
||||
|
||||
bool RegistrationPrepareWithinMemoryBudget() {
|
||||
const auto privateBytes = ReadProcessPrivateBytes();
|
||||
return !privateBytes || RegistrationPreparationAllowed(*privateBytes, RegistrationPrepareCommitBudgetBytes());
|
||||
}
|
||||
|
||||
void LogRegistrationPrepareDeferred() {
|
||||
static std::atomic<bool> reported{false};
|
||||
if (reported.exchange(true, std::memory_order_relaxed)) return;
|
||||
APS5_LOG_OUT("%s", "process private memory reached the registered shader preparation budget; later registrations are prepared when first used (APS5_REGISTRATION_PREPARE_COMMIT_GB)");
|
||||
}
|
||||
|
||||
void PrepareRegisteredInBackground(std::shared_ptr<const ShaderSnapshot> snapshot, std::shared_ptr<RegisteredPreparation> plan) {
|
||||
const auto* preparedKey = snapshot->prepared.get();
|
||||
SubmitRegistrationPreparation([snapshot = std::move(snapshot), plan = std::move(plan)] {
|
||||
PerformanceContext timingContext(FrameTiming::Preparation());
|
||||
std::vector<PreparedShaders::Entry> entries;
|
||||
std::exception_ptr failure;
|
||||
bool deferred = false;
|
||||
try {
|
||||
entries = PrepareRegistered(*plan);
|
||||
if (RegistrationPrepareWithinMemoryBudget()) entries = PrepareRegistered(*plan);
|
||||
else deferred = true;
|
||||
} catch (const std::exception& error) {
|
||||
APS5_LOG_ERR("Shader 0x%llx snapshot=0x%llx could not be prepared after registration: %s", static_cast<unsigned long long>(snapshot->codeAddress), static_cast<unsigned long long>(reinterpret_cast<std::uintptr_t>(snapshot.get())), error.what());
|
||||
failure = std::current_exception();
|
||||
@@ -1723,10 +1762,12 @@ void PrepareRegisteredInBackground(std::shared_ptr<const ShaderSnapshot> snapsho
|
||||
{
|
||||
std::lock_guard lock(prepared.mutex);
|
||||
prepared.entries.insert(prepared.entries.end(), std::make_move_iterator(entries.begin()), std::make_move_iterator(entries.end()));
|
||||
if (failure == nullptr && !plan->abiKey.empty()) prepared.registeredAbis.push_back(std::move(plan->abiKey));
|
||||
if (failure == nullptr && !deferred && !plan->abiKey.empty()) prepared.registeredAbis.push_back(std::move(plan->abiKey));
|
||||
prepared.deferred = prepared.deferred || deferred;
|
||||
prepared.failure = failure;
|
||||
prepared.pending = false;
|
||||
}
|
||||
if (deferred) LogRegistrationPrepareDeferred();
|
||||
prepared.settled.notify_all();
|
||||
}, preparedKey);
|
||||
}
|
||||
|
||||
@@ -17,6 +17,11 @@
|
||||
#include <algorithm>
|
||||
#include <bit>
|
||||
#include <emmintrin.h>
|
||||
#if defined(_MSC_VER) && !defined(__clang__)
|
||||
#include <intrin.h>
|
||||
#else
|
||||
#include <cpuid.h>
|
||||
#endif
|
||||
#include <functional>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
@@ -2821,7 +2826,31 @@ void WriteChangedCommitted(std::uint64_t address, std::span<const std::byte> cur
|
||||
}
|
||||
}
|
||||
|
||||
static std::uint32_t changedByteCount(__m128i same) {
|
||||
const auto sums = _mm_sad_epu8(_mm_and_si128(same, _mm_set1_epi8(1)), _mm_setzero_si128());
|
||||
return 16u - static_cast<std::uint32_t>(_mm_cvtsi128_si32(_mm_add_epi32(sums, _mm_unpackhi_epi64(sums, sums))));
|
||||
}
|
||||
|
||||
std::uint32_t ChangedByteStoreLimit() {
|
||||
static const auto limit = [] {
|
||||
#if defined(_MSC_VER) && !defined(__clang__)
|
||||
int registers[4]{};
|
||||
__cpuid(registers, 0);
|
||||
const auto ebx = static_cast<unsigned>(registers[1]), ecx = static_cast<unsigned>(registers[2]), edx = static_cast<unsigned>(registers[3]);
|
||||
#else
|
||||
unsigned eax = 0, ebx = 0, ecx = 0, edx = 0;
|
||||
if (__get_cpuid(0, &eax, &ebx, &ecx, &edx) == 0) return 4u;
|
||||
#endif
|
||||
return ebx == 0x68747541u && edx == 0x69746e65u && ecx == 0x444d4163u ? 16u : 4u;
|
||||
}();
|
||||
return limit;
|
||||
}
|
||||
|
||||
void WriteChanged(std::uint64_t address, std::span<const std::byte> current, std::span<const std::byte> original) {
|
||||
WriteChanged(address, current, original, ChangedByteStoreLimit());
|
||||
}
|
||||
|
||||
void WriteChanged(std::uint64_t address, std::span<const std::byte> current, std::span<const std::byte> original, std::uint32_t byteStoreLimit) {
|
||||
require(current.size() == original.size(), "write-back snapshot sizes differ");
|
||||
BreakProofs();
|
||||
if (current.empty()) return;
|
||||
@@ -2837,19 +2866,28 @@ void WriteChanged(std::uint64_t address, std::span<const std::byte> current, std
|
||||
CheckRange(destination, size, 1, true);
|
||||
std::size_t firstChanged = size;
|
||||
std::size_t lastChanged = 0;
|
||||
bool masked = false;
|
||||
std::size_t at = 0;
|
||||
for (; at + 16 <= size; at += 16) {
|
||||
const auto bytes = _mm_loadu_si128(reinterpret_cast<const __m128i*>(current.data() + at));
|
||||
const auto same = _mm_cmpeq_epi8(bytes, _mm_loadu_si128(reinterpret_cast<const __m128i*>(original.data() + at)));
|
||||
const auto equal = static_cast<std::uint32_t>(_mm_movemask_epi8(same));
|
||||
if (equal == 0xffffu) continue;
|
||||
if (equal == 0) _mm_storeu_si128(reinterpret_cast<__m128i*>(destination + at), bytes);
|
||||
else _mm_maskmoveu_si128(bytes, _mm_xor_si128(same, _mm_set1_epi8(-1)), reinterpret_cast<char*>(destination + at));
|
||||
const auto changed = ~equal & 0xffffu;
|
||||
if (equal == 0) _mm_storeu_si128(reinterpret_cast<__m128i*>(destination + at), bytes);
|
||||
else if (byteStoreLimit < 16 && changedByteCount(same) > byteStoreLimit) {
|
||||
_mm_maskmoveu_si128(bytes, _mm_xor_si128(same, _mm_set1_epi8(-1)), reinterpret_cast<char*>(destination + at));
|
||||
masked = true;
|
||||
} else {
|
||||
for (auto bits = changed; bits != 0; bits &= bits - 1) {
|
||||
const auto index = at + static_cast<std::size_t>(std::countr_zero(bits));
|
||||
destination[index] = current[index];
|
||||
}
|
||||
}
|
||||
firstChanged = std::min(firstChanged, at + static_cast<std::size_t>(std::countr_zero(changed)));
|
||||
lastChanged = std::max(lastChanged, at + 32 - static_cast<std::size_t>(std::countl_zero(changed)));
|
||||
}
|
||||
_mm_sfence();
|
||||
if (masked) _mm_sfence();
|
||||
for (; at < size; ++at) {
|
||||
if (current[at] == original[at]) continue;
|
||||
destination[at] = current[at];
|
||||
|
||||
@@ -15,6 +15,7 @@
|
||||
#include "prx/libkernel/AppMetadata/include/AppMetadata.hpp"
|
||||
#include <algorithm>
|
||||
#include <atomic>
|
||||
#include <cerrno>
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
@@ -25,6 +26,9 @@
|
||||
#include <mutex>
|
||||
#include <stdexcept>
|
||||
#include <string_view>
|
||||
#ifndef _WIN32
|
||||
#include <unistd.h>
|
||||
#endif
|
||||
#ifdef _WIN32
|
||||
#define WIN32_LEAN_AND_MEAN
|
||||
#ifndef NOMINMAX
|
||||
@@ -686,6 +690,20 @@ std::optional<std::uint64_t> ReadPageFaults() {
|
||||
#endif
|
||||
}
|
||||
|
||||
std::optional<std::uint64_t> ReadPhysicalMemoryBytes() {
|
||||
#ifdef _WIN32
|
||||
MEMORYSTATUSEX status{};
|
||||
status.dwLength = sizeof(status);
|
||||
if (::GlobalMemoryStatusEx(&status) == 0) return std::nullopt;
|
||||
return static_cast<std::uint64_t>(status.ullTotalPhys);
|
||||
#else
|
||||
const auto pages = ::sysconf(_SC_PHYS_PAGES);
|
||||
const auto pageSize = ::sysconf(_SC_PAGESIZE);
|
||||
if (pages <= 0 || pageSize <= 0) return std::nullopt;
|
||||
return static_cast<std::uint64_t>(pages) * static_cast<std::uint64_t>(pageSize);
|
||||
#endif
|
||||
}
|
||||
|
||||
std::int32_t OverlayScale(VkExtent2D extent, const OverlayContent& content) {
|
||||
auto scale = std::max<std::int32_t>(1, static_cast<std::int32_t>((extent.height + 240) / 480));
|
||||
while (scale > 1 && !fits(extent, content, scale)) --scale;
|
||||
|
||||
@@ -57,7 +57,13 @@ void TraceFile::WriteGzip(const std::filesystem::path& path, std::string_view te
|
||||
void TraceFile::ReplaceGzip(const std::filesystem::path& path, std::string_view text) {
|
||||
auto temporary = path;
|
||||
temporary += ".tmp";
|
||||
WriteGzip(temporary, text);
|
||||
try {
|
||||
WriteGzip(temporary, text);
|
||||
} catch (...) {
|
||||
std::error_code removeError;
|
||||
if (!std::filesystem::is_directory(temporary, removeError)) std::filesystem::remove(temporary, removeError);
|
||||
throw;
|
||||
}
|
||||
std::error_code error;
|
||||
#ifdef _WIN32
|
||||
if (::MoveFileExW(temporary.c_str(), path.c_str(), MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH) == 0) error = std::error_code(static_cast<int>(::GetLastError()), std::system_category());
|
||||
|
||||
@@ -405,6 +405,7 @@ struct VulkanDevice::State {
|
||||
bool exactRobustLoads = false;
|
||||
bool subgroupControlBarriers = true;
|
||||
bool workgroupScopeFences = true;
|
||||
bool ldsLockFences = false;
|
||||
// VK_EXT_descriptor_indexing with non-uniform image array indexing (bindless image tables in
|
||||
// graphics stages, and compute workgroups wider than a wave).
|
||||
bool descriptorIndexing = false;
|
||||
@@ -1137,7 +1138,7 @@ VulkanDevice::VulkanDevice(const PresentationWindow* window, bool compileOnly) :
|
||||
state->library = SDL_LoadObject("libvulkan.so.1");
|
||||
#endif
|
||||
if (state->library == nullptr) {
|
||||
throw std::runtime_error(std::string("Vulkan loader: ") + SDL_GetError());
|
||||
throw VulkanUnavailable(std::string("Vulkan loader: ") + SDL_GetError());
|
||||
}
|
||||
APS5_LOG_OUT("Vulkan loader loaded library=%p", state->library);
|
||||
state->instanceProc = reinterpret_cast<PFN_vkGetInstanceProcAddr>(SDL_LoadFunction(state->library, "vkGetInstanceProcAddr"));
|
||||
@@ -1176,7 +1177,9 @@ VulkanDevice::VulkanDevice(const PresentationWindow* window, bool compileOnly) :
|
||||
create.enabledExtensionCount = static_cast<std::uint32_t>(instanceExtensions.size());
|
||||
create.ppEnabledExtensionNames = instanceExtensions.data();
|
||||
}
|
||||
check(state->InstanceFunction<PFN_vkCreateInstance>("vkCreateInstance")(&create, nullptr, &state->instance), "vkCreateInstance");
|
||||
const VkResult instanceResult = state->InstanceFunction<PFN_vkCreateInstance>("vkCreateInstance")(&create, nullptr, &state->instance);
|
||||
if (instanceResult == VK_ERROR_INCOMPATIBLE_DRIVER) throw VulkanUnavailable("vkCreateInstance: Vulkan result " + std::to_string(instanceResult));
|
||||
check(instanceResult, "vkCreateInstance");
|
||||
APS5_LOG_OUT("Vulkan instance created instance=%p", reinterpret_cast<void*>(state->instance));
|
||||
if (window != nullptr) {
|
||||
state->surface = window->createSurface(window->context, state->instance);
|
||||
@@ -1266,7 +1269,7 @@ VulkanDevice::VulkanDevice(const PresentationWindow* window, bool compileOnly) :
|
||||
throw std::runtime_error(std::string("Vulkan: no usable device whose name contains ANYPS5_GPU=\"") + requestedName + "\"; devices: " + candidateNames);
|
||||
}
|
||||
if (selected == VK_NULL_HANDLE) {
|
||||
throw std::runtime_error(window ? "Vulkan: no Vulkan 1.1 device with graphics, compute and swapchain presentation" : "Vulkan: no Vulkan 1.1 graphics and compute queue");
|
||||
throw VulkanUnavailable(window ? "Vulkan: no Vulkan 1.1 device with graphics, compute and swapchain presentation" : "Vulkan: no Vulkan 1.1 graphics and compute queue");
|
||||
}
|
||||
APS5_LOG_OUT("Physical device selected physical=%p queueFamily=%u", reinterpret_cast<void*>(selected), family);
|
||||
VkPhysicalDeviceProperties2 properties{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2};
|
||||
@@ -1306,6 +1309,7 @@ VulkanDevice::VulkanDevice(const PresentationWindow* window, bool compileOnly) :
|
||||
state->tessellationPipelineCache = TessellationPipelineCacheUsable(driver.driverID);
|
||||
state->subgroupControlBarriers = SubgroupControlBarrierUsable(driver.driverID);
|
||||
state->workgroupScopeFences = WorkgroupScopeFenceUsable(driver.driverID);
|
||||
state->ldsLockFences = LdsLockFencesRequired(driver.driverID);
|
||||
}
|
||||
if (driverId == VK_DRIVER_ID_NVIDIA_PROPRIETARY && hasExtension(VK_NV_SHADER_SM_BUILTINS_EXTENSION_NAME)) {
|
||||
VkPhysicalDeviceShaderSMBuiltinsPropertiesNV smBuiltins{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_SM_BUILTINS_PROPERTIES_NV};
|
||||
@@ -3293,7 +3297,9 @@ void WriteFrameBmp(int index, std::uint32_t width, std::uint32_t height, std::sp
|
||||
|
||||
ResidentPresent ResidentPresentable(const Graphics::Context& context, const Graphics::StorageTexture& image, const DisplayBuffer& buffer, VkFilter& filter, std::uint32_t& layer) {
|
||||
const auto& descriptor = image.Descriptor();
|
||||
if (descriptor.width != buffer.width || descriptor.height != buffer.height || descriptor.mipCount != 1 || image.ImageDepth() != 1) return ResidentPresent::None;
|
||||
const bool gcn = buffer.tilingMode == DisplayTilingGcn;
|
||||
if (gcn && (descriptor.tileMode != Graphics::TextureTileMode::kGcnDisplay2D || descriptor.width != buffer.pitchInPixel || descriptor.height < buffer.height || descriptor.mipCount != 1 || image.ImageDepth() != 1)) return ResidentPresent::None;
|
||||
if (!gcn && (descriptor.width != buffer.width || descriptor.height != buffer.height || descriptor.mipCount != 1 || image.ImageDepth() != 1)) return ResidentPresent::None;
|
||||
const auto slice = ResidentPresentSlice(descriptor.baseAddress, image.GuestBytes(), image.ImageLayers(), buffer.address, DisplayBufferSize(buffer));
|
||||
if (!slice) return ResidentPresent::None;
|
||||
layer = *slice;
|
||||
@@ -4061,6 +4067,7 @@ ShaderRecompiler::SpirvTarget VulkanDevice::buildTarget() const {
|
||||
target.largePixelFunctionLdsBuffer = state->driverId == VK_DRIVER_ID_NVIDIA_PROPRIETARY;
|
||||
target.pixelFunctionStorageDwords = state->pixelFunctionStorageDwords;
|
||||
target.deviceScopeLdsMemoryBarriers = !state->workgroupScopeFences;
|
||||
target.ldsLockFences = state->ldsLockFences;
|
||||
target.srgbDecodeFormats = state->srgbDecodeFormats & ~state->srgbCopyFormats;
|
||||
target.vertexSubgroups = (state->subgroup.supportedStages & VK_SHADER_STAGE_VERTEX_BIT) != 0;
|
||||
if (state->meshShader) {
|
||||
@@ -4282,7 +4289,7 @@ bool VulkanDevice::PrebuildGraphicsLibraries(const Graphics::ShaderStages& stage
|
||||
return Graphics::Pipeline::Prebuild(context, state, Graphics::VertexInputLayout{}, layouts.View(), group);
|
||||
}
|
||||
|
||||
void VulkanDevice::Draw(const Graphics::State& graphics, const Pm4::DrawParameters& draw, std::span<const Graphics::CompiledShader> shaders, std::span<const Graphics::GuestMemorySnapshot> snapshots, std::shared_ptr<const DrawRecipe>* recipe, const DrawTraceContext* trace) {
|
||||
void VulkanDevice::Draw(const Graphics::State& graphics, const Pm4::DrawParameters& draw, std::span<const Graphics::CompiledShader> shaders, std::span<const Graphics::GuestMemorySnapshot> snapshots, std::shared_ptr<const DrawRecipe>* recipe, const DrawTraceContext* trace, std::uint64_t shape) {
|
||||
startJournalReplay();
|
||||
for (const auto& shader : shaders) {
|
||||
require(shader.program != nullptr, "missing compiled shader");
|
||||
@@ -4293,7 +4300,7 @@ void VulkanDevice::Draw(const Graphics::State& graphics, const Pm4::DrawParamete
|
||||
static const bool traceDraws = std::getenv("APS5_TRACE_DRAWS") != nullptr;
|
||||
if (traceDraws) APS5_LOG_OUT("VulkanDevice::Draw indices=%u instances=%u indexSize=%u address=0x%llx shaders=%zu colorTarget=%u", draw.indexCount, draw.instanceCount, draw.indexSize, static_cast<unsigned long long>(draw.indexAddress), shaders.size(), static_cast<unsigned>(graphics.hasColorTarget));
|
||||
const auto context = graphicsContext();
|
||||
Graphics::Draw(context, graphics, draw, shaders, snapshots, recipe, trace);
|
||||
Graphics::Draw(context, graphics, draw, shaders, snapshots, recipe, trace, shape);
|
||||
if (traceDraws) APS5_LOG_CHARS_OUT("VulkanDevice::Draw complete");
|
||||
}
|
||||
|
||||
|
||||
@@ -326,9 +326,13 @@ void StartCallingThreadSampler(const char* path, std::jthread& slot) {
|
||||
|
||||
}
|
||||
|
||||
void StartWorkerSampler() {
|
||||
StartProcessSampler();
|
||||
StartCallingThreadSampler(std::getenv("APS5_SAMPLE_WORKER"), workerSamplerThread);
|
||||
void StartWorkerSampler(std::uint32_t queue) {
|
||||
if (queue == 0) StartProcessSampler();
|
||||
static const auto sampledQueue = [] {
|
||||
const char* value = std::getenv("APS5_SAMPLE_WORKER_QUEUE");
|
||||
return value != nullptr ? static_cast<std::uint32_t>(std::strtoul(value, nullptr, 0)) : 0u;
|
||||
}();
|
||||
if (queue == sampledQueue) StartCallingThreadSampler(std::getenv("APS5_SAMPLE_WORKER"), workerSamplerThread);
|
||||
}
|
||||
|
||||
void StartCommitterSampler() {
|
||||
@@ -344,7 +348,7 @@ void StopWorkerSampler() {
|
||||
if (committerSamplerThread.joinable()) committerSamplerThread.join();
|
||||
}
|
||||
#else
|
||||
void StartWorkerSampler() {}
|
||||
void StartWorkerSampler(std::uint32_t) {}
|
||||
void StartCommitterSampler() {}
|
||||
void StopWorkerSampler() {}
|
||||
#endif
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
|
||||
#include "prx/libSceAgcDriver/Graphics/include/GuestTextureResource.hpp"
|
||||
#include "prx/libSceAgcDriver/Graphics/include/TextureTiling.hpp"
|
||||
#include <array>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <span>
|
||||
@@ -20,9 +21,17 @@ enum class ColorTileMode : std::uint32_t {
|
||||
D4KBX = 0x16,
|
||||
Z64KBX = 0x18,
|
||||
D64KBX = 0x1a,
|
||||
RenderTarget = 0x1b
|
||||
RenderTarget = 0x1b,
|
||||
GcnThin1D = 0x100,
|
||||
GcnDisplay1D = 0x101,
|
||||
GcnDisplay2D = 0x102,
|
||||
GcnThin2D = 0x103
|
||||
};
|
||||
|
||||
constexpr bool ColorTileModeIsGcn(ColorTileMode mode) {
|
||||
return mode == ColorTileMode::GcnThin1D || mode == ColorTileMode::GcnDisplay1D || mode == ColorTileMode::GcnDisplay2D || mode == ColorTileMode::GcnThin2D;
|
||||
}
|
||||
|
||||
constexpr bool ColorTileModeIsXor(ColorTileMode mode) {
|
||||
return mode == ColorTileMode::S4KBX || mode == ColorTileMode::D4KBX || mode == ColorTileMode::Z64KBX || mode == ColorTileMode::D64KBX || mode == ColorTileMode::RenderTarget;
|
||||
}
|
||||
@@ -32,6 +41,10 @@ constexpr std::uint32_t ColorTileModeBlockBytes(ColorTileMode mode) {
|
||||
}
|
||||
|
||||
constexpr TextureTileMode ColorTextureTileMode(ColorTileMode mode) {
|
||||
if (mode == ColorTileMode::GcnThin1D) return TextureTileMode::kGcnThin1D;
|
||||
if (mode == ColorTileMode::GcnDisplay1D) return TextureTileMode::kGcnDisplay1D;
|
||||
if (mode == ColorTileMode::GcnDisplay2D) return TextureTileMode::kGcnDisplay2D;
|
||||
if (mode == ColorTileMode::GcnThin2D) return TextureTileMode::kGcnThin2D;
|
||||
return mode == ColorTileMode::Linear ? TextureTileMode::kLinear : mode == ColorTileMode::Standard4KB ? TextureTileMode::kStandard4KB : mode == ColorTileMode::Standard64KB ? TextureTileMode::kStandard64KB : mode == ColorTileMode::S4KBX ? TextureTileMode::kS4KBX : mode == ColorTileMode::D4KBX ? TextureTileMode::kD4KBX : mode == ColorTileMode::D64KBX ? TextureTileMode::kD64KBX : mode == ColorTileMode::Z64KBX ? TextureTileMode::kZ64KBX : TextureTileMode::kR64KBX;
|
||||
}
|
||||
|
||||
@@ -43,7 +56,7 @@ public:
|
||||
ColorTargetLayout(std::uint32_t width, std::uint32_t height, ColorTileMode mode, std::uint32_t bytesPerElement = 4, std::uint32_t pipeBankXor = 0);
|
||||
std::size_t Bytes() const { return bytes; }
|
||||
std::size_t LinearBytes() const { return static_cast<std::size_t>(width) * height * elementBytes; }
|
||||
std::size_t Alignment() const { return ColorTileModeBlockBytes(mode); }
|
||||
std::size_t Alignment() const { return blockBytes; }
|
||||
std::uint32_t BlocksPerRow() const { return pitch / blockWidth; }
|
||||
std::size_t Offset(std::uint32_t x, std::uint32_t y) const;
|
||||
void Detile(std::span<const std::byte> source, std::span<std::byte> destination) const;
|
||||
@@ -59,7 +72,10 @@ private:
|
||||
std::uint32_t elementBytes;
|
||||
std::uint32_t blockWidth = 1;
|
||||
std::uint32_t blockHeight = 1;
|
||||
std::size_t blockBytes = 0;
|
||||
std::uint32_t pipeBankXor = 0;
|
||||
bool gcn = false;
|
||||
std::array<std::uint32_t, 16> gcnEquation{};
|
||||
// The XOR swizzle is linear over GF(2), so a block offset is xOffsets[x] ^ yOffsets[y].
|
||||
const std::uint32_t* xOffsets = nullptr;
|
||||
const std::uint32_t* yOffsets = nullptr;
|
||||
|
||||
@@ -25,7 +25,7 @@ struct DrawTraceContext {
|
||||
// `recipe`, when given, receives the DrawRecipe a recorded, cacheable, reusable, non-indirect draw
|
||||
// built for its draw-cache entry (design_cpu_final M8; null otherwise, and always under
|
||||
// APS5_NO_DRAW_RECIPE=1).
|
||||
void Draw(const Context& context, const State& state, const Pm4::DrawParameters& draw, std::span<const CompiledShader> shaders, std::span<const GuestMemorySnapshot> snapshots = {}, std::shared_ptr<const DrawRecipe>* recipe = nullptr, const DrawTraceContext* trace = nullptr);
|
||||
void Draw(const Context& context, const State& state, const Pm4::DrawParameters& draw, std::span<const CompiledShader> shaders, std::span<const GuestMemorySnapshot> snapshots = {}, std::shared_ptr<const DrawRecipe>* recipe = nullptr, const DrawTraceContext* trace = nullptr, std::uint64_t shape = 0);
|
||||
|
||||
struct PixelFunctionLdsLayouts {
|
||||
VkDescriptorSetLayout empty = VK_NULL_HANDLE;
|
||||
|
||||
@@ -25,6 +25,21 @@ enum class TextureTileMode {
|
||||
kD64KBT,
|
||||
kS4KBX,
|
||||
kD4KBX,
|
||||
kGcnThin1D,
|
||||
kGcnDisplay1D,
|
||||
kGcnDisplay2D,
|
||||
kGcnThin2D,
|
||||
kGcnDepth2D64,
|
||||
kGcnDepth2D128,
|
||||
kGcnDepth2D256,
|
||||
kGcnDepth2D512,
|
||||
kGcnDepth2D1K,
|
||||
kGcnDepthPrt256,
|
||||
kGcnDepthPrt1K,
|
||||
kGcnDisplayPrt,
|
||||
kGcnDisplay2DPrt,
|
||||
kGcnThinPrt,
|
||||
kGcnThin2DPrt,
|
||||
// Upstream's name for SW_64KB_R_X (tile mode 0x1b).
|
||||
RenderTarget64KB = kR64KBX
|
||||
};
|
||||
@@ -91,8 +106,37 @@ struct GuestTextureResource {
|
||||
std::uint32_t allocatedMipCount = 0;
|
||||
std::uint32_t samples = 1;
|
||||
std::uint64_t fmaskCmaskAddress = 0;
|
||||
std::uint32_t gcnPitch = 0;
|
||||
bool gcnPow2Pad = false;
|
||||
bool gcnLinearGeneral = false;
|
||||
};
|
||||
|
||||
constexpr bool IsGcnMicroTiled(TextureTileMode mode) {
|
||||
return mode == TextureTileMode::kGcnThin1D || mode == TextureTileMode::kGcnDisplay1D;
|
||||
}
|
||||
|
||||
constexpr bool IsGcnDepthTiled(TextureTileMode mode) {
|
||||
return mode == TextureTileMode::kGcnDepth2D64 || mode == TextureTileMode::kGcnDepth2D128 || mode == TextureTileMode::kGcnDepth2D256 || mode == TextureTileMode::kGcnDepth2D512 || mode == TextureTileMode::kGcnDepth2D1K
|
||||
|| mode == TextureTileMode::kGcnDepthPrt256 || mode == TextureTileMode::kGcnDepthPrt1K;
|
||||
}
|
||||
|
||||
constexpr bool IsGcnPrtTiled(TextureTileMode mode) {
|
||||
return mode == TextureTileMode::kGcnDepthPrt256 || mode == TextureTileMode::kGcnDepthPrt1K || mode == TextureTileMode::kGcnDisplayPrt || mode == TextureTileMode::kGcnDisplay2DPrt || mode == TextureTileMode::kGcnThinPrt || mode == TextureTileMode::kGcnThin2DPrt;
|
||||
}
|
||||
|
||||
constexpr bool IsGcnMacroTiled(TextureTileMode mode) {
|
||||
return mode == TextureTileMode::kGcnDisplay2D || mode == TextureTileMode::kGcnThin2D || IsGcnDepthTiled(mode) || IsGcnPrtTiled(mode);
|
||||
}
|
||||
|
||||
constexpr bool IsGcnTiled(TextureTileMode mode) {
|
||||
return IsGcnMicroTiled(mode) || IsGcnMacroTiled(mode);
|
||||
}
|
||||
|
||||
constexpr TextureTileMode GcnMicroTileMode(TextureTileMode mode) {
|
||||
if (mode == TextureTileMode::kGcnDisplay2D || mode == TextureTileMode::kGcnDisplayPrt || mode == TextureTileMode::kGcnDisplay2DPrt) return TextureTileMode::kGcnDisplay1D;
|
||||
return IsGcnMacroTiled(mode) ? TextureTileMode::kGcnThin1D : mode;
|
||||
}
|
||||
|
||||
float EffectiveMinLod(const GuestTextureResource& resource);
|
||||
|
||||
bool IsNullTextureResource(std::span<const std::uint32_t> words);
|
||||
|
||||
@@ -115,7 +115,8 @@ private:
|
||||
// APS5_NO_PIPELINE_CACHE=1 builds one per draw as before.
|
||||
std::shared_ptr<Pipeline> CachedPipeline(const Context& context, const State& state, const VertexInputLayout& vertexInput, const ShaderResources& resources, std::span<const CompiledShader> shaders, VkImageLayout attachmentLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL);
|
||||
// `created` reports whether this call built the pipeline (false: served from the store or private).
|
||||
std::shared_ptr<Pipeline> CachedPipeline(const Context& context, const State& state, const VertexInputLayout& vertexInput, const PipelineSetLayouts& resources, std::span<const CompiledShader> shaders, VkImageLayout attachmentLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, bool* created = nullptr);
|
||||
std::shared_ptr<Pipeline> CachedPipeline(const Context& context, const State& state, const VertexInputLayout& vertexInput, const PipelineSetLayouts& resources, std::span<const CompiledShader> shaders, VkImageLayout attachmentLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, bool* created = nullptr, std::uint64_t* storeHash = nullptr);
|
||||
std::shared_ptr<Pipeline> TouchCachedPipeline(const Context& context, std::uint64_t hash, const std::weak_ptr<Pipeline>& expected);
|
||||
// Cumulative pipeline store outcomes since start-up (the [pipecache] line reports 10 s windows).
|
||||
struct PipelineStoreCounters {
|
||||
std::uint64_t hits = 0;
|
||||
|
||||
@@ -65,6 +65,7 @@ std::shared_ptr<StorageTexture> CachedStorageLayers(const Context& context, cons
|
||||
// would return); a true answer counts as a use for the cache's eviction order, as a lookup would.
|
||||
bool StorageImageCached(const Context& context, const StorageTexture* image);
|
||||
bool StorageImageServesKeys(const StorageTexture& image, std::uint64_t dccAddress);
|
||||
std::shared_ptr<StorageTexture> RepeatStorageSurface(const Context& context, const GuestTextureResource& resource, const std::shared_ptr<StorageTexture>& stored);
|
||||
|
||||
// Defined in Texture.cpp beside the pending-results registry, for the fast Revalidate below: whether
|
||||
// a storage image other than `except` has results pending in [address, address + bytes).
|
||||
|
||||
@@ -42,8 +42,11 @@ struct ShaderStages {
|
||||
float maxTessellationLevel = 64.0f;
|
||||
std::uint32_t hullWaveSize = 64;
|
||||
std::optional<ShaderRecompiler::MeshConfiguration> tessellationGeometry;
|
||||
bool legacyVertex = false;
|
||||
};
|
||||
|
||||
inline constexpr std::uint16_t UnclampedBlendMask = 0xffffu;
|
||||
|
||||
struct ColorTarget {
|
||||
std::uint64_t address;
|
||||
VkExtent2D extent;
|
||||
@@ -305,7 +308,7 @@ struct DrawKeyRange {
|
||||
std::uint32_t first;
|
||||
std::uint32_t count;
|
||||
};
|
||||
inline constexpr std::array<DrawKeyRange, 50> DrawKeyRegisters{{
|
||||
inline constexpr std::array<DrawKeyRange, 52> DrawKeyRegisters{{
|
||||
{RegisterBank::Context, 0x000, 1}, {RegisterBank::Context, 0x002, 2}, {RegisterBank::Context, 0x005, 1}, {RegisterBank::Context, 0x007, 7}, {RegisterBank::Context, 0x010, 6}, {RegisterBank::Context, 0x01a, 5},
|
||||
{RegisterBank::Context, 0x080, 4}, {RegisterBank::Context, 0x08c, 4}, {RegisterBank::Context, 0x090, 2}, {RegisterBank::Context, 0x094, 2}, {RegisterBank::Context, 0x0b4, 2}, {RegisterBank::Context, 0x105, 4}, {RegisterBank::Context, 0x10b, 3}, {RegisterBank::Context, 0x10f, 6},
|
||||
// SPI_PS_INPUT_CNTL_0..31, SPI_PS_INPUT_ENA/ADDR, SPI_PS_IN_CONTROL .. SPI_BARYC_CNTL, SPI_SHADER_POS/Z/COL_FORMAT,
|
||||
@@ -313,13 +316,13 @@ inline constexpr std::array<DrawKeyRange, 50> DrawKeyRegisters{{
|
||||
{RegisterBank::Context, 0x191, 32}, {RegisterBank::Context, 0x1b3, 2}, {RegisterBank::Context, 0x1b6, 3}, {RegisterBank::Context, 0x1c3, 3}, {RegisterBank::Context, 0x1e0, 8}, {RegisterBank::Context, 0x1ff, 1},
|
||||
// DB_DEPTH_CONTROL .. PA_CL_VS_OUT_CNTL, PA_SC_MODE_CNTL_0/1, VGT_GS_MODE, VGT_GS_VERT_ITEMSIZE,
|
||||
// PA_SU_VTX_CNTL, the sample masks, PA_SC_CONSERVATIVE_RASTERIZATION_CNTL.
|
||||
{RegisterBank::Context, 0x200, 8}, {RegisterBank::Context, 0x286, 2}, {RegisterBank::Context, 0x292, 2}, {RegisterBank::Context, 0x29b, 1}, {RegisterBank::Context, 0x2ab, 1}, {RegisterBank::Context, 0x2af, 1}, {RegisterBank::Context, 0x2ce, 1}, {RegisterBank::Context, 0x2d5, 2}, {RegisterBank::Context, 0x2db, 2}, {RegisterBank::Context, 0x2de, 6}, {RegisterBank::Context, 0x2f8, 2}, {RegisterBank::Context, 0x2fe, 16}, {RegisterBank::Context, 0x30e, 2}, {RegisterBank::Context, 0x313, 1},
|
||||
{RegisterBank::Context, 0x200, 8}, {RegisterBank::Context, 0x286, 2}, {RegisterBank::Context, 0x292, 2}, {RegisterBank::Context, 0x29b, 1}, {RegisterBank::Context, 0x2a8, 2}, {RegisterBank::Context, 0x2ab, 1}, {RegisterBank::Context, 0x2af, 1}, {RegisterBank::Context, 0x2ce, 1}, {RegisterBank::Context, 0x2d5, 2}, {RegisterBank::Context, 0x2db, 2}, {RegisterBank::Context, 0x2de, 6}, {RegisterBank::Context, 0x2f8, 2}, {RegisterBank::Context, 0x2fe, 16}, {RegisterBank::Context, 0x30e, 2}, {RegisterBank::Context, 0x313, 1},
|
||||
// CB_COLOR0..7_BASE .. DCC_BASE (15 words a slot), CB_COLOR0..7_BASE_EXT, DCC_BASE_EXT, ATTRIB2, ATTRIB3.
|
||||
{RegisterBank::Context, 0x318, 0x78}, {RegisterBank::Context, 0x390, 8}, {RegisterBank::Context, 0x398, 0x10}, {RegisterBank::Context, 0x3a8, 0x18},
|
||||
// The pixel program address, RSRC2 and user words; the geometry-back user pointer and program
|
||||
// address; the vertex/geometry-front RSRC1/RSRC2 and user words; the vertex program address;
|
||||
// the hull user pointer, program address, RSRC2 and user words; the local program address.
|
||||
{RegisterBank::Shader, 0x008, 0x24}, {RegisterBank::Shader, 0x082, 2}, {RegisterBank::Shader, 0x088, 2}, {RegisterBank::Shader, 0x08a, 0x22}, {RegisterBank::Shader, 0x0c8, 2}, {RegisterBank::Shader, 0x102, 2}, {RegisterBank::Shader, 0x108, 2}, {RegisterBank::Shader, 0x10b, 0x21}, {RegisterBank::Shader, 0x148, 2},
|
||||
{RegisterBank::Shader, 0x008, 0x24}, {RegisterBank::Shader, 0x048, 0x14}, {RegisterBank::Shader, 0x082, 2}, {RegisterBank::Shader, 0x088, 2}, {RegisterBank::Shader, 0x08a, 0x22}, {RegisterBank::Shader, 0x0c8, 2}, {RegisterBank::Shader, 0x102, 2}, {RegisterBank::Shader, 0x108, 2}, {RegisterBank::Shader, 0x10b, 0x21}, {RegisterBank::Shader, 0x148, 2},
|
||||
// GE_PRIM_TYPE, GE_MULTI_PRIM_IB_RESET_EN, the geometry subgroup sizes.
|
||||
{RegisterBank::UserConfig, 0x242, 1}, {RegisterBank::UserConfig, 0x24b, 1}, {RegisterBank::UserConfig, 0x25b, 1},
|
||||
}};
|
||||
|
||||
@@ -163,6 +163,7 @@ private:
|
||||
VkFormat blockFormat = VK_FORMAT_UNDEFINED;
|
||||
bool repackCopy = false;
|
||||
std::uint32_t copyWidth = 0, copyHeight = 0, copyLevels = 0, copyLayers = 0, copyElementBytes = 0;
|
||||
std::uint32_t copyTexelsPerElement = 4;
|
||||
};
|
||||
|
||||
VkFormat AttachmentProxyFormat(const Context& context, VkFormat format);
|
||||
|
||||
@@ -22,6 +22,8 @@ struct TileMipLayout {
|
||||
bool tail;
|
||||
std::uint32_t tailX;
|
||||
std::uint32_t tailY;
|
||||
bool gcnMicroTiled = false;
|
||||
std::uint32_t gcnSplitStride = 0;
|
||||
};
|
||||
|
||||
std::vector<TileMipLayout> ComputeMipLayout(TextureTileMode tileMode, std::uint32_t format, std::uint32_t width, std::uint32_t height, std::uint32_t mipCount);
|
||||
@@ -67,6 +69,10 @@ struct SurfaceGeometry {
|
||||
std::uint32_t blockDepth = 1;
|
||||
std::uint64_t layerBytes = 0;
|
||||
|
||||
bool levelMajor = false;
|
||||
std::uint64_t GuestOffset(std::uint32_t layer, const TileMipLayout& mip) const {
|
||||
return levelMajor ? mip.tiledOffset + static_cast<std::uint64_t>(layer) * mip.tiledSize : GuestLayerOffset(layer) + mip.tiledOffset;
|
||||
}
|
||||
std::uint64_t GuestLayerOffset(std::uint32_t layer) const { return thick ? static_cast<std::uint64_t>(layer / blockDepth) * layerBytes : static_cast<std::uint64_t>(layer) * layerBytes; }
|
||||
std::uint64_t LinearLayerOffset(std::uint32_t layer) const { return static_cast<std::uint64_t>(layer) * sliceLinearBytes; }
|
||||
std::uint32_t CopyLayer(std::uint32_t layer) const { return imageDepth > 1 ? 0u : layer; }
|
||||
@@ -74,6 +80,17 @@ struct SurfaceGeometry {
|
||||
bool HasLayer(std::uint32_t level, std::uint32_t layer) const { return imageDepth <= 1 || layer < std::max(imageDepth >> level, 1u); }
|
||||
};
|
||||
SurfaceGeometry DescribeSurface(const GuestTextureResource& descriptor);
|
||||
std::vector<TileMipLayout> ComputeGcnMipLayout(TextureTileMode tileMode, std::uint32_t format, std::uint32_t width, std::uint32_t height, std::uint32_t pitch, bool pow2Pad, std::uint32_t mipCount, bool linearGeneral = false, std::uint32_t layers = 1);
|
||||
struct GcnTileGeometry {
|
||||
std::uint32_t blockBytes;
|
||||
std::uint32_t blockWidth;
|
||||
std::uint32_t blockHeight;
|
||||
std::array<std::uint32_t, 16> equation;
|
||||
std::uint32_t splitSlices = 1;
|
||||
std::array<std::uint32_t, 4> splitMasks{};
|
||||
};
|
||||
GcnTileGeometry GcnTiling(TextureTileMode tileMode, std::uint32_t bytesPerElement);
|
||||
inline TextureTileMode MipTileMode(TextureTileMode tileMode, const TileMipLayout& mip) { return mip.gcnMicroTiled ? GcnMicroTileMode(tileMode) : tileMode; }
|
||||
bool LevelsFitAllocation(const GuestTextureResource& surface, std::uint32_t levels);
|
||||
GuestTextureResource ViewedArrayWindow(const GuestTextureResource& viewed, bool keysReadAsStored);
|
||||
GuestTextureResource ArrayLayerWindow(const GuestTextureResource& viewed, std::uint32_t maxArrayLayers);
|
||||
|
||||
@@ -427,6 +427,32 @@ inline std::optional<std::uint32_t> HighestDrawIndex(std::span<const std::byte>
|
||||
return indexSize == 2 ? HighestDrawIndexOf<std::uint16_t>(indices, skipRestart) : HighestDrawIndexOf<std::uint32_t>(indices, skipRestart);
|
||||
}
|
||||
|
||||
inline std::uint32_t CompactListRestart(std::span<std::byte> indices, std::uint32_t indexSize, std::uint32_t primitiveSize) {
|
||||
Require(indexSize == 2 || indexSize == 4, "unsupported index size");
|
||||
Require(primitiveSize != 0, "invalid list primitive size");
|
||||
const auto restartIndex = indexSize == 2 ? 0xffffu : 0xffffffffu;
|
||||
std::size_t written = 0;
|
||||
std::size_t primitiveStart = 0;
|
||||
for (std::size_t offset = 0; offset + indexSize <= indices.size(); offset += indexSize) {
|
||||
std::uint32_t index = 0;
|
||||
if (indexSize == 2) {
|
||||
std::uint16_t value = 0;
|
||||
std::memcpy(&value, indices.data() + offset, sizeof(value));
|
||||
index = value;
|
||||
} else {
|
||||
std::memcpy(&index, indices.data() + offset, sizeof(index));
|
||||
}
|
||||
if (index == restartIndex) {
|
||||
written = primitiveStart;
|
||||
continue;
|
||||
}
|
||||
std::memmove(indices.data() + written * indexSize, indices.data() + offset, indexSize);
|
||||
++written;
|
||||
if (written - primitiveStart == primitiveSize) primitiveStart = written;
|
||||
}
|
||||
return static_cast<std::uint32_t>(primitiveStart);
|
||||
}
|
||||
|
||||
inline std::vector<std::uint32_t> MeshRestartTable(std::span<const std::byte> indices, std::uint32_t indexSize) {
|
||||
Require(indexSize == 2 || indexSize == 4, "unsupported index size");
|
||||
const auto restartIndex = indexSize == 2 ? 0xffffu : 0xffffffffu;
|
||||
|
||||
@@ -29,6 +29,10 @@ layout(constant_id = 19) const uint EQ15 = 0u;
|
||||
// Nonzero: block extent in elements (thick 3D blocks are not the thin 2D shape derived below).
|
||||
layout(constant_id = 20) const uint BLOCK_WIDTH = 0u;
|
||||
layout(constant_id = 21) const uint BLOCK_HEIGHT = 0u;
|
||||
layout(constant_id = 22) const uint SPLIT0 = 0u;
|
||||
layout(constant_id = 23) const uint SPLIT1 = 0u;
|
||||
layout(constant_id = 24) const uint SPLIT2 = 0u;
|
||||
layout(constant_id = 25) const uint SPLIT3 = 0u;
|
||||
|
||||
layout(local_size_x = 8, local_size_y = 8) in;
|
||||
|
||||
@@ -64,6 +68,7 @@ layout(push_constant) uniform Push {
|
||||
uint columnBegin;
|
||||
uint rowBegin;
|
||||
uint pipeBankXor;
|
||||
uint splitStride;
|
||||
} params;
|
||||
|
||||
uint equationBit(uint mask, uvec2 p) {
|
||||
@@ -242,6 +247,10 @@ void main() {
|
||||
|
||||
uint blockIndex = block.y * params.blocksPerRow + block.x;
|
||||
uint tiledOffset = blockIndex * BLOCK_BYTES + blockOffset(swizzle);
|
||||
if (SPLIT0 != 0u) {
|
||||
uint split = equationBit(SPLIT0, p) | (equationBit(SPLIT1, p) << 1) | (equationBit(SPLIT2, p) << 2) | (equationBit(SPLIT3, p) << 3);
|
||||
tiledOffset += split * params.splitStride;
|
||||
}
|
||||
if (tiledOffset < params.rangeBegin || tiledOffset >= params.rangeEnd) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -54,6 +54,7 @@ ColorTileMode DecodeColorTileMode(std::uint32_t attrib3) {
|
||||
}
|
||||
|
||||
TileMipLayout ComputeColorTargetMipLayout(ColorTileMode mode, std::uint32_t bytesPerElement, std::uint32_t surfaceWidth, std::uint32_t surfaceHeight, std::uint32_t mipCount, std::uint32_t mipLevel) {
|
||||
require(!ColorTileModeIsGcn(mode), "AGC graphics: PS4 color target mips are laid out by ComputeGcnMipLayout");
|
||||
auto mips = ComputeElementMipLayout(ColorTextureTileMode(mode), bytesPerElement, surfaceWidth, surfaceHeight, mipCount);
|
||||
require(mipLevel < mips.size(), "AGC graphics: color target mip is outside its surface");
|
||||
auto mip = mips[mipLevel];
|
||||
@@ -156,8 +157,22 @@ ColorTargetLayout::ColorTargetLayout(std::uint32_t width, std::uint32_t height,
|
||||
yOffsets = tables.y.data();
|
||||
break;
|
||||
}
|
||||
case ColorTileMode::GcnThin1D:
|
||||
case ColorTileMode::GcnDisplay1D:
|
||||
case ColorTileMode::GcnDisplay2D:
|
||||
case ColorTileMode::GcnThin2D: {
|
||||
const auto geometry = GcnTiling(ColorTextureTileMode(mode), bytesPerElement);
|
||||
blockWidth = geometry.blockWidth;
|
||||
blockHeight = geometry.blockHeight;
|
||||
pitch = (width + blockWidth - 1u) / blockWidth * blockWidth;
|
||||
paddedHeight = (height + blockHeight - 1u) / blockHeight * blockHeight;
|
||||
gcn = true;
|
||||
gcnEquation = geometry.equation;
|
||||
break;
|
||||
}
|
||||
default: throw std::runtime_error("AGC graphics: unsupported color tile mode");
|
||||
}
|
||||
blockBytes = gcn ? static_cast<std::size_t>(blockWidth) * blockHeight * bytesPerElement : ColorTileModeBlockBytes(mode);
|
||||
const auto size = static_cast<std::uint64_t>(pitch) * paddedHeight * bytesPerElement;
|
||||
require(size <= std::numeric_limits<std::size_t>::max(), "AGC graphics: color surface size overflow");
|
||||
bytes = static_cast<std::size_t>(size);
|
||||
@@ -166,6 +181,11 @@ ColorTargetLayout::ColorTargetLayout(std::uint32_t width, std::uint32_t height,
|
||||
std::size_t ColorTargetLayout::offset(std::uint32_t x, std::uint32_t y) const {
|
||||
if (mode == ColorTileMode::Linear) return (static_cast<std::size_t>(y) * pitch + x) * elementBytes;
|
||||
const auto block = static_cast<std::size_t>(y / blockHeight) * (pitch / blockWidth) + x / blockWidth;
|
||||
if (gcn) {
|
||||
std::uint32_t inBlock = 0;
|
||||
for (std::uint32_t bit = 0; bit < 16u; ++bit) inBlock |= parity((x & gcnEquation[bit] & 0xfffu) ^ ((y << 12u) & gcnEquation[bit] & 0xfff000u)) << bit;
|
||||
return block * blockBytes + inBlock;
|
||||
}
|
||||
auto inBlock = xOffsets[x % blockWidth] ^ yOffsets[y % blockHeight];
|
||||
if (equation != nullptr) {
|
||||
const auto highX = (x & ~(blockWidth - 1u)) & 0xfffu;
|
||||
|
||||
@@ -897,9 +897,29 @@ public:
|
||||
std::vector<bool> WrittenUnits(const GuestTextureResource& resource, std::uint64_t& generation) {
|
||||
const auto bytes = static_cast<std::size_t>(DescribeSurface(resource).guestBytes);
|
||||
SizeUnits(bytes);
|
||||
GuestMemory::CollectWrites(resource.baseAddress, bytes);
|
||||
const auto collected = GuestMemory::CollectWrites(resource.baseAddress, bytes);
|
||||
generation = GuestMemory::TrackerGeneration();
|
||||
std::vector<bool> changed(unitGeneration.size(), false);
|
||||
if (collected == 0u) {
|
||||
for (std::size_t unit = 0; unit < unitGeneration.size(); ++unit) {
|
||||
const auto offset = unit * unitBytes;
|
||||
const auto address = resource.baseAddress + offset;
|
||||
const auto length = static_cast<std::size_t>(std::min<std::uint64_t>(unitBytes, bytes - offset));
|
||||
if (GuestMemory::CollectWritesUncached(address, length) != 0u) {
|
||||
changed[unit] = unitGeneration[unit] != 0u && GuestMemory::WrittenSince(address, length, unitGeneration[unit]);
|
||||
continue;
|
||||
}
|
||||
constexpr std::uint64_t pageBytes = 4096u;
|
||||
for (std::size_t page = 0; page < length;) {
|
||||
const auto pageAddress = address + page;
|
||||
const auto pageLength = static_cast<std::size_t>(std::min<std::uint64_t>(length - page, pageBytes - pageAddress % pageBytes));
|
||||
if (GuestMemory::CollectWritesUncached(pageAddress, pageLength) != 0u && unitGeneration[unit] != 0u && GuestMemory::WrittenSince(pageAddress, pageLength, unitGeneration[unit])) changed[unit] = true;
|
||||
page += pageLength;
|
||||
}
|
||||
}
|
||||
generation = GuestMemory::TrackerGeneration();
|
||||
return changed;
|
||||
}
|
||||
if (unitGeneration.size() == 1u) {
|
||||
changed[0] = GuestMemory::WrittenSince(resource.baseAddress, bytes, unitGeneration[0]);
|
||||
return changed;
|
||||
@@ -1299,6 +1319,7 @@ public:
|
||||
Require(requested != 0 && requested <= layers, "depth plane copy slices exceed its layers");
|
||||
Require(baseLayer < requested, "a depth plane copy view starts past the slices it was given");
|
||||
const auto geometry = DescribeSurface(resource);
|
||||
Require(!geometry.levelMajor, "depth planes of a PS4 layered surface with several mip levels (stored level by level) are not implemented");
|
||||
const bool guestFill = std::any_of(slices.begin(), slices.end(), [](const auto& slice) { return slice.image == VK_NULL_HANDLE; });
|
||||
if (guestFill && (geometry.layers != requested || geometry.sliceLinearBytes < sliceBytes() || geometry.mips.empty())) {
|
||||
char text[320];
|
||||
@@ -2510,6 +2531,7 @@ std::shared_ptr<Texture> DepthSurfaceTexture(const Context& context, std::span<c
|
||||
}
|
||||
std::vector<DepthPlaneSlice> slices;
|
||||
const auto geometry = DescribeSurface(resource);
|
||||
Require(!geometry.levelMajor, "depth planes of a PS4 layered surface with several mip levels (stored level by level) are not implemented");
|
||||
for (std::uint32_t layer = 0; layer < layers; ++layer) {
|
||||
const auto address = base.address + geometry.GuestLayerOffset(layer);
|
||||
auto* slice = depthSlice(context.device, address, base);
|
||||
@@ -2646,6 +2668,7 @@ std::shared_ptr<StorageTexture> layeredDepthStorage(const Context& context, Dept
|
||||
const bool d16 = target.format == VK_FORMAT_D16_UNORM || target.format == VK_FORMAT_D16_UNORM_S8_UINT;
|
||||
const auto bytesPerTexel = d16 ? 2u : 4u;
|
||||
surface.RequireStorable(resource);
|
||||
Require(!DescribeSurface(resource).levelMajor, "depth planes of a PS4 layered surface with several mip levels (stored level by level) are not implemented");
|
||||
auto& entry = layeredStorages()[{context.device, resource.baseAddress, resource.width, resource.height, layers, resource.format, static_cast<int>(resource.tileMode), static_cast<int>(resource.dimension), resource.baseArray}];
|
||||
if (entry == nullptr) entry = std::make_unique<LayeredDepthStorage>(context, resource, target, bytesPerTexel, resource.baseArray, layers);
|
||||
else static_cast<void>(entry->storage->Refresh());
|
||||
|
||||
@@ -1298,6 +1298,8 @@ struct DrawInputs {
|
||||
VkBuffer indexHandle = VK_NULL_HANDLE;
|
||||
VkDeviceSize indexOffset = 0;
|
||||
std::uint32_t maxIndex = 0;
|
||||
std::optional<std::uint32_t> indexCount;
|
||||
std::uint32_t listRestartPrimitive = 0;
|
||||
VertexInputLayout vertexInput;
|
||||
std::shared_ptr<const VertexInputLayout> retainedVertexInput;
|
||||
std::vector<std::shared_ptr<Buffer>> vertexBuffers;
|
||||
@@ -1412,6 +1414,7 @@ DrawInputs prepareDrawInputs(const Context& context, const State& state, const P
|
||||
return inputs;
|
||||
}
|
||||
const std::uint32_t corners = state.quadList ? 6u : 3u;
|
||||
Require(primitives <= std::numeric_limits<std::uint32_t>::max() / corners, "expanded index count overflow");
|
||||
const std::uint32_t outputIndexCount = primitives * corners;
|
||||
const std::size_t expandedIndexBytes = static_cast<std::size_t>(outputIndexCount) * sizeof(std::uint32_t);
|
||||
auto indexCopy = std::make_shared<Buffer>(context, expandedIndexBytes, VK_BUFFER_USAGE_INDEX_BUFFER_BIT);
|
||||
@@ -1483,6 +1486,37 @@ DrawInputs prepareDrawInputs(const Context& context, const State& state, const P
|
||||
inputs.indexOffset = 0;
|
||||
inputs.expandedIndexCount = outputIndexCount;
|
||||
inputs.indices = std::move(indexCopy);
|
||||
} else if (draw.indexed && state.primitiveRestart && !context.primitiveListRestart && (state.topology == VK_PRIMITIVE_TOPOLOGY_POINT_LIST || state.topology == VK_PRIMITIVE_TOPOLOGY_LINE_LIST || state.topology == VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST)) {
|
||||
Require(!state.stages.mesh, "AGC graphics: primitive restart in a mesh list draw needs VK_EXT_primitive_topology_list_restart");
|
||||
if (indexBytes == 0) {
|
||||
inputs.nothing = true;
|
||||
return inputs;
|
||||
}
|
||||
GuestMemory::FlushGpuWrites(draw.indexAddress, static_cast<std::size_t>(indexBytes));
|
||||
auto compacted = std::make_shared<Buffer>(context, static_cast<std::size_t>(indexBytes), VK_BUFFER_USAGE_INDEX_BUFFER_BIT);
|
||||
const auto bytes = compacted->Bytes().first(static_cast<std::size_t>(indexBytes));
|
||||
GuestMemory::Read(draw.indexAddress, bytes, draw.indexSize);
|
||||
const auto primitiveSize = state.topology == VK_PRIMITIVE_TOPOLOGY_POINT_LIST ? 1u : state.topology == VK_PRIMITIVE_TOPOLOGY_LINE_LIST ? 2u : 3u;
|
||||
const auto count = draw.indirect ? draw.indexCount : CompactListRestart(bytes, draw.indexSize, primitiveSize);
|
||||
const auto kept = bytes.first(static_cast<std::size_t>(count) * draw.indexSize);
|
||||
const bool restartLeft = draw.indirect.has_value();
|
||||
auto highest = HighestDrawIndex(kept, draw.indexSize, restartLeft);
|
||||
constexpr std::uint32_t ZeroFetchSlack = 0x10000u;
|
||||
if (const auto zeroFrom = highest ? ZeroFetchVertex(shaders.front().program->vertexAttributes) : std::nullopt) {
|
||||
const auto limit = *zeroFrom > draw.firstVertex ? *zeroFrom - draw.firstVertex : 0u;
|
||||
if (*highest >= limit && *highest - limit >= ZeroFetchSlack) highest = ClampDrawIndices(kept, draw.indexSize, restartLeft, limit);
|
||||
}
|
||||
if (!highest) {
|
||||
inputs.nothing = true;
|
||||
return inputs;
|
||||
}
|
||||
Require(*highest <= context.limits.maxDrawIndexedIndexValue, "index exceeds the device's indexed draw limit");
|
||||
inputs.maxIndex = *highest;
|
||||
inputs.indexCount = count;
|
||||
inputs.listRestartPrimitive = primitiveSize;
|
||||
inputs.indices = std::move(compacted);
|
||||
inputs.indexHandle = inputs.indices->Handle();
|
||||
inputs.indexOffset = 0;
|
||||
} else if (draw.indexed) {
|
||||
const bool listTopology = state.topology == VK_PRIMITIVE_TOPOLOGY_POINT_LIST || state.topology == VK_PRIMITIVE_TOPOLOGY_LINE_LIST || state.topology == VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST;
|
||||
const bool fanGeometry = state.stages.mesh && state.stages.mesh->inputPrimitive == 5;
|
||||
@@ -1754,9 +1788,38 @@ struct IndirectRecord {
|
||||
double readMs = 0;
|
||||
};
|
||||
|
||||
void CompactIndirectListRestart(const Context& context, const Pm4::DrawParameters& draw, DrawInputs& inputs, std::vector<Pm4::DrawArguments>& records) {
|
||||
const auto bound = inputs.indexCount.value_or(draw.indexCount);
|
||||
const auto raw = inputs.indices->Bytes();
|
||||
std::uint64_t total = 0;
|
||||
for (const auto& record : records) {
|
||||
if (record.count != 0 && record.instances != 0 && record.firstVertexOrIndex < bound) total += std::min(record.count, bound - record.firstVertexOrIndex);
|
||||
}
|
||||
Require(total <= std::numeric_limits<std::uint32_t>::max(), "indirect list restart index count overflow");
|
||||
auto compacted = std::make_shared<Buffer>(context, static_cast<std::size_t>(std::max<std::uint64_t>(total, 1u) * draw.indexSize), VK_BUFFER_USAGE_INDEX_BUFFER_BIT);
|
||||
const auto out = compacted->Bytes();
|
||||
std::uint32_t cursor = 0;
|
||||
for (auto& record : records) {
|
||||
if (record.count == 0 || record.instances == 0 || record.firstVertexOrIndex >= bound) {
|
||||
record.count = 0;
|
||||
continue;
|
||||
}
|
||||
const auto count = std::min(record.count, bound - record.firstVertexOrIndex);
|
||||
const auto at = out.subspan(static_cast<std::size_t>(cursor) * draw.indexSize, static_cast<std::size_t>(count) * draw.indexSize);
|
||||
std::memcpy(at.data(), raw.data() + static_cast<std::size_t>(record.firstVertexOrIndex) * draw.indexSize, at.size());
|
||||
record.count = CompactListRestart(at, draw.indexSize, inputs.listRestartPrimitive);
|
||||
record.firstVertexOrIndex = cursor;
|
||||
cursor += record.count;
|
||||
}
|
||||
inputs.indexCount = cursor;
|
||||
inputs.indices = std::move(compacted);
|
||||
inputs.indexHandle = inputs.indices->Handle();
|
||||
inputs.indexOffset = 0;
|
||||
}
|
||||
|
||||
// The draw commands of one draw: the vertex and index buffer binds, then the direct draw, the
|
||||
// GPU-side indirect draw from `argumentBuffer` or the CPU-read records with the driver's rules.
|
||||
void recordDrawCommands(const Context& context, VkCommandBuffer commands, const State& state, const Pm4::DrawParameters& draw, const DrawInputs& inputs, const IndirectRecord* indirect, VkBuffer argumentBuffer, VkDeviceSize argumentOffset, const DrawTraceContext* trace, std::uint32_t& subdraw, std::uint32_t firstIndex = 0) {
|
||||
void recordDrawCommands(const Context& context, VkCommandBuffer commands, const State& state, const Pm4::DrawParameters& draw, const DrawInputs& inputs, const IndirectRecord* indirect, VkBuffer argumentBuffer, VkDeviceSize argumentOffset, const DrawTraceContext* trace, std::uint32_t& subdraw, std::optional<std::uint32_t> pieceFirstIndex = std::nullopt) {
|
||||
if (context.recorder != nullptr) context.recorder->NoteSampledDraw(commands);
|
||||
const auto recorded = [&](std::uint32_t index) {
|
||||
if (trace != nullptr && context.recorder != nullptr) {
|
||||
@@ -1785,7 +1848,7 @@ void recordDrawCommands(const Context& context, VkCommandBuffer commands, const
|
||||
if (draw.indexed) context.Resolved(&DeviceFunctions::cmdBindIndexBuffer, "vkCmdBindIndexBuffer")(commands, inputs.indexHandle, inputs.indexOffset, draw.indexSize == 2 ? VK_INDEX_TYPE_UINT16 : VK_INDEX_TYPE_UINT32);
|
||||
if (args == nullptr) {
|
||||
if (draw.indexed) {
|
||||
context.Resolved(&DeviceFunctions::cmdDrawIndexed, "vkCmdDrawIndexed")(commands, draw.indexCount, draw.instanceCount, firstIndex, static_cast<std::int32_t>(draw.firstVertex), draw.firstInstance);
|
||||
context.Resolved(&DeviceFunctions::cmdDrawIndexed, "vkCmdDrawIndexed")(commands, pieceFirstIndex ? draw.indexCount : inputs.indexCount.value_or(draw.indexCount), draw.instanceCount, pieceFirstIndex.value_or(0u), static_cast<std::int32_t>(draw.firstVertex), draw.firstInstance);
|
||||
recorded(subdraw++);
|
||||
} else {
|
||||
context.Resolved(&DeviceFunctions::cmdDraw, "vkCmdDraw")(commands, draw.indexCount, draw.instanceCount, draw.firstVertex, draw.firstInstance);
|
||||
@@ -1814,9 +1877,10 @@ void recordDrawCommands(const Context& context, VkCommandBuffer commands, const
|
||||
const auto firstInstance = args->instanceRule == Rule::InPlace ? record.firstInstance : args->instanceConstant;
|
||||
if (draw.indexed) {
|
||||
// The CP clamps the index range to INDEX_BUFFER_SIZE (the bound copy).
|
||||
if (record.firstVertexOrIndex >= draw.indexCount) continue;
|
||||
const auto boundCount = inputs.indexCount.value_or(draw.indexCount);
|
||||
if (record.firstVertexOrIndex >= boundCount) continue;
|
||||
const auto vertexOffset = args->vertexRule == Rule::InPlace ? record.vertexOffset : args->vertexConstant;
|
||||
context.Resolved(&DeviceFunctions::cmdDrawIndexed, "vkCmdDrawIndexed")(commands, std::min(record.count, draw.indexCount - record.firstVertexOrIndex), record.instances, record.firstVertexOrIndex, static_cast<std::int32_t>(vertexOffset), firstInstance);
|
||||
context.Resolved(&DeviceFunctions::cmdDrawIndexed, "vkCmdDrawIndexed")(commands, std::min(record.count, boundCount - record.firstVertexOrIndex), record.instances, record.firstVertexOrIndex, static_cast<std::int32_t>(vertexOffset), firstInstance);
|
||||
} else {
|
||||
const auto firstVertex = args->vertexRule == Rule::InPlace ? record.firstVertexOrIndex : args->vertexConstant;
|
||||
context.Resolved(&DeviceFunctions::cmdDraw, "vkCmdDraw")(commands, record.count, record.instances, firstVertex, firstInstance);
|
||||
@@ -2047,7 +2111,7 @@ void recordStencilReplay(const Context& context, VkCommandBuffer commands, const
|
||||
Require(fragment != shaders.end(), "stencil replay fragment stage is missing");
|
||||
const auto referenceOffset = fragment->pushConstantOffset + fragment->program->stencilReferenceDword * sizeof(std::uint32_t);
|
||||
Require(referenceOffset <= block.size() - sizeof(std::uint32_t), "stencil replay reference exceeds the push block");
|
||||
const auto run = [&](const Pm4::DrawParameters& piece, std::uint32_t firstIndex) {
|
||||
const auto run = [&](const Pm4::DrawParameters& piece, std::optional<std::uint32_t> firstIndex) {
|
||||
std::uint32_t unusedSubdraw = 0;
|
||||
for (const auto& [reference, pipeline] : replay) {
|
||||
selected.stencilReplayReference = reference;
|
||||
@@ -2060,11 +2124,12 @@ void recordStencilReplay(const Context& context, VkCommandBuffer commands, const
|
||||
}
|
||||
};
|
||||
if (replay.size() == 1u) {
|
||||
run(draw, 0u);
|
||||
run(draw, std::nullopt);
|
||||
return;
|
||||
}
|
||||
const auto indexCount = draw.indexed ? inputs.indexCount.value_or(draw.indexCount) : draw.indexCount;
|
||||
for (std::uint32_t instance = 0; instance < draw.instanceCount; ++instance) {
|
||||
for (std::uint32_t first = 0; first < draw.indexCount - draw.indexCount % 3u; first += 3u) {
|
||||
for (std::uint32_t first = 0; first < indexCount - indexCount % 3u; first += 3u) {
|
||||
auto piece = draw;
|
||||
piece.instanceCount = 1u;
|
||||
piece.firstInstance = draw.firstInstance + instance;
|
||||
@@ -2515,6 +2580,7 @@ struct PreparedDraw {
|
||||
PreparedDraw& operator=(const PreparedDraw&) = delete;
|
||||
std::shared_ptr<const DrawRecipe>* recipeOut = nullptr;
|
||||
const DrawTraceContext* trace = nullptr;
|
||||
std::uint64_t shape = 0;
|
||||
std::vector<std::uint32_t> stencilReferences;
|
||||
std::optional<PerformanceTimer> timing;
|
||||
DrawTimer timer;
|
||||
@@ -2547,6 +2613,137 @@ struct PreparedDraw {
|
||||
std::optional<DepthSampleLocations> depthLocations;
|
||||
};
|
||||
|
||||
bool ShapeMemoEnabled() {
|
||||
static const bool enabled = std::getenv("APS5_NO_SHAPE_MEMO") == nullptr;
|
||||
return enabled;
|
||||
}
|
||||
|
||||
bool VerifyShapeMemo() {
|
||||
static const bool verify = std::getenv("APS5_VERIFY_SHAPE_MEMO") != nullptr;
|
||||
return verify;
|
||||
}
|
||||
|
||||
void noteShapeMemoVerified(bool pipeline) {
|
||||
static std::atomic<std::uint64_t> targets{0};
|
||||
static std::atomic<std::uint64_t> pipelines{0};
|
||||
static std::atomic<std::int64_t> last{0};
|
||||
(pipeline ? pipelines : targets).fetch_add(1, std::memory_order_relaxed);
|
||||
const auto now = std::chrono::duration_cast<std::chrono::seconds>(std::chrono::steady_clock::now().time_since_epoch()).count();
|
||||
auto previous = last.load(std::memory_order_relaxed);
|
||||
if (now - previous < 10 || !last.compare_exchange_strong(previous, now)) return;
|
||||
std::fprintf(stderr, "[shape-memo] verified %llu targets and %llu pipelines\n", static_cast<unsigned long long>(targets.load()), static_cast<unsigned long long>(pipelines.load()));
|
||||
}
|
||||
|
||||
struct ShapeChoice {
|
||||
VkImageLayout attachmentLayout = VK_IMAGE_LAYOUT_UNDEFINED;
|
||||
std::uint32_t fragmentOutputs = 0;
|
||||
std::vector<std::uint64_t> stages;
|
||||
std::vector<VkVertexInputBindingDescription> bindings;
|
||||
std::vector<VkVertexInputAttributeDescription> attributes;
|
||||
std::vector<std::uint32_t> mainKey;
|
||||
std::vector<std::uint32_t> fragmentKey;
|
||||
std::uint64_t hash = 0;
|
||||
std::weak_ptr<Pipeline> pipeline;
|
||||
};
|
||||
|
||||
struct ShapeEntry {
|
||||
VkDevice device = VK_NULL_HANDLE;
|
||||
std::vector<std::weak_ptr<StorageTexture>> targets;
|
||||
std::vector<ShapeChoice> choices;
|
||||
};
|
||||
|
||||
struct ShapeMemoStorage {};
|
||||
constexpr std::size_t ShapeMemoEntries = 4096;
|
||||
constexpr std::size_t ShapeMemoChoices = 4;
|
||||
|
||||
std::unordered_map<std::uint64_t, ShapeEntry>& shapeMemo() {
|
||||
return HostThreadLocal<std::unordered_map<std::uint64_t, ShapeEntry>, ShapeMemoStorage>();
|
||||
}
|
||||
|
||||
const ShapeEntry* findShape(const Context& context, std::uint64_t shape) {
|
||||
if (shape == 0 || !ShapeMemoEnabled()) return nullptr;
|
||||
const auto& entries = shapeMemo();
|
||||
const auto found = entries.find(shape);
|
||||
return found == entries.end() || found->second.device != context.device ? nullptr : &found->second;
|
||||
}
|
||||
|
||||
std::shared_ptr<StorageTexture> shapeTarget(const Context& context, std::uint64_t shape, std::size_t index) {
|
||||
const auto* entry = findShape(context, shape);
|
||||
return entry == nullptr || index >= entry->targets.size() ? nullptr : entry->targets[index].lock();
|
||||
}
|
||||
|
||||
bool sameStages(std::span<const std::uint64_t> kept, std::span<const CompiledShader> shaders) {
|
||||
if (kept.size() != shaders.size() * 4u + 1u) return false;
|
||||
std::size_t at = 0;
|
||||
for (const auto& shader : shaders) {
|
||||
const auto identity = shader.program->Identity();
|
||||
if (identity.Empty() || kept[at] != static_cast<std::uint64_t>(shader.stage) || kept[at + 1] != identity.low || kept[at + 2] != identity.high || kept[at + 3] != shader.pushConstantOffset) return false;
|
||||
at += 4;
|
||||
}
|
||||
return kept[at] == PushConstantStages(shaders);
|
||||
}
|
||||
|
||||
bool sameChoice(const ShapeChoice& choice, const VertexInputLayout& input, const PipelineSetLayouts& layouts, std::span<const CompiledShader> shaders, VkImageLayout attachmentLayout, std::uint32_t fragmentOutputs) {
|
||||
const auto sameBinding = [](const VkVertexInputBindingDescription& a, const VkVertexInputBindingDescription& b) { return a.binding == b.binding && a.stride == b.stride && a.inputRate == b.inputRate; };
|
||||
const auto sameAttribute = [](const VkVertexInputAttributeDescription& a, const VkVertexInputAttributeDescription& b) { return a.location == b.location && a.binding == b.binding && a.format == b.format && a.offset == b.offset; };
|
||||
return choice.attachmentLayout == attachmentLayout && choice.fragmentOutputs == fragmentOutputs && std::ranges::equal(choice.bindings, input.bindings, sameBinding) && std::ranges::equal(choice.attributes, input.attributes, sameAttribute) && std::ranges::equal(choice.mainKey, layouts.mainKey) && std::ranges::equal(choice.fragmentKey, layouts.fragmentKey) && sameStages(choice.stages, shaders);
|
||||
}
|
||||
|
||||
std::shared_ptr<Pipeline> shapePipeline(const Context& context, std::uint64_t shape, const VertexInputLayout& input, const PipelineSetLayouts& layouts, std::span<const CompiledShader> shaders, VkImageLayout attachmentLayout, std::uint32_t fragmentOutputs) {
|
||||
const auto* entry = findShape(context, shape);
|
||||
if (entry == nullptr) return nullptr;
|
||||
for (const auto& choice : entry->choices) {
|
||||
if (!sameChoice(choice, input, layouts, shaders, attachmentLayout, fragmentOutputs)) continue;
|
||||
const auto hash = choice.hash;
|
||||
const auto expected = choice.pipeline;
|
||||
return TouchCachedPipeline(context, hash, expected);
|
||||
}
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
void rememberShape(const Context& context, std::uint64_t shape, std::span<const TargetBinding> targets, const std::shared_ptr<Pipeline>* pipeline, std::uint64_t hash, const VertexInputLayout& input, const PipelineSetLayouts& layouts, std::span<const CompiledShader> shaders, VkImageLayout attachmentLayout, std::uint32_t fragmentOutputs) {
|
||||
if (shape == 0 || !ShapeMemoEnabled()) return;
|
||||
auto& entries = shapeMemo();
|
||||
if (entries.size() >= ShapeMemoEntries && !entries.contains(shape)) entries.clear();
|
||||
auto& entry = entries[shape];
|
||||
if (entry.device != context.device) {
|
||||
entry = {};
|
||||
entry.device = context.device;
|
||||
}
|
||||
entry.targets.resize(targets.size());
|
||||
for (std::size_t index = 0; index < targets.size(); ++index) {
|
||||
const auto& resident = targets[index].resident;
|
||||
if (resident == nullptr || targets[index].color.arrayLastSlice != 0) entry.targets[index].reset();
|
||||
else if (entry.targets[index].owner_before(resident) || resident.owner_before(entry.targets[index])) entry.targets[index] = resident;
|
||||
}
|
||||
if (pipeline == nullptr || hash == 0) return;
|
||||
auto& choices = entry.choices;
|
||||
const auto kept = std::ranges::find_if(choices, [&](const ShapeChoice& choice) { return sameChoice(choice, input, layouts, shaders, attachmentLayout, fragmentOutputs); });
|
||||
if (kept != choices.end()) {
|
||||
kept->hash = hash;
|
||||
kept->pipeline = *pipeline;
|
||||
std::rotate(choices.begin(), kept, std::next(kept));
|
||||
return;
|
||||
}
|
||||
ShapeChoice choice;
|
||||
choice.attachmentLayout = attachmentLayout;
|
||||
choice.fragmentOutputs = fragmentOutputs;
|
||||
for (const auto& shader : shaders) {
|
||||
const auto identity = shader.program->Identity();
|
||||
if (identity.Empty()) return;
|
||||
choice.stages.insert(choice.stages.end(), {static_cast<std::uint64_t>(shader.stage), identity.low, identity.high, shader.pushConstantOffset});
|
||||
}
|
||||
choice.stages.push_back(PushConstantStages(shaders));
|
||||
choice.bindings = input.bindings;
|
||||
choice.attributes = input.attributes;
|
||||
choice.mainKey.assign(layouts.mainKey.begin(), layouts.mainKey.end());
|
||||
choice.fragmentKey.assign(layouts.fragmentKey.begin(), layouts.fragmentKey.end());
|
||||
choice.hash = hash;
|
||||
choice.pipeline = *pipeline;
|
||||
if (choices.size() >= ShapeMemoChoices) choices.pop_back();
|
||||
choices.insert(choices.begin(), std::move(choice));
|
||||
}
|
||||
|
||||
bool prepareDraw(const Context& context, const State& state, const Pm4::DrawParameters& draw, std::span<const CompiledShader> shaders, std::span<const GuestMemorySnapshot> snapshots, PreparedDraw& prepared) {
|
||||
auto*& recipeOut = prepared.recipeOut;
|
||||
auto& stencilReferences = prepared.stencilReferences;
|
||||
@@ -2650,7 +2847,13 @@ bool prepareDraw(const Context& context, const State& state, const Pm4::DrawPara
|
||||
Require(resident->Attachable(), "storage format cannot be a color attachment");
|
||||
return resident;
|
||||
}
|
||||
auto resident = CachedStorageSurface(context, SurfaceForTarget(color));
|
||||
const auto surface = SurfaceForTarget(color);
|
||||
auto resident = RepeatStorageSurface(context, surface, shapeTarget(context, prepared.shape, index));
|
||||
if (resident != nullptr && VerifyShapeMemo()) {
|
||||
Require(CachedStorageSurface(context, surface) == resident, "APS5_VERIFY_SHAPE_MEMO: the shape memo's resident target differs from the storage cache's");
|
||||
noteShapeMemoVerified(false);
|
||||
}
|
||||
if (resident == nullptr) resident = CachedStorageSurface(context, surface);
|
||||
Require(resident->Attachable(), "storage format cannot be a color attachment");
|
||||
Require(color.mipCount > 1 || color.depth > 1 || resident->GuestBytes() == colorLayout.Bytes(), "resident image layout differs from the color layout");
|
||||
return resident;
|
||||
@@ -2791,6 +2994,7 @@ bool prepareDraw(const Context& context, const State& state, const Pm4::DrawPara
|
||||
}
|
||||
Require(rangeBytes <= std::numeric_limits<std::size_t>::max(), "indirect draw record range overflow");
|
||||
if (!gpuIndirectDraws) indirect.path = IndirectDrawPath::Disabled;
|
||||
else if (inputs.listRestartPrimitive != 0) indirect.path = IndirectDrawPath::FeatureGap;
|
||||
else indirect.path = decide(args->arguments, static_cast<std::size_t>(rangeBytes), indirect.argumentImport);
|
||||
if (indirect.path == IndirectDrawPath::Gpu && args->countIndirect) {
|
||||
Require(context.drawIndirectCount, "indirect draw count without VK_KHR_draw_indirect_count must be resolved by the driver");
|
||||
@@ -2804,6 +3008,7 @@ bool prepareDraw(const Context& context, const State& state, const Pm4::DrawPara
|
||||
records.reserve(count);
|
||||
for (std::uint32_t record = 0; record < count; ++record) records.push_back(Pm4::ReadDrawArguments(*args, record));
|
||||
indirect.readMs = std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - readStart).count();
|
||||
if (inputs.listRestartPrimitive != 0) CompactIndirectListRestart(context, draw, inputs, records);
|
||||
indirect.records = records;
|
||||
if (std::none_of(records.begin(), records.end(), [](const Pm4::DrawArguments& record) { return record.count != 0 && record.instances != 0; })) {
|
||||
CountIndirectDraw(indirect.path, indirect.readMs);
|
||||
@@ -2910,7 +3115,22 @@ bool prepareDraw(const Context& context, const State& state, const Pm4::DrawPara
|
||||
stencilReplay.emplace_back(reference, std::move(selectedPipeline));
|
||||
}
|
||||
auto& pipeline = prepared.pipeline;
|
||||
pipeline = stencilReplay.empty() ? CachedPipeline(context, pipelineState, inputs.VertexLayout(), *resources, shaders, lean ? VK_IMAGE_LAYOUT_GENERAL : VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL) : stencilReplay.front().second;
|
||||
const auto attachmentLayout = lean ? VK_IMAGE_LAYOUT_GENERAL : VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
|
||||
if (!stencilReplay.empty()) {
|
||||
pipeline = stencilReplay.front().second;
|
||||
} else {
|
||||
const bool memoized = stencilReferences.empty() && std::none_of(targets.begin(), targets.end(), [](const TargetBinding& binding) { return binding.proxied || binding.multisampled; });
|
||||
const auto layouts = resources->SetLayouts();
|
||||
std::uint64_t storeHash = 0;
|
||||
if (memoized) pipeline = shapePipeline(context, prepared.shape, inputs.VertexLayout(), layouts, shaders, attachmentLayout, inputs.fragmentOutputs);
|
||||
if (pipeline != nullptr && VerifyShapeMemo()) {
|
||||
Require(CachedPipeline(context, pipelineState, inputs.VertexLayout(), layouts, shaders, attachmentLayout) == pipeline, "APS5_VERIFY_SHAPE_MEMO: the shape memo's pipeline differs from the pipeline store's");
|
||||
noteShapeMemoVerified(true);
|
||||
}
|
||||
const bool repeated = pipeline != nullptr;
|
||||
if (!repeated) pipeline = CachedPipeline(context, pipelineState, inputs.VertexLayout(), layouts, shaders, attachmentLayout, nullptr, &storeHash);
|
||||
if (memoized) rememberShape(context, prepared.shape, targets, repeated ? nullptr : &pipeline, storeHash, inputs.VertexLayout(), layouts, shaders, attachmentLayout, inputs.fragmentOutputs);
|
||||
}
|
||||
// Resident targets' views are stable while their storage image lives, so the framebuffer is
|
||||
// reused with the pipeline; a per-draw RenderTarget gets a framebuffer of its own.
|
||||
auto& owners = prepared.owners;
|
||||
@@ -3374,7 +3594,7 @@ void drawTessellationGeometry(const Context& context, const State& state, const
|
||||
Draw(context, meshed, captured, second, snapshots, nullptr, trace);
|
||||
}
|
||||
|
||||
void Draw(const Context& context, const State& state, const Pm4::DrawParameters& draw, std::span<const CompiledShader> shaders, std::span<const GuestMemorySnapshot> snapshots, std::shared_ptr<const DrawRecipe>* recipeOut, const DrawTraceContext* trace) {
|
||||
void Draw(const Context& context, const State& state, const Pm4::DrawParameters& draw, std::span<const CompiledShader> shaders, std::span<const GuestMemorySnapshot> snapshots, std::shared_ptr<const DrawRecipe>* recipeOut, const DrawTraceContext* trace, std::uint64_t shape) {
|
||||
const DepthCopySourceScope depthCopySource(state.depthCopySource);
|
||||
if (state.stages.tessellationGeometry) {
|
||||
drawTessellationGeometry(context, state, draw, shaders, snapshots, trace);
|
||||
@@ -3384,6 +3604,7 @@ void Draw(const Context& context, const State& state, const Pm4::DrawParameters&
|
||||
PreparedDraw prepared(profile);
|
||||
prepared.recipeOut = recipeOut;
|
||||
prepared.trace = trace;
|
||||
prepared.shape = shape;
|
||||
if (prepareDraw(context, state, draw, shaders, snapshots, prepared)) recordPreparedDraw(context, state, draw, shaders, prepared);
|
||||
}
|
||||
|
||||
|
||||
@@ -5416,6 +5416,7 @@ void GuestBufferMemory::UploadFinish(bool addressable) {
|
||||
if (space != nullptr) completeSpaceWrites();
|
||||
uploaded = true;
|
||||
for (const auto& region : regions) static_cast<void>(FlushDepthPlanes(region.begin, static_cast<std::size_t>(region.end - region.begin)));
|
||||
for (const auto& [begin, end] : writes) RequireNoResidentDepthRead_nid_no_patch(begin, static_cast<std::size_t>(end - begin));
|
||||
for (const auto& [begin, end] : writes) StorageTexture::FlushPending(begin, static_cast<std::size_t>(end - begin), nullptr, "written buffer range");
|
||||
if (context.hostImportAlignment != 0) {
|
||||
auto& state = Imports();
|
||||
|
||||
@@ -4,6 +4,8 @@
|
||||
#include "prx/libSceAgcDriver/Graphics/include/TextureTiling.hpp"
|
||||
#include "prx/libSceAgcDriver/Graphics/include/TextureFormat.hpp"
|
||||
#include "RdnaDecoder/RdnaDescriptorFormat.hpp"
|
||||
#include "RdnaDecoder/RdnaInstructionDecoder.hpp"
|
||||
#include <array>
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
#include <bit>
|
||||
@@ -40,6 +42,28 @@ TextureTileMode resolveTileMode(std::uint32_t raw) {
|
||||
}
|
||||
}
|
||||
|
||||
TextureTileMode resolveGcnTileMode(std::uint32_t index) {
|
||||
switch (index) {
|
||||
case 0u: return TextureTileMode::kGcnDepth2D64;
|
||||
case 1u: return TextureTileMode::kGcnDepth2D128;
|
||||
case 2u: return TextureTileMode::kGcnDepth2D256;
|
||||
case 3u: return TextureTileMode::kGcnDepth2D512;
|
||||
case 4u: return TextureTileMode::kGcnDepth2D1K;
|
||||
case 6u: return TextureTileMode::kGcnDepthPrt256;
|
||||
case 7u: return TextureTileMode::kGcnDepthPrt1K;
|
||||
case 8u: case 31u: return TextureTileMode::kLinear;
|
||||
case 11u: return TextureTileMode::kGcnDisplayPrt;
|
||||
case 12u: return TextureTileMode::kGcnDisplay2DPrt;
|
||||
case 16u: return TextureTileMode::kGcnThinPrt;
|
||||
case 17u: return TextureTileMode::kGcnThin2DPrt;
|
||||
case 5u: case 13u: return TextureTileMode::kGcnThin1D;
|
||||
case 9u: return TextureTileMode::kGcnDisplay1D;
|
||||
case 10u: return TextureTileMode::kGcnDisplay2D;
|
||||
case 14u: return TextureTileMode::kGcnThin2D;
|
||||
default: throw std::runtime_error("AGC graphics: PS4 texture tile mode index " + std::to_string(index) + " (3D or thick) is not implemented");
|
||||
}
|
||||
}
|
||||
|
||||
TextureDimension resolveDimension(std::uint32_t raw) {
|
||||
switch (raw) {
|
||||
case 8: return TextureDimension::k1D;
|
||||
@@ -101,8 +125,14 @@ bool IsNullTextureResource(std::span<const std::uint32_t> words) {
|
||||
return base40 == 0 || type <= 1;
|
||||
}
|
||||
|
||||
GuestTextureResource DecodeTextureResource(std::span<const std::uint32_t> words) {
|
||||
Require(words.size() == 8, "guest texture descriptor must contain 8 dwords");
|
||||
GuestTextureResource DecodeTextureResource(std::span<const std::uint32_t> descriptor) {
|
||||
Require(descriptor.size() == 8, "guest texture descriptor must contain 8 dwords");
|
||||
const bool gcn = ShaderRecompiler::GcnGuestShaders();
|
||||
std::array<std::uint32_t, 8> local{};
|
||||
std::copy(descriptor.begin(), descriptor.end(), local.begin());
|
||||
const auto gcnTiling = gcn ? local[7] : 0u;
|
||||
if (gcn) local[6] = local[7] = 0u;
|
||||
const std::span<const std::uint32_t> words(local);
|
||||
|
||||
const auto base40 = (static_cast<std::uint64_t>(words[0]) | (static_cast<std::uint64_t>(words[1]) << 32u)) & 0xffffffffffull;
|
||||
auto baseAddress = base40 << 8u;
|
||||
@@ -191,11 +221,11 @@ GuestTextureResource DecodeTextureResource(std::span<const std::uint32_t> words)
|
||||
for (const auto selector : {dstSelX, dstSelY, dstSelZ, dstSelW}) Require(identity || selector == 0u || selector == 1u || selector == 4u, "FMASK destination channel selector is not implemented");
|
||||
}
|
||||
|
||||
const auto describe = [&] { return " (format " + std::to_string(format) + ", " + std::to_string(width) + "x" + std::to_string(height) + "x" + std::to_string(depth + 1) + ", type " + std::to_string(typeRaw) + ", tile " + std::to_string(tileModeRaw) + ", mips " + std::to_string(baseLevel) + ".." + std::to_string(lastLevel) + " of " + std::to_string(maxMip + 1) + ")"; };
|
||||
const auto describe = [&] { return " (format " + std::to_string(format) + ", " + std::to_string(width) + "x" + std::to_string(height) + "x" + std::to_string(depth + 1) + ", type " + std::to_string(typeRaw) + (gcn ? ", PS4 tile index " + std::to_string(ShaderRecompiler::GcnImageTilingIndex(gcnTiling)) : ", tile " + std::to_string(tileModeRaw)) + ", mips " + std::to_string(baseLevel) + ".." + std::to_string(lastLevel) + " of " + std::to_string(maxMip + 1) + ")"; };
|
||||
TextureTileMode tileMode;
|
||||
TextureDimension dimension;
|
||||
try {
|
||||
tileMode = resolveTileMode(tileModeRaw);
|
||||
tileMode = gcn ? resolveGcnTileMode(ShaderRecompiler::GcnImageTilingIndex(gcnTiling)) : resolveTileMode(tileModeRaw);
|
||||
dimension = resolveDimension(typeRaw);
|
||||
} catch (const std::exception& error) {
|
||||
throw std::runtime_error(std::string(error.what()) + describe());
|
||||
@@ -278,6 +308,12 @@ GuestTextureResource DecodeTextureResource(std::span<const std::uint32_t> words)
|
||||
result.iterate256 = iterate256;
|
||||
result.minLod = minLod;
|
||||
result.samples = samples;
|
||||
if (gcn) {
|
||||
result.gcnPitch = ShaderRecompiler::GcnImagePitch(gcnTiling);
|
||||
result.gcnPow2Pad = ShaderRecompiler::GcnImagePow2Pad(gcnTiling);
|
||||
result.gcnLinearGeneral = ShaderRecompiler::GcnImageTilingIndex(gcnTiling) == 31u;
|
||||
Require(result.gcnPitch >= width, "PS4 texture descriptor has a pitch below its width" + describe());
|
||||
}
|
||||
if (baseLevel > maxMip) {
|
||||
const bool fits = LevelsFitAllocation(result, lastLevel + 1u);
|
||||
if (!fits && ZeroTail(words)) {
|
||||
|
||||
@@ -675,6 +675,13 @@ Pipeline::Pipeline(const Context& context, const State& state, const VertexInput
|
||||
const bool alternateAlpha = SplitsAlternateAlpha(state);
|
||||
std::vector<VkPipelineColorBlendAttachmentState> firstChannels(state.blends.begin(), state.blends.end());
|
||||
std::vector<VkPipelineColorBlendAttachmentState> secondChannels(state.blends.begin(), state.blends.end());
|
||||
for (const auto& merged : state.colors) {
|
||||
if (merged.partialWriteMask != UnclampedBlendMask) continue;
|
||||
for (auto* channels : {&firstChannels, &secondChannels}) {
|
||||
channels->at(merged.exportIndex).blendEnable = VK_FALSE;
|
||||
channels->at(merged.exportIndex).colorWriteMask = 0;
|
||||
}
|
||||
}
|
||||
if (alternateAlpha) {
|
||||
const auto keepsStencil = [](const VkStencilOpState& face) { return face.writeMask == 0 || (face.failOp == VK_STENCIL_OP_KEEP && face.passOp == VK_STENCIL_OP_KEEP && face.depthFailOp == VK_STENCIL_OP_KEEP); };
|
||||
Require(!(state.depth && (state.depthWrite || (state.stencilTest && (!keepsStencil(state.stencilFront) || !keepsStencil(state.stencilBack))))) && !state.depthBiasPerFace, "blending into an 8_8 color target with the alternate component order and a separate alpha blend from a draw that writes depth or stencil is not implemented");
|
||||
@@ -1228,9 +1235,10 @@ std::shared_ptr<Pipeline> CachedPipeline(const Context& context, const State& st
|
||||
return CachedPipeline(context, state, vertexInput, resources.SetLayouts(), shaders, attachmentLayout);
|
||||
}
|
||||
|
||||
std::shared_ptr<Pipeline> CachedPipeline(const Context& context, const State& state, const VertexInputLayout& vertexInput, const PipelineSetLayouts& resources, std::span<const CompiledShader> shaders, VkImageLayout attachmentLayout, bool* created) {
|
||||
std::shared_ptr<Pipeline> CachedPipeline(const Context& context, const State& state, const VertexInputLayout& vertexInput, const PipelineSetLayouts& resources, std::span<const CompiledShader> shaders, VkImageLayout attachmentLayout, bool* created, std::uint64_t* storeHash) {
|
||||
static const bool disabled = std::getenv("APS5_NO_PIPELINE_CACHE") != nullptr;
|
||||
if (created != nullptr) *created = false;
|
||||
if (storeHash != nullptr) *storeHash = 0;
|
||||
if (disabled) return std::make_shared<Pipeline>(context, state, vertexInput, resources, shaders, attachmentLayout);
|
||||
auto& store = Pipelines();
|
||||
struct PipelineKeyStorage {};
|
||||
@@ -1270,6 +1278,7 @@ std::shared_ptr<Pipeline> CachedPipeline(const Context& context, const State& st
|
||||
if (auto pipeline = lookup(collision)) {
|
||||
++store.hits;
|
||||
++store.totals.hits;
|
||||
if (storeHash != nullptr) *storeHash = hash;
|
||||
return pipeline;
|
||||
}
|
||||
if (collision) {
|
||||
@@ -1290,7 +1299,10 @@ std::shared_ptr<Pipeline> CachedPipeline(const Context& context, const State& st
|
||||
{
|
||||
std::lock_guard lock(store.mutex);
|
||||
bool collision = false;
|
||||
if (auto raced = lookup(collision)) return raced;
|
||||
if (auto raced = lookup(collision)) {
|
||||
if (storeHash != nullptr) *storeHash = hash;
|
||||
return raced;
|
||||
}
|
||||
if (collision) {
|
||||
++store.uncached;
|
||||
++store.totals.uncached;
|
||||
@@ -1325,12 +1337,27 @@ std::shared_ptr<Pipeline> CachedPipeline(const Context& context, const State& st
|
||||
++store.evicted;
|
||||
++store.totals.evicted;
|
||||
}
|
||||
if (storeHash != nullptr && store.index.contains(hash)) *storeHash = hash;
|
||||
}
|
||||
if (created != nullptr) *created = true;
|
||||
if (PipelineJournalEnabled() && !PipelineJournalReplaying() && state.tessellationCapture == nullptr) RecordGraphicsPipeline(MakeGraphicsPipelineRecipe(state, vertexInput, resources, shaders, attachmentLayout), shaders);
|
||||
return pipeline;
|
||||
}
|
||||
|
||||
std::shared_ptr<Pipeline> TouchCachedPipeline(const Context& context, std::uint64_t hash, const std::weak_ptr<Pipeline>& expected) {
|
||||
auto& store = Pipelines();
|
||||
std::lock_guard lock(store.mutex);
|
||||
reportPipelines(store);
|
||||
const auto found = store.index.find(hash);
|
||||
if (found == store.index.end()) return nullptr;
|
||||
const auto it = found->second;
|
||||
if (it->pipeline.owner_before(expected) || expected.owner_before(it->pipeline) || !alive(*it, context)) return nullptr;
|
||||
store.entries.splice(store.entries.end(), store.entries, it);
|
||||
++store.hits;
|
||||
++store.totals.hits;
|
||||
return it->pipeline;
|
||||
}
|
||||
|
||||
void BuildPipelineStoreKey(std::vector<std::byte>& key, const Context& context, const State& state, const VertexInputLayout& vertexInput, const PipelineSetLayouts& resources, std::span<const CompiledShader> shaders, VkImageLayout attachmentLayout) {
|
||||
pipelineKey(key, context, state, vertexInput, resources, shaders, attachmentLayout);
|
||||
}
|
||||
|
||||
@@ -38,8 +38,8 @@ static_assert(sizeof(VkStencilOpState) == 28, "VkStencilOpState changed: update
|
||||
static_assert(sizeof(VkVertexInputBindingDescription) == 12, "VkVertexInputBindingDescription changed: update the recipe codec");
|
||||
static_assert(sizeof(VkVertexInputAttributeDescription) == 16, "VkVertexInputAttributeDescription changed: update the recipe codec");
|
||||
#if defined(__linux__) && defined(__x86_64__) && defined(__GLIBCXX__)
|
||||
static_assert(sizeof(State) == 912, "State changed: update CanonicalPipelineState and the recipe codec");
|
||||
static_assert(sizeof(ShaderStages) == 160, "ShaderStages changed: update the recipe codec");
|
||||
static_assert(sizeof(State) == 920, "State changed: update CanonicalPipelineState and the recipe codec");
|
||||
static_assert(sizeof(ShaderStages) == 164, "ShaderStages changed: update the recipe codec");
|
||||
static_assert(sizeof(ShaderRecompiler::MeshConfiguration) == 40, "MeshConfiguration changed: update the recipe codec");
|
||||
static_assert(sizeof(ShaderRecompiler::TessellationConfiguration) == 40, "TessellationConfiguration changed: update the recipe codec");
|
||||
#endif
|
||||
|
||||
@@ -1545,6 +1545,32 @@ bool StorageImageServesKeys(const StorageTexture& image, std::uint64_t dccAddres
|
||||
return !MetadataMoved(image, resource);
|
||||
}
|
||||
|
||||
std::shared_ptr<StorageTexture> RepeatStorageSurface(const Context& context, const GuestTextureResource& requested, const std::shared_ptr<StorageTexture>& stored) {
|
||||
static const bool disabled = std::getenv("APS5_NO_TEXTURE_CACHE") != nullptr;
|
||||
if (disabled || stored == nullptr) return nullptr;
|
||||
const auto viewed = ArrayLayerWindow(requested, context.limits.maxImageArrayLayers);
|
||||
Require(viewed.dimension != TextureDimension::k2DMsaa, "storage image access to a multisampled texture is not implemented");
|
||||
const auto viewedBytes = DescribeSurface(viewed).guestBytes;
|
||||
RequireNoMultisampleTarget(viewed.baseAddress, static_cast<std::size_t>(viewedBytes), "a storage image access");
|
||||
if (DepthSurfaceStorage(context, {}, viewed, 0) != nullptr) return nullptr;
|
||||
if (DepthPlanesStale()) static_cast<void>(FlushDepthPlanes(viewed.baseAddress, static_cast<std::size_t>(viewedBytes), DepthPlaneScope::Overlapped));
|
||||
if (auto* recorder = Recorder::Active(); recorder != nullptr) recorder->BoundKeptBytes();
|
||||
const bool profile = LookupOutcomes::Profiled();
|
||||
const auto start = profile ? std::chrono::steady_clock::now() : std::chrono::steady_clock::time_point{};
|
||||
const auto resource = StorageSurface(context, viewed);
|
||||
auto& cache = StorageTextures();
|
||||
std::lock_guard lock(cache.mutex);
|
||||
const CacheHold held(storageCacheHeld);
|
||||
if (resource.mipCount > AllocatedLevels(resource)) return nullptr;
|
||||
const auto it = findStorageByImage(cache, context.device, stored.get());
|
||||
if (it == cache.entries.end() || MetadataMoved(*it->texture, resource)) return nullptr;
|
||||
it->texture->Refresh();
|
||||
cache.entries.splice(cache.entries.begin(), cache.entries, it);
|
||||
TextureCounts().storageHits.fetch_add(1, std::memory_order_relaxed);
|
||||
if (profile) LookupOutcomes::Add(LookupOutcomes::StorageHit, start);
|
||||
return it->texture;
|
||||
}
|
||||
|
||||
namespace {
|
||||
|
||||
const char* roleName(ShaderRecompiler::DescriptorRole role) {
|
||||
|
||||
@@ -10,6 +10,7 @@
|
||||
#include "prx/libSceAgcDriver/Graphics/include/Pipeline.hpp"
|
||||
#include "prx/libSceAgcDriver/Execution/include/GuestMemory.hpp"
|
||||
#include "prx/libc/include/General.hpp"
|
||||
#include "RdnaDecoder/RdnaInstructionDecoder.hpp"
|
||||
#include <algorithm>
|
||||
#include <bit>
|
||||
#include <bitset>
|
||||
@@ -449,8 +450,9 @@ DepthTarget decodeDepthPlane(const Registers& cx) {
|
||||
};
|
||||
DepthTarget depth{};
|
||||
depth.samples = 1u << ((read(cx, 0x010) >> 2u) & 3u);
|
||||
depth.depthSwizzle = (read(cx, 0x010) >> 4u) & 31u;
|
||||
depth.iterate256 = (read(cx, 0x010) & (1u << 20u)) != 0;
|
||||
const bool gcn = ShaderRecompiler::GcnGuestShaders();
|
||||
depth.depthSwizzle = gcn ? 0u : (read(cx, 0x010) >> 4u) & 31u;
|
||||
depth.iterate256 = !gcn && (read(cx, 0x010) & (1u << 20u)) != 0;
|
||||
depth.firstSlice = view & 0x1fffu;
|
||||
depth.lastSlice = (view >> 13u) & 0x7ffu;
|
||||
depth.address = zFormat != 0 ? base(0x012, 0x01a) : 0;
|
||||
@@ -464,8 +466,14 @@ DepthTarget decodeDepthPlane(const Registers& cx) {
|
||||
depth.htileVrsEncoding = (surface->second >> 19u) & 3u;
|
||||
}
|
||||
}
|
||||
const auto size = read(cx, 0x007);
|
||||
depth.extent = {(size & 0x3fffu) + 1u, ((size >> 16u) & 0x3fffu) + 1u};
|
||||
if (gcn) {
|
||||
const auto size = read(cx, 0x016);
|
||||
depth.extent = {((size & 0x7ffu) + 1u) * 8u, (((size >> 11u) & 0x7ffu) + 1u) * 8u};
|
||||
} else {
|
||||
const auto size = read(cx, 0x007);
|
||||
depth.extent = {(size & 0x3fffu) + 1u, ((size >> 16u) & 0x3fffu) + 1u};
|
||||
}
|
||||
Require(!gcn || (maxMip == 0 && viewMip == 0), "PS4 depth targets with mip levels are not implemented");
|
||||
if (maxMip != 0) {
|
||||
char message[320];
|
||||
std::snprintf(message, sizeof(message), "depth view mip %u of %u at %ux%u (DB_Z_INFO 0x%08x, DB_DEPTH_VIEW 0x%08x)", viewMip, maxMip + 1u, depth.extent.width, depth.extent.height, read(cx, 0x010), view);
|
||||
@@ -1290,7 +1298,16 @@ ShaderStages DecodeShaderStages(const QueueState& queue, bool vertexWorkgroup) {
|
||||
const auto provokingVertex = raster != queue.context.end() && (raster->second & (1u << 19u)) != 0 ? outputSize - 1u : 0u;
|
||||
return ShaderRecompiler::MeshConfiguration{inputPrimitive, groupPrimitives, (groupPrimitives - 1u) * inputStep + inputSize, maxVertices, maxPrimitives, ((threads + result.vertexWaveSize - 1u) / result.vertexWaveSize) * result.vertexWaveSize, ((resources >> 19u) & 0xffu) * 128u, provokingVertex, esgsItemSize, outputSize};
|
||||
};
|
||||
if (path == ShaderPath::Vertex) {
|
||||
if (path == ShaderPath::Vertex && ShaderRecompiler::GcnGuestShaders() && (value & 0x2000u) == 0) {
|
||||
validate(value == 0, "GCN vertex routing other than a plain VS is unsupported");
|
||||
const auto unitStepRate = [&](std::uint32_t offset) {
|
||||
const auto rate = find(queue.context, offset);
|
||||
return rate == queue.context.end() || rate->second == 1u;
|
||||
};
|
||||
const auto components = (read(queue.shader, 0x4a, RegisterBank::Shader) >> 24u) & 3u;
|
||||
validate(components == 0 || (unitStepRate(0x2a8) && (components == 1 || unitStepRate(0x2a9))), "GCN vertex instance step rates other than 1 are not implemented");
|
||||
result.legacyVertex = true;
|
||||
} else if (path == ShaderPath::Vertex) {
|
||||
validate((value & 0x2000u) != 0, "legacy vertex routing without PRIMGEN_EN is unsupported");
|
||||
validate((value & ~0x0247a010u) == 0 || value == 0x02002008u, "unsupported vertex routing, scheduling or wave-ID state");
|
||||
} else if (path == ShaderPath::Tessellation || path == ShaderPath::TessellationGeometry) {
|
||||
@@ -1454,6 +1471,20 @@ void ApplyDepthRemap(const Context& context, State& state) {
|
||||
state.depthClamp = true;
|
||||
}
|
||||
|
||||
static bool SignedNormalizedFormat(VkFormat format) {
|
||||
return format == VK_FORMAT_R8_SNORM || format == VK_FORMAT_R16_SNORM || format == VK_FORMAT_R8G8_SNORM || format == VK_FORMAT_R16G16_SNORM || format == VK_FORMAT_R8G8B8A8_SNORM || format == VK_FORMAT_B8G8R8A8_SNORM || format == VK_FORMAT_R16G16B16A16_SNORM;
|
||||
}
|
||||
|
||||
static std::uint32_t NormalizedChannelMask(VkFormat format) {
|
||||
switch (format) {
|
||||
case VK_FORMAT_R8_SNORM:
|
||||
case VK_FORMAT_R16_SNORM: return 0x1u;
|
||||
case VK_FORMAT_R8G8_SNORM:
|
||||
case VK_FORMAT_R16G16_SNORM: return 0x3u;
|
||||
default: return 0xfu;
|
||||
}
|
||||
}
|
||||
|
||||
State DecodeState(const QueueState& queue, bool vertexWorkgroup) {
|
||||
if (auto reason = DepthMaintenanceRejection(queue); !reason.empty()) throw std::runtime_error(reason);
|
||||
const auto& cx = queue.context;
|
||||
@@ -1809,7 +1840,7 @@ State DecodeState(const QueueState& queue, bool vertexWorkgroup) {
|
||||
Require(nibbles || (exportedMask & packedMask) == packedMask, "partial writes of " + packed + " color target are unsupported");
|
||||
if ((exportedMask & packedMask) != packedMask) {
|
||||
Require(color.mipCount == 1u && color.depth == 1u && color.layers == 1u && color.arrayLastSlice == 0u, "partial writes of a mipmapped, volume or array " + std::string(PackedColorTargetName(color.packing)) + " color target are not implemented");
|
||||
Require(std::ranges::none_of(result.colors, [](const ColorTarget& other) { return other.partialWriteMask != 0; }), "partial writes of more than one packed color target are not implemented");
|
||||
Require(std::ranges::none_of(result.colors, [](const ColorTarget& other) { return other.partialWriteMask != 0; }), "a draw merges into one color target at most, so partial writes of a packed color target cannot join another merged color target");
|
||||
color.partialWriteMask = PackedWriteMask(mapping, exportedMask);
|
||||
state.colorWriteMask = 0;
|
||||
if (color.samples > 1u) {
|
||||
@@ -1836,7 +1867,13 @@ State DecodeState(const QueueState& queue, bool vertexWorkgroup) {
|
||||
if (const auto info = read(cx, 0x31c + slot * 0xfu); state.blendEnable && (info & 0x8000u) == 0 && ((info >> 8u) & 7u) <= 1u) {
|
||||
char detail[80];
|
||||
std::snprintf(detail, sizeof(detail), " (CB_COLOR_INFO 0x%08x, CB_BLEND%u_CONTROL 0x%08x)", info, slot, blend);
|
||||
throw std::runtime_error(std::string("AGC graphics: blending unclamped normalized color is not implemented") + detail);
|
||||
const std::string where = detail;
|
||||
Require(color.samples == 1u && color.packing == ShaderRecompiler::ColorExportPacking::None, "blending unclamped normalized color into a multisampled or packed color target is not implemented" + where);
|
||||
Require(!reversed && mapping != 0xecu, "blending unclamped normalized color into a color target with a reversed or alternate component order is not implemented" + where);
|
||||
Require(!(secondSource(state.srcColorBlendFactor) || secondSource(state.dstColorBlendFactor) || secondSource(state.srcAlphaBlendFactor) || secondSource(state.dstAlphaBlendFactor)), "dual-source blending of unclamped normalized color is not implemented" + where);
|
||||
Require(std::ranges::none_of(result.colors, [&](const ColorTarget& other) { return &other != &color && other.partialWriteMask != 0; }), "a draw merges into one color target at most, so blending unclamped normalized color cannot join another merged color target" + where);
|
||||
Require(!SignedNormalizedFormat(color.format) || (state.colorWriteMask & NormalizedChannelMask(color.format)) == NormalizedChannelMask(color.format), "blending unclamped signed normalized color with a write mask that skips a component is not implemented, since the shader rewrites the skipped component through a float and the code -128 would become -127" + where);
|
||||
color.partialWriteMask = UnclampedBlendMask;
|
||||
}
|
||||
result.blends[color.exportIndex] = state;
|
||||
}
|
||||
@@ -1906,10 +1943,11 @@ bool DepthStencilTests(const State& state) {
|
||||
}
|
||||
|
||||
ShaderRecompiler::TargetMerge ExportTargetMerge(const State& state) {
|
||||
static_assert(VK_BLEND_FACTOR_ZERO == 0 && VK_BLEND_FACTOR_SRC_ALPHA_SATURATE == 14 && VK_BLEND_OP_ADD == 0 && VK_BLEND_OP_MAX == 4);
|
||||
ShaderRecompiler::TargetMerge merge;
|
||||
for (const auto& color : state.colors) {
|
||||
if (color.partialWriteMask == 0) continue;
|
||||
Require(merge.mask == 0 && color.exportIndex < 8u && color.samples <= 8u, "a draw merges into one packed color target at most");
|
||||
Require(merge.mask == 0 && color.exportIndex < 8u && color.samples <= 8u, "a draw merges into one color target at most");
|
||||
Require(color.samples == 1u || state.perSampleShading, "a merged multisampled color target needs per-sample shading");
|
||||
merge.target = static_cast<std::uint8_t>(color.exportIndex);
|
||||
merge.mask = color.partialWriteMask;
|
||||
@@ -1917,6 +1955,19 @@ ShaderRecompiler::TargetMerge ExportTargetMerge(const State& state) {
|
||||
merge.descriptor = EncodeTextureResource(TargetMergeSurface(color));
|
||||
merge.depthStencilWrites = DepthStencilWrites(state);
|
||||
merge.depthStencilTests = DepthStencilTests(state);
|
||||
if (color.partialWriteMask != UnclampedBlendMask) continue;
|
||||
const auto& attachment = state.blends.at(color.exportIndex);
|
||||
auto& blend = merge.blend;
|
||||
blend.enabled = true;
|
||||
blend.snorm = SignedNormalizedFormat(color.format);
|
||||
blend.colorSource = static_cast<std::uint8_t>(attachment.srcColorBlendFactor);
|
||||
blend.colorDestination = static_cast<std::uint8_t>(attachment.dstColorBlendFactor);
|
||||
blend.colorOperation = static_cast<std::uint8_t>(attachment.colorBlendOp);
|
||||
blend.alphaSource = static_cast<std::uint8_t>(attachment.srcAlphaBlendFactor);
|
||||
blend.alphaDestination = static_cast<std::uint8_t>(attachment.dstAlphaBlendFactor);
|
||||
blend.alphaOperation = static_cast<std::uint8_t>(attachment.alphaBlendOp);
|
||||
blend.writeMask = static_cast<std::uint8_t>(attachment.colorWriteMask & 0xfu);
|
||||
for (std::size_t i = 0; i < 4; ++i) blend.constants[i] = std::bit_cast<std::uint32_t>(state.blendConstants[i]);
|
||||
}
|
||||
return merge;
|
||||
}
|
||||
@@ -2028,6 +2079,7 @@ GuestTextureResource SurfaceForTarget(const ColorTarget& color) {
|
||||
surface.dccAddress = color.dccAddress != 0 ? color.dccAddress : color.chainDccAddress;
|
||||
surface.dccAlphaOnMsb = color.dccAlphaOnMsb;
|
||||
surface.dccPipeAligned = color.dccPipeAligned;
|
||||
if (ColorTileModeIsGcn(color.tileMode)) surface.gcnPitch = surface.width;
|
||||
return surface;
|
||||
}
|
||||
DecodedColorFormat DecodeColorFormat(std::uint32_t format, std::uint32_t number, std::uint32_t swap) {
|
||||
@@ -2037,7 +2089,54 @@ DecodedColorFormat DecodeColorFormat(std::uint32_t format, std::uint32_t number,
|
||||
}
|
||||
|
||||
|
||||
ColorTarget DecodeGcnColorBuffer(const Registers& cx, std::uint32_t slot) {
|
||||
const auto stride = slot * 0xfu;
|
||||
ColorTarget color{};
|
||||
color.slot = slot;
|
||||
const auto info = read(cx, 0x31c + stride);
|
||||
const auto number = (info >> 8u) & 7u;
|
||||
const auto swap = (info >> 11u) & 3u;
|
||||
const auto decoded = DecodeColorFormat((info >> 2u) & 0x1fu, number, swap);
|
||||
const auto attrib = read(cx, 0x31d + stride);
|
||||
color.samples = 1u << ((attrib >> 12u) & 7u);
|
||||
Require(color.samples == 1u, "multisampled GCN color targets are not implemented");
|
||||
Require((info & 0x3u) == 0 && (info & 0x80u) == 0, "endian-swapped or linear-general GCN color targets are not implemented");
|
||||
Require((info & 0x8000u) != 0 || number == 7 || number == 4 || number == 5, "unclamped normalized color is unsupported");
|
||||
const auto view = read(cx, 0x31b + stride);
|
||||
Require((view & 0x7ffu) == 0 && ((view >> 13u) & 0x7ffu) == 0, "GCN color array slices are not implemented");
|
||||
const auto pitch = ((read(cx, 0x319 + stride) & 0x7ffu) + 1u) * 8u;
|
||||
const auto sliceElements = ((read(cx, 0x31a + stride) & 0x3fffffu) + 1u) * 64u;
|
||||
color.extent = {pitch, sliceElements / pitch};
|
||||
color.surfaceExtent = color.extent;
|
||||
color.elementBytes = decoded.elementBytes;
|
||||
switch (attrib & 0x1fu) {
|
||||
case 8u: color.tileMode = ColorTileMode::Linear; break;
|
||||
case 5u: case 13u: color.tileMode = ColorTileMode::GcnThin1D; break;
|
||||
case 9u: color.tileMode = ColorTileMode::GcnDisplay1D; break;
|
||||
case 10u: color.tileMode = ColorTileMode::GcnDisplay2D; break;
|
||||
case 14u: color.tileMode = ColorTileMode::GcnThin2D; break;
|
||||
default: throw std::runtime_error("AGC graphics: PS4 color target tile mode index " + std::to_string(attrib & 0x1fu) + " is not implemented");
|
||||
}
|
||||
color.mipCount = 1;
|
||||
color.surfaceAddress = static_cast<std::uint64_t>(read(cx, 0x318 + stride)) << 8u;
|
||||
color.address = color.surfaceAddress;
|
||||
const ColorTargetLayout layout(color.extent.width, color.extent.height, color.tileMode, color.elementBytes);
|
||||
Require(layout.Bytes() == static_cast<std::size_t>(pitch) * color.extent.height * color.elementBytes, "PS4 color target pitch or slice is not padded the way its tile mode pads them");
|
||||
color.bytes = layout.Bytes();
|
||||
color.format = decoded.format;
|
||||
color.componentMapping = decoded.componentMapping;
|
||||
color.packing = decoded.packing;
|
||||
for (std::uint32_t word = 0; word < 2; ++word) {
|
||||
const auto clear = find(cx, 0x323 + word + stride);
|
||||
color.clearWords[word] = clear == cx.end() ? 0u : clear->second;
|
||||
}
|
||||
Require(((info >> 13u) & 1u) == 0, "PS4 color target fast clear (CMASK) is not implemented");
|
||||
GuestMemory::CheckRange(reinterpret_cast<const void*>(color.address), color.bytes, layout.Alignment(), true);
|
||||
return color;
|
||||
}
|
||||
|
||||
ColorTarget DecodeColorBuffer(const Registers& cx, std::uint32_t slot, bool allowMultisampleDcc) {
|
||||
if (ShaderRecompiler::GcnGuestShaders()) return DecodeGcnColorBuffer(cx, slot);
|
||||
const auto stride = slot * 0xfu;
|
||||
ColorTarget color{};
|
||||
color.slot = slot;
|
||||
|
||||
@@ -453,12 +453,11 @@ Texture::Texture(const Context& context, TextureDetiler& detiler, const GuestTex
|
||||
RecordMemoryBarrier(context, commands, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_ACCESS_TRANSFER_WRITE_BIT, VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT);
|
||||
|
||||
for (std::uint32_t layer = 0; layer < arrayLayers; ++layer) {
|
||||
const auto guestLayerOffset = geometry.GuestLayerOffset(layer);
|
||||
const auto linearLayerOffset = geometry.LinearLayerOffset(layer);
|
||||
for (std::uint32_t level = 0; level < mips.size(); ++level) {
|
||||
if (!geometry.HasLayer(level, layer)) continue;
|
||||
const auto& mip = mips[level];
|
||||
detiler.Dispatch(commands, descriptor.tileMode, elementBytes, tiled->Handle(), guestLayerOffset + mip.tiledOffset, linear->Handle(), linearLayerOffset + mip.linearOffset, mip, false, layer, geometry.thick, {.pipeBankXor = descriptor.pipeBankXor});
|
||||
detiler.Dispatch(commands, descriptor.tileMode, elementBytes, tiled->Handle(), geometry.GuestOffset(layer, mip), linear->Handle(), linearLayerOffset + mip.linearOffset, mip, false, layer, geometry.thick, {.pipeBankXor = descriptor.pipeBankXor});
|
||||
}
|
||||
}
|
||||
if (IsRepackedTextureFormat(descriptor.format)) {
|
||||
@@ -615,6 +614,12 @@ bool Texture::CanDepthCopyFrom(const StorageTexture& source, const GuestTextureR
|
||||
|
||||
bool Texture::CanBlockCopyFrom(const StorageTexture& source, const GuestTextureResource& descriptor) {
|
||||
const auto& from = source.Descriptor();
|
||||
if (descriptor.gcnPitch != 0 && from.gcnPitch == descriptor.gcnPitch && (descriptor.width != from.width || descriptor.height != from.height)) {
|
||||
return !IsBlockCompressed(descriptor.format) && !IsBlockCompressed(from.format) && !IsSrgbTextureFormat(descriptor.format) && BytesPerElement(from.format) == BytesPerElement(descriptor.format)
|
||||
&& descriptor.baseAddress == from.baseAddress && descriptor.tileMode == from.tileMode && descriptor.dimension == TextureDimension::k2D && from.dimension == TextureDimension::k2D
|
||||
&& descriptor.mipCount == 1u && from.mipCount == 1u && descriptor.width <= from.width && descriptor.height <= from.height
|
||||
&& source.ImageDepth() == 1 && DescribeSurface(descriptor).guestBytes == source.GuestBytes();
|
||||
}
|
||||
if (!IsBlockCompressed(descriptor.format) || IsBlockCompressed(from.format) || BytesPerElement(from.format) != BytesPerElement(descriptor.format)) return false;
|
||||
if (descriptor.dimension != TextureDimension::k2D && descriptor.dimension != TextureDimension::k2DArray) return false;
|
||||
if (descriptor.baseAddress != from.baseAddress || descriptor.pipeBankXor != from.pipeBankXor || descriptor.dimension != from.dimension || descriptor.tileMode != from.tileMode || descriptor.depthOrLastArray != from.depthOrLastArray || descriptor.mipCount > from.mipCount) return false;
|
||||
@@ -701,6 +706,7 @@ Texture::Texture(const Context& context, const std::shared_ptr<StorageTexture>&
|
||||
Require(source != nullptr && CanBlockCopyFrom(*source, descriptor), "storage image cannot serve a block copy of the sampled texture");
|
||||
blockFormat = SampledTextureFormat(context, descriptor.format);
|
||||
const auto geometry = DescribeSurface(descriptor);
|
||||
copyTexelsPerElement = IsBlockCompressed(descriptor.format) ? 4u : 1u;
|
||||
copyWidth = descriptor.width;
|
||||
copyHeight = descriptor.height;
|
||||
copyLevels = descriptor.mipCount;
|
||||
@@ -999,7 +1005,7 @@ bool Texture::refreshBlockCopy() {
|
||||
VkImageCopy region{};
|
||||
region.srcSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, level, 0, copyLayers};
|
||||
region.dstSubresource = region.srcSubresource;
|
||||
region.extent = {std::max(copyWidth >> level, 1u) / 4u, std::max(copyHeight >> level, 1u) / 4u, 1u};
|
||||
region.extent = {std::max(copyWidth >> level, 1u) / copyTexelsPerElement, std::max(copyHeight >> level, 1u) / copyTexelsPerElement, 1u};
|
||||
regions.push_back(region);
|
||||
}
|
||||
auto* recorder = Recorder::Active();
|
||||
@@ -1442,6 +1448,7 @@ StorageTexture::StorageTexture(const Context& context, TextureDetiler& detiler,
|
||||
descriptor.depthOrLastArray, descriptor.baseArray, static_cast<int>(descriptor.dimension), static_cast<int>(descriptor.tileMode), descriptor.format, static_cast<int>(vkFormat));
|
||||
#endif
|
||||
geometry = DescribeSurface(descriptor);
|
||||
Require(!geometry.levelMajor, "a storage image of a PS4 layered surface with several mip levels (stored level by level) is not implemented");
|
||||
mips = geometry.mips;
|
||||
arrayLayers = geometry.layers;
|
||||
const auto elementBytes = BytesPerElement(descriptor.format);
|
||||
@@ -1452,7 +1459,8 @@ StorageTexture::StorageTexture(const Context& context, TextureDetiler& detiler,
|
||||
const bool layered = geometry.layers >= 2 && !geometry.thick && geometry.imageDepth == 1 && geometry.layers == geometry.imageLayers && geometry.layerBytes * geometry.layers == guestBytes && geometry.layerBytes % 65536 == 0 && descriptor.baseAddress % 65536 == 0;
|
||||
// Tile blocks divide the stamp blocks, so at an aligned base every unit is whole tile blocks
|
||||
// of its (layer, mip) slices (sliceWindows).
|
||||
blockUnits = LayerTrackingEnabled() && BlockTrackingEnabled() && !geometry.thick && descriptor.tileMode != TextureTileMode::kLinear && descriptor.baseAddress % 65536 == 0;
|
||||
blockUnits = LayerTrackingEnabled() && BlockTrackingEnabled() && !geometry.thick && descriptor.tileMode != TextureTileMode::kLinear && descriptor.baseAddress % 65536 == 0
|
||||
&& std::none_of(mips.begin(), mips.end(), [](const TileMipLayout& mip) { return mip.gcnSplitStride != 0; });
|
||||
trackedLayers = blockUnits ? static_cast<std::uint32_t>((guestBytes + 65535) / 65536) : layered && LayerTrackingEnabled() ? geometry.layers : 1u;
|
||||
trackedLayerBytes = blockUnits ? 65536 : guestBytes / trackedLayers;
|
||||
layerGeneration.assign(trackedLayers, 0);
|
||||
@@ -2977,12 +2985,12 @@ std::vector<std::pair<std::uint64_t, std::uint64_t>> StorageTexture::unitRuns(co
|
||||
std::vector<StorageTexture::SliceWindow> StorageTexture::sliceWindows(std::span<const std::pair<std::uint64_t, std::uint64_t>> runs) const {
|
||||
std::vector<SliceWindow> windows;
|
||||
const auto elementBytes = BytesPerElement(descriptor.format);
|
||||
const auto block = ThinBlockLayout(descriptor.tileMode, elementBytes);
|
||||
for (const auto& [runBegin, runEnd] : runs) {
|
||||
for (std::uint32_t layer = 0; layer < arrayLayers; ++layer) {
|
||||
for (std::uint32_t level = 0; level < descriptor.mipCount; ++level) {
|
||||
if (!geometry.HasLayer(level, layer)) continue;
|
||||
const auto& mip = mips[level];
|
||||
const auto block = ThinBlockLayout(MipTileMode(descriptor.tileMode, mip), elementBytes);
|
||||
const auto sliceBegin = geometry.GuestLayerOffset(layer) + mip.tiledOffset;
|
||||
const auto sliceEnd = sliceBegin + mip.tiledSize;
|
||||
if (runEnd <= sliceBegin || sliceEnd <= runBegin) continue;
|
||||
@@ -6382,9 +6390,9 @@ void StorageTexture::writeBackLayers(const std::vector<bool>& layers) {
|
||||
context.Function<PFN_vkCmdPipelineBarrier>("vkCmdPipelineBarrier")(commands, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT | VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT | VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, 0, 0, nullptr, 1, &toCopy, 1, &backToGeneral);
|
||||
CopyBuffer(context, commands, tiled.Handle(), 0, host.Handle(), 0, original.size());
|
||||
RecordMemoryBarrier(context, commands, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_HOST_BIT, VK_ACCESS_TRANSFER_WRITE_BIT, VK_ACCESS_HOST_READ_BIT);
|
||||
APS5_LOG_CHARS_OUT("StorageTexture writeback submit");
|
||||
APS5_LOG_CHARS_OUT_DEBUG("StorageTexture writeback submit");
|
||||
batch.SubmitAndWait();
|
||||
APS5_LOG_CHARS_OUT("StorageTexture writeback done");
|
||||
APS5_LOG_CHARS_OUT_DEBUG("StorageTexture writeback done");
|
||||
std::uint64_t storedBytes = 0;
|
||||
for (const auto& [from, to] : stores) storedBytes += to - from;
|
||||
countStorageWriteBack(drawn.rect ? storedBytes : guestBytes, false, drawn.drawn);
|
||||
|
||||
@@ -37,6 +37,7 @@ struct Push {
|
||||
std::uint32_t columnBegin;
|
||||
std::uint32_t rowBegin;
|
||||
std::uint32_t pipeBankXor;
|
||||
std::uint32_t splitStride;
|
||||
};
|
||||
|
||||
std::uint32_t BlockBytesFor(TextureTileMode tileMode) {
|
||||
@@ -148,8 +149,18 @@ VkPipeline TextureDetiler::pipeline(TextureTileMode tileMode, std::uint32_t elem
|
||||
}
|
||||
// Constants 0-3 select element size, block size, addressing family and direction; 4-19 carry the
|
||||
// per-bit XOR equation for the equation family (2); 20-21 override the block extent in elements.
|
||||
std::array<std::uint32_t, 22> values{elementBytes, BlockBytesFor(tileMode), tileMode == TextureTileMode::kLinear ? 0u : 1u, retile ? 1u : 0u};
|
||||
if (thick) {
|
||||
const bool gcn = IsGcnTiled(tileMode);
|
||||
std::array<std::uint32_t, 26> values{elementBytes, gcn ? 0u : BlockBytesFor(tileMode), tileMode == TextureTileMode::kLinear ? 0u : 1u, retile ? 1u : 0u};
|
||||
if (gcn) {
|
||||
Require(!thick, "PS4 tiled surfaces are detiled thin");
|
||||
const auto geometry = GcnTiling(tileMode, elementBytes);
|
||||
values[1] = geometry.blockBytes;
|
||||
values[2] = 2u;
|
||||
std::copy(geometry.equation.begin(), geometry.equation.end(), values.begin() + 4);
|
||||
values[20] = geometry.blockWidth;
|
||||
values[21] = geometry.blockHeight;
|
||||
std::copy(geometry.splitMasks.begin(), geometry.splitMasks.end(), values.begin() + 22);
|
||||
} else if (thick) {
|
||||
const auto thickMode = tileMode == TextureTileMode::kStandard4KB ? 0x105u : tileMode == TextureTileMode::kS4KBX ? 0x115u : tileMode == TextureTileMode::kStandard64KB ? 0x109u : tileMode == TextureTileMode::kS64KBX ? 0x119u : tileMode == TextureTileMode::kD64KBX ? 0x11au : 0u;
|
||||
Require(thickMode != 0, "3D textures are only detiled thick from SW_4KB_S, SW_4KB_S_X, SW_64KB_S, SW_64KB_S_X or SW_64KB_D_X");
|
||||
const auto* equation = FindTextureSwizzleEquation(thickMode, elementBytes);
|
||||
@@ -168,7 +179,7 @@ VkPipeline TextureDetiler::pipeline(TextureTileMode tileMode, std::uint32_t elem
|
||||
if (image && imageModule == VK_NULL_HANDLE) {
|
||||
imageModule = CreateShaderModule(context, TEXTURE_DETILE_IMAGE_SPV, sizeof(TEXTURE_DETILE_IMAGE_SPV), "vkCreateShaderModule");
|
||||
}
|
||||
std::array<VkSpecializationMapEntry, 22> entries{};
|
||||
std::array<VkSpecializationMapEntry, 26> entries{};
|
||||
for (std::uint32_t index = 0; index < entries.size(); ++index) entries[index] = {index, index * 4u, 4};
|
||||
VkSpecializationInfo specialization{};
|
||||
specialization.mapEntryCount = static_cast<std::uint32_t>(entries.size());
|
||||
@@ -206,7 +217,7 @@ void TextureDetiler::Dispatch(VkCommandBuffer commands, TextureTileMode tileMode
|
||||
Require(source != VK_NULL_HANDLE && destination != VK_NULL_HANDLE, "texture detiling requires source and destination buffers");
|
||||
std::uint32_t columnEnd = 0, rowEnd = 0;
|
||||
checkWindow(layout, window, columnEnd, rowEnd);
|
||||
const auto target = pipeline(tileMode, elementBytes, retile, thick);
|
||||
const auto target = pipeline(MipTileMode(tileMode, layout), elementBytes, retile, thick);
|
||||
const auto alignment = std::max<VkDeviceSize>(context.limits.minStorageBufferOffsetAlignment, 4);
|
||||
const auto sourceDescriptorOffset = sourceOffset - sourceOffset % alignment;
|
||||
const auto destinationDescriptorOffset = destinationOffset - destinationOffset % alignment;
|
||||
@@ -258,6 +269,7 @@ void TextureDetiler::Dispatch(VkCommandBuffer commands, TextureTileMode tileMode
|
||||
push.columnBegin = window.columnBegin;
|
||||
push.rowBegin = window.rowBegin;
|
||||
push.pipeBankXor = window.pipeBankXor;
|
||||
push.splitStride = layout.gcnSplitStride;
|
||||
context.Function<PFN_vkCmdPushConstants>("vkCmdPushConstants")(commands, pipelineLayout, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(Push), &push);
|
||||
const auto groupsX = (columnEnd - window.columnBegin + 7u) / 8u;
|
||||
const auto groupsY = (rowEnd - window.rowBegin + 7u) / 8u;
|
||||
@@ -402,7 +414,7 @@ void TextureDetiler::DispatchImage(VkCommandBuffer commands, TextureTileMode til
|
||||
Require(ImageElementFormat(elementBytes) != VK_FORMAT_UNDEFINED, "unsupported element size for texture detiling through an image");
|
||||
std::uint32_t columnEnd = 0, rowEnd = 0;
|
||||
checkWindow(layout, window, columnEnd, rowEnd);
|
||||
const auto target = pipeline(tileMode, elementBytes, retile, false, true);
|
||||
const auto target = pipeline(MipTileMode(tileMode, layout), elementBytes, retile, false, true);
|
||||
const auto alignment = std::max<VkDeviceSize>(context.limits.minStorageBufferOffsetAlignment, 4);
|
||||
const auto descriptorOffset = tiledOffset - tiledOffset % alignment;
|
||||
const auto base = tiledOffset - descriptorOffset;
|
||||
@@ -448,6 +460,7 @@ void TextureDetiler::DispatchImage(VkCommandBuffer commands, TextureTileMode til
|
||||
push.columnBegin = window.columnBegin;
|
||||
push.rowBegin = window.rowBegin;
|
||||
push.pipeBankXor = window.pipeBankXor;
|
||||
push.splitStride = layout.gcnSplitStride;
|
||||
context.Function<PFN_vkCmdPushConstants>("vkCmdPushConstants")(commands, imagePipelineLayout, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(Push), &push);
|
||||
const auto groupsX = (columnEnd - window.columnBegin + 7u) / 8u;
|
||||
const auto groupsY = (rowEnd - window.rowBegin + 7u) / 8u;
|
||||
|
||||
@@ -59,6 +59,24 @@ BlockLayout GetBlockLayout(TextureTileMode tileMode, std::uint32_t bytesPerEleme
|
||||
case TextureTileMode::kS64KBX:
|
||||
case TextureTileMode::kD64KBX:
|
||||
case TextureTileMode::kR64KBX: return {65536u, 1u << kLog2BlockThin64KB[index].width, 1u << kLog2BlockThin64KB[index].height};
|
||||
case TextureTileMode::kGcnThin1D:
|
||||
case TextureTileMode::kGcnDisplay1D:
|
||||
case TextureTileMode::kGcnDisplay2D:
|
||||
case TextureTileMode::kGcnThin2D:
|
||||
case TextureTileMode::kGcnDepth2D64:
|
||||
case TextureTileMode::kGcnDepth2D128:
|
||||
case TextureTileMode::kGcnDepth2D256:
|
||||
case TextureTileMode::kGcnDepth2D512:
|
||||
case TextureTileMode::kGcnDepth2D1K:
|
||||
case TextureTileMode::kGcnDepthPrt256:
|
||||
case TextureTileMode::kGcnDepthPrt1K:
|
||||
case TextureTileMode::kGcnDisplayPrt:
|
||||
case TextureTileMode::kGcnDisplay2DPrt:
|
||||
case TextureTileMode::kGcnThinPrt:
|
||||
case TextureTileMode::kGcnThin2DPrt: {
|
||||
const auto geometry = GcnTiling(tileMode, bytesPerElement);
|
||||
return {geometry.blockBytes, geometry.blockWidth, geometry.blockHeight};
|
||||
}
|
||||
}
|
||||
throw std::runtime_error("AGC graphics: GetBlockLayout encountered an unknown tile mode");
|
||||
}
|
||||
@@ -101,7 +119,22 @@ bool GetMipTailLayout(TextureTileMode tileMode, const BlockLayout& block, std::u
|
||||
switch (tileMode) {
|
||||
case TextureTileMode::kLinear:
|
||||
case TextureTileMode::kStandard256B:
|
||||
case TextureTileMode::kD256B: return false;
|
||||
case TextureTileMode::kD256B:
|
||||
case TextureTileMode::kGcnThin1D:
|
||||
case TextureTileMode::kGcnDisplay1D:
|
||||
case TextureTileMode::kGcnDisplay2D:
|
||||
case TextureTileMode::kGcnThin2D:
|
||||
case TextureTileMode::kGcnDepth2D64:
|
||||
case TextureTileMode::kGcnDepth2D128:
|
||||
case TextureTileMode::kGcnDepth2D256:
|
||||
case TextureTileMode::kGcnDepth2D512:
|
||||
case TextureTileMode::kGcnDepth2D1K:
|
||||
case TextureTileMode::kGcnDepthPrt256:
|
||||
case TextureTileMode::kGcnDepthPrt1K:
|
||||
case TextureTileMode::kGcnDisplayPrt:
|
||||
case TextureTileMode::kGcnDisplay2DPrt:
|
||||
case TextureTileMode::kGcnThinPrt:
|
||||
case TextureTileMode::kGcnThin2DPrt: return false;
|
||||
case TextureTileMode::kStandard4KB:
|
||||
case TextureTileMode::kD4KB:
|
||||
case TextureTileMode::kS4KBX:
|
||||
@@ -248,6 +281,7 @@ std::vector<TileMipLayout> ComputeMipLayout(TextureTileMode tileMode, std::uint3
|
||||
Require(width != 0 && height != 0, "cannot compute mip layout for a zero-sized texture");
|
||||
Require(mipCount != 0 && mipCount <= 16u, "texture mip count is out of range");
|
||||
|
||||
Require(!IsGcnTiled(tileMode), "PS4 surfaces are laid out by ComputeGcnMipLayout from their pitch");
|
||||
const auto bytesPerElement = BytesPerElement(format);
|
||||
const auto texelWidth = BlockWidth(format);
|
||||
const auto texelHeight = BlockHeight(format);
|
||||
@@ -279,7 +313,7 @@ std::array<std::uint32_t, 3> ThinBlockLayout(TextureTileMode tileMode, std::uint
|
||||
|
||||
std::vector<std::pair<std::uint64_t, std::uint64_t>> CoveredMipBytes(TextureTileMode tileMode, std::uint32_t bytesPerElement, const TileMipLayout& mip) {
|
||||
std::vector<std::pair<std::uint64_t, std::uint64_t>> covered;
|
||||
if (mip.tail || mip.width == 0 || mip.height == 0) return covered;
|
||||
if (mip.tail || mip.width == 0 || mip.height == 0 || mip.gcnSplitStride != 0) return covered;
|
||||
const auto add = [&](std::uint64_t begin, std::uint64_t end) {
|
||||
end = std::min(end, mip.tiledSize);
|
||||
if (begin >= end) return;
|
||||
@@ -291,7 +325,7 @@ std::vector<std::pair<std::uint64_t, std::uint64_t>> CoveredMipBytes(TextureTile
|
||||
for (std::uint32_t row = 0; row < mip.height; ++row) add(static_cast<std::uint64_t>(row) * mip.pitchBytes, static_cast<std::uint64_t>(row) * mip.pitchBytes + rowBytes);
|
||||
return covered;
|
||||
}
|
||||
const auto block = ThinBlockLayout(tileMode, bytesPerElement);
|
||||
const auto block = ThinBlockLayout(MipTileMode(tileMode, mip), bytesPerElement);
|
||||
const auto wholeColumns = std::min(mip.width / block[1], mip.blocksPerRow);
|
||||
const auto wholeRows = mip.height / block[2];
|
||||
for (std::uint32_t row = 0; row < wholeRows && wholeColumns != 0; ++row) {
|
||||
@@ -382,7 +416,170 @@ ThickLayout ComputeThickLayout(TextureTileMode tileMode, std::uint32_t format, s
|
||||
return result;
|
||||
}
|
||||
|
||||
std::vector<TileMipLayout> ComputeGcnMipLayout(TextureTileMode tileMode, std::uint32_t format, std::uint32_t width, std::uint32_t height, std::uint32_t pitch, bool pow2Pad, std::uint32_t mipCount, bool linearGeneral, std::uint32_t layers) {
|
||||
Require(layers != 0, "a PS4 surface has at least one slice");
|
||||
Require(!linearGeneral || tileMode == TextureTileMode::kLinear, "LINEAR_GENERAL is a linear layout");
|
||||
Require(width != 0 && height != 0 && pitch >= width, "cannot compute the mip layout of an empty PS4 texture");
|
||||
Require(mipCount != 0 && mipCount <= 16u, "texture mip count is out of range");
|
||||
Require(tileMode == TextureTileMode::kLinear || IsGcnTiled(tileMode), "PS4 texture tile mode has no modeled layout");
|
||||
const auto bytes = BytesPerElement(format);
|
||||
const auto texelWidth = BlockWidth(format);
|
||||
const auto texelHeight = BlockHeight(format);
|
||||
std::vector<TileMipLayout> mips(mipCount);
|
||||
std::uint64_t offset = 0, linearOffset = 0;
|
||||
for (std::uint32_t level = 0; level < mipCount; ++level) {
|
||||
auto levelWidth = std::max(pitch >> level, 1u);
|
||||
auto levelHeight = std::max(height >> level, 1u);
|
||||
if (pow2Pad && level != 0) {
|
||||
levelWidth = std::bit_ceil(levelWidth);
|
||||
levelHeight = std::bit_ceil(levelHeight);
|
||||
}
|
||||
auto rowElements = (levelWidth + texelWidth - 1u) / texelWidth;
|
||||
auto rows = (levelHeight + texelHeight - 1u) / texelHeight;
|
||||
bool macro = false;
|
||||
std::uint32_t macroWidth = 0;
|
||||
std::uint32_t splitSlices = 1;
|
||||
if (IsGcnMacroTiled(tileMode)) {
|
||||
const auto geometry = GcnTiling(tileMode, bytes);
|
||||
macro = level == 0 || (rowElements >= geometry.blockWidth && rows >= geometry.blockHeight);
|
||||
if (macro) {
|
||||
macroWidth = geometry.blockWidth;
|
||||
splitSlices = geometry.splitSlices;
|
||||
rowElements = AlignUp(rowElements, geometry.blockWidth);
|
||||
rows = AlignUp(rows, geometry.blockHeight);
|
||||
}
|
||||
}
|
||||
const bool micro = !macro && tileMode != TextureTileMode::kLinear;
|
||||
if (micro) {
|
||||
rowElements = AlignUp(rowElements, 8u);
|
||||
rows = AlignUp(rows, 8u);
|
||||
while (static_cast<std::uint64_t>(rowElements) * rows * bytes % 256u != 0) rowElements += 8u;
|
||||
} else if (!macro && !linearGeneral) {
|
||||
const auto pitchAlign = std::max(8u, 64u / bytes);
|
||||
const auto sliceAlign = std::max(64u, 256u / bytes);
|
||||
rowElements = AlignUp(rowElements, pitchAlign);
|
||||
while (static_cast<std::uint64_t>(rowElements) * rows % sliceAlign != 0) rowElements += pitchAlign;
|
||||
}
|
||||
if (level == 0) Require(rowElements == (pitch + texelWidth - 1u) / texelWidth, "PS4 texture pitch " + std::to_string(pitch) + " is not padded the way its tile mode pads a row (" + std::to_string(rowElements * texelWidth) + ")");
|
||||
auto& mip = mips[level];
|
||||
mip.width = TexelLevelDimension(width, level, texelWidth);
|
||||
mip.height = TexelLevelDimension(height, level, texelHeight);
|
||||
mip.blocksPerRow = macro ? rowElements / macroWidth : micro ? rowElements / 8u : rowElements;
|
||||
mip.gcnMicroTiled = micro && IsGcnMacroTiled(tileMode);
|
||||
mip.gcnSplitStride = splitSlices > 1u ? static_cast<std::uint32_t>(static_cast<std::uint64_t>(rowElements) * rows * bytes / splitSlices) : 0u;
|
||||
mip.pitchBytes = rowElements * bytes;
|
||||
mip.tiledSize = static_cast<std::uint64_t>(rowElements) * rows * bytes;
|
||||
mip.linearSize = static_cast<std::uint64_t>(mip.pitchBytes) * mip.height;
|
||||
mip.tiledOffset = offset;
|
||||
mip.linearOffset = linearOffset;
|
||||
mip.tail = false;
|
||||
mip.tailX = 0;
|
||||
mip.tailY = 0;
|
||||
offset += mip.tiledSize * layers;
|
||||
linearOffset += mip.tiledSize;
|
||||
}
|
||||
return mips;
|
||||
}
|
||||
|
||||
GcnTileGeometry GcnTiling(TextureTileMode tileMode, std::uint32_t bytesPerElement) {
|
||||
Require(IsGcnTiled(tileMode), "PS4 tile geometry needs a PS4 tiled mode");
|
||||
Require(std::has_single_bit(bytesPerElement) && bytesPerElement <= 16u, "unsupported bytes per element for PS4 tiling");
|
||||
const auto x = [](std::uint32_t bit) { return 1u << bit; };
|
||||
const auto y = [](std::uint32_t bit) { return 1u << (12u + bit); };
|
||||
const std::array<std::uint32_t, 6> thin{x(0), y(0), x(1), y(1), x(2), y(2)};
|
||||
const std::array<std::array<std::uint32_t, 6>, 5> display{{
|
||||
{x(0), x(1), x(2), y(1), y(0), y(2)}, {x(0), x(1), x(2), y(0), y(1), y(2)}, {x(0), x(1), y(0), x(2), y(1), y(2)},
|
||||
{x(0), y(0), x(1), x(2), y(1), y(2)}, {x(0), y(0), x(1), y(1), x(2), y(2)},
|
||||
}};
|
||||
const auto log2Bytes = static_cast<std::uint32_t>(std::countr_zero(bytesPerElement));
|
||||
const bool displayOrder = tileMode == TextureTileMode::kGcnDisplay1D || tileMode == TextureTileMode::kGcnDisplay2D || tileMode == TextureTileMode::kGcnDisplayPrt || tileMode == TextureTileMode::kGcnDisplay2DPrt;
|
||||
const auto& order = displayOrder ? display[log2Bytes] : thin;
|
||||
const auto microBytes = 64u * bytesPerElement;
|
||||
GcnTileGeometry geometry{};
|
||||
if (IsGcnMicroTiled(tileMode)) {
|
||||
geometry = {microBytes, 8u, 8u, {}};
|
||||
for (std::uint32_t bit = 0; bit < order.size(); ++bit) geometry.equation[log2Bytes + bit] = order[bit];
|
||||
return geometry;
|
||||
}
|
||||
struct MacroMode { std::uint32_t bankHeight; std::uint32_t banks; std::uint32_t aspect; };
|
||||
constexpr std::array<MacroMode, 5> macroModes{{{4u, 16u, 4u}, {2u, 16u, 2u}, {1u, 16u, 2u}, {1u, 16u, 2u}, {1u, 8u, 1u}}};
|
||||
constexpr std::array<MacroMode, 5> prtMacroModes{{{8u, 16u, 4u}, {4u, 16u, 4u}, {2u, 16u, 2u}, {1u, 16u, 2u}, {1u, 8u, 1u}}};
|
||||
std::uint32_t tileSplit = std::min(1024u, std::max(256u, 2u * microBytes));
|
||||
switch (tileMode) {
|
||||
case TextureTileMode::kGcnDepth2D64: tileSplit = 64u; break;
|
||||
case TextureTileMode::kGcnDepth2D128: tileSplit = 128u; break;
|
||||
case TextureTileMode::kGcnDepth2D256:
|
||||
case TextureTileMode::kGcnDepthPrt256: tileSplit = 256u; break;
|
||||
case TextureTileMode::kGcnDepth2D512: tileSplit = 512u; break;
|
||||
case TextureTileMode::kGcnDepth2D1K:
|
||||
case TextureTileMode::kGcnDepthPrt1K: tileSplit = 1024u; break;
|
||||
default: break;
|
||||
}
|
||||
const bool prt = IsGcnPrtTiled(tileMode);
|
||||
const bool splitRotation = tileMode != TextureTileMode::kGcnDisplayPrt && tileMode != TextureTileMode::kGcnThinPrt;
|
||||
const bool pipe8x16 = tileMode == TextureTileMode::kGcnDisplayPrt || tileMode == TextureTileMode::kGcnThinPrt;
|
||||
const auto tileBytes = std::min(tileSplit, microBytes);
|
||||
const auto log2TileBytes = static_cast<std::uint32_t>(std::countr_zero(tileBytes));
|
||||
const auto& mode = (prt ? prtMacroModes : macroModes)[log2TileBytes - 6u];
|
||||
constexpr std::uint32_t pipes = 8u, log2Pipes = 3u, pipeInterleaveBits = 8u;
|
||||
const auto log2BankHeight = static_cast<std::uint32_t>(std::countr_zero(mode.bankHeight));
|
||||
const auto bankBits = static_cast<std::uint32_t>(std::countr_zero(mode.banks));
|
||||
geometry.blockWidth = 8u * pipes * mode.aspect;
|
||||
geometry.blockHeight = 8u * mode.bankHeight * mode.banks / mode.aspect;
|
||||
const auto macroBytes = tileBytes * mode.bankHeight;
|
||||
Require(macroBytes % 256u == 0, "PS4 macro tile is not a whole number of pipe interleaves");
|
||||
geometry.blockBytes = macroBytes * pipes * mode.banks;
|
||||
const auto elementBits = log2TileBytes - log2Bytes;
|
||||
geometry.splitSlices = microBytes / tileBytes;
|
||||
for (auto bit = elementBits; bit < order.size(); ++bit) geometry.splitMasks[bit - elementBits] = order[bit];
|
||||
std::array<std::uint32_t, 16> inner{};
|
||||
for (std::uint32_t bit = 0; bit < elementBits; ++bit) inner[log2Bytes + bit] = order[bit];
|
||||
auto innerBits = log2TileBytes;
|
||||
for (std::uint32_t bit = 0; bit < log2BankHeight; ++bit) inner[innerBits++] = y(3u + bit);
|
||||
const auto pipe = pipe8x16 ? std::array<std::uint32_t, 3>{x(4) | y(3) | x(5), x(3) | y(4), x(5) | y(5)} : std::array<std::uint32_t, 3>{x(3) | y(3) | x(4), x(4) | y(4), x(5) | y(5)};
|
||||
const auto log2Aspect = static_cast<std::uint32_t>(std::countr_zero(mode.aspect));
|
||||
const auto tx = [&](std::uint32_t bit) { return prt && bit >= log2Aspect ? 0u : x(3u + log2Pipes + bit); };
|
||||
const auto ty = [&](std::uint32_t bit) { return prt && bit >= bankBits - log2Aspect ? 0u : y(3u + log2BankHeight + bit); };
|
||||
std::array<std::uint32_t, 4> bank{};
|
||||
switch (mode.banks) {
|
||||
case 16u: bank = {tx(0) | ty(3), tx(1) | ty(2) | ty(3), tx(2) | ty(1), tx(3) | ty(0)}; break;
|
||||
case 8u: bank = {tx(0) | ty(2), tx(1) | ty(1) | ty(2), tx(2) | ty(0), 0u}; break;
|
||||
default: Require(false, "PS4 macro tile bank count is not modeled");
|
||||
}
|
||||
for (std::uint32_t split = 0; splitRotation && split < 4u && geometry.splitMasks[split] != 0; ++split) {
|
||||
const auto rotation = ((mode.banks / 2u + 1u) << split) & (mode.banks - 1u);
|
||||
for (std::uint32_t bit = 0; bit < bankBits; ++bit) {
|
||||
if ((rotation >> bit) & 1u) bank[bit] ^= geometry.splitMasks[split];
|
||||
}
|
||||
}
|
||||
Require(innerBits + log2Pipes + bankBits <= 16u, "PS4 macro tile exceeds 64 KiB");
|
||||
for (std::uint32_t bit = 0; bit < pipeInterleaveBits; ++bit) geometry.equation[bit] = inner[bit];
|
||||
for (std::uint32_t bit = 0; bit < log2Pipes; ++bit) geometry.equation[pipeInterleaveBits + bit] = pipe[bit];
|
||||
for (std::uint32_t bit = 0; bit < bankBits; ++bit) geometry.equation[pipeInterleaveBits + log2Pipes + bit] = bank[bit];
|
||||
for (auto bit = pipeInterleaveBits; bit < innerBits; ++bit) geometry.equation[bit + log2Pipes + bankBits] = inner[bit];
|
||||
return geometry;
|
||||
}
|
||||
|
||||
namespace {
|
||||
|
||||
SurfaceGeometry describeGcnSurface(const GuestTextureResource& descriptor) {
|
||||
Require(descriptor.dimension != TextureDimension::k3D && descriptor.dimension != TextureDimension::k2DMsaa, "PS4 3D and multisampled textures are not implemented");
|
||||
const bool layered = descriptor.dimension == TextureDimension::k2DArray || descriptor.dimension == TextureDimension::k1DArray || descriptor.dimension == TextureDimension::kCube;
|
||||
SurfaceGeometry geometry;
|
||||
geometry.layers = layered ? descriptor.depthOrLastArray + 1u : 1u;
|
||||
geometry.levelMajor = geometry.layers > 1u && descriptor.mipCount > 1u;
|
||||
geometry.mips = ComputeGcnMipLayout(descriptor.tileMode, descriptor.format, descriptor.width, descriptor.height, descriptor.gcnPitch, descriptor.gcnPow2Pad, descriptor.mipCount, descriptor.gcnLinearGeneral, geometry.layers);
|
||||
geometry.imageLayers = geometry.layers;
|
||||
geometry.guestBytes = geometry.mips.back().tiledOffset + geometry.mips.back().tiledSize * geometry.layers;
|
||||
geometry.layerBytes = geometry.guestBytes / geometry.layers;
|
||||
for (const auto& mip : geometry.mips) geometry.sliceLinearBytes = std::max(geometry.sliceLinearBytes, mip.linearOffset + mip.linearSize);
|
||||
return geometry;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
SurfaceGeometry DescribeSurface(const GuestTextureResource& descriptor) {
|
||||
if (descriptor.gcnPitch != 0) return describeGcnSurface(descriptor);
|
||||
SurfaceGeometry geometry;
|
||||
if (descriptor.samples != 1u && descriptor.tileMode != TextureTileMode::kLinear) {
|
||||
Require(descriptor.samples == 2u || descriptor.samples == 4u || descriptor.samples == 8u, "multisampled surface fragment count is not implemented");
|
||||
@@ -510,6 +707,7 @@ GuestTextureResource ArrayLayerWindow(const GuestTextureResource& viewed, std::u
|
||||
|
||||
std::vector<TileMipLayout> ComputeElementMipLayout(TextureTileMode tileMode, std::uint32_t bytesPerElement, std::uint32_t width, std::uint32_t height, std::uint32_t mipCount) {
|
||||
Require(width != 0 && height != 0 && mipCount != 0 && mipCount <= 16u, "invalid surface mip chain");
|
||||
Require(!IsGcnTiled(tileMode), "PS4 surfaces are laid out by ComputeGcnMipLayout from their pitch");
|
||||
if (tileMode == TextureTileMode::kLinear) return ComputeLinearMipLayout(bytesPerElement, 1u, 1u, width, height, mipCount);
|
||||
return ComputeTiledMipLayout(tileMode, bytesPerElement, 1u, 1u, width, height, mipCount);
|
||||
}
|
||||
|
||||
@@ -1838,14 +1838,23 @@ void UnclampedNormalizedColorTests() {
|
||||
const auto pass = AgcDriver::Graphics::DecodeColorMetadataPass(eliminate);
|
||||
Require(pass.has_value() && pass->mode == AgcDriver::Graphics::ColorMetadataPass::Mode::EliminateFastClear && pass->targets.size() == 1 && pass->targets[0].format == VK_FORMAT_R8G8_UNORM, "a fast-clear eliminate over an unclamped UNORM target was refused");
|
||||
queue.context[0x1e0] = blending;
|
||||
expectFailure([&] { DecodeState(queue); }, "blending unclamped normalized color is not implemented (CB_COLOR_INFO 0x0000000c, CB_BLEND0_CONTROL 0x40000504)");
|
||||
state = DecodeState(queue);
|
||||
Require(state.colors.at(0).partialWriteMask == AgcDriver::Graphics::UnclampedBlendMask && state.blends.at(0).blendEnable && state.blends.at(0).colorWriteMask != 0, "an 8_8 UNORM target that blends with BLEND_CLAMP clear (CB_COLOR_INFO 0x0000000c, CB_BLEND0_CONTROL 0x40000504) was not routed to the pixel shader");
|
||||
const auto merge = AgcDriver::Graphics::ExportTargetMerge(state);
|
||||
Require(merge.blend.enabled && !merge.blend.snorm && merge.mask == AgcDriver::Graphics::UnclampedBlendMask && merge.samples == 1u && merge.blend.colorSource == VK_BLEND_FACTOR_SRC_ALPHA && merge.blend.colorDestination == VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA && merge.blend.colorOperation == VK_BLEND_OP_ADD && merge.blend.writeMask == state.blends.at(0).colorWriteMask, "the unclamped blend of an 8_8 UNORM target was not described to the pixel shader");
|
||||
queue.context[0x31c] |= 0x10000u;
|
||||
state = DecodeState(queue);
|
||||
Require(!state.blends.at(0).blendEnable && state.blends.at(0).colorWriteMask != 0, "an unclamped UNORM target with BLEND_BYPASS was refused or blended");
|
||||
queue = target(0x0000010cu);
|
||||
Require(DecodeState(queue).colors.at(0).format == VK_FORMAT_R8G8_SNORM, "an unclamped SNORM target that does not blend was refused");
|
||||
queue.context[0x1e0] = blending;
|
||||
expectFailure([&] { DecodeState(queue); }, "blending unclamped normalized color is not implemented");
|
||||
state = DecodeState(queue);
|
||||
Require(state.colors.at(0).partialWriteMask == AgcDriver::Graphics::UnclampedBlendMask && AgcDriver::Graphics::ExportTargetMerge(state).blend.snorm, "an unclamped SNORM target that blends was not routed to the pixel shader as signed");
|
||||
auto unsignedMasked = target(0x0000000cu);
|
||||
unsignedMasked.context[0x1e0] = blending;
|
||||
unsignedMasked.context[0x8e] = 0x1u;
|
||||
state = DecodeState(unsignedMasked);
|
||||
Require(state.colors.at(0).partialWriteMask == AgcDriver::Graphics::UnclampedBlendMask && state.blends.at(0).colorWriteMask == VK_COLOR_COMPONENT_R_BIT, "an unclamped UNORM target that blends with a write mask that skips a component was not routed to the pixel shader");
|
||||
queue = target(0x00000604u);
|
||||
expectFailure([&] { DecodeState(queue); }, "unclamped normalized color is unsupported");
|
||||
queue = target(0x0000800cu);
|
||||
@@ -11627,6 +11636,20 @@ void highestDrawIndexTests() {
|
||||
Require(HighestDrawIndex(std::span<const std::byte>(shifted).subspan(1, 2 * 1000 + 1), 2, false) == 0x8001u, "an unaligned 16-bit range with a trailing byte");
|
||||
}
|
||||
|
||||
void compactListRestartTests() {
|
||||
using AgcDriver::Graphics::CompactListRestart;
|
||||
std::array<std::uint16_t, 9> triangles{0, 1, 2, 3, 4, 0xffff, 5, 6, 7};
|
||||
Require(CompactListRestart(std::as_writable_bytes(std::span(triangles)), 2, 3) == 6 && triangles[0] == 0 && triangles[2] == 2 && triangles[3] == 5 && triangles[5] == 7, "a restart did not drop the incomplete triangle before it");
|
||||
std::array<std::uint32_t, 7> lines{0, 1, 0xffffffffu, 2, 0xffffffffu, 3, 4};
|
||||
Require(CompactListRestart(std::as_writable_bytes(std::span(lines)), 4, 2) == 4 && lines[2] == 3 && lines[3] == 4, "a restart between whole lines changed them");
|
||||
std::array<std::uint16_t, 4> points{0xffff, 6, 0xffff, 9};
|
||||
Require(CompactListRestart(std::as_writable_bytes(std::span(points)), 2, 1) == 2 && points[0] == 6 && points[1] == 9, "restart indices were drawn as points");
|
||||
std::array<std::uint16_t, 5> tail{0, 1, 2, 3, 4};
|
||||
Require(CompactListRestart(std::as_writable_bytes(std::span(tail)), 2, 3) == 3, "the incomplete last triangle was kept");
|
||||
std::array<std::uint16_t, 2> restartOnly{0xffff, 0xffff};
|
||||
Require(CompactListRestart(std::as_writable_bytes(std::span(restartOnly)), 2, 3) == 0, "a draw of only restart indices kept an index");
|
||||
}
|
||||
|
||||
void storeAtFlipTests() {
|
||||
using AgcDriver::Graphics::StorageTexture;
|
||||
Require(!StorageTexture::StoreAtFlipRequested(nullptr), "an unset APS5_STORE_AT_FLIP stored at each flip");
|
||||
@@ -11952,6 +11975,57 @@ void pipelineStoreGrowthTests(bool fixed) {
|
||||
Require(mock.live == 0, "pipeline store growth tests leaked Vulkan objects");
|
||||
}
|
||||
|
||||
void pipelineStoreTouchTests() {
|
||||
using namespace AgcDriver::Graphics;
|
||||
mock = MockVulkan{};
|
||||
auto context = mockContext();
|
||||
context.device = makeHandle<VkDevice>();
|
||||
context.graphicsPipelineLibrary = true;
|
||||
context.pipelineLinkTimeOptimization = false;
|
||||
context.limits.framebufferNoAttachmentsSampleCounts = VK_SAMPLE_COUNT_1_BIT;
|
||||
ShaderRecompiler::RecompileResult vertex, fragment;
|
||||
vertex.spirv = makeModule({});
|
||||
fragment.spirv = makeModule({.fragment = true});
|
||||
vertex.variantId = 401;
|
||||
fragment.variantId = 402;
|
||||
const std::array<CompiledShader, 2> shaders{{{ShaderRecompiler::ShaderStage::Vertex, &vertex, 0}, {ShaderRecompiler::ShaderStage::Fragment, &fragment, PipelinePushSlotBytes}}};
|
||||
std::array<std::uint32_t, 1> mainKey{51}, fragmentKey{52};
|
||||
const PipelineSetLayouts resources{makeHandle<VkDescriptorSetLayout>(), makeHandle<VkDescriptorSetLayout>(), true, mainKey, fragmentKey};
|
||||
const auto layout = [](std::uint32_t configuration) {
|
||||
VertexInputLayout input;
|
||||
input.bindings.push_back({0, 4u * (configuration + 1u), VK_VERTEX_INPUT_RATE_VERTEX});
|
||||
return input;
|
||||
};
|
||||
std::uint64_t hash = 0;
|
||||
std::weak_ptr<Pipeline> touched;
|
||||
std::weak_ptr<Pipeline> other;
|
||||
{
|
||||
auto first = CachedPipeline(context, State{}, layout(0), resources, shaders, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, nullptr, &hash);
|
||||
Require(hash != 0, "a stored pipeline reported no store hash");
|
||||
std::uint64_t secondHash = 0;
|
||||
auto second = CachedPipeline(context, State{}, layout(1), resources, shaders, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, nullptr, &secondHash);
|
||||
Require(secondHash != 0 && secondHash != hash, "two configurations reported the same store hash");
|
||||
touched = first;
|
||||
other = second;
|
||||
const auto hits = PipelineStoreTotals().hits;
|
||||
Require(TouchCachedPipeline(context, hash, touched) == first && PipelineStoreTotals().hits == hits + 1, "touching a stored pipeline did not return it as a hit");
|
||||
Require(TouchCachedPipeline(context, hash, other) == nullptr, "touching a hash with another pipeline returned the stored one");
|
||||
Require(TouchCachedPipeline(context, hash, std::weak_ptr<Pipeline>{}) == nullptr, "touching a hash without a pipeline returned the stored one");
|
||||
}
|
||||
for (std::uint32_t configuration = 2; configuration < PipelineStoreTotals().bound; ++configuration) static_cast<void>(CachedPipeline(context, State{}, layout(configuration), resources, shaders));
|
||||
Require(TouchCachedPipeline(context, hash, touched) != nullptr, "the first pipeline left a store that was not yet full");
|
||||
bool created = false;
|
||||
static_cast<void>(CachedPipeline(context, State{}, layout(PipelineStoreTotals().bound), resources, shaders, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, &created));
|
||||
Require(created, "the configuration that fills the store was already stored");
|
||||
static_cast<void>(CachedPipeline(context, State{}, layout(0), resources, shaders, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, &created));
|
||||
Require(!created, "a touched pipeline was evicted as the least recently used one");
|
||||
static_cast<void>(CachedPipeline(context, State{}, layout(1), resources, shaders, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, &created));
|
||||
Require(created, "the least recently used pipeline stayed while a touched one was older");
|
||||
ClearCachedPipelines(context.device);
|
||||
Require(TouchCachedPipeline(context, hash, touched) == nullptr, "touching a pipeline of a cleared store returned it");
|
||||
Require(mock.live == 0, "pipeline store touch tests leaked Vulkan objects");
|
||||
}
|
||||
|
||||
// A journal longer than the store's starting bound: 1032 recorded pipelines replayed into an empty
|
||||
// store all stay resident (the replay grows the bound instead of dropping what does not fit).
|
||||
void pipelineStoreReplayGrowthTests() {
|
||||
@@ -12467,6 +12541,11 @@ int main(int argc, char** argv) {
|
||||
std::cout << "pipeline store bound follows the evicted pipelines that come back\n";
|
||||
return 0;
|
||||
}
|
||||
if (argc == 2 && std::string_view(argv[1]) == "--pipeline-store-touch") {
|
||||
pipelineStoreTouchTests();
|
||||
std::cout << "a touched pipeline is returned as a hit and stays recently used\n";
|
||||
return 0;
|
||||
}
|
||||
if (argc == 2 && std::string_view(argv[1]) == "--pipeline-store-lazy-buffer-pool") {
|
||||
pipelineStoreLazyBufferPoolTests();
|
||||
std::cout << "cached pipelines survive lazy buffer pool creation\n";
|
||||
@@ -12838,6 +12917,7 @@ int main(int argc, char** argv) {
|
||||
validationTests();
|
||||
vertexCopyTests();
|
||||
highestDrawIndexTests();
|
||||
compactListRestartTests();
|
||||
storeAtFlipTests();
|
||||
storeAtLabelTests();
|
||||
nullVertexDescriptorTests();
|
||||
|
||||
@@ -689,7 +689,7 @@ void pageTwoSamplerTest(const Device& device) {
|
||||
const auto present = [&](std::chrono::milliseconds at, std::uint64_t address, std::uint64_t drops) { overlay.NotePresent(start + at, VkExtent2D{640, 360}, AgcDriver::OverlayPresentInfo{address, VK_PRESENT_MODE_FIFO_KHR, drops}); };
|
||||
present(0ms, 0x1000, 7);
|
||||
const auto& sample = overlay.DetailSample();
|
||||
Require(sample.commit.has_value() && sample.unimplementedTotal.has_value() && sample.presentMode == "fifo" && sample.pipelinesCompiling == std::optional<std::uint64_t>{0}, "page 2's first sample does not read the commit charge, the unimplemented calls, the compile backlog and the present mode");
|
||||
Require(sample.commit.has_value() == AgcDriver::ReadCommitCharge().has_value() && sample.unimplementedTotal.has_value() && sample.presentMode == "fifo" && sample.pipelinesCompiling == std::optional<std::uint64_t>{0}, "page 2's first sample does not read the commit charge where the system reports one, the unimplemented calls, the compile backlog and the present mode");
|
||||
Require(!sample.flipsPerSecond && !sample.pageFaultsPerSecond && !sample.cpuCopyMegabytesPerSecond && sample.busy.empty() && sample.phases.empty(), "page 2's first sample shows rates before a second has passed");
|
||||
Require(sample.hostImports.has_value() == (context.hostImportAlignment != 0), "the host import line does not follow the device's host import support");
|
||||
std::thread([] {
|
||||
|
||||
@@ -737,7 +737,11 @@ void operatingSystemTests() {
|
||||
require(!AgcDriver::ParseCommitCharge("CommitLimit: 8159204 kB\nCommitted_AS: 12 MB\n"), "a value in another unit is read as kB");
|
||||
require(!AgcDriver::ParseCommitCharge(""), "an empty /proc/meminfo gives a commit charge");
|
||||
const auto commit = AgcDriver::ReadCommitCharge();
|
||||
#ifdef __APPLE__
|
||||
require(!commit, "a commit charge is read on macOS, which reports none");
|
||||
#else
|
||||
require(commit && commit->used != 0 && commit->budget != 0, "the system's commit charge and limit cannot be read");
|
||||
#endif
|
||||
static std::uint8_t* volatile touched = nullptr;
|
||||
const auto before = AgcDriver::ReadPageFaults();
|
||||
require(before.has_value(), "the process's page faults cannot be read");
|
||||
|
||||
@@ -512,10 +512,28 @@ void ReplaceGzipFile() {
|
||||
bool writeFailed = false;
|
||||
try { AgcDriver::TraceFile::ReplaceGzip(path, "{\"third\":3}\n"); } catch (const std::exception&) { writeFailed = true; }
|
||||
const auto keptAfterWrite = ReadGzip(path);
|
||||
#endif
|
||||
#ifdef __linux__
|
||||
bool fullFailed = false;
|
||||
bool fullLeft = false;
|
||||
if (std::filesystem::exists("/dev/full")) {
|
||||
const auto fullPath = directory / "aps5-bench-full.json.gz";
|
||||
auto fullTemporary = fullPath;
|
||||
fullTemporary += ".tmp";
|
||||
std::filesystem::create_symlink("/dev/full", fullTemporary);
|
||||
try { AgcDriver::TraceFile::ReplaceGzip(fullPath, "{\"full\":1}\n"); } catch (const std::exception&) { fullFailed = true; }
|
||||
std::error_code linkError;
|
||||
fullLeft = std::filesystem::symlink_status(fullTemporary, linkError).type() != std::filesystem::file_type::not_found;
|
||||
} else {
|
||||
fullFailed = true;
|
||||
}
|
||||
#endif
|
||||
std::filesystem::remove_all(directory);
|
||||
Check(failed && blockedKept && !temporaryLeft, "a replace that could not move its file over the destination did not fail cleanly or left its temporary file");
|
||||
Check(kept == "{\"second\":2}\n", "a failed replace of another file damaged the benchmark file");
|
||||
#ifdef __linux__
|
||||
Check(fullFailed && !fullLeft, "a replace whose write failed left its temporary file behind");
|
||||
#endif
|
||||
#ifndef _WIN32
|
||||
Check(writeFailed && keptAfterWrite == "{\"second\":2}\n", "a failed rewrite damaged the previous benchmark file");
|
||||
#endif
|
||||
|
||||
@@ -13,6 +13,7 @@
|
||||
#include "prx/libc/include/FailureReport.hpp"
|
||||
#include "prx/libc/include/Shutdown.hpp"
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
#include <atomic>
|
||||
#include <chrono>
|
||||
#include <condition_variable>
|
||||
@@ -851,6 +852,35 @@ void testWriteChangedStoresExactlyTheChangedRuns() {
|
||||
}
|
||||
}
|
||||
|
||||
void testWriteChangedChunksOfEveryDensity() {
|
||||
alignas(64) static std::uint8_t guest[128];
|
||||
constexpr std::size_t Tail = 5;
|
||||
std::vector<std::byte> original(96 + Tail), current(96 + Tail);
|
||||
for (std::size_t i = 0; i < original.size(); ++i) original[i] = current[i] = static_cast<std::byte>(i);
|
||||
const std::array<std::uint32_t, 6> masks = {0x0421u, 0x8421u, 0x8423u, 0xfb7bu, 0x5ad7u, 0xffffu};
|
||||
for (std::size_t chunk = 0; chunk < masks.size(); ++chunk) {
|
||||
for (std::size_t bit = 0; bit < 16; ++bit) {
|
||||
if ((masks[chunk] >> bit) & 1u) current[chunk * 16 + bit] ^= std::byte{0xff};
|
||||
}
|
||||
}
|
||||
current[96] ^= std::byte{0xff};
|
||||
current[99] ^= std::byte{0xff};
|
||||
const auto limit = AgcDriver::GuestMemory::ChangedByteStoreLimit();
|
||||
check(limit == 4u || limit == 16u, "the byte-store limit is neither the masked-store cut-off nor every density");
|
||||
for (const std::size_t offset : {std::size_t{0}, std::size_t{1}}) {
|
||||
const auto size = offset == 0 ? std::size_t{96} : current.size();
|
||||
for (const auto byteStoreLimit : {0u, 4u, 16u, limit}) {
|
||||
for (std::size_t i = 0; i < sizeof(guest); ++i) guest[i] = static_cast<std::uint8_t>(0xa0u ^ i);
|
||||
AgcDriver::GuestMemory::WriteChanged(reinterpret_cast<std::uintptr_t>(guest + offset), std::span(current).first(size), std::span(original).first(size), byteStoreLimit);
|
||||
for (std::size_t i = 0; i < sizeof(guest); ++i) {
|
||||
const bool inside = i >= offset && i - offset < size;
|
||||
const auto expected = inside && current[i - offset] != original[i - offset] ? static_cast<std::uint8_t>(current[i - offset]) : static_cast<std::uint8_t>(0xa0u ^ i);
|
||||
check(guest[i] == expected, "write-back of chunks with 3, 4, 5, 13, 10 and 16 changed bytes, aligned or one byte off with a 5-byte tail, stored a byte the GPU did not change or missed one it did");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void testEventWrite() {
|
||||
for (const auto eventType : {0x07u, 0x0fu, 0x10u}) {
|
||||
AgcDriver::Pm4::Validate(makePacket(0x46, {0x400u | eventType}), 0);
|
||||
@@ -2111,6 +2141,7 @@ int main(int argc, char** argv) {
|
||||
testWorkloadNopPayloadsIgnored();
|
||||
testRewindPayloadBits();
|
||||
testWriteChangedKeepsUntouchedBytes();
|
||||
testWriteChangedChunksOfEveryDensity();
|
||||
testWriteChangedStoresExactlyTheChangedRuns();
|
||||
testRegisters();
|
||||
testRegisterFile();
|
||||
|
||||
@@ -9327,6 +9327,109 @@ void multisampleGuestAccessTests(const Device& device, Recorder& recorder) {
|
||||
std::cout << "Multisampled target guest access tests passed\n";
|
||||
}
|
||||
|
||||
void repeatStorageGuardTests(const Device& device, Recorder& recorder) {
|
||||
const auto& base = device.GetContext();
|
||||
if ((base.limits.framebufferColorSampleCounts & VK_SAMPLE_COUNT_4_BIT) == 0 || !device.NullDescriptors()) {
|
||||
std::cout << "4x color targets or nullDescriptor unavailable: repeated storage surface guard not tested\n";
|
||||
return;
|
||||
}
|
||||
constexpr std::uint32_t side = 256;
|
||||
constexpr std::uint32_t targetSide = 64;
|
||||
constexpr std::size_t surfaceBytes = side * side * 4;
|
||||
constexpr std::size_t targetBytes = 65536u;
|
||||
constexpr std::size_t bytes = surfaceBytes + 2u * targetBytes;
|
||||
#ifdef _WIN32
|
||||
void* block = VirtualAlloc(nullptr, bytes, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
|
||||
#else
|
||||
void* block = std::aligned_alloc(65536, bytes);
|
||||
#endif
|
||||
Require(block != nullptr, "cannot allocate the repeated storage surface block");
|
||||
std::memset(block, 0, bytes);
|
||||
const auto address = reinterpret_cast<std::uint64_t>(block);
|
||||
{
|
||||
GuestAllocations::Mutation mutation;
|
||||
mutation.Add(block, bytes, true, true, true);
|
||||
}
|
||||
struct Unregister {
|
||||
const Context& context;
|
||||
void* block;
|
||||
~Unregister() {
|
||||
ClearMultisampleTargets(context.device);
|
||||
ClearCachedTextures(context.device);
|
||||
{
|
||||
GuestAllocations::Mutation mutation;
|
||||
mutation.Remove(block);
|
||||
}
|
||||
#ifdef _WIN32
|
||||
VirtualFree(block, 0, MEM_RELEASE);
|
||||
#else
|
||||
std::free(block);
|
||||
#endif
|
||||
}
|
||||
} unregister{base, block};
|
||||
TextureDetiler detiler(base);
|
||||
auto context = base;
|
||||
context.detiler = &detiler;
|
||||
context.nullDescriptors = true;
|
||||
TextureCache cache(context);
|
||||
context.textureCache = &cache;
|
||||
GuestTextureResource resource{};
|
||||
resource.baseAddress = address;
|
||||
resource.width = side;
|
||||
resource.height = side;
|
||||
resource.mipCount = 1;
|
||||
resource.tileMode = TextureTileMode::kR64KBX;
|
||||
resource.dimension = TextureDimension::k2D;
|
||||
resource.format = 56;
|
||||
resource.dstSelX = 4;
|
||||
resource.dstSelY = 5;
|
||||
resource.dstSelZ = 6;
|
||||
resource.dstSelW = 7;
|
||||
Require(DescribeSurface(resource).guestBytes == surfaceBytes, "the repeated storage surface has an unexpected size");
|
||||
const auto guard = [&](std::uint64_t at) {
|
||||
ColorTarget target{};
|
||||
target.address = at;
|
||||
target.surfaceAddress = at;
|
||||
target.extent = {targetSide, targetSide};
|
||||
target.surfaceExtent = target.extent;
|
||||
target.format = VK_FORMAT_R8G8B8A8_UNORM;
|
||||
target.bytes = targetBytes;
|
||||
target.samples = 4;
|
||||
std::lock_guard gpu(GpuMutex());
|
||||
Require(MultisampleTargetView(context, target) != VK_NULL_HANDLE, "the guarding multisampled target has no view");
|
||||
recorder.Submit();
|
||||
device.WaitQueue();
|
||||
recorder.Sync();
|
||||
};
|
||||
const auto clearTargets = [&] {
|
||||
recorder.Submit();
|
||||
device.WaitQueue();
|
||||
recorder.Sync();
|
||||
ClearMultisampleTargets(context.device);
|
||||
};
|
||||
const auto refusal = [](const std::function<void()>& access) {
|
||||
try {
|
||||
access();
|
||||
} catch (const std::exception& error) {
|
||||
return std::string(error.what());
|
||||
}
|
||||
return std::string();
|
||||
};
|
||||
const auto stored = CachedStorageSurface(context, resource);
|
||||
Require(stored != nullptr, "the storage surface has no image");
|
||||
Require(RepeatStorageSurface(context, resource, stored) == stored && CachedStorageSurface(context, resource) == stored, "without a guarded target the repeat path and the lookup returned different images");
|
||||
guard(address + surfaceBytes);
|
||||
Require(RepeatStorageSurface(context, resource, stored) == stored && CachedStorageSurface(context, resource) == stored, "a guarded target that starts where the surface ends changed the repeat path's or the lookup's image");
|
||||
clearTargets();
|
||||
guard(address + targetBytes);
|
||||
const auto repeated = refusal([&] { static_cast<void>(RepeatStorageSurface(context, resource, stored)); });
|
||||
const auto looked = refusal([&] { static_cast<void>(CachedStorageSurface(context, resource)); });
|
||||
Require(!looked.empty() && looked.find("a storage image access") != std::string::npos && looked.find("multisampled color target") != std::string::npos, "the lookup did not refuse a surface a guarded target overlaps after its first byte: " + looked);
|
||||
Require(repeated == looked, "the repeat path decided differently from the lookup for a guarded target after the surface's first byte: " + repeated);
|
||||
clearTargets();
|
||||
std::cout << "Repeated storage surface guard tests passed\n";
|
||||
}
|
||||
|
||||
void oneFragmentFmaskGuardTests(const Device& device) {
|
||||
const auto& base = device.GetContext();
|
||||
if (!device.NullDescriptors()) {
|
||||
@@ -12128,6 +12231,10 @@ int main(int argc, char** argv) {
|
||||
std::cout << "Copied draw input tests passed\n";
|
||||
return 0;
|
||||
}
|
||||
if (argc == 2 && std::string_view(argv[1]) == "--repeat-storage-guard-only") {
|
||||
repeatStorageGuardTests(device, recorder);
|
||||
return 0;
|
||||
}
|
||||
if (argc == 2 && std::string_view(argv[1]) == "--multisample-only") {
|
||||
multisampleGuestAccessTests(device, recorder);
|
||||
oneFragmentFmaskGuardTests(device);
|
||||
@@ -12192,6 +12299,7 @@ int main(int argc, char** argv) {
|
||||
bdaStagingTests(device, recorder);
|
||||
depthSurfaceProofTests(device, recorder);
|
||||
multisampleGuestAccessTests(device, recorder);
|
||||
repeatStorageGuardTests(device, recorder);
|
||||
oneFragmentFmaskGuardTests(device);
|
||||
tiledResolveTests(device, recorder);
|
||||
fmaskDecompressMsaaTests(device, recorder);
|
||||
|
||||
@@ -11,6 +11,7 @@
|
||||
#include <spirv/unified1/spirv.hpp>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <unordered_map>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
@@ -188,6 +189,30 @@ int CornerIndex(std::span<const std::uint32_t> words, float x, float y) {
|
||||
|
||||
}
|
||||
|
||||
std::vector<std::uint32_t> VertexWithClipDistances(std::uint32_t count) {
|
||||
constexpr auto word = [](std::uint32_t words, spv::Op opcode) { return (words << spv::WordCountShift) | static_cast<std::uint32_t>(opcode); };
|
||||
return {
|
||||
spv::MagicNumber, 0x00010400u, 0u, 7u, 0u,
|
||||
word(3, spv::OpTypeFloat), 1u, 32u,
|
||||
word(4, spv::OpTypeInt), 2u, 32u, 0u,
|
||||
word(4, spv::OpConstant), 2u, 3u, count,
|
||||
word(4, spv::OpTypeArray), 4u, 1u, 3u,
|
||||
word(4, spv::OpTypePointer), 5u, spv::StorageClassOutput, 4u,
|
||||
word(4, spv::OpVariable), 5u, 6u, spv::StorageClassOutput,
|
||||
word(4, spv::OpDecorate), 6u, spv::DecorationBuiltIn, spv::BuiltInClipDistance,
|
||||
};
|
||||
}
|
||||
|
||||
bool BuildRejected(const RecompileResult& vertex, const SpirvTarget& target) {
|
||||
RecompileResult fragment;
|
||||
try {
|
||||
static_cast<void>(BuildRectListShaders(vertex, fragment, target));
|
||||
} catch (const std::runtime_error& error) {
|
||||
return std::string_view(error.what()).find("exceeds device limits") != std::string_view::npos;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
int main() {
|
||||
try {
|
||||
static constexpr std::array<std::uint32_t, 2> capabilities{spv::CapabilityShader, spv::CapabilityTessellation};
|
||||
@@ -217,6 +242,15 @@ int main() {
|
||||
std::snprintf(message, sizeof(message), "rect-list corner (%.9g, %.9g) selected vertex %d, expected %.0f", static_cast<double>(corner[0]), static_cast<double>(corner[1]), selected, static_cast<double>(corner[2]));
|
||||
Check(selected == static_cast<int>(corner[2]), message);
|
||||
}
|
||||
static constexpr std::array<std::uint32_t, 3> clipCapabilities{spv::CapabilityShader, spv::CapabilityClipDistance, spv::CapabilityTessellation};
|
||||
SpirvTarget clipTarget = target;
|
||||
clipTarget.supportedCapabilities = clipCapabilities;
|
||||
clipTarget.tessellation = TessellationTargetLimits{32, 8, 8, 120, 4096, 8, 8};
|
||||
RecompileResult clipVertex;
|
||||
clipVertex.spirv = VertexWithClipDistances(2);
|
||||
Check(!BuildRejected(clipVertex, clipTarget), "rect-list rejected a ClipDistance[2] vertex that fits eight per-vertex components");
|
||||
clipVertex.spirv = VertexWithClipDistances(8);
|
||||
Check(BuildRejected(clipVertex, clipTarget), "rect-list accepted a ClipDistance[8] vertex whose position and clip distances need twelve per-vertex components");
|
||||
std::printf("rect-list position invariant tests passed\n");
|
||||
return 0;
|
||||
} catch (const std::exception& error) {
|
||||
|
||||
@@ -23,16 +23,16 @@ std::uint64_t baselineRegisterStateKey(const QueueState& queue, bool allUserWord
|
||||
key ^= value;
|
||||
key *= 0x100000001b3ull;
|
||||
};
|
||||
const auto userEnd = [&](std::uint32_t base) {
|
||||
if (allUserWords) return base + 32u;
|
||||
const auto userEnd = [&](std::uint32_t base, std::uint32_t limit) {
|
||||
if (allUserWords) return base + limit;
|
||||
const auto resources = queue.shader.find(base - 1);
|
||||
if (resources == queue.shader.end()) return base;
|
||||
const auto count = ((resources->second >> 1u) & 0x1fu) | (((resources->second >> 27u) & 1u) << 5u);
|
||||
return base + std::min(count, 32u);
|
||||
return base + std::min(count, limit);
|
||||
};
|
||||
const std::array<std::pair<std::uint32_t, std::uint32_t>, 3> users{{{0x00cu, userEnd(0x00cu)}, {0x08cu, userEnd(0x08cu)}, {0x10cu, userEnd(0x10cu)}}};
|
||||
const std::array<std::array<std::uint32_t, 3>, 4> users{{{0x00cu, userEnd(0x00cu, 32u), 32u}, {0x04cu, userEnd(0x04cu, 16u), 16u}, {0x08cu, userEnd(0x08cu, 32u), 32u}, {0x10cu, userEnd(0x10cu, 32u), 32u}}};
|
||||
const auto unread = [&](std::uint32_t offset) {
|
||||
return std::any_of(users.begin(), users.end(), [&](const auto& user) { return offset >= user.second && offset < user.first + 32u; });
|
||||
return std::any_of(users.begin(), users.end(), [&](const auto& user) { return offset >= user[1] && offset < user[0] + user[2]; });
|
||||
};
|
||||
for (const auto& range : Graphics::DrawKeyRegisters) {
|
||||
const auto& bank = range.bank == Graphics::RegisterBank::Context ? queue.context : range.bank == Graphics::RegisterBank::Shader ? queue.shader : queue.userConfig;
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
#include "prx/libSceAgcDriver/Execution/include/Driver/Shaders/RegistrationPreparationBudget.hpp"
|
||||
#include <cstdint>
|
||||
#include <iostream>
|
||||
#include <limits>
|
||||
#include <stdexcept>
|
||||
|
||||
namespace {
|
||||
|
||||
void Require(bool condition, const char* message) {
|
||||
if (!condition) throw std::runtime_error(message);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
int main() {
|
||||
try {
|
||||
using AgcDriver::DriverDetail::RegistrationPreparationCommitBudgetBytes;
|
||||
using AgcDriver::DriverDetail::RegistrationPreparationAllowed;
|
||||
constexpr std::uint64_t GiB = 1024ull * 1024 * 1024;
|
||||
constexpr std::uint64_t defaultBudget = 8ull * GiB;
|
||||
Require(RegistrationPreparationCommitBudgetBytes(nullptr, defaultBudget) == defaultBudget, "an unset budget should preserve the host-derived default");
|
||||
Require(RegistrationPreparationCommitBudgetBytes("0", defaultBudget) == 0, "zero GiB should disable registration preparation");
|
||||
Require(RegistrationPreparationCommitBudgetBytes("0.5", defaultBudget) == GiB / 2, "fractional GiB should convert to bytes");
|
||||
Require(RegistrationPreparationCommitBudgetBytes("2", defaultBudget) == GiB * 2, "whole GiB should convert to bytes");
|
||||
for (const auto* invalid : {"", "-1", "1x", "inf", "nan", "1e1000"}) {
|
||||
bool rejected = false;
|
||||
try {
|
||||
static_cast<void>(RegistrationPreparationCommitBudgetBytes(invalid, defaultBudget));
|
||||
} catch (const std::runtime_error&) {
|
||||
rejected = true;
|
||||
}
|
||||
Require(rejected, "invalid budget text should be rejected");
|
||||
}
|
||||
Require(RegistrationPreparationAllowed(0, 1), "preparation should be allowed below the budget");
|
||||
Require(RegistrationPreparationAllowed(1023, 1024), "preparation should be allowed immediately below the budget");
|
||||
Require(!RegistrationPreparationAllowed(1024, 1024), "preparation should defer at the budget");
|
||||
Require(!RegistrationPreparationAllowed(1025, 1024), "preparation should defer above the budget");
|
||||
Require(!RegistrationPreparationAllowed(0, 0), "a zero budget should defer every preparation");
|
||||
const auto unlimited = std::numeric_limits<std::uint64_t>::max();
|
||||
Require(RegistrationPreparationAllowed(unlimited - 1, unlimited), "the maximum budget should allow values below it");
|
||||
Require(!RegistrationPreparationAllowed(unlimited, unlimited), "the maximum budget should defer at its limit");
|
||||
std::cout << "registration prepare budget tests passed\n";
|
||||
return 0;
|
||||
} catch (const std::exception& error) {
|
||||
std::cerr << error.what() << '\n';
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
@@ -527,6 +527,62 @@ std::vector<std::byte> packBytes(const std::vector<std::pair<std::vector<std::by
|
||||
return bytes;
|
||||
}
|
||||
|
||||
void verifyPrebuiltPackOwnership(const std::filesystem::path& directory) {
|
||||
using namespace ShaderRecompiler::ShaderDiskCache;
|
||||
SampleRequest sample;
|
||||
const auto key = sample.Key();
|
||||
const auto variant = sampleVariant();
|
||||
const auto path = directory / "ownership.pack";
|
||||
require(WriteFileAtomically(path, packBytes({{key, EncodeEntry(key, variant)}})), "cannot write the ownership test pack");
|
||||
CompiledVariant first, second;
|
||||
PackLoadTimings timings;
|
||||
const std::uint32_t* words = nullptr;
|
||||
{
|
||||
CachePack pack(path);
|
||||
require(pack.Valid(), "the ownership test pack is invalid");
|
||||
require(pack.Load(key, first, timings) == LoadStatus::Loaded, "cannot load the first packed variant");
|
||||
require(pack.Load(key, second, timings) == LoadStatus::Loaded, "cannot load the second packed variant");
|
||||
words = first.artifact.spirv.Words().data();
|
||||
require(!first.artifact.spirv.empty() && words == second.artifact.spirv.Words().data(), "packed SPIR-V was copied instead of sharing its mapping");
|
||||
}
|
||||
requireSameVariant(variant, first, "packed variant outlives its pack");
|
||||
#ifdef _WIN32
|
||||
MEMORY_BASIC_INFORMATION region{};
|
||||
require(VirtualQuery(words, ®ion, sizeof(region)) == sizeof(region) && region.Type == MEM_MAPPED, "packed SPIR-V lost its mapping after pack destruction");
|
||||
#endif
|
||||
auto edited = first.artifact.spirv;
|
||||
edited[0] ^= 1u;
|
||||
require(edited.Words().data() != words && edited.Words()[0] != first.artifact.spirv.Words()[0], "editing packed SPIR-V modified the shared mapping");
|
||||
first = {};
|
||||
requireSameVariant(variant, second, "last packed variant retains its mapping");
|
||||
std::vector<std::byte> published;
|
||||
require(ReadWholeFile(path, published) && published == packBytes({{key, EncodeEntry(key, variant)}}), "editing packed SPIR-V modified the cache file");
|
||||
second = {};
|
||||
#ifdef _WIN32
|
||||
require(VirtualQuery(words, ®ion, sizeof(region)) == sizeof(region) && region.State == MEM_FREE, "the final packed variant did not release its mapping");
|
||||
#endif
|
||||
const auto offset = sizeof(PackHeader) + sizeof(PackRecord);
|
||||
published.insert(published.begin() + offset, std::byte{});
|
||||
PackHeader header;
|
||||
PackRecord record;
|
||||
std::memcpy(&header, published.data(), sizeof(header));
|
||||
std::memcpy(&record, published.data() + sizeof(header), sizeof(record));
|
||||
++header.fileBytes;
|
||||
++record.offset;
|
||||
std::memcpy(published.data() + sizeof(header), &record, sizeof(record));
|
||||
header.indexHash = ShaderRecompiler::HashBytes(std::span<const std::byte>(published).subspan(sizeof(header), sizeof(record)));
|
||||
std::memcpy(published.data(), &header, sizeof(header));
|
||||
require(WriteFileAtomically(path, published), "cannot publish an unaligned packed entry");
|
||||
{
|
||||
CachePack pack(path);
|
||||
require(pack.Valid(), "an unaligned packed entry was rejected");
|
||||
require(pack.Load(key, first, timings) == LoadStatus::Loaded && pack.Load(key, second, timings) == LoadStatus::Loaded, "an unaligned packed entry did not load");
|
||||
require(first.artifact.spirv.Words().data() != second.artifact.spirv.Words().data(), "an unaligned packed module did not use aligned owned storage");
|
||||
}
|
||||
requireSameVariant(variant, first, "unaligned packed variant outlives its pack");
|
||||
requireSameVariant(variant, second, "second unaligned packed variant outlives its pack");
|
||||
}
|
||||
|
||||
void refreshIndexHash(std::vector<std::byte>& pack, std::size_t entries) {
|
||||
using namespace ShaderRecompiler::ShaderDiskCache;
|
||||
const auto index = std::span(pack).subspan(sizeof(PackHeader), entries * sizeof(PackRecord));
|
||||
@@ -781,6 +837,7 @@ void verifyKeySensitivity() {
|
||||
changes("exact robust loads", [](SampleRequest& sample) { sample.request.target.exactRobustLoads = true; });
|
||||
changes("wave LDS memory barriers", [](SampleRequest& sample) { sample.request.target.waveLdsMemoryBarriers = true; });
|
||||
changes("device-scope LDS memory barriers", [](SampleRequest& sample) { sample.request.target.deviceScopeLdsMemoryBarriers = true; });
|
||||
changes("LDS lock fences", [](SampleRequest& sample) { sample.request.target.ldsLockFences = true; });
|
||||
changes("the workgroup size limit", [](SampleRequest& sample) { sample.request.target.maxWorkgroupSize[2] = 128; });
|
||||
changes("the invocation limit", [](SampleRequest& sample) { sample.request.target.maxWorkgroupInvocations = 512; });
|
||||
changes("the shared memory limit", [](SampleRequest& sample) { sample.request.target.maxWorkgroupSharedMemoryBytes = 32768; });
|
||||
@@ -2542,6 +2599,13 @@ int main(int argc, char** argv) {
|
||||
std::cout << "housekeeping version " << directory.filename().string() << '\n';
|
||||
return 0;
|
||||
}
|
||||
if (argc == 2 && std::string_view(argv[1]) == "--prebuilt-pack-ownership") {
|
||||
const auto directory = std::filesystem::temp_directory_path() / ("aps5-pack-ownership-" + std::to_string(std::random_device{}()));
|
||||
std::filesystem::create_directories(directory);
|
||||
verifyPrebuiltPackOwnership(directory);
|
||||
std::filesystem::remove_all(directory);
|
||||
return 0;
|
||||
}
|
||||
if (argc == 2 && std::string_view(argv[1]) == "--resource-plan-codec") {
|
||||
verifyResultRoundTrip();
|
||||
verifyEntryRoundTrip();
|
||||
|
||||
@@ -6216,6 +6216,30 @@ void verifyPixelRequestSerialization() {
|
||||
depthTestingMerge.context.pixel->targetMerge.depthStencilTests = true;
|
||||
RecompileCacheKey::Build(depthTestingMerge, replayKey);
|
||||
require(key != replayKey, "the merge draw's depth or stencil tests did not change the static shader identity");
|
||||
auto blending = request;
|
||||
blending.context.pixel->targetMerge.blend = {true, false, 6u, 7u, 0u, 1u, 0u, 0u, 0xfu, {}};
|
||||
RecompileCacheKey::Build(blending, replayKey);
|
||||
require(key != replayKey && RecompileCacheKey::ContextHash(request) != RecompileCacheKey::ContextHash(blending), "an unclamped color target blend did not change the static shader identity");
|
||||
const auto blendKey = replayKey;
|
||||
for (const auto change : {0, 1, 2, 3, 4, 5, 6, 7, 8}) {
|
||||
auto other = blending;
|
||||
auto& blend = other.context.pixel->targetMerge.blend;
|
||||
if (change == 0) blend.snorm = true;
|
||||
if (change == 1) blend.colorSource = 2u;
|
||||
if (change == 2) blend.colorDestination = 2u;
|
||||
if (change == 3) blend.colorOperation = 1u;
|
||||
if (change == 4) blend.alphaSource = 2u;
|
||||
if (change == 5) blend.alphaDestination = 2u;
|
||||
if (change == 6) blend.alphaOperation = 1u;
|
||||
if (change == 7) blend.writeMask = 0x5u;
|
||||
if (change == 8) blend.constants[2] = 0x3f800000u;
|
||||
RecompileCacheKey::Build(other, replayKey);
|
||||
require(blendKey != replayKey, "a field of the unclamped color target blend did not change the static shader identity");
|
||||
}
|
||||
auto disabled = blending;
|
||||
disabled.context.pixel->targetMerge.blend.enabled = false;
|
||||
RecompileCacheKey::Build(disabled, replayKey);
|
||||
require(key == replayKey && RecompileCacheKey::ContextHash(request) == RecompileCacheKey::ContextHash(disabled), "a disabled color target blend changed the static shader identity");
|
||||
auto withoutMerge = request;
|
||||
withoutMerge.context.pixel->targetMerge = {};
|
||||
RecompileCacheKey::Build(withoutMerge, replayKey);
|
||||
@@ -6229,6 +6253,17 @@ void verifyPixelRequestSerialization() {
|
||||
RecompileCacheKey::Build(withoutStencilRef, replayKey);
|
||||
require(key != replayKey && RecompileCacheKey::ContextHash(request) != RecompileCacheKey::ContextHash(withoutStencilRef), "the stencil reference export did not change the static shader identity");
|
||||
}
|
||||
auto blendedDepth = request;
|
||||
blendedDepth.context.pixel = pixel;
|
||||
blendedDepth.context.pixel->depthExportEnable = true;
|
||||
blendedDepth.context.pixel->depthExportMin = -0.25f;
|
||||
blendedDepth.context.pixel->depthExportMax = 0.75f;
|
||||
blendedDepth.context.pixel->targetMerge.blend = {true, true, 6u, 7u, 1u, 2u, 3u, 4u, 0xau, {0x3f800000u, 0x40000000u, 0x40400000u, 0x40800000u}};
|
||||
const auto blendedReplay = serializer.Deserialize(serializer.Serialize(blendedDepth));
|
||||
require(blendedReplay.request.context.pixel.has_value() && fields(*blendedReplay.request.context.pixel) == fields(*blendedDepth.context.pixel), "a pixel request with a target blend and depth export bounds lost pixel fields in serialization");
|
||||
require(blendedReplay.request.context.pixel->targetMerge.blend == blendedDepth.context.pixel->targetMerge.blend, "the target blend did not round-trip beside the depth export bounds");
|
||||
require(blendedReplay.request.context.pixel->depthExportMin == -0.25f && blendedReplay.request.context.pixel->depthExportMax == 0.75f, "the depth export bounds did not round-trip beside the target blend");
|
||||
require(blendedReplay.request.context.vertex.has_value() && blendedReplay.request.context.vertex->fetchAttribReg == 17u && blendedReplay.request.context.memory.size() == 1u && blendedReplay.request.context.memory[0].guestAddress == 0x60000u, "a target blend with depth export bounds displaced the following guest context");
|
||||
request.context.pixel.reset();
|
||||
request.shader.stage = ShaderStage::Vertex;
|
||||
const auto withoutPixel = serializer.Deserialize(serializer.Serialize(request));
|
||||
@@ -6646,6 +6681,15 @@ void verifyVertexInfoVersion19() {
|
||||
const auto mergingBytes = decodeBase64(serializer.Serialize(merging));
|
||||
require(mergingBytes.size() == plainPixel.size() && std::equal(plainPixel.begin(), plainPixel.begin() + mergeOffset, mergingBytes.begin()) && mergingBytes[mergeOffset] == 3u && mergingBytes[mergeOffset + 1] == 0x0fu && mergingBytes[mergeOffset + 2] == 0xf0u && mergingBytes[mergeOffset + 5] == 2u && mergingBytes[mergeOffset + 6] == 1u && mergingBytes[mergeOffset + 34] == 0xefu && mergingBytes[mergeOffset + 37] == 0x89u && mergingBytes[mergeOffset + 38] == 1u && mergingBytes[mergeOffset + 39] == 1u && std::equal(plainPixel.begin() + mergeOffset + static_cast<std::ptrdiff_t>(mergeBytes), plainPixel.end(), mergingBytes.begin() + mergeOffset + static_cast<std::ptrdiff_t>(mergeBytes)), "the color target merge is not the 40 bytes the version 46 pixel info adds after the sample order");
|
||||
require(serializer.Deserialize(serializer.Serialize(merging)).request.context.pixel->targetMerge == merging.context.pixel->targetMerge, "a serialized request lost its color target merge");
|
||||
auto blendMerging = pixel;
|
||||
blendMerging.context.pixel->targetMerge = {1u, 0xffffu, 1u, {1u, 2u, 3u, 4u, 5u, 6u, 7u, 8u}, true, false, {true, true, 6u, 7u, 1u, 1u, 0u, 4u, 0xbu, {0x3fc00000u, 0xbe800000u, 0x3f000000u, 0x40000000u}}};
|
||||
const auto blendMergingBytes = decodeBase64(serializer.Serialize(blendMerging));
|
||||
constexpr std::size_t blendPayloadBytes = 24u;
|
||||
require(blendMergingBytes.size() == plainPixel.size() + blendPayloadBytes && std::equal(plainPixel.begin(), plainPixel.begin() + mergeOffset, blendMergingBytes.begin()) && blendMergingBytes[mergeOffset] == 1u && blendMergingBytes[mergeOffset + 1] == 0xffu && blendMergingBytes[mergeOffset + 2] == 0xffu && blendMergingBytes[mergeOffset + 3] == 0x01u && blendMergingBytes[mergeOffset + 4] == 0x00u, "a color target blend is not flagged in the merge mask word, or changed the bytes before the merge");
|
||||
require(serializer.Deserialize(serializer.Serialize(blendMerging)).request.context.pixel->targetMerge == blendMerging.context.pixel->targetMerge, "a serialized request lost its color target blend");
|
||||
auto disabledBlend = merging;
|
||||
disabledBlend.context.pixel->targetMerge.blend = {false, true, 6u, 7u, 1u, 1u, 0u, 4u, 0xbu, {1u, 2u, 3u, 4u}};
|
||||
require(serializer.Serialize(disabledBlend) == serializer.Serialize(merging), "a disabled color target blend changed the serialized request");
|
||||
// A version 43 request: no color target merge, and no fused arithmetic flag, pixel function LDS flag, storage size or barycentric built-ins flag at the end.
|
||||
const auto version43Bytes = [&](std::vector<std::uint8_t> bytes) {
|
||||
require(bytes.end() - bytes.begin() > mergeOffset + static_cast<std::ptrdiff_t>(mergeBytes) && std::equal(plainPixel.begin() + mergeOffset, plainPixel.begin() + mergeOffset + static_cast<std::ptrdiff_t>(mergeBytes), bytes.begin() + mergeOffset), "a replay fixture does not hold the default color target merge after the sample order");
|
||||
|
||||
@@ -49,6 +49,32 @@ int main(int argc, char** argv) try {
|
||||
file << RequestSerializer{}.Serialize(request);
|
||||
if (!file) throw std::runtime_error("cannot write synthetic replay request");
|
||||
}
|
||||
const std::array<std::uint32_t, 19> ldsCode{
|
||||
0x34040082u, 0x4a020081u, 0xd8340000u, 0x00000102u, 0xbf8cc07fu, 0xbf8a0000u, 0x7da800ffu, 0x00000080u,
|
||||
0xbf880006u, 0xd8d80200u, 0x03000002u, 0xbf8cc07fu, 0x4a020701u, 0xd8340000u, 0x00000102u, 0xbefe03c1u,
|
||||
0xbf8cc07fu, 0xbf8a0000u, 0xbf810000u,
|
||||
};
|
||||
const std::array<std::uint32_t, 2> ldsCapabilities{spv::CapabilityShader, spv::CapabilityGroupNonUniform};
|
||||
const std::array<std::string_view, 1> ldsExtensions{"SPV_KHR_storage_buffer_storage_class"};
|
||||
RecompileRequest lds{};
|
||||
lds.shader = {ShaderStage::Compute, 0x20000u, ldsCode, 0, {}};
|
||||
lds.context.waveSize = 32u;
|
||||
lds.context.compute = ShaderComputeStageInfo{{256u, 1u, 1u}, 512u, {false, false, false}, false, 1u};
|
||||
lds.target.vulkanVersion = 0x00403000u;
|
||||
lds.target.spirvVersion = 0x00010600u;
|
||||
lds.target.subgroupSize = 32u;
|
||||
lds.target.bdaAbiVersion = 1u;
|
||||
lds.target.supportedCapabilities = ldsCapabilities;
|
||||
lds.target.supportedExtensions = ldsExtensions;
|
||||
lds.target.maxWorkgroupSize = {1024u, 1024u, 64u};
|
||||
lds.target.maxWorkgroupInvocations = 1024u;
|
||||
lds.target.maxWorkgroupSharedMemoryBytes = 49152u;
|
||||
lds.layout = {0, 0, 0, 128};
|
||||
{
|
||||
std::ofstream file(directory / "lds.req", std::ios::binary);
|
||||
file << RequestSerializer{}.Serialize(lds);
|
||||
if (!file) throw std::runtime_error("cannot write synthetic replay request");
|
||||
}
|
||||
std::puts("synthetic guarded replay requests written");
|
||||
return 0;
|
||||
} catch (const std::exception& error) {
|
||||
|
||||
@@ -28,3 +28,17 @@ execute_process(COMMAND "${TOOL}" --maintenance8 --materialize "${CAPTURE}/inact
|
||||
if(NOT code STREQUAL "0" OR NOT output MATCHES "materialized: [0-9]+ SPIR-V words")
|
||||
message(FATAL_ERROR "prepared replay with maintenance8 failed: ${code}\n${output}${errors}")
|
||||
endif()
|
||||
|
||||
foreach(mode IN ITEMS --prepare --materialize)
|
||||
execute_process(COMMAND "${TOOL}" ${mode} "${CAPTURE}/lds.req" RESULT_VARIABLE code OUTPUT_VARIABLE baseline ERROR_VARIABLE errors)
|
||||
if(NOT code STREQUAL "0" OR NOT baseline MATCHES "prepared: [0-9]+ SPIR-V words")
|
||||
message(FATAL_ERROR "${mode} of the LDS request failed: ${code}\n${baseline}${errors}")
|
||||
endif()
|
||||
execute_process(COMMAND "${TOOL}" ${mode} --wave-lds-memory-barriers "${CAPTURE}/lds.req" RESULT_VARIABLE code OUTPUT_VARIABLE overridden ERROR_VARIABLE errors)
|
||||
if(NOT code STREQUAL "0" OR NOT overridden MATCHES "prepared: [0-9]+ SPIR-V words")
|
||||
message(FATAL_ERROR "${mode} --wave-lds-memory-barriers of the LDS request failed: ${code}\n${overridden}${errors}")
|
||||
endif()
|
||||
if(baseline STREQUAL overridden)
|
||||
message(FATAL_ERROR "${mode} ignored --wave-lds-memory-barriers\n${baseline}")
|
||||
endif()
|
||||
endforeach()
|
||||
@@ -24,7 +24,19 @@ constexpr std::uint32_t DsOperand32 = 0x00000401u;
|
||||
constexpr std::uint32_t FlatAtomicAddU32 = 0xdcc90000u;
|
||||
constexpr std::uint32_t FlatAtomicOperands = 0x0a7d0402u;
|
||||
|
||||
struct LockFence {
|
||||
std::uint32_t scope = 0u;
|
||||
std::uint32_t semantics = 0u;
|
||||
std::size_t accessesBefore = 0;
|
||||
};
|
||||
|
||||
struct LockRegion {
|
||||
std::vector<LockFence> fences;
|
||||
std::size_t accesses = 0;
|
||||
};
|
||||
|
||||
struct Usage {
|
||||
std::vector<LockRegion> regions;
|
||||
std::size_t elects = 0;
|
||||
std::size_t exchanges = 0;
|
||||
std::size_t releases = 0;
|
||||
@@ -40,7 +52,7 @@ void Require(bool condition, const std::string& message) {
|
||||
if (!condition) throw std::runtime_error(message);
|
||||
}
|
||||
|
||||
std::vector<std::uint32_t> RecompileProgram(std::span<const std::uint32_t> code) {
|
||||
std::vector<std::uint32_t> RecompileProgram(std::span<const std::uint32_t> code, bool ldsLockFences) {
|
||||
const std::array<std::uint32_t, 7> capabilities{spv::CapabilityShader, spv::CapabilityGroupNonUniform, spv::CapabilityGroupNonUniformBallot, spv::CapabilityGroupNonUniformShuffle, spv::CapabilityInt64, spv::CapabilityPhysicalStorageBufferAddresses, spv::CapabilityStorageBuffer8BitAccess};
|
||||
const std::array<std::uint32_t, 4> userData{};
|
||||
const std::array<std::string_view, 2> extensions{"SPV_KHR_physical_storage_buffer", "SPV_KHR_8bit_storage"};
|
||||
@@ -59,6 +71,7 @@ std::vector<std::uint32_t> RecompileProgram(std::span<const std::uint32_t> code)
|
||||
request.target.maxWorkgroupSize = {1024u, 1024u, 64u};
|
||||
request.target.maxWorkgroupInvocations = 1024;
|
||||
request.target.maxWorkgroupSharedMemoryBytes = 49152;
|
||||
request.target.ldsLockFences = ldsLockFences;
|
||||
request.layout = {0, 0, 0, 128};
|
||||
request.useCache = false;
|
||||
auto result = Recompile(request);
|
||||
@@ -101,8 +114,10 @@ Usage Scan(std::span<const std::uint32_t> words) {
|
||||
if (op == spv::OpBranchConditional && count >= 4u && words[cursor + 1u] == laneZeroCondition) laneZeroBody = words[cursor + 2u];
|
||||
if (op == spv::OpConstant && count == 4) constants[words[cursor + 2]] = words[cursor + 3];
|
||||
if (op == spv::OpGroupNonUniformElect) ++usage.elects;
|
||||
if (locked && (op == spv::OpLoad || op == spv::OpStore || op == spv::OpAtomicIAdd || op == spv::OpAtomicCompareExchange)) ++usage.regions.back().accesses;
|
||||
if (op == spv::OpAtomicCompareExchange) {
|
||||
++usage.exchanges;
|
||||
if (!locked) usage.regions.emplace_back();
|
||||
locked = true;
|
||||
if (count >= 4u) lockPointer = words[cursor + 3u];
|
||||
}
|
||||
@@ -116,7 +131,13 @@ Usage Scan(std::span<const std::uint32_t> words) {
|
||||
++usage.storeReleases;
|
||||
locked = false;
|
||||
}
|
||||
if (op == spv::OpMemoryBarrier && locked) usage.fenceBetweenLock = true;
|
||||
if (op == spv::OpMemoryBarrier && locked) {
|
||||
usage.fenceBetweenLock = true;
|
||||
const auto scope = constants.find(words[cursor + 1]);
|
||||
const auto semantics = constants.find(words[cursor + 2]);
|
||||
Require(scope != constants.end() && semantics != constants.end(), "a memory barrier inside the workgroup lock has a non-constant scope or semantics");
|
||||
usage.regions.back().fences.push_back({scope->second, semantics->second, usage.regions.back().accesses});
|
||||
}
|
||||
if (op == spv::OpAtomicIAdd) {
|
||||
++usage.adds;
|
||||
if (locked) usage.addBetweenLock = true;
|
||||
@@ -156,11 +177,11 @@ Usage Scan(std::span<const std::uint32_t> words) {
|
||||
return usage;
|
||||
}
|
||||
|
||||
Usage Compile(std::initializer_list<std::uint32_t> body) {
|
||||
Usage Compile(std::initializer_list<std::uint32_t> body, bool ldsLockFences = false) {
|
||||
std::vector<std::uint32_t> code{0x7e020280u, 0x7e0402c1u, 0x7e060280u, 0x7e080281u};
|
||||
code.insert(code.end(), body);
|
||||
code.insert(code.end(), {0xbf8cc07fu, 0xbf810000u});
|
||||
return Scan(RecompileProgram(code));
|
||||
return Scan(RecompileProgram(code, ldsLockFences));
|
||||
}
|
||||
|
||||
void Check64BitOnlyLocks() {
|
||||
@@ -190,6 +211,28 @@ void CheckFlatAtomicTakesLockWith64Bit() {
|
||||
Require(!usage.fenceBetweenLock, "a 32-bit flat atomic into the LDS aperture emits a memory barrier while it holds the workgroup lock");
|
||||
}
|
||||
|
||||
void RequireFencedRegions(const Usage& usage, std::size_t expected, const std::string& name) {
|
||||
Require(usage.regions.size() == expected, name + " with LDS lock fences took the workgroup lock " + std::to_string(usage.regions.size()) + " times, expected " + std::to_string(expected));
|
||||
for (const auto& region : usage.regions) {
|
||||
Require(region.fences.size() == 2, name + " with LDS lock fences emitted " + std::to_string(region.fences.size()) + " memory barriers inside the workgroup lock, expected 2");
|
||||
const auto& acquire = region.fences.front();
|
||||
const auto& release = region.fences.back();
|
||||
Require(acquire.scope == spv::ScopeWorkgroup && release.scope == spv::ScopeWorkgroup, name + " with LDS lock fences emitted a lock fence that is not workgroup scope");
|
||||
Require((acquire.semantics & spv::MemorySemanticsAcquireMask) != 0 && (acquire.semantics & spv::MemorySemanticsWorkgroupMemoryMask) != 0, name + " with LDS lock fences does not start its critical section with an acquire fence on workgroup memory");
|
||||
Require((release.semantics & spv::MemorySemanticsReleaseMask) != 0 && (release.semantics & spv::MemorySemanticsWorkgroupMemoryMask) != 0, name + " with LDS lock fences does not end its critical section with a release fence on workgroup memory");
|
||||
Require(region.accesses != 0 && acquire.accessesBefore == 0 && release.accessesBefore == region.accesses, name + " with LDS lock fences accesses LDS outside the fences inside the workgroup lock");
|
||||
}
|
||||
}
|
||||
|
||||
void CheckLockFences() {
|
||||
RequireFencedRegions(Compile({DsAddU64, DsOperands}, true), 1, "ds_add_u64");
|
||||
const auto mixed = Compile({DsAddU64, DsOperands, DsAddU32Hi, DsOperand32}, true);
|
||||
RequireFencedRegions(mixed, 2, "ds_add_u32 with ds_add_u64");
|
||||
Require(mixed.adds == 1 && mixed.addBetweenLock, "with LDS lock fences, the 32-bit OpAtomicIAdd is not between the lock acquire and the lock release");
|
||||
const auto unfenced = Compile({DsAddU32Hi, DsOperand32}, true);
|
||||
Require(unfenced.regions.empty() && !unfenced.fenceBetweenLock, "with LDS lock fences, a program with only ds_add_u32 got a workgroup lock");
|
||||
}
|
||||
|
||||
void CheckFlatAtomicOnlyIsUnchanged() {
|
||||
const auto usage = Compile({FlatAtomicAddU32, FlatAtomicOperands});
|
||||
Require(usage.elects == 0, "a program with only a 32-bit flat atomic got a workgroup lock: elect " + std::to_string(usage.elects));
|
||||
@@ -212,6 +255,7 @@ int main() {
|
||||
CheckFlatAtomicTakesLockWith64Bit();
|
||||
CheckFlatAtomicOnlyIsUnchanged();
|
||||
Check32BitOnlyIsUnchanged();
|
||||
CheckLockFences();
|
||||
} catch (const std::exception& error) {
|
||||
std::fprintf(stderr, "SpirvLdsAtomicLock: %s\n", error.what());
|
||||
return 1;
|
||||
|
||||
@@ -384,7 +384,7 @@ std::optional<std::pair<std::uint32_t, std::uint32_t>> storedLaneFunction(const
|
||||
bool function = false;
|
||||
for (std::size_t offset = 5; offset < words.size(); offset += words[offset] >> spv::WordCountShift) {
|
||||
const auto opcode = static_cast<spv::Op>(words[offset] & spv::OpCodeMask);
|
||||
const auto* operands = &words[offset + 1];
|
||||
const auto* operands = words.data() + offset + 1;
|
||||
if (opcode == spv::OpFunction) function = true;
|
||||
if (opcode == spv::OpConstant) values[operands[1]] = {0u, operands[2]};
|
||||
if (opcode == spv::OpVariable && operands[2] == spv::StorageClassInput) inputs.insert(operands[1]);
|
||||
|
||||
@@ -144,11 +144,18 @@ void verifyEmittedBarriers() {
|
||||
require(single.subgroupControl == 0 && single.subgroupMemory == 0, "with wave LDS memory barriers, a single-wave workgroup did not keep workgroup-scope barriers");
|
||||
}
|
||||
|
||||
void verifyLdsLockFenceDrivers() {
|
||||
for (const auto& item : Cases) {
|
||||
require(AgcDriver::LdsLockFencesRequired(item.driver) == (item.driver == VK_DRIVER_ID_MOLTENVK), "driver " + std::to_string(static_cast<int>(item.driver)) + ": expected LDS lock fences only on MoltenVK");
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
int main() {
|
||||
try {
|
||||
verifyDriverQuirk();
|
||||
verifyLdsLockFenceDrivers();
|
||||
verifyEmittedBarriers();
|
||||
verifyLdsMemoryBarrierScope();
|
||||
std::puts("subgroup barrier tests passed");
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
#include "prx/libkernel/include/Api.hpp"
|
||||
#include "prx/libSceAgcDriver/Execution/include/Driver.hpp"
|
||||
#include "prx/libSceAgcDriver/Execution/include/Driver/Driver.hpp"
|
||||
#include "execution/VulkanTestDevice.hpp"
|
||||
#include "prx/libSceAgcDriver/Execution/include/QueueState.hpp"
|
||||
#include "prx/libSceAgcDriver/Execution/include/Driver/Draw/DrawCache.hpp"
|
||||
@@ -115,6 +116,14 @@ void testValidation() {
|
||||
AgcDriverWaitIdle_nid_postfix();
|
||||
}
|
||||
|
||||
void testThreadDimensionGroups() {
|
||||
using AgcDriver::DriverDetail::ThreadDimensionGroups;
|
||||
check(ThreadDimensionGroups(0, 64) == 0, "no threads need no groups");
|
||||
check(ThreadDimensionGroups(64, 64) == 1 && ThreadDimensionGroups(65, 64) == 2, "a partial group still counts");
|
||||
check(ThreadDimensionGroups(0xffffffffu, 1) == 0xffffffffu, "one thread per group keeps the thread count");
|
||||
check(ThreadDimensionGroups(0xffffffffu, 64) == 0x4000000u, "a thread count near 2^32 wrapped before the division");
|
||||
}
|
||||
|
||||
void testReadOnlyResummarize() {
|
||||
std::vector<std::uint32_t> commands;
|
||||
for (const auto [offset, value] : {std::pair{0x000u, 0x10u}, {0x200u, 0x007007f3u}, {0x010u, 0xa0000183u}, {0x011u, 0x20000180u}, {0x8eu, 0xffffffffu}, {0x8fu, 0u}, {0x1c4u, 0u}, {0x203u, 0u}}) {
|
||||
@@ -1055,6 +1064,7 @@ int main(int argc, char** argv) {
|
||||
testRegisteredFastLaunchWorkgroupVertex();
|
||||
testEvents();
|
||||
testValidation();
|
||||
testThreadDimensionGroups();
|
||||
testClearState();
|
||||
testSubmissions();
|
||||
testEndOfPipeInterrupts();
|
||||
|
||||
@@ -30,6 +30,7 @@ struct Push {
|
||||
std::uint32_t columnBegin;
|
||||
std::uint32_t rowBegin;
|
||||
std::uint32_t pipeBankXor;
|
||||
std::uint32_t splitStride;
|
||||
};
|
||||
|
||||
Push decodePush(const std::vector<std::byte>& bytes) {
|
||||
|
||||
@@ -140,9 +140,144 @@ void requireSliceAddresses(const GuestTextureResource& resource, std::uint32_t b
|
||||
}
|
||||
}
|
||||
|
||||
std::uint64_t referenceGcnAddress(TextureTileMode mode, std::uint32_t bytes, std::uint32_t pitch, std::uint32_t height, std::uint32_t x, std::uint32_t y) {
|
||||
const auto bit = [](std::uint32_t value, std::uint32_t index) { return (value >> index) & 1u; };
|
||||
const std::uint32_t x0 = bit(x, 0), x1 = bit(x, 1), x2 = bit(x, 2), y0 = bit(y, 0), y1 = bit(y, 1), y2 = bit(y, 2);
|
||||
std::array<std::uint32_t, 6> pixel{x0, y0, x1, y1, x2, y2};
|
||||
if (mode == TextureTileMode::kGcnDisplay1D || mode == TextureTileMode::kGcnDisplay2D || mode == TextureTileMode::kGcnDisplayPrt || mode == TextureTileMode::kGcnDisplay2DPrt) {
|
||||
switch (bytes) {
|
||||
case 1u: pixel = {x0, x1, x2, y1, y0, y2}; break;
|
||||
case 2u: pixel = {x0, x1, x2, y0, y1, y2}; break;
|
||||
case 4u: pixel = {x0, x1, y0, x2, y1, y2}; break;
|
||||
case 8u: pixel = {x0, y0, x1, x2, y1, y2}; break;
|
||||
default: pixel = {x0, y0, x1, y1, x2, y2}; break;
|
||||
}
|
||||
}
|
||||
std::uint32_t pixelIndex = 0;
|
||||
for (std::uint32_t index = 0; index < 6u; ++index) pixelIndex |= pixel[index] << index;
|
||||
std::uint64_t microBytes = 64u * bytes;
|
||||
std::uint64_t elementOffset = static_cast<std::uint64_t>(pixelIndex) * bytes;
|
||||
if (mode == TextureTileMode::kGcnThin1D || mode == TextureTileMode::kGcnDisplay1D) {
|
||||
return (static_cast<std::uint64_t>(y / 8u) * (pitch / 8u) + x / 8u) * microBytes + elementOffset;
|
||||
}
|
||||
std::uint32_t tileSplit = std::min(1024u, std::max(256u, 2u * static_cast<std::uint32_t>(microBytes)));
|
||||
if (mode >= TextureTileMode::kGcnDepth2D64 && mode <= TextureTileMode::kGcnDepth2D1K) tileSplit = 64u << (static_cast<std::uint32_t>(mode) - static_cast<std::uint32_t>(TextureTileMode::kGcnDepth2D64));
|
||||
if (mode == TextureTileMode::kGcnDepthPrt256) tileSplit = 256u;
|
||||
if (mode == TextureTileMode::kGcnDepthPrt1K) tileSplit = 1024u;
|
||||
const bool prt = IsGcnPrtTiled(mode);
|
||||
const auto macroMode = std::bit_width(std::min<std::uint64_t>(tileSplit, microBytes) / 64u) - 1u + (prt ? 8u : 0u);
|
||||
std::uint64_t splitSlice = 0;
|
||||
if (microBytes > tileSplit) {
|
||||
splitSlice = elementOffset / tileSplit;
|
||||
elementOffset %= tileSplit;
|
||||
microBytes = tileSplit;
|
||||
}
|
||||
constexpr std::uint32_t bankHeights[] = {4u, 2u, 1u, 1u, 1u, 0u, 0u, 0u, 8u, 4u, 2u, 1u, 1u}, bankCounts[] = {16u, 16u, 16u, 16u, 8u, 0u, 0u, 0u, 16u, 16u, 16u, 16u, 8u}, aspects[] = {4u, 2u, 2u, 2u, 1u, 0u, 0u, 0u, 4u, 4u, 2u, 2u, 1u};
|
||||
const std::uint32_t pipes = 8u, bankWidth = 1u, bankHeight = bankHeights[macroMode], banks = bankCounts[macroMode], aspect = aspects[macroMode];
|
||||
const std::uint32_t macroPitch = 8u * bankWidth * pipes * aspect;
|
||||
const std::uint32_t macroHeight = 8u * bankHeight * banks / aspect;
|
||||
const std::uint64_t macroBytes = microBytes * (macroPitch / 8u) * (macroHeight / 8u) / (pipes * banks);
|
||||
const std::uint64_t macroOffset = (static_cast<std::uint64_t>(y / macroHeight) * (pitch / macroPitch) + x / macroPitch) * macroBytes;
|
||||
const std::uint32_t tileIndex = ((y / 8u) % bankHeight) * bankWidth + ((x / 8u) / pipes) % bankWidth;
|
||||
const std::uint64_t sliceBytes = static_cast<std::uint64_t>(pitch / macroPitch) * (height / macroHeight) * macroBytes;
|
||||
const std::uint64_t total = splitSlice * sliceBytes + macroOffset + elementOffset + static_cast<std::uint64_t>(tileIndex) * microBytes;
|
||||
const std::uint32_t px = prt ? x % macroPitch : x, py = prt ? y % macroHeight : y;
|
||||
const std::uint32_t tx = px / 8u, ty = py / 8u;
|
||||
const bool pipe8x16 = mode == TextureTileMode::kGcnDisplayPrt || mode == TextureTileMode::kGcnThinPrt;
|
||||
const std::uint32_t pipe = pipe8x16 ? (bit(tx, 1) ^ bit(ty, 0) ^ bit(tx, 2)) | ((bit(tx, 0) ^ bit(ty, 1)) << 1u) | ((bit(tx, 2) ^ bit(ty, 2)) << 2u)
|
||||
: (bit(tx, 0) ^ bit(ty, 0) ^ bit(tx, 1)) | ((bit(tx, 1) ^ bit(ty, 1)) << 1u) | ((bit(tx, 2) ^ bit(ty, 2)) << 2u);
|
||||
const std::uint32_t bx = px / 8u / (bankWidth * pipes), by = py / 8u / bankHeight;
|
||||
std::uint32_t bank = 0;
|
||||
if (banks == 16u) bank = (bit(bx, 0) ^ bit(by, 3)) | ((bit(bx, 1) ^ bit(by, 2) ^ bit(by, 3)) << 1u) | ((bit(bx, 2) ^ bit(by, 1)) << 2u) | ((bit(bx, 3) ^ bit(by, 0)) << 3u);
|
||||
else bank = (bit(bx, 0) ^ bit(by, 2)) | ((bit(bx, 1) ^ bit(by, 1) ^ bit(by, 2)) << 1u) | ((bit(bx, 2) ^ bit(by, 0)) << 2u);
|
||||
if (!pipe8x16) bank = (bank ^ static_cast<std::uint32_t>((banks / 2u + 1u) * splitSlice)) & (banks - 1u);
|
||||
const std::uint32_t bankBits = static_cast<std::uint32_t>(std::countr_zero(banks));
|
||||
return ((total >> 8u) << (8u + 3u + bankBits)) | (static_cast<std::uint64_t>(bank) << 11u) | (static_cast<std::uint64_t>(pipe) << 8u) | (total & 0xffu);
|
||||
}
|
||||
|
||||
void gcnTilingTests() {
|
||||
using enum TextureTileMode;
|
||||
for (const auto mode : {kGcnThin1D, kGcnDisplay1D, kGcnDisplay2D, kGcnThin2D, kGcnDepth2D64, kGcnDepth2D128, kGcnDepth2D256, kGcnDepth2D512, kGcnDepth2D1K, kGcnDepthPrt256, kGcnDepthPrt1K, kGcnDisplayPrt, kGcnDisplay2DPrt, kGcnThinPrt, kGcnThin2DPrt}) {
|
||||
for (std::uint32_t bytes = 1u; bytes <= 16u; bytes <<= 1u) {
|
||||
const auto geometry = GcnTiling(mode, bytes);
|
||||
const auto what = "PS4 tile mode " + std::to_string(static_cast<int>(mode)) + " at " + std::to_string(bytes) + " bytes";
|
||||
Require(geometry.blockBytes * geometry.splitSlices == geometry.blockWidth * geometry.blockHeight * bytes, what + ": a block holds its elements exactly");
|
||||
const auto splitStride = 16u * geometry.blockBytes;
|
||||
const auto pitch = geometry.blockWidth * 4u;
|
||||
const auto height = geometry.blockHeight * 4u;
|
||||
std::vector<std::uint8_t> seen(static_cast<std::size_t>(pitch) * height, 0u);
|
||||
for (std::uint32_t y = 0; y < height; ++y) {
|
||||
for (std::uint32_t x = 0; x < pitch; ++x) {
|
||||
std::uint32_t inBlock = 0;
|
||||
for (std::uint32_t bit = 0; bit < 16u; ++bit) inBlock |= static_cast<std::uint32_t>(std::popcount((x & geometry.equation[bit] & 0xfffu) ^ ((y << 12u) & geometry.equation[bit] & 0xfff000u)) & 1) << bit;
|
||||
const auto block = static_cast<std::uint64_t>(y / geometry.blockHeight) * (pitch / geometry.blockWidth) + x / geometry.blockWidth;
|
||||
std::uint32_t split = 0;
|
||||
for (std::uint32_t bit = 0; bit < 4u; ++bit) split |= static_cast<std::uint32_t>(std::popcount((x & geometry.splitMasks[bit] & 0xfffu) ^ ((y << 12u) & geometry.splitMasks[bit] & 0xfff000u)) & 1) << bit;
|
||||
const auto address = block * geometry.blockBytes + inBlock + static_cast<std::uint64_t>(split) * splitStride;
|
||||
if (address != referenceGcnAddress(mode, bytes, pitch, height, x, y)) Require(false, what + ": element " + std::to_string(x) + "," + std::to_string(y) + " is at " + std::to_string(address) + ", addrlib places it at " + std::to_string(referenceGcnAddress(mode, bytes, pitch, height, x, y)));
|
||||
Require(address % bytes == 0 && address / bytes < seen.size() && seen[address / bytes]++ == 0, what + ": two elements share an address or one leaves the surface");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
constexpr std::array<std::pair<std::uint32_t, std::uint32_t>, 5> display2DPrt{{{256u, 256u}, {256u, 128u}, {128u, 128u}, {128u, 64u}, {64u, 64u}}};
|
||||
for (std::uint32_t log2 = 0; log2 < 5u; ++log2) {
|
||||
const auto geometry = GcnTiling(TextureTileMode::kGcnDisplay2DPrt, 1u << log2);
|
||||
Require(geometry.blockWidth == display2DPrt[log2].first && geometry.blockHeight == display2DPrt[log2].second, "PS4 Display2DThinPrt macro tile extent changed");
|
||||
}
|
||||
{
|
||||
Require(ComputeGcnMipLayout(TextureTileMode::kLinear, 20u, 100u, 3u, 100u, false, 1u, true)[0].pitchBytes == 400u, "PS4 linear general pitch changed");
|
||||
reject([] { ComputeGcnMipLayout(TextureTileMode::kLinear, 20u, 100u, 3u, 100u, false, 1u); }, "is not padded the way its tile mode pads a row");
|
||||
}
|
||||
constexpr std::array<std::pair<std::uint32_t, std::uint32_t>, 5> display2D{{{256u, 128u}, {128u, 128u}, {128u, 64u}, {128u, 64u}, {64u, 64u}}};
|
||||
for (std::uint32_t log2 = 0; log2 < 5u; ++log2) {
|
||||
const auto geometry = GcnTiling(TextureTileMode::kGcnDisplay2D, 1u << log2);
|
||||
Require(geometry.blockWidth == display2D[log2].first && geometry.blockHeight == display2D[log2].second, "PS4 Display2DThin macro tile extent changed");
|
||||
}
|
||||
{
|
||||
GuestTextureResource array{};
|
||||
array.baseAddress = 0x10000;
|
||||
array.width = 16u;
|
||||
array.height = 16u;
|
||||
array.depthOrLastArray = 2u;
|
||||
array.mipCount = 3u;
|
||||
array.lastLevel = 2u;
|
||||
array.tileMode = TextureTileMode::kGcnThin1D;
|
||||
array.dimension = TextureDimension::k2DArray;
|
||||
array.format = 20u;
|
||||
array.gcnPitch = 16u;
|
||||
const auto geometry = DescribeSurface(array);
|
||||
Require(geometry.levelMajor && geometry.layers == 3u && geometry.guestBytes == 4608u, "PS4 layered mip chain size changed");
|
||||
Require(geometry.mips[1].tiledOffset == 3072u && geometry.mips[2].tiledOffset == 3840u && geometry.mips[1].tiledSize == 256u, "PS4 levels do not follow every slice of the level before");
|
||||
Require(geometry.GuestOffset(2u, geometry.mips[1]) == 3584u && geometry.GuestOffset(1u, geometry.mips[0]) == 1024u, "PS4 slice of a level is misplaced");
|
||||
Require(geometry.mips[1].linearOffset == 1024u && geometry.mips[2].linearOffset == 1280u, "PS4 linear staging is not per slice");
|
||||
array.mipCount = 1u;
|
||||
array.lastLevel = 0u;
|
||||
Require(!DescribeSurface(array).levelMajor, "a single-level PS4 array is slice-major");
|
||||
}
|
||||
{
|
||||
const auto mips = ComputeGcnMipLayout(TextureTileMode::kGcnDepth2D64, 20u, 2048u, 1152u, 2048u, false, 1u);
|
||||
Require(mips[0].tiledSize == 2048u * 1152u * 4u && mips[0].gcnSplitStride == 2048u * 1152u, "PS4 tile-split depth layout changed");
|
||||
Require(GcnTiling(TextureTileMode::kGcnDepth2D64, 4u).splitSlices == 4u && GcnTiling(TextureTileMode::kGcnDepth2D256, 4u).splitSlices == 1u, "PS4 depth split slice count changed");
|
||||
}
|
||||
{
|
||||
const auto mips = ComputeGcnMipLayout(TextureTileMode::kGcnThin1D, 14u, 212u, 35u, 224u, false, 1u);
|
||||
Require(mips[0].tiledSize == 224u * 40u * 2u && mips[0].blocksPerRow == 28u && mips[0].pitchBytes == 448u && !mips[0].gcnMicroTiled, "PS4 1D thin texture layout changed");
|
||||
reject([] { ComputeGcnMipLayout(TextureTileMode::kGcnThin1D, 14u, 212u, 35u, 216u, false, 1u); }, "is not padded the way its tile mode pads a row");
|
||||
}
|
||||
{
|
||||
const auto mips = ComputeGcnMipLayout(TextureTileMode::kGcnDisplay2D, 56u, 256u, 256u, 256u, false, 4u);
|
||||
Require(!mips[0].gcnMicroTiled && !mips[1].gcnMicroTiled && mips[2].gcnMicroTiled && mips[3].gcnMicroTiled, "PS4 2D tiled mips switch to 1D tiling below one macro tile");
|
||||
Require(mips[0].tiledOffset == 0u && mips[1].tiledOffset == 256u * 256u * 4u && mips[1].blocksPerRow == 1u, "PS4 mips follow level 0 in order");
|
||||
Require(mips[2].tiledOffset == mips[1].tiledOffset + 128u * 128u * 4u && mips[2].blocksPerRow == 8u, "PS4 1D tiled mip after the 2D levels");
|
||||
Require(MipTileMode(TextureTileMode::kGcnDisplay2D, mips[2]) == TextureTileMode::kGcnDisplay1D, "a 1D tiled level of a 2D surface uses the 1D display mode");
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
void RunTextureTilingTests() {
|
||||
gcnTilingTests();
|
||||
{
|
||||
const auto mips = ComputeMipLayout(TextureTileMode::kLinear, 1, 4, 4, 2);
|
||||
Require(mips.size() == 2, "linear mip chain must contain the requested mip count");
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
#include "prx/libSceAgcDriver/Execution/include/WorkerSampler.hpp"
|
||||
#include <chrono>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <filesystem>
|
||||
#include <fstream>
|
||||
#include <string>
|
||||
#include <thread>
|
||||
#include <windows.h>
|
||||
|
||||
int main(int argc, char** argv) {
|
||||
if (argc != 2) return 1;
|
||||
const std::string mode = argv[1];
|
||||
const bool selected = mode == "selected";
|
||||
const bool process = mode == "process";
|
||||
const bool workerExpected = selected || mode == "default";
|
||||
const auto stem = std::filesystem::temp_directory_path() / ("anyps5-sampler-" + std::to_string(GetCurrentProcessId()));
|
||||
const auto workerPath = stem.string() + "-worker.txt";
|
||||
const auto processPath = stem.string() + "-process.txt";
|
||||
_putenv_s("APS5_SAMPLE_WORKER", workerPath.c_str());
|
||||
_putenv_s("APS5_SAMPLE_THREADS", process ? processPath.c_str() : "");
|
||||
_putenv_s("APS5_SAMPLE_WORKER_QUEUE", mode == "default" ? "" : "0x50");
|
||||
AgcDriver::StartWorkerSampler(selected ? 0x50 : 0);
|
||||
const auto until = std::chrono::steady_clock::now() + std::chrono::milliseconds(200);
|
||||
while (std::chrono::steady_clock::now() < until) std::this_thread::yield();
|
||||
AgcDriver::StopWorkerSampler();
|
||||
const auto sampled = [](const std::string& path) {
|
||||
std::ifstream file(path);
|
||||
std::string marker;
|
||||
std::uint64_t samples = 0;
|
||||
return (file >> marker >> samples) && marker == "#" && samples != 0;
|
||||
};
|
||||
const bool passed = sampled(workerPath) == workerExpected && sampled(processPath) == process;
|
||||
std::filesystem::remove(workerPath);
|
||||
std::filesystem::remove(processPath);
|
||||
std::filesystem::remove(stem.string() + "-worker.collapsed.txt");
|
||||
std::filesystem::remove(stem.string() + "-worker.collapsed.txt.tmp");
|
||||
std::printf("worker sampler %s: %s\n", mode.c_str(), passed ? "passed" : "failed");
|
||||
return passed ? 0 : 1;
|
||||
}
|
||||
@@ -142,12 +142,31 @@ int main(int argc, char** argv) {
|
||||
const auto draw = [&](const Surface& surface, const DrawOptions& options) { return Draw(*device, shaders, surface, options, PlaneExtent, Colors); };
|
||||
const DrawOptions writeHalf{.depthWrite = true, .depthCompare = VK_COMPARE_OP_ALWAYS};
|
||||
|
||||
if (argc == 2 && std::string_view(argv[1]) == "--cpu-write-after-memo") {
|
||||
const bool pageWatch = argc == 2 && std::string_view(argv[1]) == "--cpu-write-after-page-unwatch";
|
||||
const bool partialWatch = pageWatch || (argc == 2 && std::string_view(argv[1]) == "--cpu-write-after-partial-unwatch");
|
||||
if (partialWatch || (argc == 2 && std::string_view(argv[1]) == "--cpu-write-after-memo")) {
|
||||
if (!AgcDriver::GuestMemory::WriteWatched() || !AgcDriver::GuestMemory::Watched(base, PlaneBytes)) return VulkanTestSkipped;
|
||||
if (pageWatch) {
|
||||
#ifdef _WIN32
|
||||
AgcDriver::GuestMemory::Unwatch(base + 4u * Block, Block);
|
||||
const std::array<std::pair<std::uint64_t, std::uint64_t>, 1> descriptorPage{{{base + 4u * Block + 4096u, base + 4u * Block + 8192u}}};
|
||||
AgcDriver::GuestMemory::Rewatch(descriptorPage);
|
||||
#else
|
||||
AgcDriver::GuestMemory::Unwatch(base + 4u * Block + 8192u, 4096u);
|
||||
#endif
|
||||
} else if (partialWatch) {
|
||||
AgcDriver::GuestMemory::Unwatch(base + 5u * Block, Block);
|
||||
}
|
||||
if (partialWatch) {
|
||||
Require(!AgcDriver::GuestMemory::Watched(base, PlaneBytes), "the regression plane remains fully watched");
|
||||
Require(AgcDriver::GuestMemory::Watched(base + 4u * Block + 4096u, pageWatch ? 4096u : Block - 4096u), "the descriptor page lost write watching");
|
||||
Require(!pageWatch || !AgcDriver::GuestMemory::Watched(base + 4u * Block, Block), "the descriptor unit remains fully watched");
|
||||
}
|
||||
Fill(plane, 1.0f);
|
||||
Require(draw(depth, writeHalf) == PlaneTexels, "the memo regression depth draw did not cover the plane");
|
||||
AgcDriver::GuestMemory::BumpCollectEpoch();
|
||||
AgcDriver::GuestMemory::CollectWrites(base, PlaneBytes);
|
||||
const auto collected = AgcDriver::GuestMemory::CollectWrites(base, PlaneBytes);
|
||||
Require(!partialWatch || collected == 0, "a whole-plane collect did not refuse partial watch coverage");
|
||||
const auto vertexAddress = base + 2u * Block + 256u;
|
||||
const std::array<std::uint32_t, 4> descriptor{static_cast<std::uint32_t>(vertexAddress), static_cast<std::uint32_t>((vertexAddress >> 32u) & 0xffffu) | (32u << 16u), 4u, 0x0004dfacu};
|
||||
auto* table = reinterpret_cast<std::byte*>(plane) + 4u * Block + 4096u;
|
||||
@@ -159,7 +178,7 @@ int main(int argc, char** argv) {
|
||||
Require(!ReadStart(*device, base).empty(), "preserving the CPU descriptors dropped an untouched depth unit");
|
||||
RequireUnit(plane, 0, 0.5f, UnitTexels, "the untouched unit retains its GPU depth results");
|
||||
Require(std::memcmp(table, descriptor.data(), sizeof(descriptor)) == 0, "storing an untouched depth unit changed the CPU descriptors");
|
||||
std::puts("depth plane CPU descriptors after memoized collect tests passed");
|
||||
std::puts(partialWatch ? "depth plane CPU descriptors with partial write watch tests passed" : "depth plane CPU descriptors after memoized collect tests passed");
|
||||
return 0;
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,222 @@
|
||||
#include "prx/libSceAgcDriver/Execution/include/VulkanDevice.hpp"
|
||||
#include "prx/libSceAgcDriver/Graphics/include/Draw.hpp"
|
||||
#include "Recompiler.hpp"
|
||||
#include "VulkanTestDevice.hpp"
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
#include <iostream>
|
||||
#include <optional>
|
||||
#include <span>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace {
|
||||
|
||||
using AgcDriver::Graphics::Require;
|
||||
using ShaderRecompiler::ShaderStage;
|
||||
|
||||
constexpr std::uint32_t Threads = 32;
|
||||
constexpr std::uint32_t Inputs = 4;
|
||||
constexpr std::uint32_t Results = 5;
|
||||
constexpr std::uint32_t Stride = 8;
|
||||
alignas(256) std::array<std::uint32_t, Threads * Inputs> Input{};
|
||||
alignas(256) std::array<std::uint32_t, Threads * Stride> Output{};
|
||||
|
||||
alignas(256) constexpr std::array<std::uint32_t, 20> Code{
|
||||
0x34020084u, 0x34040085u, 0xe0381000u, 0x80000401u, 0xbf8c3f70u, 0xd56d6a0au, 0x04160904u, 0xd501000bu,
|
||||
0x01a90280u, 0xd56d6a0cu, 0x04160905u, 0xd501000du, 0x01a90280u, 0xd55f000eu, 0x04160906u, 0xe0781000u,
|
||||
0x80010a02u, 0xe0701010u, 0x80010e02u, 0xbf810000u,
|
||||
};
|
||||
|
||||
constexpr const char* Names[Results] = {
|
||||
"v_div_scale_f32 v10, vcc_lo, v4, v4, v5",
|
||||
"its vcc_lo",
|
||||
"v_div_scale_f32 v12, vcc_lo, v5, v4, v5",
|
||||
"its vcc_lo",
|
||||
"v_div_fixup_f32 v14, v6, v4, v5",
|
||||
};
|
||||
|
||||
constexpr std::uint32_t Rows[Threads][3] = {
|
||||
{0x7e800000u, 0x00000001u, 0x00000005u},
|
||||
{0x7f7fffffu, 0x807fffffu, 0x3f800000u},
|
||||
{0x7e800000u, 0x00400000u, 0x80400000u},
|
||||
{0xff7fffffu, 0x00000003u, 0x7fc00001u},
|
||||
{0x00000001u, 0x3f800000u, 0x00000005u},
|
||||
{0x007fffffu, 0x40490fdbu, 0x3f800000u},
|
||||
{0x80000001u, 0xbfc00000u, 0x80400000u},
|
||||
{0x00400000u, 0x7f7fffffu, 0x7fc00001u},
|
||||
{0x3f800000u, 0x00000003u, 0x00000005u},
|
||||
{0xbfc00000u, 0x80000001u, 0x3f800000u},
|
||||
{0x40490fdbu, 0x007fffffu, 0x80400000u},
|
||||
{0x5f800000u, 0x00400000u, 0x7fc00001u},
|
||||
{0x00000001u, 0x00000001u, 0x00000005u},
|
||||
{0x007fffffu, 0x807fffffu, 0x3f800000u},
|
||||
{0x00400000u, 0x00000003u, 0x80400000u},
|
||||
{0x00800000u, 0x00000001u, 0x7fc00001u},
|
||||
{0x00000001u, 0x00800000u, 0x00000005u},
|
||||
{0x0c000000u, 0x00000001u, 0x3f800000u},
|
||||
{0x00000003u, 0x0c800000u, 0x80400000u},
|
||||
{0x34000000u, 0x80000001u, 0x7fc00001u},
|
||||
{0x00000001u, 0x00000000u, 0x00000005u},
|
||||
{0x00000000u, 0x00000001u, 0x3f800000u},
|
||||
{0x7f800000u, 0x00000001u, 0x80400000u},
|
||||
{0x00000001u, 0xff800000u, 0x7fc00001u},
|
||||
{0x7fc00000u, 0x00000001u, 0x00000005u},
|
||||
{0x00000003u, 0x7fc00000u, 0x3f800000u},
|
||||
{0x00000001u, 0x7e800000u, 0x80400000u},
|
||||
{0x807fffffu, 0x5f800000u, 0x7fc00001u},
|
||||
{0x3f800000u, 0x3f800000u, 0x00000005u},
|
||||
{0x40490fdbu, 0xbfc00000u, 0x3f800000u},
|
||||
{0x0c800000u, 0x7f7fffffu, 0x80400000u},
|
||||
{0x00800000u, 0x0c000000u, 0x7fc00001u}
|
||||
};
|
||||
constexpr std::uint32_t Mode1Expected[Threads][Results] = {
|
||||
{0x5e800000u, 0x00000001u, 0x00000000u, 0x00000001u, 0x00000000u},
|
||||
{0x5f7fffffu, 0x00000001u, 0x80000000u, 0x00000001u, 0x80000000u},
|
||||
{0x5e800000u, 0x00000001u, 0x00000000u, 0x00000001u, 0x00000000u},
|
||||
{0xdf7fffffu, 0x00000001u, 0x00000000u, 0x00000001u, 0x80000000u},
|
||||
{0x15000000u, 0x00000001u, 0x3f800000u, 0x00000001u, 0x00000005u},
|
||||
{0x207ffffeu, 0x00000001u, 0x40490fdbu, 0x00000001u, 0x3f800000u},
|
||||
{0x95000000u, 0x00000001u, 0xbfc00000u, 0x00000001u, 0x00400000u},
|
||||
{0x20000000u, 0x00000001u, 0x7f7fffffu, 0x00000001u, 0x7f800000u},
|
||||
{0x3f800000u, 0x00000001u, 0x15c00000u, 0x00000001u, 0x00000005u},
|
||||
{0xbfc00000u, 0x00000001u, 0x95000000u, 0x00000001u, 0x3f800000u},
|
||||
{0x40490fdbu, 0x00000001u, 0x207ffffeu, 0x00000001u, 0x00400000u},
|
||||
{0x5f800000u, 0x00000001u, 0x20000000u, 0x00000001u, 0x00000000u},
|
||||
{0x15000000u, 0x00000000u, 0x15000000u, 0x00000000u, 0x00000005u},
|
||||
{0x207ffffeu, 0x00000000u, 0xa07ffffeu, 0x00000000u, 0xbf800000u},
|
||||
{0x20000000u, 0x00000000u, 0x15c00000u, 0x00000000u, 0x00400000u},
|
||||
{0x20800000u, 0x00000000u, 0x15000000u, 0x00000000u, 0x7f800000u},
|
||||
{0x15000000u, 0x00000000u, 0x20800000u, 0x00000000u, 0x00000005u},
|
||||
{0x2c000000u, 0x00000000u, 0x15000000u, 0x00000000u, 0x3f800000u},
|
||||
{0x15c00000u, 0x00000000u, 0x2c800000u, 0x00000000u, 0x00400000u},
|
||||
{0x34000000u, 0x00000001u, 0x95000000u, 0x00000001u, 0xff800000u},
|
||||
{0xffc00000u, 0x00000000u, 0xffc00000u, 0x00000000u, 0x00000000u},
|
||||
{0xffc00000u, 0x00000000u, 0xffc00000u, 0x00000000u, 0x7f800000u},
|
||||
{0x7f800000u, 0x00000001u, 0x00000000u, 0x00000001u, 0x00000000u},
|
||||
{0x15000000u, 0x00000001u, 0xff800000u, 0x00000001u, 0xff800000u},
|
||||
{0x7fc00000u, 0x00000001u, 0x00000000u, 0x00000001u, 0x7fc00000u},
|
||||
{0x15c00000u, 0x00000001u, 0x7fc00000u, 0x00000001u, 0x7fc00000u},
|
||||
{0x15000000u, 0x00000001u, 0x7e800000u, 0x00000001u, 0x00400000u},
|
||||
{0xa07ffffeu, 0x00000001u, 0x5f800000u, 0x00000001u, 0xff800000u},
|
||||
{0x3f800000u, 0x00000000u, 0x3f800000u, 0x00000000u, 0x00000005u},
|
||||
{0x40490fdbu, 0x00000000u, 0xbfc00000u, 0x00000000u, 0xbf800000u},
|
||||
{0x2c800000u, 0x00000001u, 0x7f7fffffu, 0x00000001u, 0x00400000u},
|
||||
{0x20800000u, 0x00000000u, 0x2c000000u, 0x00000000u, 0x7f800000u}
|
||||
};
|
||||
constexpr std::uint32_t Mode2Expected[Threads][Results] = {
|
||||
{0xffc00000u, 0x00000001u, 0xffc00000u, 0x00000001u, 0x00000000u},
|
||||
{0xffc00000u, 0x00000001u, 0xffc00000u, 0x00000001u, 0x80000000u},
|
||||
{0xffc00000u, 0x00000001u, 0xffc00000u, 0x00000001u, 0x00000000u},
|
||||
{0xffc00000u, 0x00000001u, 0xffc00000u, 0x00000001u, 0x80000000u},
|
||||
{0xffc00000u, 0x00000001u, 0xffc00000u, 0x00000001u, 0x7f800000u},
|
||||
{0xffc00000u, 0x00000001u, 0xffc00000u, 0x00000001u, 0x7f800000u},
|
||||
{0xffc00000u, 0x00000001u, 0xffc00000u, 0x00000001u, 0x7f800000u},
|
||||
{0xffc00000u, 0x00000001u, 0xffc00000u, 0x00000001u, 0x7f800000u},
|
||||
{0xffc00000u, 0x00000001u, 0xffc00000u, 0x00000001u, 0x00000000u},
|
||||
{0xffc00000u, 0x00000001u, 0xffc00000u, 0x00000001u, 0x00000000u},
|
||||
{0xffc00000u, 0x00000001u, 0xffc00000u, 0x00000001u, 0x00000000u},
|
||||
{0xffc00000u, 0x00000001u, 0xffc00000u, 0x00000001u, 0x00000000u},
|
||||
{0xffc00000u, 0x00000000u, 0xffc00000u, 0x00000000u, 0xffc00000u},
|
||||
{0xffc00000u, 0x00000000u, 0xffc00000u, 0x00000000u, 0xffc00000u},
|
||||
{0xffc00000u, 0x00000000u, 0xffc00000u, 0x00000000u, 0xffc00000u},
|
||||
{0xffc00000u, 0x00000000u, 0xffc00000u, 0x00000000u, 0x00000000u},
|
||||
{0xffc00000u, 0x00000000u, 0xffc00000u, 0x00000000u, 0x7f800000u},
|
||||
{0xffc00000u, 0x00000000u, 0xffc00000u, 0x00000000u, 0x00000000u},
|
||||
{0xffc00000u, 0x00000000u, 0xffc00000u, 0x00000000u, 0x7f800000u},
|
||||
{0xffc00000u, 0x00000001u, 0xffc00000u, 0x00000001u, 0x80000000u},
|
||||
{0xffc00000u, 0x00000000u, 0xffc00000u, 0x00000000u, 0xffc00000u},
|
||||
{0xffc00000u, 0x00000000u, 0xffc00000u, 0x00000000u, 0xffc00000u},
|
||||
{0xffc00000u, 0x00000001u, 0xffc00000u, 0x00000001u, 0x00000000u},
|
||||
{0xffc00000u, 0x00000001u, 0xffc00000u, 0x00000001u, 0xff800000u},
|
||||
{0xffc00000u, 0x00000001u, 0xffc00000u, 0x00000001u, 0x7fc00000u},
|
||||
{0xffc00000u, 0x00000001u, 0xffc00000u, 0x00000001u, 0x7fc00000u},
|
||||
{0xffc00000u, 0x00000001u, 0xffc00000u, 0x00000001u, 0x7f800000u},
|
||||
{0xffc00000u, 0x00000001u, 0xffc00000u, 0x00000001u, 0xff800000u},
|
||||
{0x3f800000u, 0x00000000u, 0x3f800000u, 0x00000000u, 0x00000005u},
|
||||
{0x40490fdbu, 0x00000000u, 0xbfc00000u, 0x00000000u, 0xbf800000u},
|
||||
{0x2c800000u, 0x00000001u, 0x7f7fffffu, 0x00000001u, 0x00400000u},
|
||||
{0x20800000u, 0x00000000u, 0x2c000000u, 0x00000000u, 0x7f800000u}
|
||||
};
|
||||
|
||||
std::array<std::uint32_t, 4> BufferDescriptor(const void* data, std::uint32_t bytes) {
|
||||
const auto address = reinterpret_cast<std::uintptr_t>(data);
|
||||
return {static_cast<std::uint32_t>(address), static_cast<std::uint32_t>((address >> 32u) & 0xffffu), bytes, 0x31016facu};
|
||||
}
|
||||
|
||||
std::string Hex(std::uint32_t value) {
|
||||
char text[16];
|
||||
std::snprintf(text, sizeof(text), "0x%08x", value);
|
||||
return text;
|
||||
}
|
||||
|
||||
std::optional<std::string> Run(AgcDriver::VulkanDevice& device, ShaderRecompiler::ShaderFloatMode floatMode) {
|
||||
Input.fill(0u);
|
||||
for (std::uint32_t tid = 0; tid < Threads; ++tid) std::copy(std::begin(Rows[tid]), std::end(Rows[tid]), &Input[tid * Inputs]);
|
||||
Output.fill(0xdeadbeefu);
|
||||
std::vector<std::uint32_t> userData(8, 0u);
|
||||
const auto input = BufferDescriptor(Input.data(), static_cast<std::uint32_t>(Input.size() * 4u));
|
||||
const auto output = BufferDescriptor(Output.data(), static_cast<std::uint32_t>(Output.size() * 4u));
|
||||
std::copy(input.begin(), input.end(), userData.begin());
|
||||
std::copy(output.begin(), output.end(), userData.begin() + 4);
|
||||
const std::span<const std::uint32_t> code(Code);
|
||||
const std::array<ShaderRecompiler::MemoryRegion, 1> memory{{{reinterpret_cast<std::uintptr_t>(code.data()), std::as_bytes(code)}}};
|
||||
const ShaderRecompiler::ShaderComputeStageInfo compute{{Threads, 1, 1}, 0, {false, false, false}, false, 1};
|
||||
ShaderRecompiler::RecompileRequest request{
|
||||
{ShaderStage::Compute, reinterpret_cast<std::uintptr_t>(code.data()), code, 0, {}},
|
||||
{32, 0, userData, compute, std::nullopt, std::nullopt, memory},
|
||||
device.Target(),
|
||||
{0, 0, 0, 128}
|
||||
};
|
||||
request.useCache = false;
|
||||
request.context.floatMode = floatMode;
|
||||
std::optional<decltype(ShaderRecompiler::Recompile(request))> result;
|
||||
try {
|
||||
result.emplace(ShaderRecompiler::Recompile(request));
|
||||
} catch (const std::exception& error) {
|
||||
return std::string(error.what());
|
||||
}
|
||||
device.Dispatch(*result, 1, 1, 1, {}, reinterpret_cast<std::uintptr_t>(code.data()));
|
||||
device.WaitIdle();
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
void Check(std::uint32_t denormals, bool ieee) {
|
||||
const auto& expected = denormals == 1u ? Mode1Expected : Mode2Expected;
|
||||
for (std::uint32_t tid = 0; tid < Threads; ++tid) {
|
||||
for (std::uint32_t i = 0; i < Results; ++i) {
|
||||
const std::uint32_t actual = Output[tid * Stride + i];
|
||||
Require(actual == expected[tid][i], "f32 denormal mode " + std::to_string(denormals) + (ieee ? ", IEEE=1, " : ", IEEE=0, ") + Names[i] + " with v4 " + Hex(Rows[tid][0]) + ", v5 " + Hex(Rows[tid][1]) + ", v6 " + Hex(Rows[tid][2]) + " is " + Hex(actual) + ", expected " + Hex(expected[tid][i]));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
int main() {
|
||||
try {
|
||||
const auto device = OpenVulkanTestDevice();
|
||||
if (!device) return VulkanTestSkipped;
|
||||
const bool keepsDenormals = device->Target().float32DenormPreserve;
|
||||
std::uint32_t checked = 0u;
|
||||
for (const std::uint32_t denormals : {1u, 2u}) {
|
||||
for (const bool ieee : {false, true}) {
|
||||
const ShaderRecompiler::ShaderFloatMode floatMode{0xc0u | denormals << 4u, true, ieee, false};
|
||||
const auto refusal = Run(*device, floatMode);
|
||||
if (refusal) {
|
||||
Require(denormals == 1u && !keepsDenormals && refusal->find("needs DenormPreserve 32") != std::string::npos, "FLOAT_MODE " + Hex(floatMode.floatMode) + ": " + *refusal);
|
||||
continue;
|
||||
}
|
||||
++checked;
|
||||
Check(denormals, ieee);
|
||||
}
|
||||
}
|
||||
std::printf("v_div_scale_f32 and v_div_fixup_f32 denormal mode 1 and 2 tests passed (%u of 4 modes run; the others need DenormPreserve 32)\n", checked);
|
||||
return 0;
|
||||
} catch (const std::exception& error) {
|
||||
std::cerr << error.what() << '\n';
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
@@ -700,14 +700,20 @@ bool HostFusesFma(AgcDriver::VulkanDevice& device) {
|
||||
}
|
||||
|
||||
void CheckScaleDenormals(AgcDriver::VulkanDevice& device) {
|
||||
const std::array<std::optional<ShaderRecompiler::ShaderFloatMode>, 5> modes{{
|
||||
const std::array<std::optional<ShaderRecompiler::ShaderFloatMode>, 9> modes{{
|
||||
std::nullopt,
|
||||
ShaderRecompiler::ShaderFloatMode{0xc0u, true, false, false},
|
||||
ShaderRecompiler::ShaderFloatMode{0xc0u, true, true, false},
|
||||
ShaderRecompiler::ShaderFloatMode{0xd0u, true, false, false},
|
||||
ShaderRecompiler::ShaderFloatMode{0xd0u, true, true, false},
|
||||
ShaderRecompiler::ShaderFloatMode{0xe0u, true, false, false},
|
||||
ShaderRecompiler::ShaderFloatMode{0xe0u, true, true, false},
|
||||
ShaderRecompiler::ShaderFloatMode{0xf0u, true, false, false},
|
||||
ShaderRecompiler::ShaderFloatMode{0xf0u, true, true, false},
|
||||
}};
|
||||
for (const auto& mode : modes) {
|
||||
const std::uint32_t denormals = mode.has_value() ? (mode->floatMode >> 4u) & 3u : 0u;
|
||||
if (denormals == 1u && !device.Target().float32DenormPreserve) continue;
|
||||
Shader shader(device, ScaleCode, mode);
|
||||
Input.fill(0u);
|
||||
for (std::uint32_t lane = 0; lane < std::size(ScaleVectors); ++lane) {
|
||||
@@ -718,20 +724,12 @@ void CheckScaleDenormals(AgcDriver::VulkanDevice& device) {
|
||||
for (std::uint32_t lane = 0; lane < std::size(ScaleVectors); ++lane) {
|
||||
const auto& vector = ScaleVectors[lane];
|
||||
const auto* out = &Output[lane * Stride];
|
||||
const auto expected = mode.has_value() && ((mode->floatMode >> 4u) & 3u) == 3u ? vector.kept : vector.flushed;
|
||||
const std::uint32_t keptResult = (vector.kept & 0x7f800000u) == 0u ? vector.kept & 0x80000000u : vector.kept;
|
||||
const auto expected = denormals == 3u ? vector.kept : denormals == 1u ? keptResult : vector.flushed;
|
||||
const std::string where = "division scale denormals: lane " + std::to_string(lane) + " mode " + (mode.has_value() ? Hex(mode->floatMode) : "unknown");
|
||||
Require(out[0] == expected && out[1] == vector.vcc, where + ": v_div_scale_f32 is " + Hex(out[0]) + " vcc " + std::to_string(out[1]) + ", expected " + Hex(expected) + " vcc " + std::to_string(vector.vcc));
|
||||
}
|
||||
}
|
||||
for (const std::uint32_t mode : {0xd0u, 0xe0u}) {
|
||||
bool refused = false;
|
||||
try {
|
||||
Shader shader(device, ScaleCode, ShaderRecompiler::ShaderFloatMode{mode, true, false, false});
|
||||
} catch (const std::runtime_error& error) {
|
||||
refused = std::string(error.what()).find("f32 denormal mode") != std::string::npos;
|
||||
}
|
||||
Require(refused, "division scale denormals: FLOAT_MODE " + Hex(mode) + " was not refused");
|
||||
}
|
||||
}
|
||||
|
||||
void CheckHelpers(AgcDriver::VulkanDevice& device, bool fused) {
|
||||
|
||||
@@ -10,7 +10,6 @@
|
||||
#include <cstdio>
|
||||
#include <iostream>
|
||||
#include <optional>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <spirv/unified1/spirv.hpp>
|
||||
@@ -555,15 +554,6 @@ int main() {
|
||||
CheckTinyLegacy("round mode " + std::to_string(round));
|
||||
CheckTinyDirected(round);
|
||||
}
|
||||
for (const std::uint32_t mode : {0xd0u, 0xe0u}) {
|
||||
bool refused = false;
|
||||
try {
|
||||
Run(*device, ShaderRecompiler::ShaderFloatMode{mode, true, false, false});
|
||||
} catch (const std::runtime_error& error) {
|
||||
refused = std::string(error.what()).find("f32 denormal mode") != std::string::npos;
|
||||
}
|
||||
Require(refused, "f32 denormal flush: FLOAT_MODE " + Hex(mode) + " was not refused");
|
||||
}
|
||||
}
|
||||
std::puts("f32 denormal flush tests passed");
|
||||
return 0;
|
||||
|
||||
@@ -0,0 +1,241 @@
|
||||
#include "prx/libSceAgcDriver/Execution/include/VulkanDevice.hpp"
|
||||
#include "prx/libSceAgcDriver/Graphics/include/Draw.hpp"
|
||||
#include "Recompiler.hpp"
|
||||
#include "VulkanTestDevice.hpp"
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
#include <iostream>
|
||||
#include <optional>
|
||||
#include <span>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace {
|
||||
|
||||
using AgcDriver::Graphics::Require;
|
||||
using ShaderRecompiler::ShaderStage;
|
||||
|
||||
constexpr std::uint32_t Threads = 64;
|
||||
constexpr std::uint32_t Inputs = 4;
|
||||
constexpr std::uint32_t Results = 4;
|
||||
alignas(256) std::array<std::uint32_t, Threads * Inputs> Input{};
|
||||
alignas(256) std::array<std::uint32_t, Threads * Results> Output{};
|
||||
|
||||
alignas(256) constexpr std::array<std::uint32_t, 15> Code{
|
||||
0x34020084u, 0xe0381000u, 0x80000401u, 0xbf8c3f70u, 0xd54b000au, 0x041a0b04u, 0x7e160306u, 0x56160b04u,
|
||||
0x58180d04u, 0x3f7fffffu, 0x5a1a0b04u, 0x80000001u, 0xe0781000u, 0x80010a01u, 0xbf810000u,
|
||||
};
|
||||
|
||||
constexpr const char* Names[Results] = {"v_fma_f32 v10, v4, v5, v6", "v_fmac_f32 v11, v4, v5", "v_fmamk_f32 v12, v4, 0x3f7fffff, v6", "v_fmaak_f32 v13, v4, v5, 0x80000001"};
|
||||
|
||||
constexpr std::uint32_t Rows[Threads][3] = {
|
||||
{0x00000000u, 0x7f800000u, 0x3f000000u},
|
||||
{0x00800000u, 0x00000000u, 0x00000000u},
|
||||
{0x00800000u, 0x00000000u, 0x80000000u},
|
||||
{0x00800000u, 0x00000000u, 0x00000001u},
|
||||
{0x00800000u, 0x00000000u, 0x807fffffu},
|
||||
{0x00800000u, 0x00000000u, 0x00400000u},
|
||||
{0x00800000u, 0x00000000u, 0x80800001u},
|
||||
{0x00800000u, 0x80000000u, 0x00000000u},
|
||||
{0x00800000u, 0x80000000u, 0x80000000u},
|
||||
{0x00800000u, 0x00400000u, 0x00000001u},
|
||||
{0x00800000u, 0x00800000u, 0x80000000u},
|
||||
{0x00800000u, 0x3f800000u, 0x80800001u},
|
||||
{0x00800000u, 0x3f7fffffu, 0x00000000u},
|
||||
{0x00800000u, 0x3f7fffffu, 0x80000000u},
|
||||
{0x00800000u, 0x3f7fffffu, 0x00000001u},
|
||||
{0x00800000u, 0x3f7fffffu, 0x807fffffu},
|
||||
{0x00800000u, 0x3f7fffffu, 0x00400000u},
|
||||
{0x00800000u, 0x3f7fffffu, 0x00800000u},
|
||||
{0x00800000u, 0x3f7fffffu, 0x80800001u},
|
||||
{0x00800000u, 0x3f7fffffu, 0x3f800000u},
|
||||
{0x00800000u, 0x3f7fffffu, 0xbf800000u},
|
||||
{0x00800000u, 0x3f7fffffu, 0x3f7fffffu},
|
||||
{0x00800000u, 0x3f7fffffu, 0x3f000000u},
|
||||
{0x00800000u, 0x3f7fffffu, 0x1f800000u},
|
||||
{0x00800000u, 0x3f7fffffu, 0x9fffffffu},
|
||||
{0x00800000u, 0x3f7fffffu, 0x20000000u},
|
||||
{0x00800000u, 0x3f000000u, 0x00000000u},
|
||||
{0x00800000u, 0x3f000000u, 0x80000000u},
|
||||
{0x00800000u, 0x3f000000u, 0x00000001u},
|
||||
{0x00800000u, 0x3f000000u, 0x807fffffu},
|
||||
{0x00800000u, 0x3f000000u, 0x00400000u},
|
||||
{0x00800000u, 0x3f000000u, 0x80800001u},
|
||||
{0x00800000u, 0x1f800000u, 0x80000000u},
|
||||
{0x80800001u, 0x3f800000u, 0x00800000u},
|
||||
{0x80800001u, 0x3f000000u, 0x7f800000u},
|
||||
{0x3f800000u, 0x80800001u, 0x00800000u},
|
||||
{0x3f800000u, 0x7fc00000u, 0x80800001u},
|
||||
{0x3f7fffffu, 0xbf800000u, 0x3f000000u},
|
||||
{0x1f800000u, 0x3f800000u, 0x20000000u},
|
||||
{0x9fffffffu, 0x00000001u, 0x80000000u},
|
||||
{0x9fffffffu, 0x20000000u, 0x00400000u},
|
||||
{0x20000000u, 0x3f800000u, 0x00000000u},
|
||||
{0x20000000u, 0x9fffffffu, 0x20000000u},
|
||||
{0x20000000u, 0x9fffffffu, 0x7fc00000u},
|
||||
{0x7f800000u, 0x00400000u, 0x00000001u},
|
||||
{0xa041753bu, 0x1f0d790au, 0x80000000u},
|
||||
{0x9efedcd2u, 0x9ff05395u, 0x80000000u},
|
||||
{0x1f47e4fdu, 0x1eb6f5c4u, 0x80000000u},
|
||||
{0x9e9e1749u, 0x1f7a0022u, 0x8086d61eu},
|
||||
{0x9fc47dc5u, 0x1f7a84eeu, 0x80ad97ffu},
|
||||
{0x9e398753u, 0x20a52a9au, 0x809fead7u},
|
||||
{0x1ee684f0u, 0x204b1dd4u, 0x00000000u},
|
||||
{0x1e8933deu, 0x205cc4a7u, 0x00000000u},
|
||||
{0x1f19a9f4u, 0x9fbc243cu, 0x80000000u},
|
||||
{0x9eb3c398u, 0x9f630477u, 0x00000000u},
|
||||
{0x1e32d290u, 0x1fa0e0b3u, 0x00000000u},
|
||||
{0x1f074330u, 0x9e704ff0u, 0x00000000u},
|
||||
{0x1ea63ad2u, 0x1e7c9dc9u, 0x806cc811u},
|
||||
{0x9f42587bu, 0xa0dd6a0cu, 0x80000000u},
|
||||
{0x202187c6u, 0x1eb02829u, 0x80000000u},
|
||||
{0x1fe6f5d7u, 0x208cc5a7u, 0x80df394au},
|
||||
{0x1f2af88cu, 0x9e6ce54fu, 0x80000000u},
|
||||
{0x1eeac417u, 0x9e8ead57u, 0x00000000u},
|
||||
{0x9e406f2cu, 0x20e09d8du, 0x004226bcu}
|
||||
};
|
||||
constexpr std::uint32_t Expected[Threads][Results] = {
|
||||
{0xffc00000u, 0xffc00000u, 0x3f000000u, 0xffc00000u},
|
||||
{0x00000000u, 0x00000000u, 0x00800000u, 0x00000000u},
|
||||
{0x00000000u, 0x00000000u, 0x00800000u, 0x00000000u},
|
||||
{0x00000000u, 0x00000000u, 0x00800000u, 0x00000000u},
|
||||
{0x00000000u, 0x00000000u, 0x00800000u, 0x00000000u},
|
||||
{0x00000000u, 0x00000000u, 0x00800000u, 0x00000000u},
|
||||
{0x80800001u, 0x80800001u, 0x80000002u, 0x00000000u},
|
||||
{0x00000000u, 0x00000000u, 0x00800000u, 0x80000000u},
|
||||
{0x80000000u, 0x80000000u, 0x00800000u, 0x80000000u},
|
||||
{0x00000000u, 0x00000000u, 0x00800000u, 0x00000000u},
|
||||
{0x00000000u, 0x00000000u, 0x00800000u, 0x00000000u},
|
||||
{0x80000001u, 0x80000001u, 0x80000002u, 0x00800000u},
|
||||
{0x00800000u, 0x00800000u, 0x00800000u, 0x00800000u},
|
||||
{0x00800000u, 0x00800000u, 0x00800000u, 0x00800000u},
|
||||
{0x00800000u, 0x00800000u, 0x00800000u, 0x00800000u},
|
||||
{0x00800000u, 0x00800000u, 0x00800000u, 0x00800000u},
|
||||
{0x00800000u, 0x00800000u, 0x00800000u, 0x00800000u},
|
||||
{0x01000000u, 0x01000000u, 0x01000000u, 0x00800000u},
|
||||
{0x80000002u, 0x80000002u, 0x80000002u, 0x00800000u},
|
||||
{0x3f800000u, 0x3f800000u, 0x3f800000u, 0x00800000u},
|
||||
{0xbf800000u, 0xbf800000u, 0xbf800000u, 0x00800000u},
|
||||
{0x3f7fffffu, 0x3f7fffffu, 0x3f7fffffu, 0x00800000u},
|
||||
{0x3f000000u, 0x3f000000u, 0x3f000000u, 0x00800000u},
|
||||
{0x1f800000u, 0x1f800000u, 0x1f800000u, 0x00800000u},
|
||||
{0x9fffffffu, 0x9fffffffu, 0x9fffffffu, 0x00800000u},
|
||||
{0x20000000u, 0x20000000u, 0x20000000u, 0x00800000u},
|
||||
{0x00400000u, 0x00400000u, 0x00800000u, 0x00400000u},
|
||||
{0x00400000u, 0x00400000u, 0x00800000u, 0x00400000u},
|
||||
{0x00400000u, 0x00400000u, 0x00800000u, 0x00400000u},
|
||||
{0x00400000u, 0x00400000u, 0x00800000u, 0x00400000u},
|
||||
{0x00400000u, 0x00400000u, 0x00800000u, 0x00400000u},
|
||||
{0x80400001u, 0x80400001u, 0x80000002u, 0x00400000u},
|
||||
{0x00000000u, 0x00000000u, 0x00800000u, 0x00000000u},
|
||||
{0x80000001u, 0x80000001u, 0x80000000u, 0x80800001u},
|
||||
{0x7f800000u, 0x7f800000u, 0x7f800000u, 0x80400000u},
|
||||
{0x80000001u, 0x80000001u, 0x3f7fffffu, 0x80800001u},
|
||||
{0x7fc00000u, 0x7fc00000u, 0x3f7fffffu, 0x7fc00000u},
|
||||
{0xbefffffeu, 0xbefffffeu, 0x3fbfffffu, 0xbf7fffffu},
|
||||
{0x20400000u, 0x20400000u, 0x20400000u, 0x1f800000u},
|
||||
{0x80000000u, 0x80000000u, 0x9ffffffeu, 0x80000000u},
|
||||
{0x80800000u, 0x80800000u, 0x9ffffffeu, 0x80800000u},
|
||||
{0x20000000u, 0x20000000u, 0x1fffffffu, 0x20000000u},
|
||||
{0x20000000u, 0x20000000u, 0x20800000u, 0x80800000u},
|
||||
{0x7fc00000u, 0x7fc00000u, 0x7fc00000u, 0x80800000u},
|
||||
{0xffc00000u, 0xffc00000u, 0x7f800000u, 0xffc00000u},
|
||||
{0x80357485u, 0x80357485u, 0xa041753au, 0x80357485u},
|
||||
{0x001de847u, 0x001de847u, 0x9efedcd1u, 0x001de847u},
|
||||
{0x0008edcbu, 0x0008edcbu, 0x1f47e4fcu, 0x0008edcbu},
|
||||
{0x80907c4bu, 0x80907c4bu, 0x9e9e1748u, 0x8009a62du},
|
||||
{0x80ddaa35u, 0x80ddaa35u, 0x9fc47dc4u, 0x80301236u},
|
||||
{0x80bdd79du, 0x80bdd79du, 0x9e398752u, 0x801decc6u},
|
||||
{0x002db992u, 0x002db992u, 0x1ee684efu, 0x002db992u},
|
||||
{0x001d947eu, 0x001d947eu, 0x1e8933ddu, 0x001d947eu},
|
||||
{0x801c3ba4u, 0x801c3ba4u, 0x1f19a9f3u, 0x801c3ba4u},
|
||||
{0x0009f699u, 0x0009f699u, 0x9eb3c397u, 0x0009f699u},
|
||||
{0x00070609u, 0x00070609u, 0x1e32d28fu, 0x00070609u},
|
||||
{0x8003f7cau, 0x8003f7cau, 0x1f07432fu, 0x8003f7cau},
|
||||
{0x00029021u, 0x00029021u, 0x1ea63ad1u, 0x00029021u},
|
||||
{0x00a816e4u, 0x00a816e4u, 0x9f42587au, 0x00a816e4u},
|
||||
{0x001bc9acu, 0x001bc9acu, 0x202187c5u, 0x001bc9acu},
|
||||
{0x001ec83du, 0x001ec83du, 0x1fe6f5d6u, 0x00fe0187u},
|
||||
{0x8004f1b2u, 0x8004f1b2u, 0x1f2af88bu, 0x8004f1b2u},
|
||||
{0x800416beu, 0x800416beu, 0x1eeac416u, 0x800416beu},
|
||||
{0x802a35edu, 0x802a35edu, 0x9e406f2bu, 0x802a35edu}
|
||||
};
|
||||
|
||||
std::array<std::uint32_t, 4> BufferDescriptor(const void* data, std::uint32_t bytes) {
|
||||
const auto address = reinterpret_cast<std::uintptr_t>(data);
|
||||
return {static_cast<std::uint32_t>(address), static_cast<std::uint32_t>((address >> 32u) & 0xffffu), bytes, 0x31016facu};
|
||||
}
|
||||
|
||||
std::string Hex(std::uint32_t value) {
|
||||
char text[16];
|
||||
std::snprintf(text, sizeof(text), "0x%08x", value);
|
||||
return text;
|
||||
}
|
||||
|
||||
std::optional<std::string> Run(AgcDriver::VulkanDevice& device, ShaderRecompiler::ShaderFloatMode floatMode) {
|
||||
Input.fill(0u);
|
||||
for (std::uint32_t tid = 0; tid < Threads; ++tid) std::copy(std::begin(Rows[tid]), std::end(Rows[tid]), &Input[tid * Inputs]);
|
||||
Output.fill(0xdeadbeefu);
|
||||
std::vector<std::uint32_t> userData(8, 0u);
|
||||
const auto input = BufferDescriptor(Input.data(), static_cast<std::uint32_t>(Input.size() * 4u));
|
||||
const auto output = BufferDescriptor(Output.data(), static_cast<std::uint32_t>(Output.size() * 4u));
|
||||
std::copy(input.begin(), input.end(), userData.begin());
|
||||
std::copy(output.begin(), output.end(), userData.begin() + 4);
|
||||
const std::span<const std::uint32_t> code(Code);
|
||||
const std::array<ShaderRecompiler::MemoryRegion, 1> memory{{{reinterpret_cast<std::uintptr_t>(code.data()), std::as_bytes(code)}}};
|
||||
const ShaderRecompiler::ShaderComputeStageInfo compute{{Threads, 1, 1}, 0, {false, false, false}, false, 1};
|
||||
ShaderRecompiler::RecompileRequest request{
|
||||
{ShaderStage::Compute, reinterpret_cast<std::uintptr_t>(code.data()), code, 0, {}},
|
||||
{32, 0, userData, compute, std::nullopt, std::nullopt, memory},
|
||||
device.Target(),
|
||||
{0, 0, 0, 128}
|
||||
};
|
||||
request.useCache = false;
|
||||
request.context.floatMode = floatMode;
|
||||
std::optional<decltype(ShaderRecompiler::Recompile(request))> result;
|
||||
try {
|
||||
result.emplace(ShaderRecompiler::Recompile(request));
|
||||
} catch (const std::exception& error) {
|
||||
return std::string(error.what());
|
||||
}
|
||||
device.Dispatch(*result, 1, 1, 1, {}, reinterpret_cast<std::uintptr_t>(code.data()));
|
||||
device.WaitIdle();
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
void Check(bool ieee) {
|
||||
for (std::uint32_t tid = 0; tid < Threads; ++tid) {
|
||||
for (std::uint32_t i = 0; i < Results; ++i) {
|
||||
const std::uint32_t actual = Output[tid * Results + i];
|
||||
Require(actual == Expected[tid][i], std::string(Names[i]) + " f32 denormal mode 2" + (ieee ? ", IEEE=1" : ", IEEE=0") + " with v4 " + Hex(Rows[tid][0]) + ", v5 " + Hex(Rows[tid][1]) + ", v6 " + Hex(Rows[tid][2]) + " is " + Hex(actual) + ", expected " + Hex(Expected[tid][i]));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
int main() {
|
||||
try {
|
||||
const auto device = OpenVulkanTestDevice();
|
||||
if (!device) return VulkanTestSkipped;
|
||||
const bool keepsDenormals = device->Target().float32DenormPreserve;
|
||||
std::uint32_t checked = 0u;
|
||||
for (const bool ieee : {false, true}) {
|
||||
const ShaderRecompiler::ShaderFloatMode floatMode{0xe0u, true, ieee, false};
|
||||
const auto refusal = Run(*device, floatMode);
|
||||
if (refusal) {
|
||||
Require(!keepsDenormals && refusal->find("needs DenormPreserve 32") != std::string::npos, "FLOAT_MODE " + Hex(floatMode.floatMode) + ": " + *refusal);
|
||||
continue;
|
||||
}
|
||||
++checked;
|
||||
Check(ieee);
|
||||
}
|
||||
std::printf("f32 fma denormal mode 2 tests passed (%u of 2 IEEE modes run; the others need DenormPreserve 32)\n", checked);
|
||||
return 0;
|
||||
} catch (const std::exception& error) {
|
||||
std::cerr << error.what() << '\n';
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,254 @@
|
||||
#include "prx/libSceAgcDriver/Execution/include/VulkanDevice.hpp"
|
||||
#include "prx/libSceAgcDriver/Graphics/include/Draw.hpp"
|
||||
#include "Recompiler.hpp"
|
||||
#include "VulkanTestDevice.hpp"
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
#include <iostream>
|
||||
#include <optional>
|
||||
#include <span>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace {
|
||||
|
||||
using AgcDriver::Graphics::Require;
|
||||
using ShaderRecompiler::ShaderStage;
|
||||
|
||||
constexpr std::uint32_t Threads = 64;
|
||||
constexpr std::uint32_t Inputs = 4;
|
||||
constexpr std::uint32_t Results = 4;
|
||||
alignas(256) std::array<std::uint32_t, Threads * Inputs> Input{};
|
||||
alignas(256) std::array<std::uint32_t, Threads * Results> Output{};
|
||||
|
||||
alignas(256) constexpr std::array<std::uint32_t, 11> Code{
|
||||
0x34020084u, 0xe0381000u, 0x80000401u, 0xbf8c3f70u, 0x7e144104u, 0x7e164904u, 0x7e184504u, 0x7e1a8104u,
|
||||
0xe0781000u, 0x80010a01u, 0xbf810000u,
|
||||
};
|
||||
|
||||
constexpr const char* Names[Results] = {"v_fract_f32", "v_floor_f32", "v_ceil_f32", "v_frexp_mant_f32"};
|
||||
|
||||
constexpr std::uint32_t Values[Threads] = {
|
||||
0x00000000u, 0x00000001u, 0x00000002u, 0x00000003u, 0x00400000u, 0x007ffffeu, 0x007fffffu, 0x00800000u,
|
||||
0x00800001u, 0x00ffffffu, 0x01000000u, 0x0c000000u, 0x33ffffffu, 0x34000000u, 0x3effffffu, 0x3f000000u,
|
||||
0x3f7fffffu, 0x3f800000u, 0x3fc00000u, 0x40490fdbu, 0x4b000000u, 0x4b7fffffu, 0x7f7fffffu, 0x7f800000u,
|
||||
0x7fc00000u, 0x7fc12345u, 0x80000000u, 0x80000001u, 0x80000002u, 0x80000003u, 0x80400000u, 0x807ffffeu,
|
||||
0x807fffffu, 0x80800000u, 0x80800001u, 0x80ffffffu, 0x81000000u, 0x8c000000u, 0xb3ffffffu, 0xb4000000u,
|
||||
0xbeffffffu, 0xbf000000u, 0xbf7fffffu, 0xbf800000u, 0xbfc00000u, 0xc0490fdbu, 0xcb000000u, 0xcb7fffffu,
|
||||
0xff7fffffu, 0xff800000u, 0xffc00000u, 0xffc12345u, 0x804fbb3fu, 0x805ef2e1u, 0x0065c8e8u, 0x806b9087u,
|
||||
0x0063529du, 0x0053119au, 0x007350b6u, 0x800e7d89u, 0x003c0a75u, 0x0030bcadu, 0x004976e8u, 0x0001adbau
|
||||
};
|
||||
constexpr std::uint32_t Mode1Expected[Threads][Results] = {
|
||||
{0x00000000u, 0x00000000u, 0x00000000u, 0x00000000u},
|
||||
{0x00000000u, 0x00000000u, 0x3f800000u, 0x3f000000u},
|
||||
{0x00000000u, 0x00000000u, 0x3f800000u, 0x3f000000u},
|
||||
{0x00000000u, 0x00000000u, 0x3f800000u, 0x3f400000u},
|
||||
{0x00000000u, 0x00000000u, 0x3f800000u, 0x3f000000u},
|
||||
{0x00000000u, 0x00000000u, 0x3f800000u, 0x3f7ffffcu},
|
||||
{0x00000000u, 0x00000000u, 0x3f800000u, 0x3f7ffffeu},
|
||||
{0x00800000u, 0x00000000u, 0x3f800000u, 0x3f000000u},
|
||||
{0x00800001u, 0x00000000u, 0x3f800000u, 0x3f000001u},
|
||||
{0x00ffffffu, 0x00000000u, 0x3f800000u, 0x3f7fffffu},
|
||||
{0x01000000u, 0x00000000u, 0x3f800000u, 0x3f000000u},
|
||||
{0x0c000000u, 0x00000000u, 0x3f800000u, 0x3f000000u},
|
||||
{0x33ffffffu, 0x00000000u, 0x3f800000u, 0x3f7fffffu},
|
||||
{0x34000000u, 0x00000000u, 0x3f800000u, 0x3f000000u},
|
||||
{0x3effffffu, 0x00000000u, 0x3f800000u, 0x3f7fffffu},
|
||||
{0x3f000000u, 0x00000000u, 0x3f800000u, 0x3f000000u},
|
||||
{0x3f7fffffu, 0x00000000u, 0x3f800000u, 0x3f7fffffu},
|
||||
{0x00000000u, 0x3f800000u, 0x3f800000u, 0x3f000000u},
|
||||
{0x3f000000u, 0x3f800000u, 0x40000000u, 0x3f400000u},
|
||||
{0x3e10fdb0u, 0x40400000u, 0x40800000u, 0x3f490fdbu},
|
||||
{0x00000000u, 0x4b000000u, 0x4b000000u, 0x3f000000u},
|
||||
{0x00000000u, 0x4b7fffffu, 0x4b7fffffu, 0x3f7fffffu},
|
||||
{0x00000000u, 0x7f7fffffu, 0x7f7fffffu, 0x3f7fffffu},
|
||||
{0xffc00000u, 0x7f800000u, 0x7f800000u, 0x7f800000u},
|
||||
{0x7fc00000u, 0x7fc00000u, 0x7fc00000u, 0x7fc00000u},
|
||||
{0x7fc12345u, 0x7fc12345u, 0x7fc12345u, 0x7fc12345u},
|
||||
{0x00000000u, 0x80000000u, 0x80000000u, 0x80000000u},
|
||||
{0x3f7fffffu, 0xbf800000u, 0x80000000u, 0xbf000000u},
|
||||
{0x3f7fffffu, 0xbf800000u, 0x80000000u, 0xbf000000u},
|
||||
{0x3f7fffffu, 0xbf800000u, 0x80000000u, 0xbf400000u},
|
||||
{0x3f7fffffu, 0xbf800000u, 0x80000000u, 0xbf000000u},
|
||||
{0x3f7fffffu, 0xbf800000u, 0x80000000u, 0xbf7ffffcu},
|
||||
{0x3f7fffffu, 0xbf800000u, 0x80000000u, 0xbf7ffffeu},
|
||||
{0x3f7fffffu, 0xbf800000u, 0x80000000u, 0xbf000000u},
|
||||
{0x3f7fffffu, 0xbf800000u, 0x80000000u, 0xbf000001u},
|
||||
{0x3f7fffffu, 0xbf800000u, 0x80000000u, 0xbf7fffffu},
|
||||
{0x3f7fffffu, 0xbf800000u, 0x80000000u, 0xbf000000u},
|
||||
{0x3f7fffffu, 0xbf800000u, 0x80000000u, 0xbf000000u},
|
||||
{0x3f7ffffeu, 0xbf800000u, 0x80000000u, 0xbf7fffffu},
|
||||
{0x3f7ffffeu, 0xbf800000u, 0x80000000u, 0xbf000000u},
|
||||
{0x3f000000u, 0xbf800000u, 0x80000000u, 0xbf7fffffu},
|
||||
{0x3f000000u, 0xbf800000u, 0x80000000u, 0xbf000000u},
|
||||
{0x33800000u, 0xbf800000u, 0x80000000u, 0xbf7fffffu},
|
||||
{0x00000000u, 0xbf800000u, 0xbf800000u, 0xbf000000u},
|
||||
{0x3f000000u, 0xc0000000u, 0xbf800000u, 0xbf400000u},
|
||||
{0x3f5bc094u, 0xc0800000u, 0xc0400000u, 0xbf490fdbu},
|
||||
{0x00000000u, 0xcb000000u, 0xcb000000u, 0xbf000000u},
|
||||
{0x00000000u, 0xcb7fffffu, 0xcb7fffffu, 0xbf7fffffu},
|
||||
{0x00000000u, 0xff7fffffu, 0xff7fffffu, 0xbf7fffffu},
|
||||
{0xffc00000u, 0xff800000u, 0xff800000u, 0xff800000u},
|
||||
{0xffc00000u, 0xffc00000u, 0xffc00000u, 0xffc00000u},
|
||||
{0xffc12345u, 0xffc12345u, 0xffc12345u, 0xffc12345u},
|
||||
{0x3f7fffffu, 0xbf800000u, 0x80000000u, 0xbf1f767eu},
|
||||
{0x3f7fffffu, 0xbf800000u, 0x80000000u, 0xbf3de5c2u},
|
||||
{0x00000000u, 0x00000000u, 0x3f800000u, 0x3f4b91d0u},
|
||||
{0x3f7fffffu, 0xbf800000u, 0x80000000u, 0xbf57210eu},
|
||||
{0x00000000u, 0x00000000u, 0x3f800000u, 0x3f46a53au},
|
||||
{0x00000000u, 0x00000000u, 0x3f800000u, 0x3f262334u},
|
||||
{0x00000000u, 0x00000000u, 0x3f800000u, 0x3f66a16cu},
|
||||
{0x3f7fffffu, 0xbf800000u, 0x80000000u, 0xbf67d890u},
|
||||
{0x00000000u, 0x00000000u, 0x3f800000u, 0x3f7029d4u},
|
||||
{0x00000000u, 0x00000000u, 0x3f800000u, 0x3f42f2b4u},
|
||||
{0x00000000u, 0x00000000u, 0x3f800000u, 0x3f12edd0u},
|
||||
{0x00000000u, 0x00000000u, 0x3f800000u, 0x3f56dd00u}
|
||||
};
|
||||
constexpr std::uint32_t Mode2Expected[Threads][Results] = {
|
||||
{0x00000000u, 0x00000000u, 0x00000000u, 0x00000000u},
|
||||
{0x00000000u, 0x00000000u, 0x00000000u, 0x00000000u},
|
||||
{0x00000000u, 0x00000000u, 0x00000000u, 0x00000000u},
|
||||
{0x00000000u, 0x00000000u, 0x00000000u, 0x00000000u},
|
||||
{0x00000000u, 0x00000000u, 0x00000000u, 0x00000000u},
|
||||
{0x00000000u, 0x00000000u, 0x00000000u, 0x00000000u},
|
||||
{0x00000000u, 0x00000000u, 0x00000000u, 0x00000000u},
|
||||
{0x00800000u, 0x00000000u, 0x3f800000u, 0x3f000000u},
|
||||
{0x00800001u, 0x00000000u, 0x3f800000u, 0x3f000001u},
|
||||
{0x00ffffffu, 0x00000000u, 0x3f800000u, 0x3f7fffffu},
|
||||
{0x01000000u, 0x00000000u, 0x3f800000u, 0x3f000000u},
|
||||
{0x0c000000u, 0x00000000u, 0x3f800000u, 0x3f000000u},
|
||||
{0x33ffffffu, 0x00000000u, 0x3f800000u, 0x3f7fffffu},
|
||||
{0x34000000u, 0x00000000u, 0x3f800000u, 0x3f000000u},
|
||||
{0x3effffffu, 0x00000000u, 0x3f800000u, 0x3f7fffffu},
|
||||
{0x3f000000u, 0x00000000u, 0x3f800000u, 0x3f000000u},
|
||||
{0x3f7fffffu, 0x00000000u, 0x3f800000u, 0x3f7fffffu},
|
||||
{0x00000000u, 0x3f800000u, 0x3f800000u, 0x3f000000u},
|
||||
{0x3f000000u, 0x3f800000u, 0x40000000u, 0x3f400000u},
|
||||
{0x3e10fdb0u, 0x40400000u, 0x40800000u, 0x3f490fdbu},
|
||||
{0x00000000u, 0x4b000000u, 0x4b000000u, 0x3f000000u},
|
||||
{0x00000000u, 0x4b7fffffu, 0x4b7fffffu, 0x3f7fffffu},
|
||||
{0x00000000u, 0x7f7fffffu, 0x7f7fffffu, 0x3f7fffffu},
|
||||
{0xffc00000u, 0x7f800000u, 0x7f800000u, 0x7f800000u},
|
||||
{0x7fc00000u, 0x7fc00000u, 0x7fc00000u, 0x7fc00000u},
|
||||
{0x7fc12345u, 0x7fc12345u, 0x7fc12345u, 0x7fc12345u},
|
||||
{0x00000000u, 0x80000000u, 0x80000000u, 0x80000000u},
|
||||
{0x00000000u, 0x80000000u, 0x80000000u, 0x80000000u},
|
||||
{0x00000000u, 0x80000000u, 0x80000000u, 0x80000000u},
|
||||
{0x00000000u, 0x80000000u, 0x80000000u, 0x80000000u},
|
||||
{0x00000000u, 0x80000000u, 0x80000000u, 0x80000000u},
|
||||
{0x00000000u, 0x80000000u, 0x80000000u, 0x80000000u},
|
||||
{0x00000000u, 0x80000000u, 0x80000000u, 0x80000000u},
|
||||
{0x3f7fffffu, 0xbf800000u, 0x80000000u, 0xbf000000u},
|
||||
{0x3f7fffffu, 0xbf800000u, 0x80000000u, 0xbf000001u},
|
||||
{0x3f7fffffu, 0xbf800000u, 0x80000000u, 0xbf7fffffu},
|
||||
{0x3f7fffffu, 0xbf800000u, 0x80000000u, 0xbf000000u},
|
||||
{0x3f7fffffu, 0xbf800000u, 0x80000000u, 0xbf000000u},
|
||||
{0x3f7ffffeu, 0xbf800000u, 0x80000000u, 0xbf7fffffu},
|
||||
{0x3f7ffffeu, 0xbf800000u, 0x80000000u, 0xbf000000u},
|
||||
{0x3f000000u, 0xbf800000u, 0x80000000u, 0xbf7fffffu},
|
||||
{0x3f000000u, 0xbf800000u, 0x80000000u, 0xbf000000u},
|
||||
{0x33800000u, 0xbf800000u, 0x80000000u, 0xbf7fffffu},
|
||||
{0x00000000u, 0xbf800000u, 0xbf800000u, 0xbf000000u},
|
||||
{0x3f000000u, 0xc0000000u, 0xbf800000u, 0xbf400000u},
|
||||
{0x3f5bc094u, 0xc0800000u, 0xc0400000u, 0xbf490fdbu},
|
||||
{0x00000000u, 0xcb000000u, 0xcb000000u, 0xbf000000u},
|
||||
{0x00000000u, 0xcb7fffffu, 0xcb7fffffu, 0xbf7fffffu},
|
||||
{0x00000000u, 0xff7fffffu, 0xff7fffffu, 0xbf7fffffu},
|
||||
{0xffc00000u, 0xff800000u, 0xff800000u, 0xff800000u},
|
||||
{0xffc00000u, 0xffc00000u, 0xffc00000u, 0xffc00000u},
|
||||
{0xffc12345u, 0xffc12345u, 0xffc12345u, 0xffc12345u},
|
||||
{0x00000000u, 0x80000000u, 0x80000000u, 0x80000000u},
|
||||
{0x00000000u, 0x80000000u, 0x80000000u, 0x80000000u},
|
||||
{0x00000000u, 0x00000000u, 0x00000000u, 0x00000000u},
|
||||
{0x00000000u, 0x80000000u, 0x80000000u, 0x80000000u},
|
||||
{0x00000000u, 0x00000000u, 0x00000000u, 0x00000000u},
|
||||
{0x00000000u, 0x00000000u, 0x00000000u, 0x00000000u},
|
||||
{0x00000000u, 0x00000000u, 0x00000000u, 0x00000000u},
|
||||
{0x00000000u, 0x80000000u, 0x80000000u, 0x80000000u},
|
||||
{0x00000000u, 0x00000000u, 0x00000000u, 0x00000000u},
|
||||
{0x00000000u, 0x00000000u, 0x00000000u, 0x00000000u},
|
||||
{0x00000000u, 0x00000000u, 0x00000000u, 0x00000000u},
|
||||
{0x00000000u, 0x00000000u, 0x00000000u, 0x00000000u}
|
||||
};
|
||||
|
||||
std::array<std::uint32_t, 4> BufferDescriptor(const void* data, std::uint32_t bytes) {
|
||||
const auto address = reinterpret_cast<std::uintptr_t>(data);
|
||||
return {static_cast<std::uint32_t>(address), static_cast<std::uint32_t>((address >> 32u) & 0xffffu), bytes, 0x31016facu};
|
||||
}
|
||||
|
||||
std::string Hex(std::uint32_t value) {
|
||||
char text[16];
|
||||
std::snprintf(text, sizeof(text), "0x%08x", value);
|
||||
return text;
|
||||
}
|
||||
|
||||
std::optional<std::string> Run(AgcDriver::VulkanDevice& device, ShaderRecompiler::ShaderFloatMode floatMode) {
|
||||
Input.fill(0u);
|
||||
for (std::uint32_t tid = 0; tid < Threads; ++tid) Input[tid * Inputs] = Values[tid];
|
||||
Output.fill(0xdeadbeefu);
|
||||
std::vector<std::uint32_t> userData(8, 0u);
|
||||
const auto input = BufferDescriptor(Input.data(), static_cast<std::uint32_t>(Input.size() * 4u));
|
||||
const auto output = BufferDescriptor(Output.data(), static_cast<std::uint32_t>(Output.size() * 4u));
|
||||
std::copy(input.begin(), input.end(), userData.begin());
|
||||
std::copy(output.begin(), output.end(), userData.begin() + 4);
|
||||
const std::span<const std::uint32_t> code(Code);
|
||||
const std::array<ShaderRecompiler::MemoryRegion, 1> memory{{{reinterpret_cast<std::uintptr_t>(code.data()), std::as_bytes(code)}}};
|
||||
const ShaderRecompiler::ShaderComputeStageInfo compute{{Threads, 1, 1}, 0, {false, false, false}, false, 1};
|
||||
ShaderRecompiler::RecompileRequest request{
|
||||
{ShaderStage::Compute, reinterpret_cast<std::uintptr_t>(code.data()), code, 0, {}},
|
||||
{32, 0, userData, compute, std::nullopt, std::nullopt, memory},
|
||||
device.Target(),
|
||||
{0, 0, 0, 128}
|
||||
};
|
||||
request.useCache = false;
|
||||
request.context.floatMode = floatMode;
|
||||
std::optional<decltype(ShaderRecompiler::Recompile(request))> result;
|
||||
try {
|
||||
result.emplace(ShaderRecompiler::Recompile(request));
|
||||
} catch (const std::exception& error) {
|
||||
return std::string(error.what());
|
||||
}
|
||||
device.Dispatch(*result, 1, 1, 1, {}, reinterpret_cast<std::uintptr_t>(code.data()));
|
||||
device.WaitIdle();
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
void Check(std::uint32_t denormals, bool ieee) {
|
||||
const auto& expected = denormals == 1u ? Mode1Expected : Mode2Expected;
|
||||
for (std::uint32_t tid = 0; tid < Threads; ++tid) {
|
||||
for (std::uint32_t i = 0; i < Results; ++i) {
|
||||
const std::uint32_t actual = Output[tid * Results + i];
|
||||
Require(actual == expected[tid][i], std::string(Names[i]) + " f32 denormal mode " + std::to_string(denormals) + (ieee ? ", IEEE=1" : ", IEEE=0") + " of " + Hex(Values[tid]) + " is " + Hex(actual) + ", expected " + Hex(expected[tid][i]));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
int main() {
|
||||
try {
|
||||
const auto device = OpenVulkanTestDevice();
|
||||
if (!device) return VulkanTestSkipped;
|
||||
const bool keepsDenormals = device->Target().float32DenormPreserve;
|
||||
std::uint32_t checked = 0u;
|
||||
for (const std::uint32_t denormals : {1u, 2u}) {
|
||||
for (const bool ieee : {false, true}) {
|
||||
const ShaderRecompiler::ShaderFloatMode floatMode{0xc0u | denormals << 4u, true, ieee, false};
|
||||
const auto refusal = Run(*device, floatMode);
|
||||
if (refusal) {
|
||||
Require(denormals == 1u && !keepsDenormals && refusal->find("needs DenormPreserve 32") != std::string::npos, "FLOAT_MODE " + Hex(floatMode.floatMode) + ": " + *refusal);
|
||||
continue;
|
||||
}
|
||||
++checked;
|
||||
Check(denormals, ieee);
|
||||
}
|
||||
}
|
||||
std::printf("f32 fract, floor, ceil and frexp_mant denormal mode 1 and 2 tests passed (%u of 4 modes run; the others need DenormPreserve 32)\n", checked);
|
||||
return 0;
|
||||
} catch (const std::exception& error) {
|
||||
std::cerr << error.what() << '\n';
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
#include "prx/libSceAgcDriver/Graphics/include/Resources.hpp"
|
||||
#include "prx/libSceAgcDriver/Graphics/include/TextureDetiler.hpp"
|
||||
#include "prx/libSceAgcDriver/Graphics/include/TextureTiling.hpp"
|
||||
#include "VulkanTestDevice.hpp"
|
||||
#include <array>
|
||||
#include <bit>
|
||||
#include <cstdint>
|
||||
#include <cstring>
|
||||
#include <iostream>
|
||||
#include <string>
|
||||
|
||||
namespace AgcDriver {
|
||||
|
||||
struct VulkanDeviceTestAccess {
|
||||
static Graphics::Context ContextOf(const VulkanDevice& device) { return device.graphicsContext(); }
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
namespace {
|
||||
|
||||
using namespace AgcDriver::Graphics;
|
||||
|
||||
std::uint32_t parity(std::uint32_t mask, std::uint32_t x, std::uint32_t y) {
|
||||
return static_cast<std::uint32_t>(std::popcount((x & mask & 0xfffu) ^ ((y << 12u) & mask & 0xfff000u))) & 1u;
|
||||
}
|
||||
|
||||
std::uint8_t elementByte(std::uint32_t x, std::uint32_t y, std::uint32_t byte) {
|
||||
return static_cast<std::uint8_t>(x * 7u + y * 13u + byte * 101u + (x >> 4u) * 3u + (y >> 3u) * 5u);
|
||||
}
|
||||
|
||||
void detile(const Context& context, TextureDetiler& detiler, TextureTileMode mode, std::uint32_t bytes) {
|
||||
constexpr std::array<std::uint32_t, 5> formats{1u, 7u, 20u, 62u, 75u};
|
||||
const auto geometry = GcnTiling(mode, bytes);
|
||||
const auto width = geometry.blockWidth * 2u;
|
||||
const auto height = geometry.blockHeight * 2u;
|
||||
const auto mip = ComputeGcnMipLayout(mode, formats[std::countr_zero(bytes)], width, height, width, false, 1u).front();
|
||||
const auto what = "PS4 tile mode " + std::to_string(static_cast<int>(mode)) + " at " + std::to_string(bytes) + " bytes";
|
||||
Buffer tiled(context, static_cast<std::size_t>(mip.tiledSize), VK_BUFFER_USAGE_STORAGE_BUFFER_BIT);
|
||||
Buffer linear(context, static_cast<std::size_t>(mip.linearSize), VK_BUFFER_USAGE_STORAGE_BUFFER_BIT);
|
||||
std::memset(tiled.Bytes().data(), 0, tiled.Bytes().size());
|
||||
std::memset(linear.Bytes().data(), 0xcd, linear.Bytes().size());
|
||||
for (std::uint32_t y = 0; y < height; ++y) {
|
||||
for (std::uint32_t x = 0; x < width; ++x) {
|
||||
std::uint32_t inBlock = 0, split = 0;
|
||||
for (std::uint32_t bit = 0; bit < 16u; ++bit) inBlock |= parity(geometry.equation[bit], x, y) << bit;
|
||||
for (std::uint32_t bit = 0; bit < 4u; ++bit) split |= parity(geometry.splitMasks[bit], x, y) << bit;
|
||||
const auto block = static_cast<std::uint64_t>(y / geometry.blockHeight) * mip.blocksPerRow + x / geometry.blockWidth;
|
||||
const auto offset = block * geometry.blockBytes + inBlock + static_cast<std::uint64_t>(split) * mip.gcnSplitStride;
|
||||
Require(offset + bytes <= tiled.Bytes().size(), what + ": an element lies outside the tiled surface");
|
||||
for (std::uint32_t byte = 0; byte < bytes; ++byte) tiled.Bytes()[offset + byte] = static_cast<std::byte>(elementByte(x, y, byte));
|
||||
}
|
||||
}
|
||||
CommandBatch batch(context);
|
||||
detiler.BeginBatch();
|
||||
detiler.Dispatch(batch.Handle(), mode, bytes, tiled.Handle(), 0, linear.Handle(), 0, mip);
|
||||
const VkMemoryBarrier toHost{VK_STRUCTURE_TYPE_MEMORY_BARRIER, nullptr, VK_ACCESS_SHADER_WRITE_BIT, VK_ACCESS_HOST_READ_BIT};
|
||||
context.Function<PFN_vkCmdPipelineBarrier>("vkCmdPipelineBarrier")(batch.Handle(), VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_HOST_BIT, 0, 1, &toHost, 0, nullptr, 0, nullptr);
|
||||
batch.SubmitAndWait();
|
||||
for (std::uint32_t y = 0; y < height; ++y) {
|
||||
for (std::uint32_t x = 0; x < width; ++x) {
|
||||
for (std::uint32_t byte = 0; byte < bytes; ++byte) {
|
||||
const auto got = static_cast<std::uint8_t>(linear.Bytes()[static_cast<std::size_t>(y) * mip.pitchBytes + static_cast<std::size_t>(x) * bytes + byte]);
|
||||
if (got != elementByte(x, y, byte)) Require(false, what + ": element " + std::to_string(x) + "," + std::to_string(y) + " byte " + std::to_string(byte) + " detiled as " + std::to_string(got) + ", expected " + std::to_string(elementByte(x, y, byte)));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
int main() {
|
||||
try {
|
||||
auto device = OpenVulkanTestDevice();
|
||||
if (!device) return VulkanTestSkipped;
|
||||
{
|
||||
const auto context = AgcDriver::VulkanDeviceTestAccess::ContextOf(*device);
|
||||
TextureDetiler detiler(context);
|
||||
using enum TextureTileMode;
|
||||
for (const auto mode : {kGcnThin1D, kGcnDisplay1D, kGcnDisplay2D, kGcnThin2D, kGcnDepth2D64, kGcnDepth2D256, kGcnDepth2D1K, kGcnDisplayPrt, kGcnThin2DPrt, kGcnDepthPrt256}) {
|
||||
for (std::uint32_t bytes = 1u; bytes <= 16u; bytes <<= 1u) detile(context, detiler, mode, bytes);
|
||||
}
|
||||
}
|
||||
device.reset();
|
||||
std::puts("PS4 detile tests passed");
|
||||
return 0;
|
||||
} catch (const std::exception& error) {
|
||||
std::cerr << error.what() << '\n';
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
@@ -43,6 +43,10 @@ alignas(256) constexpr std::array<std::uint32_t, 12> StoreCode{
|
||||
0x34020084, 0xe0381000, 0x80001401, 0xbf8c3f70, 0x7e3c0300, 0x7e3e0280, 0xf0201f08, 0x0001141e,
|
||||
0x7e3e0281, 0xf0201508, 0x0001141e, 0xbf810000,
|
||||
};
|
||||
alignas(256) constexpr std::array<std::uint32_t, 12> StoreD16Code{
|
||||
0x34020084, 0xe0381000, 0x80001401, 0xbf8c3f70, 0x7e3c0300, 0x7e3e0280, 0xf0201f08, 0x8001141e,
|
||||
0x7e3e0281, 0xf0201508, 0x8001141e, 0xbf810000,
|
||||
};
|
||||
|
||||
struct Format {
|
||||
const char* name;
|
||||
@@ -141,28 +145,35 @@ std::array<std::uint32_t, 8> TextureDescriptor(const void* data, const Format& f
|
||||
((Width - 1u) >> 2u) | ((Height - 1u) << 14u), (format.components == 2u ? TwoChannelSwizzle : IdentitySwizzle) | (Type2D << 28u), 0u, 0u, 0u, 0u};
|
||||
}
|
||||
|
||||
void Store(AgcDriver::VulkanDevice& device, std::uint8_t* texels, const Format& format) {
|
||||
std::uint16_t Half(std::uint32_t tid, std::uint32_t component) {
|
||||
return HalfTowardZero(Value(tid, component));
|
||||
}
|
||||
|
||||
void Store(AgcDriver::VulkanDevice& device, std::uint8_t* texels, const Format& format, bool d16) {
|
||||
for (std::uint32_t tid = 0; tid < Threads; ++tid) {
|
||||
for (std::uint32_t component = 0; component < 4u; ++component) Input[tid * 4u + component] = Value(tid, component);
|
||||
for (std::uint32_t component = 0; component < 4u; ++component) {
|
||||
Input[tid * 4u + component] = d16 ? component < 2u ? static_cast<std::uint32_t>(Half(tid, component * 2u)) | (static_cast<std::uint32_t>(Half(tid, component * 2u + 1u)) << 16u) : 0u : Value(tid, component);
|
||||
}
|
||||
}
|
||||
const auto& storeCode = d16 ? StoreD16Code : StoreCode;
|
||||
std::fill(texels, texels + TexelBytes, 0x5au);
|
||||
std::vector<std::uint32_t> userData(16, 0u);
|
||||
const auto buffer = BufferDescriptor(Input.data(), static_cast<std::uint32_t>(Input.size() * sizeof(Input[0])));
|
||||
const auto texture = TextureDescriptor(texels, format);
|
||||
std::copy(buffer.begin(), buffer.end(), userData.begin());
|
||||
std::copy(texture.begin(), texture.end(), userData.begin() + 4);
|
||||
const std::span<const std::uint32_t> code(StoreCode);
|
||||
const std::array<ShaderRecompiler::MemoryRegion, 1> memory{{{reinterpret_cast<std::uintptr_t>(StoreCode.data()), std::as_bytes(code)}}};
|
||||
const std::span<const std::uint32_t> code(storeCode);
|
||||
const std::array<ShaderRecompiler::MemoryRegion, 1> memory{{{reinterpret_cast<std::uintptr_t>(storeCode.data()), std::as_bytes(code)}}};
|
||||
const ShaderRecompiler::ShaderComputeStageInfo compute{{Threads, 1, 1}, 0u, {false, false, false}, false, 1};
|
||||
ShaderRecompiler::RecompileRequest request{
|
||||
{ShaderStage::Compute, reinterpret_cast<std::uintptr_t>(StoreCode.data()), code, 0, {}},
|
||||
{ShaderStage::Compute, reinterpret_cast<std::uintptr_t>(storeCode.data()), code, 0, {}},
|
||||
{32, 0, userData, compute, std::nullopt, std::nullopt, memory},
|
||||
device.Target(),
|
||||
{0, 0, 0, 128}
|
||||
};
|
||||
request.useCache = false;
|
||||
const auto result = ShaderRecompiler::Recompile(request);
|
||||
device.Dispatch(result, 1, 1, 1, {}, reinterpret_cast<std::uintptr_t>(StoreCode.data()));
|
||||
device.Dispatch(result, 1, 1, 1, {}, reinterpret_cast<std::uintptr_t>(storeCode.data()));
|
||||
device.WaitIdle();
|
||||
AgcDriver::Graphics::StorageTexture::FlushPending(reinterpret_cast<std::uintptr_t>(texels), TexelBytes, nullptr, "test");
|
||||
device.WaitIdle();
|
||||
@@ -172,10 +183,10 @@ std::uint16_t ExpectedComponent(std::uint32_t tid, std::uint32_t dmask, std::uin
|
||||
if (((dmask >> component) & 1u) == 0u) return 0u;
|
||||
std::uint32_t source = 0u;
|
||||
for (std::uint32_t lower = 0u; lower < component; ++lower) source += (dmask >> lower) & 1u;
|
||||
return HalfTowardZero(Value(tid, source));
|
||||
return Half(tid, source);
|
||||
}
|
||||
|
||||
void Check(const std::uint8_t* texels, const Format& format) {
|
||||
void Check(const std::uint8_t* texels, const Format& format, bool d16) {
|
||||
for (std::uint32_t y = 0; y < Height; ++y) {
|
||||
for (std::uint32_t x = 0; x < Width; ++x) {
|
||||
const auto offset = TexelOffset(format, x, y);
|
||||
@@ -184,7 +195,7 @@ void Check(const std::uint8_t* texels, const Format& format) {
|
||||
std::memcpy(&actual, texels + offset + component * sizeof(actual), sizeof(actual));
|
||||
const auto dmask = y == Writes[0].row ? Writes[0].dmask : y == Writes[1].row ? Writes[1].dmask : 0u;
|
||||
const auto expected = dmask != 0u ? ExpectedComponent(x, dmask, component) : 0x5a5au;
|
||||
Require(actual == expected, std::string("image_store of ") + format.name + ": texel (" + std::to_string(x) + ", " + std::to_string(y) + ") component " + std::to_string(component) + " is " + std::to_string(actual) + ", expected " + std::to_string(expected));
|
||||
Require(actual == expected, std::string(d16 ? "D16 image_store of " : "image_store of ") + format.name + ": texel (" + std::to_string(x) + ", " + std::to_string(y) + ") component " + std::to_string(component) + " is " + std::to_string(actual) + ", expected " + std::to_string(expected));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -197,9 +208,11 @@ int main() {
|
||||
const auto device = OpenVulkanTestDevice();
|
||||
if (!device) return VulkanTestSkipped;
|
||||
GuestBlock block;
|
||||
for (const auto& format : Formats) {
|
||||
Store(*device, block.Data(), format);
|
||||
Check(block.Data(), format);
|
||||
for (const bool d16 : {false, true}) {
|
||||
for (const auto& format : Formats) {
|
||||
Store(*device, block.Data(), format, d16);
|
||||
Check(block.Data(), format, d16);
|
||||
}
|
||||
}
|
||||
std::puts("image store float rounding tests passed");
|
||||
return 0;
|
||||
|
||||
@@ -0,0 +1,176 @@
|
||||
#include "prx/libSceAgcDriver/Execution/include/VulkanDevice.hpp"
|
||||
#include "prx/libSceAgcDriver/Graphics/include/Draw.hpp"
|
||||
#include "Recompiler.hpp"
|
||||
#include "VulkanTestDevice.hpp"
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
#include <iostream>
|
||||
#include <span>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace {
|
||||
|
||||
using AgcDriver::Graphics::Require;
|
||||
using ShaderRecompiler::ShaderStage;
|
||||
|
||||
constexpr std::uint32_t Width = 64;
|
||||
constexpr std::uint32_t Height = 32;
|
||||
constexpr std::uint32_t IdentitySelect = 0xfacu;
|
||||
constexpr std::uint32_t NoLocation = 0x280u;
|
||||
constexpr std::byte Background{0x40};
|
||||
constexpr std::byte Covered{0xff};
|
||||
alignas(256) std::array<std::byte, Width * Height * 4> Pixels{};
|
||||
alignas(256) std::array<std::uint32_t, 24> Output{};
|
||||
|
||||
alignas(256) constexpr std::array<std::uint32_t, 7> VertexCode{
|
||||
0xbe822100, 0x34020a84, 0xe0781000, 0x80010801, 0xf80008cf, 0x0b0a0908, 0xbf810000,
|
||||
};
|
||||
|
||||
alignas(256) constexpr std::array<std::uint32_t, 4> PixelCode{
|
||||
0x7e0e02f2, 0xf800180f, 0x07070707, 0xbf810000,
|
||||
};
|
||||
|
||||
alignas(256) constexpr std::array<std::array<float, 4>, 6> Vertices{{
|
||||
{-0.75f, -0.75f, 0.5f, 1.0f}, {-0.25f, -0.75f, 0.5f, 1.0f}, {-0.5f, 0.75f, 0.5f, 1.0f},
|
||||
{0.25f, -0.75f, 0.5f, 1.0f}, {0.75f, -0.75f, 0.5f, 1.0f}, {0.5f, 0.75f, 0.5f, 1.0f},
|
||||
}};
|
||||
|
||||
alignas(256) constexpr std::array<std::uint16_t, 10> Indices{0, 0xffff, 3, 4, 5, 0, 1, 2, 3, 4};
|
||||
|
||||
alignas(256) constexpr std::array<std::uint32_t, 10> IndirectRecords{
|
||||
4u, 1u, 1u, 0u, 0u,
|
||||
5u, 1u, 5u, 0u, 0u,
|
||||
};
|
||||
|
||||
std::array<std::uint32_t, 4> VertexBufferDescriptor() {
|
||||
const auto address = reinterpret_cast<std::uintptr_t>(Vertices.data());
|
||||
return {static_cast<std::uint32_t>(address), static_cast<std::uint32_t>((address >> 32u) & 0xffffu) | (16u << 16u), static_cast<std::uint32_t>(Vertices.size()), 0x0104d000u | IdentitySelect};
|
||||
}
|
||||
|
||||
std::array<std::uint32_t, 4> OutputDescriptor() {
|
||||
const auto address = reinterpret_cast<std::uintptr_t>(Output.data());
|
||||
return {static_cast<std::uint32_t>(address), static_cast<std::uint32_t>((address >> 32u) & 0xffffu), static_cast<std::uint32_t>(sizeof(Output)), 0x31016facu};
|
||||
}
|
||||
|
||||
std::vector<std::uint32_t> UserData() {
|
||||
std::vector<std::uint32_t> userData(12, 0u);
|
||||
userData[0] = 0x10000000u;
|
||||
userData[1] = 0x00000001u;
|
||||
const auto output = OutputDescriptor();
|
||||
std::copy(output.begin(), output.end(), userData.begin() + 4);
|
||||
return userData;
|
||||
}
|
||||
|
||||
void Draw(AgcDriver::VulkanDevice& device, const AgcDriver::Pm4::DrawParameters& draw) {
|
||||
Pixels.fill(Background);
|
||||
Output.fill(0xdeadbeefu);
|
||||
const auto userData = UserData();
|
||||
ShaderRecompiler::ShaderVertexStageInfo info{};
|
||||
info.resourcesNum = 1;
|
||||
info.resources[0].fields = VertexBufferDescriptor();
|
||||
info.resourcesDst[0] = {8, 4, 0, 0};
|
||||
info.fetchAttribReg = 8;
|
||||
info.fetchBufferReg = 10;
|
||||
info.fetchEmbedded = true;
|
||||
const std::array<ShaderRecompiler::MemoryRegion, 1> vertexMemory{{{reinterpret_cast<std::uintptr_t>(VertexCode.data()), std::as_bytes(std::span(VertexCode))}}};
|
||||
ShaderRecompiler::RecompileRequest vertex{
|
||||
{ShaderStage::Vertex, reinterpret_cast<std::uintptr_t>(VertexCode.data()), VertexCode, 0, {}},
|
||||
{64u, 0, userData, std::nullopt, std::nullopt, info, vertexMemory},
|
||||
device.Target(),
|
||||
{0, 0, 0, 64}
|
||||
};
|
||||
vertex.useCache = false;
|
||||
const auto vertexResult = ShaderRecompiler::Recompile(vertex);
|
||||
const auto vertexPush = static_cast<std::uint32_t>(vertexResult.pushConstants.size());
|
||||
|
||||
ShaderRecompiler::ShaderPixelStageInfo pixel{};
|
||||
pixel.inputAddr = ShaderRecompiler::PixelInputBit(ShaderRecompiler::PixelInput::PositionX) | ShaderRecompiler::PixelInputBit(ShaderRecompiler::PixelInput::PositionY);
|
||||
pixel.posX = true;
|
||||
pixel.posY = true;
|
||||
pixel.targetOutputMode[0] = 9;
|
||||
pixel.targetExportMapping.fill(0xe4u);
|
||||
const std::vector<std::uint32_t> pixelUserData(8, 0u);
|
||||
const std::array<ShaderRecompiler::MemoryRegion, 1> pixelMemory{{{reinterpret_cast<std::uintptr_t>(PixelCode.data()), std::as_bytes(std::span(PixelCode))}}};
|
||||
ShaderRecompiler::RecompileRequest fragment{
|
||||
{ShaderStage::Fragment, reinterpret_cast<std::uintptr_t>(PixelCode.data()), PixelCode, 0, {}},
|
||||
{64u, 0, pixelUserData, std::nullopt, pixel, std::nullopt, pixelMemory},
|
||||
device.Target(),
|
||||
PixelPushLayout(vertexPush, device.Target())
|
||||
};
|
||||
fragment.useCache = false;
|
||||
const auto pixelResult = ShaderRecompiler::Recompile(fragment);
|
||||
const std::array<AgcDriver::Graphics::CompiledShader, 2> shaders{{
|
||||
{ShaderStage::Vertex, &vertexResult, 0},
|
||||
{ShaderStage::Fragment, &pixelResult, PixelPushOffset(vertexPush, device.Target())}
|
||||
}};
|
||||
|
||||
AgcDriver::Graphics::State state{};
|
||||
state.stages = {AgcDriver::Graphics::ShaderPath::Vertex, 0u, 64u, 64u, std::nullopt, std::nullopt};
|
||||
state.color = {reinterpret_cast<std::uintptr_t>(Pixels.data()), {Width, Height}, VK_FORMAT_R8G8B8A8_UNORM, Pixels.size(), 0xe4u};
|
||||
state.colors = {state.color};
|
||||
state.hasColorTarget = true;
|
||||
state.renderExtent = {Width, Height};
|
||||
state.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST;
|
||||
state.primitiveRestart = true;
|
||||
state.viewport = {0, static_cast<float>(Height), static_cast<float>(Width), -static_cast<float>(Height), 0, 1};
|
||||
state.negativeOneToOne = false;
|
||||
state.scissor = {{0, 0}, {Width, Height}};
|
||||
state.cullMode = VK_CULL_MODE_NONE;
|
||||
state.frontFace = VK_FRONT_FACE_COUNTER_CLOCKWISE;
|
||||
state.blend.colorWriteMask = 15;
|
||||
state.blends = {state.blend};
|
||||
state.blendConstants = {};
|
||||
device.Draw(state, draw, shaders);
|
||||
device.WaitIdle();
|
||||
}
|
||||
|
||||
bool CoveredAt(std::uint32_t x, std::uint32_t y) {
|
||||
const auto* pixel = Pixels.data() + (static_cast<std::size_t>(y) * Width + x) * 4u;
|
||||
const bool covered = std::all_of(pixel, pixel + 4, [](std::byte value) { return value == Covered; });
|
||||
Require(covered || std::all_of(pixel, pixel + 4, [](std::byte value) { return value == Background; }), "pixel " + std::to_string(x) + "," + std::to_string(y) + " is neither the background nor the triangle colour");
|
||||
return covered;
|
||||
}
|
||||
|
||||
void Check(const std::string& what, bool left, bool right) {
|
||||
Require(CoveredAt(16, 20) == left, what + ": the left triangle (0 1 2) is " + (left ? "missing" : "drawn"));
|
||||
Require(CoveredAt(48, 20) == right, what + ": the right triangle (3 4 5) is " + (right ? "missing" : "drawn"));
|
||||
Require(!CoveredAt(32, 24) && !CoveredAt(32, 2), what + ": a pixel between or above the triangles was drawn");
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
int main() {
|
||||
try {
|
||||
const auto device = OpenVulkanTestDevice();
|
||||
if (!device) return VulkanTestSkipped;
|
||||
std::cout << "device list restart: " << (device->PrimitiveListRestart() ? "yes" : "no") << '\n';
|
||||
const auto indexAddress = reinterpret_cast<std::uintptr_t>(Indices.data());
|
||||
Draw(*device, AgcDriver::Pm4::DrawParameters{indexAddress, static_cast<std::uint32_t>(Indices.size()), 2, 1, 0, true});
|
||||
Check("direct triangle list with a restart and an incomplete tail", true, true);
|
||||
|
||||
AgcDriver::Pm4::DrawParameters indirect{indexAddress, static_cast<std::uint32_t>(Indices.size()), 2, 0, 0, true};
|
||||
indirect.indirect = AgcDriver::Pm4::DrawParameters::IndirectDraw{reinterpret_cast<std::uintptr_t>(IndirectRecords.data()), 0x25u, 20u, 20u, 1u, false, 0u, NoLocation, NoLocation, NoLocation, false, 0u};
|
||||
Draw(*device, indirect);
|
||||
Check("indirect record starting at the restart", false, true);
|
||||
indirect.indirect->arguments = reinterpret_cast<std::uintptr_t>(IndirectRecords.data() + 5);
|
||||
Draw(*device, indirect);
|
||||
Check("indirect record over 0 1 2 3 4", true, false);
|
||||
indirect.indirect->arguments = reinterpret_cast<std::uintptr_t>(IndirectRecords.data());
|
||||
indirect.indirect->count = 2u;
|
||||
Draw(*device, indirect);
|
||||
Check("two indirect records", true, true);
|
||||
if (!device->PrimitiveListRestart()) {
|
||||
indirect.indexCount = 0;
|
||||
Draw(*device, indirect);
|
||||
Check("indirect records over an empty index range", false, false);
|
||||
}
|
||||
std::puts("list restart tests passed");
|
||||
return 0;
|
||||
} catch (const std::exception& error) {
|
||||
std::cerr << error.what() << '\n';
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
@@ -115,6 +115,7 @@ ShaderRecompiler::RecompileResult Draw(AgcDriver::VulkanDevice& device, std::spa
|
||||
Pixels.fill(Unwritten);
|
||||
auto target = device.Target();
|
||||
target.fragmentShaderBarycentricEnabled = false;
|
||||
target.fragmentBarycentricBuiltins = false;
|
||||
|
||||
const AgcDriver::Pm4::DrawParameters draw{0, static_cast<std::uint32_t>(Vertices.size()), 0, 1, 0, false};
|
||||
std::vector<std::uint32_t> meshUserData(12, 0u);
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
#include "prx/libSceAgcDriver/Graphics/include/Texture.hpp"
|
||||
#include "prx/libSceAgcDriver/Graphics/include/TextureFormat.hpp"
|
||||
#include "prx/libSceAgcDriver/Graphics/include/DepthSurface.hpp"
|
||||
#include "prx/libSceAgcDriver/Graphics/include/GuestBufferMemory.hpp"
|
||||
#include "prx/libSceAgcDriver/Graphics/include/MultisampleTarget.hpp"
|
||||
#include "prx/libSceAgcDriver/Graphics/include/Resources.hpp"
|
||||
#include "prx/libSceAgcDriver/Graphics/include/ShaderResources.hpp"
|
||||
@@ -58,7 +59,7 @@ using namespace AgcDriver::Graphics;
|
||||
|
||||
class Device {
|
||||
public:
|
||||
Device() {
|
||||
explicit Device(bool importHost = false) {
|
||||
#ifdef _WIN32
|
||||
library = SDL_LoadObject("vulkan-1.dll");
|
||||
#elif defined(__APPLE__)
|
||||
@@ -108,11 +109,39 @@ public:
|
||||
queue.queueFamilyIndex = family;
|
||||
queue.queueCount = 1u;
|
||||
queue.pQueuePriorities = &priority;
|
||||
VkDeviceCreateInfo device{VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO};
|
||||
std::vector<VkExtensionProperties> extensions;
|
||||
if (importHost) {
|
||||
const auto enumerateExtensions = function<PFN_vkEnumerateDeviceExtensionProperties>("vkEnumerateDeviceExtensionProperties");
|
||||
Check(enumerateExtensions(context.physical, nullptr, &count, nullptr), "vkEnumerateDeviceExtensionProperties");
|
||||
extensions.resize(count);
|
||||
Check(enumerateExtensions(context.physical, nullptr, &count, extensions.data()), "vkEnumerateDeviceExtensionProperties");
|
||||
}
|
||||
const auto supported = [&](const char* name) { return std::any_of(extensions.begin(), extensions.end(), [&](const auto& item) { return std::strcmp(item.extensionName, name) == 0; }); };
|
||||
const bool externalHostExtensions = supported(VK_EXT_EXTERNAL_MEMORY_HOST_EXTENSION_NAME) && supported(VK_KHR_BUFFER_DEVICE_ADDRESS_EXTENSION_NAME);
|
||||
const std::array<const char*, 2> externalHostNames{VK_EXT_EXTERNAL_MEMORY_HOST_EXTENSION_NAME, VK_KHR_BUFFER_DEVICE_ADDRESS_EXTENSION_NAME};
|
||||
VkPhysicalDeviceBufferDeviceAddressFeatures address{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_BUFFER_DEVICE_ADDRESS_FEATURES};
|
||||
if (externalHostExtensions) {
|
||||
VkPhysicalDeviceFeatures2 features{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &address};
|
||||
function<PFN_vkGetPhysicalDeviceFeatures2>("vkGetPhysicalDeviceFeatures2")(context.physical, &features);
|
||||
}
|
||||
const bool externalHost = externalHostExtensions && address.bufferDeviceAddress == VK_TRUE;
|
||||
address.pNext = nullptr;
|
||||
address.bufferDeviceAddressCaptureReplay = VK_FALSE;
|
||||
address.bufferDeviceAddressMultiDevice = VK_FALSE;
|
||||
VkDeviceCreateInfo device{VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO, externalHost ? &address : nullptr};
|
||||
device.queueCreateInfoCount = 1u;
|
||||
device.pQueueCreateInfos = &queue;
|
||||
device.pEnabledFeatures = &enabled;
|
||||
device.enabledExtensionCount = externalHost ? static_cast<std::uint32_t>(externalHostNames.size()) : 0u;
|
||||
device.ppEnabledExtensionNames = externalHost ? externalHostNames.data() : nullptr;
|
||||
Check(function<PFN_vkCreateDevice>("vkCreateDevice")(context.physical, &device, nullptr, &context.device), "vkCreateDevice");
|
||||
if (externalHost) {
|
||||
VkPhysicalDeviceExternalMemoryHostPropertiesEXT host{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTERNAL_MEMORY_HOST_PROPERTIES_EXT};
|
||||
VkPhysicalDeviceProperties2 properties{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2, &host};
|
||||
function<PFN_vkGetPhysicalDeviceProperties2>("vkGetPhysicalDeviceProperties2")(context.physical, &properties);
|
||||
context.hostImportAlignment = host.minImportedHostPointerAlignment;
|
||||
context.bufferDeviceAddress = true;
|
||||
}
|
||||
context.deviceProc = function<PFN_vkGetDeviceProcAddr>("vkGetDeviceProcAddr");
|
||||
context.formatProperties = function<PFN_vkGetPhysicalDeviceFormatProperties>("vkGetPhysicalDeviceFormatProperties");
|
||||
context.imageFormatProperties = function<PFN_vkGetPhysicalDeviceImageFormatProperties>("vkGetPhysicalDeviceImageFormatProperties");
|
||||
@@ -1145,6 +1174,53 @@ void CheckUnwrittenGuestAccess(Context context, VkFormat format, std::uint32_t f
|
||||
std::printf("Native depth format=%u samples=%u: guest access retired the unwritten surface and refused the written one\n", static_cast<std::uint32_t>(format), fragments);
|
||||
}
|
||||
|
||||
enum class BufferWrite { DepthPlane, Htile };
|
||||
|
||||
void CheckBufferWrite(Context context, VkFormat format, std::uint32_t fragments, BufferWrite write) {
|
||||
const VkExtent2D extent{5u, 3u};
|
||||
const auto bytes = static_cast<std::size_t>(MultisampledDepthBytes_nid_no_patch(extent, format == VK_FORMAT_D16_UNORM ? 2u : 4u, fragments));
|
||||
const auto metadataBytes = static_cast<std::size_t>(HtileMetadataBytes(extent));
|
||||
TargetMemory memory(bytes, true), metadata(65536u, true), unrelated(65536u, true);
|
||||
const auto guestByte = [](std::size_t offset) { return static_cast<std::byte>(offset * 5u + 1u); };
|
||||
for (std::size_t offset = 0u; offset < bytes; ++offset) memory.Data()[offset] = guestByte(offset);
|
||||
std::memset(metadata.Data(), 0, metadataBytes);
|
||||
DepthTarget target{memory.Address(), 0u, extent, format, 0.0f, 0u, metadata.Address(), false, fragments};
|
||||
target.depthSwizzle = 24u;
|
||||
target.iterate256 = target.htilePipeAligned = target.htileDepthOnly = true;
|
||||
Recorder recorder(context);
|
||||
recorder.Activate();
|
||||
struct Cleanup {
|
||||
Recorder& recorder;
|
||||
Context context;
|
||||
~Cleanup() { recorder.Sync(); ClearCachedTextures(context.device); ClearDepthSurfaces(context.device); }
|
||||
} cleanup{recorder, context};
|
||||
const auto resident = [&] { return HasResidentDepthGuards_nid_no_patch() && DepthSurfaceAt(target.address); };
|
||||
const auto upload = [&](std::uint64_t address, std::size_t length) {
|
||||
GuestBufferMemory buffer(context);
|
||||
buffer.AddWritable(address, length);
|
||||
buffer.Upload(false);
|
||||
Require(HostImportCovers(context, address, length), "the native depth buffer-write fixture was not bound as a host import");
|
||||
buffer.WriteBack();
|
||||
};
|
||||
Require(DepthSurfaceView(context, target) != VK_NULL_HANDLE && resident(), "native depth buffer-write fixture has no resident owner");
|
||||
upload(unrelated.Address(), 256u);
|
||||
Require(resident(), "an unrelated buffer write retired a native depth surface");
|
||||
if (write == BufferWrite::DepthPlane) upload(target.address + bytes - 256u, 256u);
|
||||
else upload(target.htileAddress, metadataBytes);
|
||||
Require(!resident(), "a buffer the GPU may write left an unwritten native depth surface resident over it");
|
||||
for (std::size_t offset = 0u; offset < bytes; ++offset) Require(memory.Data()[offset] == guestByte(offset), "releasing an unwritten native depth surface for a buffer write changed its guest bytes");
|
||||
Require(std::all_of(metadata.Data(), metadata.Data() + metadataBytes, [](std::byte value) { return value == std::byte{0}; }), "releasing an unwritten native depth surface for a buffer write changed its HTILE");
|
||||
}
|
||||
|
||||
void CheckBufferWrites(Context context, VkFormat format, std::uint32_t fragments) {
|
||||
if (context.hostImportAlignment == 0u) {
|
||||
std::printf("skipped native depth buffer writes: the device lacks VK_EXT_external_memory_host, VK_KHR_buffer_device_address or the bufferDeviceAddress feature\n");
|
||||
return;
|
||||
}
|
||||
for (const auto write : {BufferWrite::DepthPlane, BufferWrite::Htile}) CheckBufferWrite(context, format, fragments, write);
|
||||
std::printf("Native depth format=%u samples=%u: a GPU buffer write over the depth or HTILE released the unwritten surface\n", static_cast<std::uint32_t>(format), fragments);
|
||||
}
|
||||
|
||||
void CheckHtileRouting(Context context, VkFormat format, std::uint32_t fragments) {
|
||||
const VkExtent2D extent{5u, 3u};
|
||||
const auto bytes = static_cast<std::size_t>(MultisampledDepthBytes_nid_no_patch(extent, format == VK_FORMAT_D16_UNORM ? 2u : 4u, fragments));
|
||||
@@ -1497,6 +1573,15 @@ int main(int argc, char** argv) {
|
||||
CheckUnwrittenGuestAccess(context, format, samples);
|
||||
}
|
||||
}
|
||||
{
|
||||
const Device importing(true);
|
||||
const auto importContext = importing.GetContext();
|
||||
for (const auto format : {VK_FORMAT_D16_UNORM, VK_FORMAT_D32_SFLOAT}) {
|
||||
for (const auto samples : {2u, 4u, 8u}) {
|
||||
if (DepthSupported(importContext, format, samples)) CheckBufferWrites(importContext, format, samples);
|
||||
}
|
||||
}
|
||||
}
|
||||
CheckEligibility(context);
|
||||
std::printf("Native multisampled depth cases checked=%u unavailable=%u\n", checked, unavailable);
|
||||
return 0;
|
||||
|
||||
@@ -82,6 +82,29 @@ void RangeTests() {
|
||||
Require(!DecodePatternFillRange(data, packet), "multidimensional fill was accepted");
|
||||
}
|
||||
|
||||
void GcnRangeTests() {
|
||||
const ShaderRecompiler::ShaderComputeStageInfo compute{{64, 1, 1}, 0, {true, false, false}, false, 1};
|
||||
constexpr std::array<std::uint32_t, 16> data{0, 0, 0, 0, 0x80600830u, 0x00040002u, 1, 0x20024004u, 0x40a00000u, 0x00047002u, 0x001fe000u, 0x18024004u, 0x806008acu, 0x00100002u, 1, 0x20077facu};
|
||||
const auto& code = GcnPatternFillKernel;
|
||||
Require(MatchesGcnPatternFillKernel(code, data, compute), "PS4 pattern fill kernel was not recognized");
|
||||
Require(!MatchesPatternFillKernel(code, data, compute), "the PS4 fill matched the PS5 kernel");
|
||||
for (std::size_t word = 0; word < code.size(); ++word) {
|
||||
auto altered = code;
|
||||
altered[word] ^= 1;
|
||||
Require(!MatchesGcnPatternFillKernel(altered, data, compute), "a different shader matched the PS4 fill kernel");
|
||||
}
|
||||
for (const auto& [word, bits] : std::array<std::pair<std::size_t, std::uint32_t>, 4>{{{5, 0x000c0000u}, {11, 0x00003000u}, {7, 0x00800000u}, {7, 0x00000001u}}}) {
|
||||
auto altered = data;
|
||||
altered[word] ^= bits;
|
||||
Require(!MatchesGcnPatternFillKernel(code, altered, compute), "unsupported PS4 fill descriptor matched");
|
||||
}
|
||||
constexpr std::array<std::uint32_t, 5> packet{0xc0031500u, 0x7f80u, 1, 1, 1};
|
||||
const auto range = DecodeGcnPatternFillRange(data, packet);
|
||||
Require(range && range->source == 0x280600830ull && range->destination == 0x240a00000ull && range->control == 0x2806008acull, "PS4 fill addresses kept bits above 44");
|
||||
Require(range->invocations == 0x7f80u * 64u && range->records == 0x1fe000u, "PS4 fill range changed");
|
||||
Require(range->UniformBytes(0x1fe000u, 0) == 8355840u, "PS4 render target clear does not cover the target");
|
||||
}
|
||||
|
||||
std::vector<std::uint32_t> Commands(std::span<const std::uint32_t> data, std::uint32_t threads, std::uint32_t wave, bool partial, bool indirect) {
|
||||
std::vector<std::uint32_t> words;
|
||||
const auto registers = [&](std::uint32_t first, std::span<const std::uint32_t> values) {
|
||||
@@ -209,6 +232,7 @@ void Benchmark() {
|
||||
int main(int argc, char** argv) {
|
||||
try {
|
||||
RangeTests();
|
||||
GcnRangeTests();
|
||||
{
|
||||
const auto device = OpenVulkanTestDevice();
|
||||
if (!device) return VulkanTestSkipped;
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
#include "prx/libSceAgcDriver/Submit/include/Dcb.hpp"
|
||||
#include "prx/libc/include/GuestAllocations.hpp"
|
||||
#include "prx/libc/include/Shutdown.hpp"
|
||||
#include "VulkanTestDevice.hpp"
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
#include <atomic>
|
||||
@@ -126,6 +127,10 @@ int main() {
|
||||
setenv("APS5_DRAW_PIPELINE", "1", 1);
|
||||
#endif
|
||||
try {
|
||||
{
|
||||
const auto device = OpenVulkanTestDevice();
|
||||
if (!device) return VulkanTestSkipped;
|
||||
}
|
||||
{
|
||||
GuestAllocations::Mutation mutation;
|
||||
mutation.Add(Surface.data(), Surface.size_bytes(), true, true, true);
|
||||
|
||||
@@ -1,201 +0,0 @@
|
||||
#include "prx/libSceAgcDriver/Execution/include/VulkanDevice.hpp"
|
||||
#include "prx/libSceAgcDriver/Graphics/include/Draw.hpp"
|
||||
#include "prx/libSceAgcDriver/Graphics/include/TextureTiling.hpp"
|
||||
#include "Recompiler.hpp"
|
||||
#include "VulkanTestDevice.hpp"
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
#include <cstdio>
|
||||
#include <iostream>
|
||||
#include <map>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace {
|
||||
|
||||
using AgcDriver::Graphics::Require;
|
||||
using ShaderRecompiler::ShaderStage;
|
||||
|
||||
constexpr std::uint32_t Sentinel = 0xdeadbeefu;
|
||||
constexpr std::uint32_t Width = 192;
|
||||
constexpr std::uint32_t Height = 128;
|
||||
constexpr std::uint32_t Size = 16;
|
||||
constexpr std::uint32_t Levels = 5;
|
||||
constexpr std::uint32_t PassLimit = 80;
|
||||
alignas(256) std::array<std::byte, Width * Height * 4> Pixels{};
|
||||
alignas(256) std::array<std::uint32_t, Width * Height * 2> Results{};
|
||||
alignas(256) std::array<std::uint8_t, 16384> Texels{};
|
||||
|
||||
alignas(256) constexpr std::array<std::uint32_t, 6> VertexCode{
|
||||
0xe0382000, 0x80000005, 0xbf8c3f70, 0xf80008cf, 0x03020100, 0xbf810000,
|
||||
};
|
||||
|
||||
alignas(256) constexpr std::array<std::uint32_t, 42> PixelCode{
|
||||
0x7e040f00, 0x7e060f01, 0xd5430006, 0x0409ff03, 0x000000c0, 0xbec4047e, 0x7e120506, 0xbefe0a7e,
|
||||
0x101400ff, 0x3baaaaab, 0x101602ff, 0x3c000000, 0xf0800f08, 0x01060c0a, 0xbe8a047e, 0xbe8c0380,
|
||||
0xbe8d0380, 0xbe940480, 0xbe82140a, 0xd7600003, 0x00000506, 0x890d030d, 0xd4c20014, 0x00020c03,
|
||||
0x8a8a140a, 0x800c810c, 0xbf09ff0c, 0x00000050, 0xbf850002, 0xbf13800a, 0xbf85fff3, 0xbefe0444,
|
||||
0x8f0c900c, 0x880d0c0d, 0x7e100209, 0x7e12020d, 0xe0742000, 0x80010806, 0xbf8c3f70, 0xf800180f,
|
||||
0x0f0e0d0c, 0xbf810000,
|
||||
};
|
||||
|
||||
std::array<std::uint32_t, 4> BufferDescriptor(const void* data, std::uint32_t stride, std::uint32_t count) {
|
||||
const auto address = reinterpret_cast<std::uintptr_t>(data);
|
||||
return {static_cast<std::uint32_t>(address), static_cast<std::uint32_t>((address >> 32u) & 0xffffu) | (stride << 16u), count, 0x01016facu};
|
||||
}
|
||||
|
||||
std::array<std::uint32_t, 8> TextureDescriptor() {
|
||||
const auto address = reinterpret_cast<std::uintptr_t>(Texels.data());
|
||||
return {static_cast<std::uint32_t>(address >> 8), static_cast<std::uint32_t>((address >> 40) & 0xffu) | (56u << 20) | (3u << 30),
|
||||
((Size - 1u) >> 2) | ((Size - 1u) << 14), 0xfacu | ((Levels - 1u) << 16) | (9u << 28), 0u, (Levels - 1u) << 4, 0u, 0u};
|
||||
}
|
||||
|
||||
void FillTexture() {
|
||||
const auto geometry = AgcDriver::Graphics::DescribeSurface(AgcDriver::Graphics::DecodeTextureResource(TextureDescriptor()));
|
||||
Require(geometry.guestBytes <= Texels.size(), "helper waterfall texture does not fit");
|
||||
Texels.fill(0xffu);
|
||||
}
|
||||
|
||||
std::vector<std::array<float, 4>> Triangles() {
|
||||
std::vector<std::array<float, 4>> vertices;
|
||||
constexpr std::uint32_t columns = 6;
|
||||
constexpr std::uint32_t rows = 4;
|
||||
for (std::uint32_t cell = 0; cell < columns * rows; ++cell) {
|
||||
const float width = 2.0f / columns;
|
||||
const float height = 2.0f / rows;
|
||||
const float x = -1.0f + width * static_cast<float>(cell % columns);
|
||||
const float y = -1.0f + height * static_cast<float>(cell / columns);
|
||||
const float skew = 0.07f * static_cast<float>(cell % 5u);
|
||||
vertices.push_back({x + (0.05f + skew) * width, y + 0.05f * height, 0.5f, 1.0f});
|
||||
vertices.push_back({x + 0.93f * width, y + (0.11f + skew) * height, 0.5f, 1.0f});
|
||||
vertices.push_back({x + (0.37f - skew * 0.5f) * width, y + 0.91f * height, 0.5f, 1.0f});
|
||||
}
|
||||
return vertices;
|
||||
}
|
||||
|
||||
void Draw(AgcDriver::VulkanDevice& device, std::uint32_t waveSize, const ShaderRecompiler::SpirvTarget& target) {
|
||||
static const auto triangles = Triangles();
|
||||
Pixels.fill(std::byte{0});
|
||||
Results.fill(Sentinel);
|
||||
|
||||
std::vector<std::uint32_t> vertexUserData(4, 0u);
|
||||
const auto vertexBuffer = BufferDescriptor(triangles.data(), 16u, static_cast<std::uint32_t>(triangles.size()));
|
||||
std::copy(vertexBuffer.begin(), vertexBuffer.end(), vertexUserData.begin());
|
||||
const std::array<ShaderRecompiler::MemoryRegion, 1> vertexMemory{{{reinterpret_cast<std::uintptr_t>(VertexCode.data()), std::as_bytes(std::span(VertexCode))}}};
|
||||
ShaderRecompiler::RecompileRequest vertex{
|
||||
{ShaderStage::Vertex, reinterpret_cast<std::uintptr_t>(VertexCode.data()), VertexCode, 0, {}},
|
||||
{waveSize, 0, vertexUserData, std::nullopt, std::nullopt, ShaderRecompiler::ShaderVertexStageInfo{}, vertexMemory},
|
||||
target,
|
||||
{0, 0, 0, 64}
|
||||
};
|
||||
vertex.useCache = false;
|
||||
const auto vertexResult = ShaderRecompiler::Recompile(vertex);
|
||||
const auto vertexPush = static_cast<std::uint32_t>(vertexResult.pushConstants.size());
|
||||
|
||||
ShaderRecompiler::ShaderPixelStageInfo pixel{};
|
||||
pixel.wave32 = waveSize == 32u;
|
||||
pixel.inputAddr = ShaderRecompiler::PixelInputBit(ShaderRecompiler::PixelInput::PositionX) | ShaderRecompiler::PixelInputBit(ShaderRecompiler::PixelInput::PositionY);
|
||||
pixel.posX = true;
|
||||
pixel.posY = true;
|
||||
pixel.targetOutputMode[0] = 9;
|
||||
pixel.targetExportMapping.fill(0xe4u);
|
||||
std::vector<std::uint32_t> pixelUserData(36, 0u);
|
||||
const auto results = BufferDescriptor(Results.data(), 8u, static_cast<std::uint32_t>(Results.size() / 2u));
|
||||
std::copy(results.begin(), results.end(), pixelUserData.begin() + 4);
|
||||
const auto texture = TextureDescriptor();
|
||||
std::copy(texture.begin(), texture.end(), pixelUserData.begin() + 24);
|
||||
const std::array<std::uint32_t, 4> sampler{0u, 0xfffu << 12, 1u << 26, 0u};
|
||||
std::copy(sampler.begin(), sampler.end(), pixelUserData.begin() + 32);
|
||||
const std::array<ShaderRecompiler::MemoryRegion, 1> pixelMemory{{{reinterpret_cast<std::uintptr_t>(PixelCode.data()), std::as_bytes(std::span(PixelCode))}}};
|
||||
ShaderRecompiler::RecompileRequest fragment{
|
||||
{ShaderStage::Fragment, reinterpret_cast<std::uintptr_t>(PixelCode.data()), PixelCode, 0, {}},
|
||||
{waveSize, 0, pixelUserData, std::nullopt, pixel, std::nullopt, pixelMemory},
|
||||
target,
|
||||
PixelPushLayout(vertexPush, target)
|
||||
};
|
||||
fragment.useCache = false;
|
||||
const auto pixelResult = ShaderRecompiler::Recompile(fragment);
|
||||
const std::array<AgcDriver::Graphics::CompiledShader, 2> shaders{{
|
||||
{ShaderStage::Vertex, &vertexResult, 0},
|
||||
{ShaderStage::Fragment, &pixelResult, PixelPushOffset(vertexPush, target)}
|
||||
}};
|
||||
|
||||
AgcDriver::Graphics::State state{};
|
||||
state.stages = {AgcDriver::Graphics::ShaderPath::Vertex, 0u, waveSize, waveSize, std::nullopt, std::nullopt};
|
||||
state.color = {reinterpret_cast<std::uintptr_t>(Pixels.data()), {Width, Height}, VK_FORMAT_R8G8B8A8_UNORM, Pixels.size(), 0xe4u};
|
||||
state.colors = {state.color};
|
||||
state.hasColorTarget = true;
|
||||
state.renderExtent = {Width, Height};
|
||||
state.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST;
|
||||
state.viewport = {0, static_cast<float>(Height), static_cast<float>(Width), -static_cast<float>(Height), 0, 1};
|
||||
state.negativeOneToOne = false;
|
||||
state.scissor = {{0, 0}, {Width, Height}};
|
||||
state.cullMode = VK_CULL_MODE_NONE;
|
||||
state.frontFace = VK_FRONT_FACE_COUNTER_CLOCKWISE;
|
||||
state.blend.colorWriteMask = 15;
|
||||
state.blends = {state.blend};
|
||||
state.blendConstants = {};
|
||||
const AgcDriver::Pm4::DrawParameters draw{0, static_cast<std::uint32_t>(triangles.size()), 0, 1, 0, false};
|
||||
device.Draw(state, draw, shaders);
|
||||
device.WaitIdle();
|
||||
}
|
||||
|
||||
void Check(std::uint32_t waveSize) {
|
||||
const auto what = "pixel helper waterfall wave" + std::to_string(waveSize);
|
||||
std::map<std::uint32_t, std::vector<std::uint32_t>> waves;
|
||||
std::uint32_t partialQuads = 0;
|
||||
for (std::uint32_t pixel = 0; pixel < Width * Height; ++pixel) {
|
||||
if (Pixels[pixel * 4u + 3u] == std::byte{0}) {
|
||||
Require(Results[pixel * 2u] == Sentinel, what + ": uncovered pixel " + std::to_string(pixel) + " stored a result");
|
||||
continue;
|
||||
}
|
||||
Require(Results[pixel * 2u] != Sentinel, what + ": covered pixel " + std::to_string(pixel) + " stored nothing");
|
||||
waves[Results[pixel * 2u]].push_back(pixel);
|
||||
const auto quad = (pixel / Width & ~1u) * Width + (pixel % Width & ~1u);
|
||||
if (quad == pixel) {
|
||||
for (const auto offset : {1u, Width, Width + 1u}) {
|
||||
if (Pixels[(quad + offset) * 4u + 3u] == std::byte{0}) {
|
||||
++partialQuads;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Require(waves.size() > 4u && partialQuads > 16u, what + ": the triangles made only " + std::to_string(waves.size()) + " waves and " + std::to_string(partialQuads) + " partly covered quads");
|
||||
for (const auto& [first, live] : waves) {
|
||||
std::uint32_t keys = 0;
|
||||
for (const auto pixel : live) keys ^= pixel;
|
||||
const auto passes = static_cast<std::uint32_t>(live.size());
|
||||
Require(passes < PassLimit, what + ": the wave whose first lane is pixel " + std::to_string(first) + " has more live lanes than the pass limit");
|
||||
for (const auto pixel : live) {
|
||||
const auto stored = Results[pixel * 2u + 1u];
|
||||
Require((stored >> 16u) == passes, what + ": pixel " + std::to_string(pixel) + " of the wave whose first lane is pixel " + std::to_string(first) + " made " + std::to_string(stored >> 16u) + " passes over " + std::to_string(passes) + " live lanes");
|
||||
Require((stored & 0xffffu) == keys, what + ": pixel " + std::to_string(pixel) + " of the wave whose first lane is pixel " + std::to_string(first) + " read keys " + std::to_string(stored & 0xffffu) + ", expected " + std::to_string(keys));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
int main() {
|
||||
try {
|
||||
const auto device = OpenVulkanTestDevice();
|
||||
if (!device) return VulkanTestSkipped;
|
||||
if (device->Target().subgroupSize < 32u) {
|
||||
std::printf("skipped, subgroup size %u cannot hold a wave32\n", device->Target().subgroupSize);
|
||||
return VulkanTestSkipped;
|
||||
}
|
||||
FillTexture();
|
||||
for (const auto waveSize : {64u, 32u}) {
|
||||
for (std::uint32_t pass = 0; pass < 4; ++pass) {
|
||||
Draw(*device, waveSize, device->Target());
|
||||
Check(waveSize);
|
||||
}
|
||||
}
|
||||
std::puts("pixel helper waterfall tests passed");
|
||||
return 0;
|
||||
} catch (const std::exception& error) {
|
||||
std::cerr << error.what() << '\n';
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
@@ -31,6 +31,7 @@
|
||||
#include <chrono>
|
||||
#include <cstdlib>
|
||||
#include <cstdio>
|
||||
#include <filesystem>
|
||||
#include <fstream>
|
||||
#include <sstream>
|
||||
#include <thread>
|
||||
@@ -40,8 +41,16 @@
|
||||
#endif
|
||||
#include <windows.h>
|
||||
#include <io.h>
|
||||
#define HOST_DUP _dup
|
||||
#define HOST_DUP2 _dup2
|
||||
#define HOST_CLOSE _close
|
||||
#define HOST_FILENO _fileno
|
||||
#else
|
||||
#include <unistd.h>
|
||||
#define HOST_DUP dup
|
||||
#define HOST_DUP2 dup2
|
||||
#define HOST_CLOSE close
|
||||
#define HOST_FILENO fileno
|
||||
#endif
|
||||
|
||||
namespace {
|
||||
@@ -241,6 +250,69 @@ void FailureCapture(AgcDriver::VulkanDevice& device) {
|
||||
capture.close();
|
||||
std::remove(capturePath.c_str());
|
||||
Require(captureText.str() == RequestSerializer{}.Serialize(request), "an earlier preparation failure dump suppressed the dispatch request dump");
|
||||
Require(AgcDriver::DriverDetail::Driver::dumpRequest(request.shader.codeAddress, request) == capturePath, "subsequent request dump has the wrong name");
|
||||
Require(!std::ifstream(capturePath, std::ios::binary).is_open(), "de-duplicated request dump was re-created on disk");
|
||||
const std::filesystem::path retryDirectory = "shader_12345cafe_retry";
|
||||
std::filesystem::remove_all(retryDirectory);
|
||||
const auto failedPath = AgcDriver::DriverDetail::Driver::dumpRequest(request.shader.codeAddress, request, "_retry/test");
|
||||
Require(!std::ifstream(failedPath, std::ios::binary).is_open(), "uncreatable dump path was unexpectedly created");
|
||||
std::filesystem::create_directories(retryDirectory);
|
||||
const auto retriedPath = AgcDriver::DriverDetail::Driver::dumpRequest(request.shader.codeAddress, request, "_retry/test");
|
||||
Require(retriedPath == failedPath, "retried dump returned a different path");
|
||||
std::ifstream retriedFile(retriedPath, std::ios::binary);
|
||||
Require(retriedFile.is_open(), "retried dump file was not created");
|
||||
std::ostringstream retriedText;
|
||||
retriedText << retriedFile.rdbuf();
|
||||
retriedFile.close();
|
||||
std::filesystem::remove_all(retryDirectory);
|
||||
Require(retriedText.str() == RequestSerializer{}.Serialize(request), "retried dump file contents do not match serialized request");
|
||||
const char* previousSkipLimit = std::getenv("APS5_SKIP_REQUEST_DUMPS");
|
||||
const std::string savedSkipLimit = previousSkipLimit != nullptr ? previousSkipLimit : "";
|
||||
#ifdef _WIN32
|
||||
Require(_putenv_s("APS5_SKIP_REQUEST_DUMPS", "-1") == 0, "cannot set uncapped skip dumps");
|
||||
#else
|
||||
Require(setenv("APS5_SKIP_REQUEST_DUMPS", "-1", 1) == 0, "cannot set uncapped skip dumps");
|
||||
#endif
|
||||
const auto skipLogPath = std::filesystem::temp_directory_path() / ("aps5_skip_report_" + std::to_string(std::chrono::steady_clock::now().time_since_epoch().count()) + ".txt");
|
||||
std::fflush(stderr);
|
||||
const int savedStderr = HOST_DUP(HOST_FILENO(stderr));
|
||||
Require(savedStderr >= 0, "stderr could not be saved");
|
||||
#ifdef _WIN32
|
||||
Require(_wfreopen(skipLogPath.wstring().c_str(), L"wb", stderr) != nullptr, "stderr could not be redirected");
|
||||
#else
|
||||
Require(std::freopen(skipLogPath.c_str(), "wb", stderr) != nullptr, "stderr could not be redirected");
|
||||
#endif
|
||||
try {
|
||||
AgcDriver::DriverDetail::Driver::reportSkip("draw", "test plain skip");
|
||||
AgcDriver::DriverDetail::Driver::reportSkip("draw", "test plain skip");
|
||||
AgcDriver::DriverDetail::Driver::reportSkip("dispatch", "test request skip\nRecompileRequest:\nshader dump test data");
|
||||
} catch (...) {
|
||||
std::fflush(stderr);
|
||||
HOST_DUP2(savedStderr, HOST_FILENO(stderr));
|
||||
HOST_CLOSE(savedStderr);
|
||||
std::filesystem::remove(skipLogPath);
|
||||
throw;
|
||||
}
|
||||
std::fflush(stderr);
|
||||
HOST_DUP2(savedStderr, HOST_FILENO(stderr));
|
||||
HOST_CLOSE(savedStderr);
|
||||
#ifdef _WIN32
|
||||
Require((previousSkipLimit != nullptr ? _putenv_s("APS5_SKIP_REQUEST_DUMPS", savedSkipLimit.c_str()) : _putenv_s("APS5_SKIP_REQUEST_DUMPS", "")) == 0, "cannot restore skip dump limit");
|
||||
#else
|
||||
Require((previousSkipLimit != nullptr ? setenv("APS5_SKIP_REQUEST_DUMPS", savedSkipLimit.c_str(), 1) : unsetenv("APS5_SKIP_REQUEST_DUMPS")) == 0, "cannot restore skip dump limit");
|
||||
#endif
|
||||
std::string capturedSkips;
|
||||
{
|
||||
std::ifstream skipFile(skipLogPath, std::ios::binary);
|
||||
std::ostringstream skipBuffer;
|
||||
skipBuffer << skipFile.rdbuf();
|
||||
capturedSkips = skipBuffer.str();
|
||||
}
|
||||
std::filesystem::remove(skipLogPath);
|
||||
Require(capturedSkips.find("RecompileRequest dumps uncapped (APS5_SKIP_REQUEST_DUMPS)") != std::string::npos, "uncapped skip dump announcement was not output to stderr");
|
||||
Require(capturedSkips.find("[gpu] skipped draw: test plain skip\n") != std::string::npos, "first plain skip was not output to stderr");
|
||||
Require(capturedSkips.find("[gpu] skipped dispatch: test request skip\nRecompileRequest:\nshader dump test data\n") != std::string::npos, "uncapped request skip was not output to stderr");
|
||||
Require(capturedSkips.find("[gpu] skipped draw: test plain skip\n") == capturedSkips.rfind("[gpu] skipped draw: test plain skip\n"), "duplicate plain skip was output multiple times");
|
||||
#ifdef _WIN32
|
||||
Require(_putenv_s("APS5_DUMP_SHADERS", saved.c_str()) == 0, "cannot restore shader capture");
|
||||
#else
|
||||
@@ -651,7 +723,9 @@ void RegisteredVertexWorkgroup(const ShaderRecompiler::SpirvTarget& target, bool
|
||||
|
||||
void LazyRegistration() {
|
||||
using namespace NarrowConstantStoreFixture;
|
||||
Require(std::getenv("APS5_LAZY_SHADER_PREPARE") != nullptr, "lazy preparation is not enabled");
|
||||
const char* registrationBudget = std::getenv("APS5_REGISTRATION_PREPARE_COMMIT_GB");
|
||||
const bool budgetOnly = std::getenv("APS5_LAZY_SHADER_PREPARE") == nullptr;
|
||||
Require(!budgetOnly || (registrationBudget != nullptr && std::string_view(registrationBudget) == "0"), "lazy preparation is not enabled");
|
||||
struct Header {
|
||||
Shader shader{};
|
||||
std::array<ShaderRegister, 7> registers{};
|
||||
@@ -669,15 +743,17 @@ void LazyRegistration() {
|
||||
header.specials.dispatch_modifier = 0x8000;
|
||||
header.registers = {{{0x20c, static_cast<std::uint32_t>(address >> 8u)}, {0x20d, static_cast<std::uint32_t>(address >> 40u)}, {0x207, Threads}, {0x208, 1}, {0x209, 1}, {0x212, 0}, {0x213, 4}}};
|
||||
AgcDriverRegisterShader_nid_postfix(&header.shader);
|
||||
++header.registers[0].value;
|
||||
ExpectFailure([&] { AgcDriverRegisterShader_nid_postfix(&header.shader); }, "entry point is outside shader code");
|
||||
--header.registers[0].value;
|
||||
header.registers[2].value = 0;
|
||||
ExpectFailure([&] { AgcDriverRegisterShader_nid_postfix(&header.shader); }, "must be nonzero");
|
||||
header.registers[2].value = Threads;
|
||||
header.shader.num_sh_registers = 255;
|
||||
ExpectFailure([&] { AgcDriverRegisterShader_nid_postfix(&header.shader); }, "truncated shader metadata");
|
||||
header.shader.num_sh_registers = header.registers.size();
|
||||
if (!budgetOnly) {
|
||||
++header.registers[0].value;
|
||||
ExpectFailure([&] { AgcDriverRegisterShader_nid_postfix(&header.shader); }, "entry point is outside shader code");
|
||||
--header.registers[0].value;
|
||||
header.registers[2].value = 0;
|
||||
ExpectFailure([&] { AgcDriverRegisterShader_nid_postfix(&header.shader); }, "must be nonzero");
|
||||
header.registers[2].value = Threads;
|
||||
header.shader.num_sh_registers = 255;
|
||||
ExpectFailure([&] { AgcDriverRegisterShader_nid_postfix(&header.shader); }, "truncated shader metadata");
|
||||
header.shader.num_sh_registers = header.registers.size();
|
||||
}
|
||||
const auto registered = [&] {
|
||||
const auto registry = AgcDriver::DriverDetail::Driver::Get().RegisteredShaders();
|
||||
Require(registry != nullptr, "lazy registration published no shader registry");
|
||||
|
||||
Loaded 100 of 531 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user