mirror of
https://github.com/hrydgard/ppsspp.git
synced 2026-11-15 18:49:51 +01:00
Merge branch 'master' into ui-translation
This commit is contained in:
407 files changed
+12964
-6513
No files matched your search
+28
-24
@@ -34,12 +34,12 @@ jobs:
|
||||
|
||||
runs-on: windows-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v2
|
||||
- uses: actions/checkout@v3
|
||||
with:
|
||||
submodules: recursive
|
||||
|
||||
- name: Add MSBuild to PATH
|
||||
uses: microsoft/setup-msbuild@v1
|
||||
uses: microsoft/setup-msbuild@v1.1
|
||||
|
||||
- name: Build Windows
|
||||
working-directory: ${{ env.GITHUB_WORKSPACE }}
|
||||
@@ -63,7 +63,7 @@ jobs:
|
||||
run: cp Windows/Release/*.exe ppsspp/
|
||||
|
||||
- name: Upload build
|
||||
uses: actions/upload-artifact@v1
|
||||
uses: actions/upload-artifact@v3
|
||||
with:
|
||||
name: Windows ${{ matrix.platform }} build
|
||||
path: ppsspp/
|
||||
@@ -71,12 +71,12 @@ jobs:
|
||||
build-uwp:
|
||||
runs-on: windows-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v2
|
||||
- uses: actions/checkout@v3
|
||||
with:
|
||||
submodules: recursive
|
||||
|
||||
- name: Add MSBuild to PATH
|
||||
uses: microsoft/setup-msbuild@v1
|
||||
uses: microsoft/setup-msbuild@v1.1
|
||||
|
||||
- name: Build UWP
|
||||
working-directory: ${{ env.GITHUB_WORKSPACE }}
|
||||
@@ -87,7 +87,7 @@ jobs:
|
||||
needs: build-windows
|
||||
timeout-minutes: 30
|
||||
steps:
|
||||
- uses: actions/checkout@v2
|
||||
- uses: actions/checkout@v3
|
||||
with:
|
||||
submodules: false
|
||||
|
||||
@@ -97,7 +97,7 @@ jobs:
|
||||
run: git submodule update --init pspautotests assets/lang
|
||||
|
||||
- name: Download build
|
||||
uses: actions/download-artifact@v2
|
||||
uses: actions/download-artifact@v3
|
||||
with:
|
||||
name: Windows x64 build
|
||||
path: ppsspp/
|
||||
@@ -168,13 +168,13 @@ jobs:
|
||||
extra: libretro
|
||||
cc: gcc
|
||||
cxx: g++
|
||||
args: ./b.sh --libretro
|
||||
args: make -C libretro -f Makefile -j2
|
||||
id: gcc-libretro
|
||||
- os: ubuntu-latest
|
||||
extra: libretro
|
||||
cc: clang
|
||||
cxx: clang++
|
||||
args: ./b.sh --libretro
|
||||
args: make -C libretro -f Makefile -j2
|
||||
id: clang-libretro
|
||||
|
||||
- os: macos-latest
|
||||
@@ -192,7 +192,7 @@ jobs:
|
||||
|
||||
runs-on: ${{ matrix.os }}
|
||||
steps:
|
||||
- uses: actions/checkout@v2
|
||||
- uses: actions/checkout@v3
|
||||
with:
|
||||
submodules: recursive
|
||||
|
||||
@@ -202,19 +202,11 @@ jobs:
|
||||
run: |
|
||||
git fetch --deepen=15000 --no-recurse-submodules --tags || exit 0
|
||||
|
||||
- name: Cache Qt
|
||||
uses: actions/cache@v1
|
||||
if: matrix.extra == 'qt'
|
||||
id: cache-qt
|
||||
with:
|
||||
path: ${{ runner.workspace }}/Qt
|
||||
key: ${{ runner.os }}-QtCache
|
||||
|
||||
- name: Install Qt
|
||||
uses: jurplel/install-qt-action@v2
|
||||
uses: jurplel/install-qt-action@v3
|
||||
if: matrix.extra == 'qt'
|
||||
with:
|
||||
cached: ${{ steps.cache-qt.outputs.cache-hit }}
|
||||
cache: true
|
||||
|
||||
- uses: nttld/setup-ndk@v1
|
||||
if: matrix.extra == 'android'
|
||||
@@ -236,7 +228,7 @@ jobs:
|
||||
echo "#define PPSSPP_GIT_VERSION_NO_UPDATE 1" >> git-version.cpp
|
||||
|
||||
- name: Setup ccache
|
||||
uses: hendrikmuhs/ccache-action@v1
|
||||
uses: hendrikmuhs/ccache-action@v1.2
|
||||
with:
|
||||
key: ${{ matrix.id }}
|
||||
|
||||
@@ -246,8 +238,20 @@ jobs:
|
||||
CXX: ${{ matrix.cxx }}
|
||||
NDK: ${{ steps.setup-ndk.outputs.ndk-path }}
|
||||
NDK_CCACHE: ccache
|
||||
USE_CCACHE: 1
|
||||
run: |
|
||||
export PATH="/usr/lib/ccache:/usr/local/opt/ccache/libexec:$PATH"
|
||||
export CCACHE_SLOPPINESS=clang_index_store,ivfsoverlay,include_file_ctime,include_file_mtime,modules,system_headers,time_macros
|
||||
if [ "${{ matrix.extra }}" == "android" ]; then
|
||||
export CCACHE_FILECLONE=true
|
||||
export CCACHE_DEPEND=true
|
||||
export CCACHE_COMPILERCHECK=content
|
||||
elif [ "$RUNNER_OS" == "macOS" ]; then
|
||||
export CCACHE_SLOPPINESS=pch_defines,$CCACHE_SLOPPINESS
|
||||
export CCACHE_FILECLONE=true
|
||||
export CCACHE_DEPEND=true
|
||||
export CCACHE_COMPILERCHECK=content
|
||||
fi
|
||||
${{ matrix.args }}
|
||||
|
||||
- name: Package build
|
||||
@@ -279,7 +283,7 @@ jobs:
|
||||
fi
|
||||
|
||||
- name: Upload build
|
||||
uses: actions/upload-artifact@v1
|
||||
uses: actions/upload-artifact@v3
|
||||
if: matrix.extra == 'test'
|
||||
with:
|
||||
name: ${{ matrix.os }} build
|
||||
@@ -313,7 +317,7 @@ jobs:
|
||||
needs: build
|
||||
timeout-minutes: 30
|
||||
steps:
|
||||
- uses: actions/checkout@v2
|
||||
- uses: actions/checkout@v3
|
||||
with:
|
||||
submodules: false
|
||||
|
||||
@@ -335,7 +339,7 @@ jobs:
|
||||
git submodule update --init SDL/macOS
|
||||
|
||||
- name: Download build
|
||||
uses: actions/download-artifact@v2
|
||||
uses: actions/download-artifact@v3
|
||||
with:
|
||||
name: ${{ matrix.os }} build
|
||||
path: ppsspp/
|
||||
|
||||
@@ -12,7 +12,7 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v2
|
||||
- uses: actions/checkout@v3
|
||||
|
||||
- name: Extract DOCKER_TAG using tag name
|
||||
if: startsWith(github.ref, 'refs/tags/')
|
||||
@@ -25,13 +25,13 @@ jobs:
|
||||
echo "DOCKER_TAG=latest" >> $GITHUB_ENV
|
||||
|
||||
- name: Login to Github registry
|
||||
uses: docker/login-action@v1
|
||||
uses: docker/login-action@v2
|
||||
with:
|
||||
username: ${{ github.actor }}
|
||||
password: ${{ secrets.GITHUB_TOKEN }}
|
||||
registry: ghcr.io
|
||||
|
||||
- uses: docker/build-push-action@v2
|
||||
- uses: docker/build-push-action@v3
|
||||
with:
|
||||
push: true
|
||||
tags: ghcr.io/${{ github.repository }}:${{ env.DOCKER_TAG }}
|
||||
tags: ghcr.io/${{ github.repository }}:${{ env.DOCKER_TAG }}
|
||||
@@ -19,14 +19,15 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v2
|
||||
- uses: actions/checkout@v3
|
||||
with:
|
||||
fetch-depth: 0
|
||||
submodules: recursive
|
||||
|
||||
- name: Setup JDK
|
||||
uses: actions/setup-java@v1
|
||||
uses: actions/setup-java@v2
|
||||
with:
|
||||
distribution: 'zulu'
|
||||
java-version: '11'
|
||||
|
||||
#- name: Setup SDK
|
||||
@@ -54,7 +55,7 @@ jobs:
|
||||
fi
|
||||
|
||||
- name: Upload APK
|
||||
uses: actions/upload-artifact@v1
|
||||
uses: actions/upload-artifact@v3
|
||||
with:
|
||||
name: android-${{ github.event.inputs.buildVariant }} build
|
||||
path: ppsspp/
|
||||
@@ -15,7 +15,7 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
|
||||
- uses: actions/checkout@v2
|
||||
- uses: actions/checkout@v3
|
||||
with:
|
||||
submodules: recursive
|
||||
|
||||
@@ -40,7 +40,7 @@ jobs:
|
||||
sed -i "s;unknown;${VERSION};" $PKGNAME/git-version.cmake || true
|
||||
TARBALL=$PKGNAME.tar.xz
|
||||
tar cJf $TARBALL $PKGNAME
|
||||
echo "::set-output name=tarball::$TARBALL"
|
||||
echo "tarball=$TARBALL" >> $GITHUB_OUTPUT
|
||||
|
||||
- name: upload tarball
|
||||
uses: softprops/action-gh-release@v1
|
||||
|
||||
+1
-1
@@ -6,7 +6,7 @@
|
||||
|
||||
# Core definitions
|
||||
variables:
|
||||
GIT_SUBMODULE_STRATEGY: normal
|
||||
GIT_SUBMODULE_STRATEGY: recursive
|
||||
|
||||
.core-defs:
|
||||
variables:
|
||||
|
||||
+31
-20
@@ -119,7 +119,6 @@ add_definitions(-DASSETS_DIR="${CMAKE_INSTALL_FULL_DATADIR}/ppsspp/assets/")
|
||||
if(OPENXR)
|
||||
add_definitions(-DOPENXR)
|
||||
add_library(openxr SHARED IMPORTED)
|
||||
include_directories(ext/openxr)
|
||||
if(OPENXR_PLATFORM_PICO)
|
||||
add_definitions(-DOPENXR_PLATFORM_PICO)
|
||||
set_property(TARGET openxr PROPERTY IMPORTED_LOCATION "${CMAKE_SOURCE_DIR}/ext/openxr/libs/pico/arm64-v8a/libopenxr_loader.so")
|
||||
@@ -507,6 +506,24 @@ if(WIN32)
|
||||
)
|
||||
endif()
|
||||
|
||||
set(CommonVR
|
||||
Common/VR/OpenXRLoader.cpp
|
||||
Common/VR/OpenXRLoader.h
|
||||
Common/VR/PPSSPPVR.cpp
|
||||
Common/VR/PPSSPPVR.h
|
||||
Common/VR/VRBase.cpp
|
||||
Common/VR/VRBase.h
|
||||
Common/VR/VRFramebuffer.cpp
|
||||
Common/VR/VRFramebuffer.h
|
||||
Common/VR/VRInput.cpp
|
||||
Common/VR/VRInput.h
|
||||
Common/VR/VRMath.cpp
|
||||
Common/VR/VRMath.h
|
||||
Common/VR/VRRenderer.cpp
|
||||
Common/VR/VRRenderer.h
|
||||
)
|
||||
include_directories(ext/openxr)
|
||||
|
||||
add_library(Common STATIC
|
||||
${CommonX86}
|
||||
${CommonARM}
|
||||
@@ -514,6 +531,7 @@ add_library(Common STATIC
|
||||
${CommonMIPS}
|
||||
${CommonRISCV64}
|
||||
${CommonD3D}
|
||||
${CommonVR}
|
||||
Common/Serialize/Serializer.cpp
|
||||
Common/Serialize/Serializer.h
|
||||
Common/Serialize/SerializeDeque.h
|
||||
@@ -650,6 +668,8 @@ add_library(Common STATIC
|
||||
Common/Math/lin/vec3.h
|
||||
Common/Math/math_util.cpp
|
||||
Common/Math/math_util.h
|
||||
Common/Math/Statistics.h
|
||||
Common/Math/Statistics.cpp
|
||||
Common/Net/HTTPClient.cpp
|
||||
Common/Net/HTTPClient.h
|
||||
Common/Net/HTTPHeaders.cpp
|
||||
@@ -1089,24 +1109,7 @@ if(ANDROID)
|
||||
android/jni/OpenSLContext.cpp
|
||||
android/jni/OpenSLContext.h
|
||||
)
|
||||
|
||||
if (OPENXR)
|
||||
set(nativeExtra ${nativeExtra}
|
||||
Common/VR/PPSSPPVR.cpp
|
||||
Common/VR/PPSSPPVR.h
|
||||
Common/VR/VRBase.cpp
|
||||
Common/VR/VRBase.h
|
||||
Common/VR/VRFramebuffer.cpp
|
||||
Common/VR/VRFramebuffer.h
|
||||
Common/VR/VRInput.cpp
|
||||
Common/VR/VRInput.h
|
||||
Common/VR/VRMath.cpp
|
||||
Common/VR/VRMath.h
|
||||
Common/VR/VRRenderer.cpp
|
||||
Common/VR/VRRenderer.h
|
||||
Common/VR/VRTweaks.cpp
|
||||
Common/VR/VRTweaks.h
|
||||
)
|
||||
set(nativeExtraLibs ${nativeExtraLibs} openxr)
|
||||
endif()
|
||||
# No target
|
||||
@@ -1562,6 +1565,8 @@ set(GPU_SOURCES
|
||||
GPU/Common/FragmentShaderGenerator.h
|
||||
GPU/Common/VertexShaderGenerator.cpp
|
||||
GPU/Common/VertexShaderGenerator.h
|
||||
GPU/Common/GeometryShaderGenerator.cpp
|
||||
GPU/Common/GeometryShaderGenerator.h
|
||||
GPU/Common/FramebufferManagerCommon.cpp
|
||||
GPU/Common/FramebufferManagerCommon.h
|
||||
GPU/Common/GPUDebugInterface.cpp
|
||||
@@ -2511,6 +2516,8 @@ if(UNIX AND NOT ANDROID AND NOT APPLE)
|
||||
DIRECTORY "${CMAKE_BINARY_DIR}/assets"
|
||||
DESTINATION "${CMAKE_INSTALL_DATADIR}/ppsspp"
|
||||
PATTERN ".git*" EXCLUDE
|
||||
PATTERN "mime" EXCLUDE
|
||||
PATTERN "lang/README.md" EXCLUDE
|
||||
)
|
||||
install(
|
||||
FILES "${CMAKE_BINARY_DIR}/ppsspp.desktop"
|
||||
@@ -2523,7 +2530,11 @@ if(UNIX AND NOT ANDROID AND NOT APPLE)
|
||||
)
|
||||
install(
|
||||
FILES "${CMAKE_SOURCE_DIR}/icons/icon-512.svg"
|
||||
DESTINATION "${CMAKE_INSTALL_DATAROOTDIR}/pixmaps"
|
||||
RENAME ppsspp.svg
|
||||
DESTINATION "${CMAKE_INSTALL_DATAROOTDIR}/icons/hicolor/scalable/apps"
|
||||
RENAME "ppsspp.svg"
|
||||
)
|
||||
install(
|
||||
FILES "${CMAKE_SOURCE_DIR}/assets/mime/ppsspp.xml"
|
||||
DESTINATION "${CMAKE_INSTALL_DATAROOTDIR}/mime/packages"
|
||||
)
|
||||
endif()
|
||||
+24
-8
@@ -136,7 +136,7 @@
|
||||
<PreprocessorDefinitions>_CRTDBG_MAP_ALLOC;USING_WIN_UI;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_WARNINGS;WIN32;_ARCH_32=1;_M_IX86=1;_DEBUG;_LIB;_UNICODE;UNICODE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
|
||||
<ForcedIncludeFiles>Common/DbgNew.h</ForcedIncludeFiles>
|
||||
<RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
|
||||
<AdditionalIncludeDirectories>../ext/glew;../ext/snappy;../ext/glslang;../ext/libpng17;../ext;../ext/zlib;..;../ext/zstd/lib</AdditionalIncludeDirectories>
|
||||
<AdditionalIncludeDirectories>../ext/openxr;../ext/glew;../ext/snappy;../ext/glslang;../ext/libpng17;../ext;../ext/zlib;..;../ext/zstd/lib</AdditionalIncludeDirectories>
|
||||
<EnableEnhancedInstructionSet>StreamingSIMDExtensions2</EnableEnhancedInstructionSet>
|
||||
<FloatingPointModel>Precise</FloatingPointModel>
|
||||
<MultiProcessorCompilation>true</MultiProcessorCompilation>
|
||||
@@ -162,7 +162,7 @@
|
||||
<ForcedIncludeFiles>Common/DbgNew.h</ForcedIncludeFiles>
|
||||
<RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
|
||||
<PreprocessorDefinitions>_CRTDBG_MAP_ALLOC;USING_WIN_UI;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_WARNINGS;WIN32;_ARCH_64=1;_M_X64=1;_DEBUG;_LIB;_UNICODE;UNICODE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
|
||||
<AdditionalIncludeDirectories>../ext/glew;../ext/snappy;../ext/glslang;../ext/libpng17;../ext;../ext/zlib;..;../ext/zstd/lib</AdditionalIncludeDirectories>
|
||||
<AdditionalIncludeDirectories>../ext/openxr;../ext/glew;../ext/snappy;../ext/glslang;../ext/libpng17;../ext;../ext/zlib;..;../ext/zstd/lib</AdditionalIncludeDirectories>
|
||||
<EnableEnhancedInstructionSet>NotSet</EnableEnhancedInstructionSet>
|
||||
<FloatingPointModel>Precise</FloatingPointModel>
|
||||
<OmitFramePointers>false</OmitFramePointers>
|
||||
@@ -189,7 +189,7 @@
|
||||
<ForcedIncludeFiles>Common/DbgNew.h</ForcedIncludeFiles>
|
||||
<RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
|
||||
<PreprocessorDefinitions>_CRTDBG_MAP_ALLOC;USING_WIN_UI;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_WARNINGS;WIN32;_ARCH_64=1;_DEBUG;_LIB;_UNICODE;UNICODE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
|
||||
<AdditionalIncludeDirectories>../ext/glew;../ext/snappy;../ext/glslang;../ext/libpng17;../ext;../ext/zlib;..;../ext/zstd/lib</AdditionalIncludeDirectories>
|
||||
<AdditionalIncludeDirectories>../ext/openxr;../ext/glew;../ext/snappy;../ext/glslang;../ext/libpng17;../ext;../ext/zlib;..;../ext/zstd/lib</AdditionalIncludeDirectories>
|
||||
<EnableEnhancedInstructionSet>NotSet</EnableEnhancedInstructionSet>
|
||||
<FloatingPointModel>Precise</FloatingPointModel>
|
||||
<OmitFramePointers>false</OmitFramePointers>
|
||||
@@ -217,7 +217,7 @@
|
||||
</ForcedIncludeFiles>
|
||||
<RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
|
||||
<PreprocessorDefinitions>_CRTDBG_MAP_ALLOC;USING_WIN_UI;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_WARNINGS;WIN32;_ARCH_32=1;_DEBUG;_LIB;_UNICODE;UNICODE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
|
||||
<AdditionalIncludeDirectories>../ext/glew;../ext/snappy;../ext/glslang;../ext/libpng17;../ext;../ext/zlib;..;../ext/zstd/lib</AdditionalIncludeDirectories>
|
||||
<AdditionalIncludeDirectories>../ext/openxr;../ext/glew;../ext/snappy;../ext/glslang;../ext/libpng17;../ext;../ext/zlib;..;../ext/zstd/lib</AdditionalIncludeDirectories>
|
||||
<EnableEnhancedInstructionSet>NotSet</EnableEnhancedInstructionSet>
|
||||
<FloatingPointModel>Precise</FloatingPointModel>
|
||||
<OmitFramePointers>false</OmitFramePointers>
|
||||
@@ -250,7 +250,7 @@
|
||||
<BufferSecurityCheck>false</BufferSecurityCheck>
|
||||
<EnableEnhancedInstructionSet>StreamingSIMDExtensions2</EnableEnhancedInstructionSet>
|
||||
<FloatingPointModel>Precise</FloatingPointModel>
|
||||
<AdditionalIncludeDirectories>../ext/glew;../ext/snappy;../ext/glslang;../ext/libpng17;../ext;../ext/zlib;..;../ext/zstd/lib</AdditionalIncludeDirectories>
|
||||
<AdditionalIncludeDirectories>../ext/openxr;../ext/glew;../ext/snappy;../ext/glslang;../ext/libpng17;../ext;../ext/zlib;..;../ext/zstd/lib</AdditionalIncludeDirectories>
|
||||
<FavorSizeOrSpeed>Speed</FavorSizeOrSpeed>
|
||||
<MultiProcessorCompilation>true</MultiProcessorCompilation>
|
||||
<RuntimeTypeInfo>false</RuntimeTypeInfo>
|
||||
@@ -280,7 +280,7 @@
|
||||
<PreprocessorDefinitions>USING_WIN_UI;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_WARNINGS;WIN32;_ARCH_64=1;_M_X64=1;NDEBUG;_LIB;_UNICODE;UNICODE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
|
||||
<ForcedIncludeFiles>
|
||||
</ForcedIncludeFiles>
|
||||
<AdditionalIncludeDirectories>../ext/glew;../ext/snappy;../ext/glslang;../ext/libpng17;../ext;../ext/zlib;..;../ext/zstd/lib</AdditionalIncludeDirectories>
|
||||
<AdditionalIncludeDirectories>../ext/openxr;../ext/glew;../ext/snappy;../ext/glslang;../ext/libpng17;../ext;../ext/zlib;..;../ext/zstd/lib</AdditionalIncludeDirectories>
|
||||
<BufferSecurityCheck>false</BufferSecurityCheck>
|
||||
<EnableEnhancedInstructionSet>NotSet</EnableEnhancedInstructionSet>
|
||||
<FloatingPointModel>Precise</FloatingPointModel>
|
||||
@@ -315,7 +315,7 @@
|
||||
<PreprocessorDefinitions>USING_WIN_UI;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_WARNINGS;WIN32;_ARCH_64=1;NDEBUG;_LIB;_UNICODE;UNICODE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
|
||||
<ForcedIncludeFiles>
|
||||
</ForcedIncludeFiles>
|
||||
<AdditionalIncludeDirectories>../ext/glew;../ext/snappy;../ext/glslang;../ext/libpng17;../ext;../ext/zlib;..;../ext/zstd/lib</AdditionalIncludeDirectories>
|
||||
<AdditionalIncludeDirectories>../ext/openxr;../ext/glew;../ext/snappy;../ext/glslang;../ext/libpng17;../ext;../ext/zlib;..;../ext/zstd/lib</AdditionalIncludeDirectories>
|
||||
<BufferSecurityCheck>false</BufferSecurityCheck>
|
||||
<EnableEnhancedInstructionSet>NotSet</EnableEnhancedInstructionSet>
|
||||
<FloatingPointModel>Precise</FloatingPointModel>
|
||||
@@ -350,7 +350,7 @@
|
||||
<PreprocessorDefinitions>USING_WIN_UI;_CRT_NONSTDC_NO_DEPRECATE;_CRT_SECURE_NO_WARNINGS;WIN32;_ARCH_32=1;NDEBUG;_LIB;_UNICODE;UNICODE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
|
||||
<ForcedIncludeFiles>
|
||||
</ForcedIncludeFiles>
|
||||
<AdditionalIncludeDirectories>../ext/glew;../ext/snappy;../ext/glslang;../ext/libpng17;../ext;../ext/zlib;..;../ext/zstd/lib</AdditionalIncludeDirectories>
|
||||
<AdditionalIncludeDirectories>../ext/openxr;../ext/glew;../ext/snappy;../ext/glslang;../ext/libpng17;../ext;../ext/zlib;..;../ext/zstd/lib</AdditionalIncludeDirectories>
|
||||
<BufferSecurityCheck>false</BufferSecurityCheck>
|
||||
<EnableEnhancedInstructionSet>NotSet</EnableEnhancedInstructionSet>
|
||||
<FloatingPointModel>Precise</FloatingPointModel>
|
||||
@@ -466,6 +466,7 @@
|
||||
<ClInclude Include="Math\lin\matrix4x4.h" />
|
||||
<ClInclude Include="Math\lin\vec3.h" />
|
||||
<ClInclude Include="Math\math_util.h" />
|
||||
<ClInclude Include="Math\Statistics.h" />
|
||||
<ClInclude Include="Net\NetBuffer.h" />
|
||||
<ClInclude Include="Net\HTTPClient.h" />
|
||||
<ClInclude Include="Net\HTTPHeaders.h" />
|
||||
@@ -556,6 +557,13 @@
|
||||
<ClInclude Include="UI\UIScreen.h" />
|
||||
<ClInclude Include="UI\View.h" />
|
||||
<ClInclude Include="UI\ViewGroup.h" />
|
||||
<ClInclude Include="VR\OpenXRLoader.h" />
|
||||
<ClInclude Include="VR\PPSSPPVR.h" />
|
||||
<ClInclude Include="VR\VRBase.h" />
|
||||
<ClInclude Include="VR\VRFramebuffer.h" />
|
||||
<ClInclude Include="VR\VRInput.h" />
|
||||
<ClInclude Include="VR\VRMath.h" />
|
||||
<ClInclude Include="VR\VRRenderer.h" />
|
||||
<ClInclude Include="x64Analyzer.h" />
|
||||
<ClInclude Include="x64Emitter.h" />
|
||||
</ItemGroup>
|
||||
@@ -886,6 +894,7 @@
|
||||
<ClCompile Include="Math\lin\matrix4x4.cpp" />
|
||||
<ClCompile Include="Math\lin\vec3.cpp" />
|
||||
<ClCompile Include="Math\math_util.cpp" />
|
||||
<ClCompile Include="Math\Statistics.cpp" />
|
||||
<ClCompile Include="Net\NetBuffer.cpp" />
|
||||
<ClCompile Include="Net\HTTPClient.cpp" />
|
||||
<ClCompile Include="Net\HTTPHeaders.cpp" />
|
||||
@@ -987,6 +996,13 @@
|
||||
<ClCompile Include="UI\UIScreen.cpp" />
|
||||
<ClCompile Include="UI\View.cpp" />
|
||||
<ClCompile Include="UI\ViewGroup.cpp" />
|
||||
<ClCompile Include="VR\OpenXRLoader.cpp" />
|
||||
<ClCompile Include="VR\PPSSPPVR.cpp" />
|
||||
<ClCompile Include="VR\VRBase.cpp" />
|
||||
<ClCompile Include="VR\VRFramebuffer.cpp" />
|
||||
<ClCompile Include="VR\VRInput.cpp" />
|
||||
<ClCompile Include="VR\VRMath.cpp" />
|
||||
<ClCompile Include="VR\VRRenderer.cpp" />
|
||||
<ClCompile Include="x64Analyzer.cpp" />
|
||||
<ClCompile Include="x64Emitter.cpp" />
|
||||
</ItemGroup>
|
||||
|
||||
@@ -422,6 +422,30 @@
|
||||
<ClInclude Include="GPU\Vulkan\VulkanFrameData.h">
|
||||
<Filter>GPU\Vulkan</Filter>
|
||||
</ClInclude>
|
||||
<ClInclude Include="Math\Statistics.h">
|
||||
<Filter>Math</Filter>
|
||||
</ClInclude>
|
||||
<ClInclude Include="VR\PPSSPPVR.h">
|
||||
<Filter>VR</Filter>
|
||||
</ClInclude>
|
||||
<ClInclude Include="VR\VRBase.h">
|
||||
<Filter>VR</Filter>
|
||||
</ClInclude>
|
||||
<ClInclude Include="VR\VRFramebuffer.h">
|
||||
<Filter>VR</Filter>
|
||||
</ClInclude>
|
||||
<ClInclude Include="VR\VRInput.h">
|
||||
<Filter>VR</Filter>
|
||||
</ClInclude>
|
||||
<ClInclude Include="VR\VRMath.h">
|
||||
<Filter>VR</Filter>
|
||||
</ClInclude>
|
||||
<ClInclude Include="VR\VRRenderer.h">
|
||||
<Filter>VR</Filter>
|
||||
</ClInclude>
|
||||
<ClInclude Include="VR\OpenXRLoader.h">
|
||||
<Filter>VR</Filter>
|
||||
</ClInclude>
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<ClCompile Include="ABI.cpp" />
|
||||
@@ -797,6 +821,30 @@
|
||||
<ClCompile Include="GPU\Vulkan\VulkanFrameData.cpp">
|
||||
<Filter>GPU\Vulkan</Filter>
|
||||
</ClCompile>
|
||||
<ClCompile Include="Math\Statistics.cpp">
|
||||
<Filter>Math</Filter>
|
||||
</ClCompile>
|
||||
<ClCompile Include="VR\PPSSPPVR.cpp">
|
||||
<Filter>VR</Filter>
|
||||
</ClCompile>
|
||||
<ClCompile Include="VR\VRBase.cpp">
|
||||
<Filter>VR</Filter>
|
||||
</ClCompile>
|
||||
<ClCompile Include="VR\VRFramebuffer.cpp">
|
||||
<Filter>VR</Filter>
|
||||
</ClCompile>
|
||||
<ClCompile Include="VR\VRInput.cpp">
|
||||
<Filter>VR</Filter>
|
||||
</ClCompile>
|
||||
<ClCompile Include="VR\VRMath.cpp">
|
||||
<Filter>VR</Filter>
|
||||
</ClCompile>
|
||||
<ClCompile Include="VR\VRRenderer.cpp">
|
||||
<Filter>VR</Filter>
|
||||
</ClCompile>
|
||||
<ClCompile Include="VR\OpenXRLoader.cpp">
|
||||
<Filter>VR</Filter>
|
||||
</ClCompile>
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<Filter Include="Crypto">
|
||||
@@ -901,6 +949,9 @@
|
||||
<Filter Include="ext\vma">
|
||||
<UniqueIdentifier>{7b17065c-729c-47c3-a02d-66dc383529dd}</UniqueIdentifier>
|
||||
</Filter>
|
||||
<Filter Include="VR">
|
||||
<UniqueIdentifier>{9d1c29fd-8ac7-4475-8ea6-c8c759b695fe}</UniqueIdentifier>
|
||||
</Filter>
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<Text Include="..\ext\libpng17\CMakeLists.txt">
|
||||
|
||||
@@ -82,6 +82,20 @@ inline void Uint8x3ToFloat4(float f[4], uint32_t u) {
|
||||
#endif
|
||||
}
|
||||
|
||||
inline void Uint8x3ToFloat3(float f[4], uint32_t u) {
|
||||
#if defined(_M_SSE) || PPSSPP_ARCH(ARM_NEON)
|
||||
float temp[4];
|
||||
Uint8x4ToFloat4(temp, u & 0xFFFFFF);
|
||||
f[0] = temp[0];
|
||||
f[1] = temp[1];
|
||||
f[2] = temp[2];
|
||||
#else
|
||||
f[0] = ((u >> 0) & 0xFF) * (1.0f / 255.0f);
|
||||
f[1] = ((u >> 8) & 0xFF) * (1.0f / 255.0f);
|
||||
f[2] = ((u >> 16) & 0xFF) * (1.0f / 255.0f);
|
||||
#endif
|
||||
}
|
||||
|
||||
inline void Uint8x3ToInt4(int i[4], uint32_t u) {
|
||||
i[0] = ((u >> 0) & 0xFF);
|
||||
i[1] = ((u >> 8) & 0xFF);
|
||||
|
||||
@@ -95,7 +95,6 @@ bool decompress_string(const std::string& str, std::string *dest) {
|
||||
inflateEnd(&zs);
|
||||
|
||||
if (ret != Z_STREAM_END) { // an error occurred that was not EOF
|
||||
std::ostringstream oss;
|
||||
ERROR_LOG(IO, "Exception during zlib decompression: (%i) %s", ret, zs.msg);
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -206,7 +206,7 @@ void Section::Set(const char* key, const char* newValue)
|
||||
else
|
||||
{
|
||||
// The key did not already exist in this section - let's add it.
|
||||
lines.push_back(std::string(key) + " = " + EscapeComments(newValue));
|
||||
lines.emplace_back(std::string(key) + " = " + EscapeComments(newValue));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -272,7 +272,7 @@ void Section::Set(const char* key, const std::vector<std::string>& newValues)
|
||||
}
|
||||
|
||||
void Section::AddComment(const std::string &comment) {
|
||||
lines.push_back("# " + comment);
|
||||
lines.emplace_back("# " + comment);
|
||||
}
|
||||
|
||||
bool Section::Get(const char* key, std::vector<std::string>& values)
|
||||
|
||||
@@ -39,7 +39,7 @@ const char *I18NCategory::T(const char *key, const char *def) {
|
||||
if (def)
|
||||
missedKeyLog_[key] = def;
|
||||
else
|
||||
missedKeyLog_[key] = modifiedKey.c_str();
|
||||
missedKeyLog_[key] = modifiedKey;
|
||||
// INFO_LOG(SYSTEM, "Missed translation key in %s: %s", name_.c_str(), key);
|
||||
return def ? def : key;
|
||||
}
|
||||
|
||||
@@ -206,11 +206,13 @@ bool Android_FileExists(const std::string &fileUri) {
|
||||
return exists;
|
||||
}
|
||||
|
||||
std::vector<File::FileInfo> Android_ListContentUri(const std::string &path) {
|
||||
std::vector<File::FileInfo> Android_ListContentUri(const std::string &path, bool *exists) {
|
||||
if (!g_nativeActivity) {
|
||||
*exists = false;
|
||||
return std::vector<File::FileInfo>();
|
||||
}
|
||||
auto env = getEnv();
|
||||
*exists = true;
|
||||
|
||||
double start = time_now_d();
|
||||
|
||||
@@ -224,8 +226,12 @@ std::vector<File::FileInfo> Android_ListContentUri(const std::string &path) {
|
||||
jstring str = (jstring)env->GetObjectArrayElement(fileList, i);
|
||||
const char *charArray = env->GetStringUTFChars(str, 0);
|
||||
if (charArray) { // paranoia
|
||||
std::string line = charArray;
|
||||
File::FileInfo info;
|
||||
if (ParseFileInfo(std::string(charArray), &info)) {
|
||||
if (line == "X") {
|
||||
// Indicates an exception thrown, path doesn't exist.
|
||||
*exists = false;
|
||||
} else if (ParseFileInfo(line, &info)) {
|
||||
// We can just reconstruct the URI.
|
||||
info.fullName = Path(path) / info.name;
|
||||
items.push_back(info);
|
||||
@@ -238,7 +244,7 @@ std::vector<File::FileInfo> Android_ListContentUri(const std::string &path) {
|
||||
|
||||
double elapsed = time_now_d() - start;
|
||||
if (elapsed > 0.1) {
|
||||
INFO_LOG(FILESYS, "Listing directory on content URI took %0.3f s (%d files)", elapsed, (int)size);
|
||||
INFO_LOG(FILESYS, "Listing directory on content URI took %0.3f s (%d files)", elapsed, (int)items.size());
|
||||
}
|
||||
return items;
|
||||
}
|
||||
|
||||
@@ -55,7 +55,7 @@ int64_t Android_GetFreeSpaceByFilePath(const std::string &filePath);
|
||||
bool Android_IsExternalStoragePreservedLegacy();
|
||||
const char *Android_ErrorToString(StorageError error);
|
||||
|
||||
std::vector<File::FileInfo> Android_ListContentUri(const std::string &uri);
|
||||
std::vector<File::FileInfo> Android_ListContentUri(const std::string &uri, bool *exists);
|
||||
|
||||
void Android_RegisterStorageCallbacks(JNIEnv * env, jobject obj);
|
||||
|
||||
@@ -78,7 +78,8 @@ inline int64_t Android_GetFreeSpaceByContentUri(const std::string &uri) { return
|
||||
inline int64_t Android_GetFreeSpaceByFilePath(const std::string &filePath) { return -1; }
|
||||
inline bool Android_IsExternalStoragePreservedLegacy() { return false; }
|
||||
inline const char *Android_ErrorToString(StorageError error) { return ""; }
|
||||
inline std::vector<File::FileInfo> Android_ListContentUri(const std::string &uri) {
|
||||
inline std::vector<File::FileInfo> Android_ListContentUri(const std::string &uri, bool *exists) {
|
||||
*exists = false;
|
||||
return std::vector<File::FileInfo>();
|
||||
}
|
||||
|
||||
|
||||
@@ -148,7 +148,7 @@ std::vector<File::FileInfo> ApplyFilter(std::vector<File::FileInfo> files, const
|
||||
std::string tmp;
|
||||
while (*filter) {
|
||||
if (*filter == ':') {
|
||||
filters.insert("." + tmp);
|
||||
filters.emplace("." + tmp);
|
||||
tmp.clear();
|
||||
} else {
|
||||
tmp.push_back(*filter);
|
||||
@@ -156,7 +156,7 @@ std::vector<File::FileInfo> ApplyFilter(std::vector<File::FileInfo> files, const
|
||||
filter++;
|
||||
}
|
||||
if (!tmp.empty())
|
||||
filters.insert("." + tmp);
|
||||
filters.emplace("." + tmp);
|
||||
}
|
||||
|
||||
auto pred = [&](const File::FileInfo &info) {
|
||||
@@ -171,10 +171,11 @@ std::vector<File::FileInfo> ApplyFilter(std::vector<File::FileInfo> files, const
|
||||
|
||||
bool GetFilesInDir(const Path &directory, std::vector<FileInfo> *files, const char *filter, int flags) {
|
||||
if (directory.Type() == PathType::CONTENT_URI) {
|
||||
std::vector<File::FileInfo> fileList = Android_ListContentUri(directory.ToString());
|
||||
bool exists = false;
|
||||
std::vector<File::FileInfo> fileList = Android_ListContentUri(directory.ToString(), &exists);
|
||||
*files = ApplyFilter(fileList, filter);
|
||||
std::sort(files->begin(), files->end());
|
||||
return true;
|
||||
return exists;
|
||||
}
|
||||
|
||||
std::set<std::string> filters;
|
||||
@@ -219,7 +220,7 @@ bool GetFilesInDir(const Path &directory, std::vector<FileInfo> *files, const ch
|
||||
HANDLE hFind = FindFirstFileEx((directory.ToWString() + L"\\*").c_str(), FindExInfoStandard, &ffd, FindExSearchNameMatch, NULL, 0);
|
||||
#endif
|
||||
if (hFind == INVALID_HANDLE_VALUE) {
|
||||
return 0;
|
||||
return false;
|
||||
}
|
||||
do {
|
||||
const std::string virtualName = ConvertWStringToUTF8(ffd.cFileName);
|
||||
@@ -266,7 +267,7 @@ bool GetFilesInDir(const Path &directory, std::vector<FileInfo> *files, const ch
|
||||
struct dirent *result = NULL;
|
||||
DIR *dirp = opendir(directory.c_str());
|
||||
if (!dirp)
|
||||
return 0;
|
||||
return false;
|
||||
while ((result = readdir(dirp))) {
|
||||
const std::string virtualName(result->d_name);
|
||||
// check for "." and ".."
|
||||
@@ -316,7 +317,7 @@ std::vector<std::string> GetWindowsDrives()
|
||||
{
|
||||
if (logicaldrives & (1 << i))
|
||||
{
|
||||
CHAR driveName[] = { TEXT('A') + i, TEXT(':'), TEXT('\\'), TEXT('\0') };
|
||||
CHAR driveName[] = { (CHAR)(TEXT('A') + i), TEXT(':'), TEXT('\\'), TEXT('\0') };
|
||||
std::string str(driveName);
|
||||
drives.push_back(driveName);
|
||||
}
|
||||
|
||||
@@ -271,7 +271,7 @@ bool Path::CanNavigateUp() const {
|
||||
if (type_ == PathType::CONTENT_URI) {
|
||||
return AndroidContentURI(path_).CanNavigateUp();
|
||||
}
|
||||
if (path_ == "/" || path_ == "") {
|
||||
if (path_ == "/" || path_.empty()) {
|
||||
return false;
|
||||
}
|
||||
if (type_ == PathType::HTTP) {
|
||||
@@ -357,7 +357,6 @@ bool Path::ComputePathTo(const Path &other, std::string &path) const {
|
||||
return true;
|
||||
}
|
||||
|
||||
std::string diff;
|
||||
if (type_ == PathType::CONTENT_URI) {
|
||||
AndroidContentURI a(path_);
|
||||
AndroidContentURI b(other.path_);
|
||||
|
||||
@@ -95,16 +95,13 @@ public:
|
||||
|
||||
// These functions should be self explanatory.
|
||||
void BindFramebufferAsRenderTarget(Framebuffer *fbo, const RenderPassInfo &rp, const char *tag) override;
|
||||
Framebuffer *GetCurrentRenderTarget() override {
|
||||
return curRenderTarget_;
|
||||
}
|
||||
void BindFramebufferAsTexture(Framebuffer *fbo, int binding, FBChannel channelBit, int attachment) override;
|
||||
void BindFramebufferAsTexture(Framebuffer *fbo, int binding, FBChannel channelBit, int layer) override;
|
||||
|
||||
void GetFramebufferDimensions(Framebuffer *fbo, int *w, int *h) override;
|
||||
|
||||
void InvalidateCachedState() override;
|
||||
|
||||
void BindTextures(int start, int count, Texture **textures) override;
|
||||
void BindTextures(int start, int count, Texture **textures, TextureBindFlags flags) override;
|
||||
void BindNativeTexture(int index, void *nativeTexture) override;
|
||||
void BindSamplerStates(int start, int count, SamplerState **states) override;
|
||||
void BindVertexBuffers(int start, int count, Buffer **buffers, const int *offsets) override;
|
||||
@@ -1306,35 +1303,38 @@ public:
|
||||
Framebuffer *D3D11DrawContext::CreateFramebuffer(const FramebufferDesc &desc) {
|
||||
HRESULT hr;
|
||||
D3D11Framebuffer *fb = new D3D11Framebuffer(desc.width, desc.height);
|
||||
if (desc.numColorAttachments) {
|
||||
fb->colorFormat = DXGI_FORMAT_R8G8B8A8_UNORM;
|
||||
D3D11_TEXTURE2D_DESC descColor{};
|
||||
descColor.Width = desc.width;
|
||||
descColor.Height = desc.height;
|
||||
descColor.MipLevels = 1;
|
||||
descColor.ArraySize = 1;
|
||||
descColor.Format = fb->colorFormat;
|
||||
descColor.SampleDesc.Count = 1;
|
||||
descColor.SampleDesc.Quality = 0;
|
||||
descColor.Usage = D3D11_USAGE_DEFAULT;
|
||||
descColor.BindFlags = D3D11_BIND_RENDER_TARGET | D3D11_BIND_SHADER_RESOURCE;
|
||||
descColor.CPUAccessFlags = 0;
|
||||
descColor.MiscFlags = 0;
|
||||
hr = device_->CreateTexture2D(&descColor, nullptr, &fb->colorTex);
|
||||
if (FAILED(hr)) {
|
||||
delete fb;
|
||||
return nullptr;
|
||||
}
|
||||
hr = device_->CreateRenderTargetView(fb->colorTex, nullptr, &fb->colorRTView);
|
||||
if (FAILED(hr)) {
|
||||
delete fb;
|
||||
return nullptr;
|
||||
}
|
||||
hr = device_->CreateShaderResourceView(fb->colorTex, nullptr, &fb->colorSRView);
|
||||
if (FAILED(hr)) {
|
||||
delete fb;
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
// We don't (yet?) support multiview for D3D11. Not sure if there's a way to do it.
|
||||
// Texture arrays are supported but we don't have any other use cases yet.
|
||||
_dbg_assert_(desc.numLayers == 1);
|
||||
|
||||
fb->colorFormat = DXGI_FORMAT_R8G8B8A8_UNORM;
|
||||
D3D11_TEXTURE2D_DESC descColor{};
|
||||
descColor.Width = desc.width;
|
||||
descColor.Height = desc.height;
|
||||
descColor.MipLevels = 1;
|
||||
descColor.ArraySize = 1;
|
||||
descColor.Format = fb->colorFormat;
|
||||
descColor.SampleDesc.Count = 1;
|
||||
descColor.SampleDesc.Quality = 0;
|
||||
descColor.Usage = D3D11_USAGE_DEFAULT;
|
||||
descColor.BindFlags = D3D11_BIND_RENDER_TARGET | D3D11_BIND_SHADER_RESOURCE;
|
||||
descColor.CPUAccessFlags = 0;
|
||||
descColor.MiscFlags = 0;
|
||||
hr = device_->CreateTexture2D(&descColor, nullptr, &fb->colorTex);
|
||||
if (FAILED(hr)) {
|
||||
delete fb;
|
||||
return nullptr;
|
||||
}
|
||||
hr = device_->CreateRenderTargetView(fb->colorTex, nullptr, &fb->colorRTView);
|
||||
if (FAILED(hr)) {
|
||||
delete fb;
|
||||
return nullptr;
|
||||
}
|
||||
hr = device_->CreateShaderResourceView(fb->colorTex, nullptr, &fb->colorSRView);
|
||||
if (FAILED(hr)) {
|
||||
delete fb;
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
if (desc.z_stencil) {
|
||||
@@ -1381,7 +1381,7 @@ Framebuffer *D3D11DrawContext::CreateFramebuffer(const FramebufferDesc &desc) {
|
||||
return fb;
|
||||
}
|
||||
|
||||
void D3D11DrawContext::BindTextures(int start, int count, Texture **textures) {
|
||||
void D3D11DrawContext::BindTextures(int start, int count, Texture **textures, TextureBindFlags flags) {
|
||||
// Collect the resource views from the textures.
|
||||
ID3D11ShaderResourceView *views[MAX_BOUND_TEXTURES];
|
||||
_assert_(start + count <= ARRAY_SIZE(views));
|
||||
@@ -1509,7 +1509,7 @@ bool D3D11DrawContext::BlitFramebuffer(Framebuffer *srcfb, int srcX1, int srcY1,
|
||||
return false;
|
||||
}
|
||||
|
||||
bool D3D11DrawContext::CopyFramebufferToMemorySync(Framebuffer *src, int channelBits, int bx, int by, int bw, int bh, Draw::DataFormat format, void *pixels, int pixelStride, const char *tag) {
|
||||
bool D3D11DrawContext::CopyFramebufferToMemorySync(Framebuffer *src, int channelBits, int bx, int by, int bw, int bh, Draw::DataFormat destFormat, void *pixels, int pixelStride, const char *tag) {
|
||||
D3D11Framebuffer *fb = (D3D11Framebuffer *)src;
|
||||
|
||||
if (fb) {
|
||||
@@ -1569,15 +1569,18 @@ bool D3D11DrawContext::CopyFramebufferToMemorySync(Framebuffer *src, int channel
|
||||
}
|
||||
|
||||
D3D11_BOX srcBox{ (UINT)bx, (UINT)by, 0, (UINT)(bx + bw), (UINT)(by + bh), 1 };
|
||||
DataFormat srcFormat = DataFormat::UNDEFINED;
|
||||
switch (channelBits) {
|
||||
case FB_COLOR_BIT:
|
||||
context_->CopySubresourceRegion(packTex, 0, bx, by, 0, fb ? fb->colorTex : bbRenderTargetTex_, 0, &srcBox);
|
||||
srcFormat = DataFormat::R8G8B8A8_UNORM;
|
||||
break;
|
||||
case FB_DEPTH_BIT:
|
||||
case FB_STENCIL_BIT:
|
||||
// For depth/stencil buffers, we can't reliably copy subrectangles, so just copy the whole resource.
|
||||
_assert_(fb); // Can't copy depth/stencil from backbuffer. Shouldn't happen thanks to checks above.
|
||||
context_->CopyResource(packTex, fb->depthStencilTex);
|
||||
srcFormat = Draw::DataFormat::D24_S8;
|
||||
break;
|
||||
default:
|
||||
_assert_(false);
|
||||
@@ -1594,28 +1597,51 @@ bool D3D11DrawContext::CopyFramebufferToMemorySync(Framebuffer *src, int channel
|
||||
return false;
|
||||
}
|
||||
|
||||
const int srcByteOffset = by * map.RowPitch + bx * 4;
|
||||
const size_t srcByteOffset = by * map.RowPitch + bx * DataFormatSizeInBytes(srcFormat);
|
||||
const uint8_t *srcWithOffset = (const uint8_t *)map.pData + srcByteOffset;
|
||||
switch (channelBits) {
|
||||
case FB_COLOR_BIT:
|
||||
// Pixel size always 4 here because we always request BGRA8888.
|
||||
ConvertFromRGBA8888((uint8_t *)pixels, (uint8_t *)map.pData + srcByteOffset, pixelStride, map.RowPitch / sizeof(uint32_t), bw, bh, format);
|
||||
ConvertFromRGBA8888((uint8_t *)pixels, srcWithOffset, pixelStride, map.RowPitch / sizeof(uint32_t), bw, bh, destFormat);
|
||||
break;
|
||||
case FB_DEPTH_BIT:
|
||||
for (int y = by; y < by + bh; y++) {
|
||||
float *dest = (float *)((uint8_t *)pixels + y * pixelStride * sizeof(float));
|
||||
const uint32_t *src = (const uint32_t *)((const uint8_t *)map.pData + map.RowPitch * y);
|
||||
for (int x = bx; x < bx + bw; x++) {
|
||||
dest[x] = (src[x] & 0xFFFFFF) / (256.f * 256.f * 256.f);
|
||||
if (srcFormat == destFormat) {
|
||||
// Can just memcpy when it matches no matter the format!
|
||||
uint8_t *dst = (uint8_t *)pixels;
|
||||
const uint8_t *src = (const uint8_t *)srcWithOffset;
|
||||
for (int y = 0; y < bh; ++y) {
|
||||
memcpy(dst, src, bw * DataFormatSizeInBytes(srcFormat));
|
||||
dst += pixelStride * DataFormatSizeInBytes(srcFormat);
|
||||
src += map.RowPitch;
|
||||
}
|
||||
} else if (destFormat == DataFormat::D32F) {
|
||||
ConvertToD32F((uint8_t *)pixels, srcWithOffset, pixelStride, map.RowPitch / sizeof(uint32_t), bw, bh, srcFormat);
|
||||
} else if (destFormat == DataFormat::D16) {
|
||||
ConvertToD16((uint8_t *)pixels, srcWithOffset, pixelStride, map.RowPitch / sizeof(uint32_t), bw, bh, srcFormat);
|
||||
} else {
|
||||
_assert_(false);
|
||||
}
|
||||
break;
|
||||
case FB_STENCIL_BIT:
|
||||
for (int y = by; y < by + bh; y++) {
|
||||
uint8_t *destStencil = (uint8_t *)pixels + y * pixelStride;
|
||||
const uint32_t *src = (const uint32_t *)((const uint8_t *)map.pData + map.RowPitch * y);
|
||||
for (int x = bx; x < bx + bw; x++) {
|
||||
destStencil[x] = src[x] >> 24;
|
||||
if (srcFormat == destFormat) {
|
||||
// Can just memcpy when it matches no matter the format!
|
||||
uint8_t *dst = (uint8_t *)pixels;
|
||||
const uint8_t *src = (const uint8_t *)srcWithOffset;
|
||||
for (int y = 0; y < bh; ++y) {
|
||||
memcpy(dst, src, bw * DataFormatSizeInBytes(srcFormat));
|
||||
dst += pixelStride * DataFormatSizeInBytes(srcFormat);
|
||||
src += map.RowPitch;
|
||||
}
|
||||
} else if (destFormat == DataFormat::S8) {
|
||||
for (int y = 0; y < bh; y++) {
|
||||
uint8_t *destStencil = (uint8_t *)pixels + y * pixelStride;
|
||||
const uint32_t *src = (const uint32_t *)(srcWithOffset + map.RowPitch * y);
|
||||
for (int x = 0; x < bw; x++) {
|
||||
destStencil[x] = src[x] >> 24;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
_assert_(false);
|
||||
}
|
||||
break;
|
||||
}
|
||||
@@ -1675,8 +1701,9 @@ void D3D11DrawContext::BindFramebufferAsRenderTarget(Framebuffer *fbo, const Ren
|
||||
stepId_++;
|
||||
}
|
||||
|
||||
void D3D11DrawContext::BindFramebufferAsTexture(Framebuffer *fbo, int binding, FBChannel channelBit, int attachment) {
|
||||
_assert_(binding < MAX_BOUND_TEXTURES);
|
||||
void D3D11DrawContext::BindFramebufferAsTexture(Framebuffer *fbo, int binding, FBChannel channelBit, int layer) {
|
||||
_dbg_assert_(binding < MAX_BOUND_TEXTURES);
|
||||
_dbg_assert_(layer == ALL_LAYERS || layer == 0); // No multiple layer support on D3D
|
||||
D3D11Framebuffer *fb = (D3D11Framebuffer *)fbo;
|
||||
switch (channelBit) {
|
||||
case FBChannel::FB_COLOR_BIT:
|
||||
|
||||
@@ -47,7 +47,7 @@ LPD3DBLOB CompileShaderToByteCodeD3D9(const char *code, const char *target, std:
|
||||
pShaderCode = nullptr;
|
||||
}
|
||||
} else {
|
||||
*errorMessage = "";
|
||||
errorMessage->clear();
|
||||
}
|
||||
|
||||
return pShaderCode;
|
||||
|
||||
@@ -398,15 +398,3 @@ public:
|
||||
#undef STATE2
|
||||
|
||||
extern DirectXState dxstate;
|
||||
|
||||
struct GLExtensions {
|
||||
bool OES_depth24;
|
||||
bool OES_packed_depth_stencil;
|
||||
bool OES_depth_texture;
|
||||
bool EXT_discard_framebuffer;
|
||||
bool FBO_ARB;
|
||||
};
|
||||
|
||||
extern GLExtensions gl_extensions;
|
||||
|
||||
void CheckGLExtensions();
|
||||
+127
-15
@@ -201,11 +201,19 @@ public:
|
||||
D3DTEXTUREFILTERTYPE magFilt, minFilt, mipFilt;
|
||||
|
||||
void Apply(LPDIRECT3DDEVICE9 device, int index) {
|
||||
dxstate.texAddressU.set(wrapS);
|
||||
dxstate.texAddressV.set(wrapT);
|
||||
dxstate.texMagFilter.set(magFilt);
|
||||
dxstate.texMinFilter.set(minFilt);
|
||||
dxstate.texMipFilter.set(mipFilt);
|
||||
if (index == 0) {
|
||||
dxstate.texAddressU.set(wrapS);
|
||||
dxstate.texAddressV.set(wrapT);
|
||||
dxstate.texMagFilter.set(magFilt);
|
||||
dxstate.texMinFilter.set(minFilt);
|
||||
dxstate.texMipFilter.set(mipFilt);
|
||||
} else {
|
||||
pD3Ddevice9->SetSamplerState(index, D3DSAMP_ADDRESSU, wrapS);
|
||||
pD3Ddevice9->SetSamplerState(index, D3DSAMP_ADDRESSV, wrapT);
|
||||
pD3Ddevice9->SetSamplerState(index, D3DSAMP_MAGFILTER, magFilt);
|
||||
pD3Ddevice9->SetSamplerState(index, D3DSAMP_MINFILTER, minFilt);
|
||||
pD3Ddevice9->SetSamplerState(index, D3DSAMP_MIPFILTER, mipFilt);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
@@ -520,19 +528,17 @@ public:
|
||||
// Not implemented
|
||||
}
|
||||
bool BlitFramebuffer(Framebuffer *src, int srcX1, int srcY1, int srcX2, int srcY2, Framebuffer *dst, int dstX1, int dstY1, int dstX2, int dstY2, int channelBits, FBBlitFilter filter, const char *tag) override;
|
||||
bool CopyFramebufferToMemorySync(Framebuffer *src, int channelBits, int x, int y, int w, int h, Draw::DataFormat format, void *pixels, int pixelStride, const char *tag) override;
|
||||
|
||||
// These functions should be self explanatory.
|
||||
void BindFramebufferAsRenderTarget(Framebuffer *fbo, const RenderPassInfo &rp, const char *tag) override;
|
||||
Framebuffer *GetCurrentRenderTarget() override {
|
||||
return curRenderTarget_;
|
||||
}
|
||||
void BindFramebufferAsTexture(Framebuffer *fbo, int binding, FBChannel channelBit, int attachment) override;
|
||||
|
||||
void BindFramebufferAsTexture(Framebuffer *fbo, int binding, FBChannel channelBit, int layer) override;
|
||||
|
||||
uintptr_t GetFramebufferAPITexture(Framebuffer *fbo, int channelBits, int attachment) override;
|
||||
|
||||
void GetFramebufferDimensions(Framebuffer *fbo, int *w, int *h) override;
|
||||
|
||||
void BindTextures(int start, int count, Texture **textures) override;
|
||||
void BindTextures(int start, int count, Texture **textures, TextureBindFlags flags) override;
|
||||
void BindNativeTexture(int index, void *nativeTexture) override;
|
||||
|
||||
void BindSamplerStates(int start, int count, SamplerState **states) override {
|
||||
@@ -740,7 +746,6 @@ D3D9Context::D3D9Context(IDirect3D9 *d3d, IDirect3D9Ex *d3dEx, int adapterId, ID
|
||||
}
|
||||
|
||||
caps_.deviceID = identifier_.DeviceId;
|
||||
caps_.multiViewport = false;
|
||||
caps_.depthRangeMinusOneToOne = false;
|
||||
caps_.preferredDepthBufferFormat = DataFormat::D24_S8;
|
||||
caps_.dualSourceBlend = false;
|
||||
@@ -906,7 +911,7 @@ Texture *D3D9Context::CreateTexture(const TextureDesc &desc) {
|
||||
return tex;
|
||||
}
|
||||
|
||||
void D3D9Context::BindTextures(int start, int count, Texture **textures) {
|
||||
void D3D9Context::BindTextures(int start, int count, Texture **textures, TextureBindFlags flags) {
|
||||
_assert_(start + count <= MAX_BOUND_TEXTURES);
|
||||
for (int i = start; i < start + count; i++) {
|
||||
D3D9Texture *tex = static_cast<D3D9Texture *>(textures[i - start]);
|
||||
@@ -1235,6 +1240,9 @@ public:
|
||||
};
|
||||
|
||||
Framebuffer *D3D9Context::CreateFramebuffer(const FramebufferDesc &desc) {
|
||||
// Don't think D3D9 does array layers.
|
||||
_dbg_assert_(desc.numLayers == 1);
|
||||
|
||||
static uint32_t id = 0;
|
||||
|
||||
D3D9Framebuffer *fbo = new D3D9Framebuffer(desc.width, desc.height);
|
||||
@@ -1309,6 +1317,7 @@ void D3D9Context::BindFramebufferAsRenderTarget(Framebuffer *fbo, const RenderPa
|
||||
}
|
||||
|
||||
dxstate.scissorRect.restore();
|
||||
dxstate.scissorTest.restore();
|
||||
dxstate.viewport.restore();
|
||||
stepId_++;
|
||||
}
|
||||
@@ -1338,8 +1347,9 @@ uintptr_t D3D9Context::GetFramebufferAPITexture(Framebuffer *fbo, int channelBit
|
||||
}
|
||||
}
|
||||
|
||||
void D3D9Context::BindFramebufferAsTexture(Framebuffer *fbo, int binding, FBChannel channelBit, int color) {
|
||||
_assert_(binding < MAX_BOUND_TEXTURES);
|
||||
void D3D9Context::BindFramebufferAsTexture(Framebuffer *fbo, int binding, FBChannel channelBit, int layer) {
|
||||
_dbg_assert_(binding < MAX_BOUND_TEXTURES);
|
||||
_dbg_assert_(layer == ALL_LAYERS || layer == 0); // No stereo support
|
||||
D3D9Framebuffer *fb = (D3D9Framebuffer *)fbo;
|
||||
switch (channelBit) {
|
||||
case FB_DEPTH_BIT:
|
||||
@@ -1392,6 +1402,108 @@ bool D3D9Context::BlitFramebuffer(Framebuffer *srcfb, int srcX1, int srcY1, int
|
||||
return SUCCEEDED(device_->StretchRect(srcSurf, &srcRect, dstSurf, &dstRect, (filter == FB_BLIT_LINEAR && channelBits == FB_COLOR_BIT) ? D3DTEXF_LINEAR : D3DTEXF_POINT));
|
||||
}
|
||||
|
||||
bool D3D9Context::CopyFramebufferToMemorySync(Framebuffer *src, int channelBits, int bx, int by, int bw, int bh, Draw::DataFormat destFormat, void *pixels, int pixelStride, const char *tag) {
|
||||
D3D9Framebuffer *fb = (D3D9Framebuffer *)src;
|
||||
|
||||
if (fb) {
|
||||
if (bx + bw > fb->Width()) {
|
||||
bw -= (bx + bw) - fb->Width();
|
||||
}
|
||||
if (by + bh > fb->Height()) {
|
||||
bh -= (by + bh) - fb->Height();
|
||||
}
|
||||
}
|
||||
|
||||
if (bh <= 0 || bw <= 0)
|
||||
return true;
|
||||
|
||||
DataFormat srcFormat = Draw::DataFormat::R8G8B8A8_UNORM;
|
||||
if (channelBits != FB_COLOR_BIT) {
|
||||
srcFormat = Draw::DataFormat::D24_S8;
|
||||
if (!supportsINTZ)
|
||||
return false;
|
||||
}
|
||||
|
||||
D3DSURFACE_DESC desc;
|
||||
D3DLOCKED_RECT locked;
|
||||
RECT rect = { (LONG)bx, (LONG)by, (LONG)bw, (LONG)bh };
|
||||
|
||||
LPDIRECT3DSURFACE9 offscreen = nullptr;
|
||||
HRESULT hr = E_UNEXPECTED;
|
||||
if (channelBits == FB_COLOR_BIT) {
|
||||
fb->tex->GetLevelDesc(0, &desc);
|
||||
|
||||
hr = device_->CreateOffscreenPlainSurface(desc.Width, desc.Height, desc.Format, D3DPOOL_SYSTEMMEM, &offscreen, nullptr);
|
||||
if (SUCCEEDED(hr)) {
|
||||
hr = device_->GetRenderTargetData(fb->surf, offscreen);
|
||||
if (SUCCEEDED(hr)) {
|
||||
hr = offscreen->LockRect(&locked, &rect, D3DLOCK_READONLY);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
fb->depthstenciltex->GetLevelDesc(0, &desc);
|
||||
hr = fb->depthstenciltex->LockRect(0, &locked, &rect, D3DLOCK_READONLY);
|
||||
}
|
||||
|
||||
if (SUCCEEDED(hr)) {
|
||||
switch (channelBits) {
|
||||
case FB_COLOR_BIT:
|
||||
// Pixel size always 4 here because we always request BGRA8888.
|
||||
ConvertFromBGRA8888((uint8_t *)pixels, (const uint8_t *)locked.pBits, pixelStride, locked.Pitch / sizeof(uint32_t), bw, bh, destFormat);
|
||||
break;
|
||||
case FB_DEPTH_BIT:
|
||||
if (srcFormat == destFormat) {
|
||||
// Can just memcpy when it matches no matter the format!
|
||||
uint8_t *dst = (uint8_t *)pixels;
|
||||
const uint8_t *src = (const uint8_t *)locked.pBits;
|
||||
for (int y = 0; y < bh; ++y) {
|
||||
memcpy(dst, src, bw * DataFormatSizeInBytes(srcFormat));
|
||||
dst += pixelStride * DataFormatSizeInBytes(srcFormat);
|
||||
src += locked.Pitch;
|
||||
}
|
||||
} else if (destFormat == DataFormat::D32F) {
|
||||
ConvertToD32F((uint8_t *)pixels, (const uint8_t *)locked.pBits, pixelStride, locked.Pitch / sizeof(uint32_t), bw, bh, srcFormat);
|
||||
} else if (destFormat == DataFormat::D16) {
|
||||
ConvertToD16((uint8_t *)pixels, (const uint8_t *)locked.pBits, pixelStride, locked.Pitch / sizeof(uint32_t), bw, bh, srcFormat);
|
||||
} else {
|
||||
_assert_(false);
|
||||
}
|
||||
break;
|
||||
case FB_STENCIL_BIT:
|
||||
if (srcFormat == destFormat) {
|
||||
uint8_t *dst = (uint8_t *)pixels;
|
||||
const uint8_t *src = (const uint8_t *)locked.pBits;
|
||||
for (int y = 0; y < bh; ++y) {
|
||||
memcpy(dst, src, bw * DataFormatSizeInBytes(srcFormat));
|
||||
dst += pixelStride * DataFormatSizeInBytes(srcFormat);
|
||||
src += locked.Pitch;
|
||||
}
|
||||
} else if (destFormat == DataFormat::S8) {
|
||||
for (int y = 0; y < bh; y++) {
|
||||
uint8_t *destStencil = (uint8_t *)pixels + y * pixelStride;
|
||||
const uint32_t *src = (const uint32_t *)((const uint8_t *)locked.pBits + locked.Pitch * y);
|
||||
for (int x = 0; x < bw; x++) {
|
||||
destStencil[x] = src[x] >> 24;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
_assert_(false);
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (channelBits != FB_COLOR_BIT) {
|
||||
fb->depthstenciltex->UnlockRect(0);
|
||||
}
|
||||
if (offscreen) {
|
||||
offscreen->UnlockRect();
|
||||
offscreen->Release();
|
||||
}
|
||||
|
||||
return SUCCEEDED(hr);
|
||||
}
|
||||
|
||||
void D3D9Context::HandleEvent(Event ev, int width, int height, void *param1, void *param2) {
|
||||
switch (ev) {
|
||||
case Event::LOST_BACKBUFFER:
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
#include "Common/GPU/OpenGL/DataFormatGL.h"
|
||||
#include "Common/GPU/OpenGL/GLFeatures.h"
|
||||
#include "Common/Log.h"
|
||||
|
||||
namespace Draw {
|
||||
@@ -15,8 +16,16 @@ bool Thin3DFormatToGLFormatAndType(DataFormat fmt, GLuint &internalFormat, GLuin
|
||||
break;
|
||||
|
||||
case DataFormat::R8_UNORM:
|
||||
internalFormat = GL_RGBA;
|
||||
format = GL_RED;
|
||||
if (gl_extensions.IsGLES) {
|
||||
internalFormat = GL_LUMINANCE;
|
||||
format = GL_LUMINANCE;
|
||||
} else if (gl_extensions.VersionGEThan(3, 0)) {
|
||||
internalFormat = GL_RED;
|
||||
format = GL_RED;
|
||||
} else {
|
||||
internalFormat = GL_RGBA;
|
||||
format = GL_RED;
|
||||
}
|
||||
type = GL_UNSIGNED_BYTE;
|
||||
alignment = 1;
|
||||
break;
|
||||
|
||||
@@ -51,7 +51,7 @@ static void ParseExtensionsString(const std::string& str, std::set<std::string>
|
||||
size_t next = 0;
|
||||
for (size_t pos = 0, len = str.length(); pos < len; ++pos) {
|
||||
if (str[pos] == ' ') {
|
||||
output.insert(str.substr(next, pos - next));
|
||||
output.emplace(str.substr(next, pos - next));
|
||||
// Skip the delimiter itself.
|
||||
next = pos + 1;
|
||||
}
|
||||
@@ -60,7 +60,7 @@ static void ParseExtensionsString(const std::string& str, std::set<std::string>
|
||||
if (next == 0 && str.length() != 0) {
|
||||
output.insert(str);
|
||||
} else if (next < str.length()) {
|
||||
output.insert(str.substr(next));
|
||||
output.emplace(str.substr(next));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -386,6 +386,7 @@ void CheckGLExtensions() {
|
||||
gl_extensions.OES_texture_3D = g_set_gl_extensions.count("GL_OES_texture_3D") != 0;
|
||||
gl_extensions.EXT_buffer_storage = g_set_gl_extensions.count("GL_EXT_buffer_storage") != 0;
|
||||
gl_extensions.EXT_clip_cull_distance = g_set_gl_extensions.count("GL_EXT_clip_cull_distance") != 0;
|
||||
gl_extensions.EXT_depth_clamp = g_set_gl_extensions.count("GL_EXT_depth_clamp") != 0;
|
||||
gl_extensions.APPLE_clip_distance = g_set_gl_extensions.count("GL_APPLE_clip_distance") != 0;
|
||||
|
||||
#if defined(__ANDROID__)
|
||||
@@ -543,8 +544,8 @@ void CheckGLExtensions() {
|
||||
}
|
||||
if (gl_extensions.VersionGEThan(4, 3)) {
|
||||
gl_extensions.ARB_copy_image = true;
|
||||
gl_extensions.ARB_stencil_texturing = true;
|
||||
// ARB_explicit_uniform_location = true;
|
||||
// ARB_stencil_texturing = true;
|
||||
// ARB_texture_view = true;
|
||||
// ARB_vertex_attrib_binding = true;
|
||||
}
|
||||
|
||||
@@ -71,6 +71,7 @@ struct GLExtensions {
|
||||
bool ARB_depth_clamp;
|
||||
bool ARB_uniform_buffer_object;
|
||||
bool ARB_texture_non_power_of_two;
|
||||
bool ARB_stencil_texturing;
|
||||
|
||||
// EXT
|
||||
bool EXT_swap_control_tear;
|
||||
@@ -87,6 +88,7 @@ struct GLExtensions {
|
||||
bool EXT_draw_instanced;
|
||||
bool EXT_buffer_storage;
|
||||
bool EXT_clip_cull_distance;
|
||||
bool EXT_depth_clamp;
|
||||
|
||||
// NV
|
||||
bool NV_copy_image;
|
||||
|
||||
@@ -24,6 +24,12 @@
|
||||
#elif !defined(GL_CLIP_DISTANCE0)
|
||||
#define GL_CLIP_DISTANCE0 0x3000
|
||||
#endif
|
||||
#ifndef GL_DEPTH_STENCIL_TEXTURE_MODE
|
||||
#define GL_DEPTH_STENCIL_TEXTURE_MODE 0x90EA
|
||||
#endif
|
||||
#ifndef GL_STENCIL_INDEX
|
||||
#define GL_STENCIL_INDEX 0x1901
|
||||
#endif
|
||||
|
||||
static constexpr int TEXCACHE_NAME_CACHE_SIZE = 16;
|
||||
|
||||
@@ -274,7 +280,7 @@ void GLQueueRunner::RunInitSteps(const std::vector<GLRInitStep> &steps, bool ski
|
||||
_dbg_assert_(query.name);
|
||||
|
||||
int location = -1;
|
||||
if (IsVRBuild() && IsMultiviewSupported()) {
|
||||
if (IsVREnabled() && IsMultiviewSupported()) {
|
||||
int index = GetStereoBufferIndex(query.name);
|
||||
if (index >= 0) {
|
||||
std::string layout = GetStereoBufferLayout(query.name);
|
||||
@@ -642,7 +648,7 @@ retry_depth:
|
||||
currentReadHandle_ = fbo->handle;
|
||||
}
|
||||
|
||||
void GLQueueRunner::RunSteps(const std::vector<GLRStep *> &steps, bool skipGLCalls, bool keepSteps) {
|
||||
void GLQueueRunner::RunSteps(const std::vector<GLRStep *> &steps, bool skipGLCalls, bool keepSteps, bool useVR) {
|
||||
if (skipGLCalls) {
|
||||
if (keepSteps) {
|
||||
return;
|
||||
@@ -701,7 +707,7 @@ void GLQueueRunner::RunSteps(const std::vector<GLRStep *> &steps, bool skipGLCal
|
||||
switch (step.stepType) {
|
||||
case GLRStepType::RENDER:
|
||||
renderCount++;
|
||||
if (IsVRBuild()) {
|
||||
if (IsVREnabled()) {
|
||||
GLRStep vrStep = step;
|
||||
PreprocessStepVR(&vrStep);
|
||||
PerformRenderPass(vrStep, renderCount == 1, renderCount == totalRenderCount);
|
||||
@@ -1114,8 +1120,16 @@ void GLQueueRunner::PerformRenderPass(const GLRStep &step, bool first, bool last
|
||||
glBindTexture(GL_TEXTURE_2D, c.bind_fb_texture.framebuffer->z_stencil_texture.texture);
|
||||
curTex[slot] = &c.bind_fb_texture.framebuffer->z_stencil_texture;
|
||||
}
|
||||
// This should be uncommon, so always set the mode.
|
||||
glTexParameteri(GL_TEXTURE_2D, GL_DEPTH_STENCIL_TEXTURE_MODE, GL_DEPTH_COMPONENT);
|
||||
} else if (c.bind_fb_texture.aspect == GL_STENCIL_BUFFER_BIT) {
|
||||
if (curTex[slot] != &c.bind_fb_texture.framebuffer->z_stencil_texture) {
|
||||
glBindTexture(GL_TEXTURE_2D, c.bind_fb_texture.framebuffer->z_stencil_texture.texture);
|
||||
curTex[slot] = &c.bind_fb_texture.framebuffer->z_stencil_texture;
|
||||
}
|
||||
// This should be uncommon, so always set the mode.
|
||||
glTexParameteri(GL_TEXTURE_2D, GL_DEPTH_STENCIL_TEXTURE_MODE, GL_STENCIL_INDEX);
|
||||
} else {
|
||||
// Can't texture from stencil buffers.
|
||||
curTex[slot] = nullptr;
|
||||
}
|
||||
CHECK_GL_ERROR_IF_DEBUG();
|
||||
@@ -1589,6 +1603,9 @@ void GLQueueRunner::PerformBindFramebufferAsRenderTarget(const GLRStep &pass) {
|
||||
fbo_bind_fb_target(false, curFB_->handle);
|
||||
} else {
|
||||
fbo_unbind();
|
||||
if (IsVREnabled()) {
|
||||
BindVRFramebuffer();
|
||||
}
|
||||
// Backbuffer is now bound.
|
||||
}
|
||||
CHECK_GL_ERROR_IF_DEBUG();
|
||||
@@ -1741,10 +1758,6 @@ void GLQueueRunner::fbo_unbind() {
|
||||
bindDefaultFBO();
|
||||
#endif
|
||||
|
||||
if (IsVRBuild()) {
|
||||
BindVRFramebuffer();
|
||||
}
|
||||
|
||||
currentDrawHandle_ = 0;
|
||||
currentReadHandle_ = 0;
|
||||
CHECK_GL_ERROR_IF_DEBUG();
|
||||
|
||||
@@ -363,7 +363,7 @@ public:
|
||||
|
||||
void RunInitSteps(const std::vector<GLRInitStep> &steps, bool skipGLCalls);
|
||||
|
||||
void RunSteps(const std::vector<GLRStep *> &steps, bool skipGLCalls, bool keepSteps = false);
|
||||
void RunSteps(const std::vector<GLRStep *> &steps, bool skipGLCalls, bool keepSteps, bool useVR);
|
||||
void LogSteps(const std::vector<GLRStep *> &steps);
|
||||
|
||||
void CreateDeviceObjects();
|
||||
|
||||
@@ -5,8 +5,6 @@
|
||||
#include "Common/Thread/ThreadUtil.h"
|
||||
#include "Common/VR/PPSSPPVR.h"
|
||||
|
||||
#include "Core/Config.h"
|
||||
|
||||
#include "Common/Log.h"
|
||||
#include "Common/MemoryUtil.h"
|
||||
#include "Common/Math/math_util.h"
|
||||
@@ -236,28 +234,12 @@ bool GLRenderManager::ThreadFrame() {
|
||||
firstFrame = false;
|
||||
}
|
||||
|
||||
// Start of an OpenXR frame. This updates user's head pose and VR timestamps.
|
||||
// For fluent rendering, delay between StartVRRender and FinishVRRender must be very short.
|
||||
if (IsVRBuild() && !vrRenderStarted) {
|
||||
if (StartVRRender()) {
|
||||
vrRenderStarted = true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// Render the scene.
|
||||
Run(threadFrame_);
|
||||
|
||||
VLOG("PULL: Finished frame %d", threadFrame_);
|
||||
} while (!nextFrame);
|
||||
|
||||
// Post OpenXR frame on a screen.
|
||||
if (IsVRBuild() && vrRenderStarted) {
|
||||
FinishVRRender();
|
||||
vrRenderStarted = false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -374,7 +356,7 @@ void GLRenderManager::BindFramebufferAsRenderTarget(GLRFramebuffer *fb, GLRRende
|
||||
}
|
||||
}
|
||||
|
||||
void GLRenderManager::BindFramebufferAsTexture(GLRFramebuffer *fb, int binding, int aspectBit, int attachment) {
|
||||
void GLRenderManager::BindFramebufferAsTexture(GLRFramebuffer *fb, int binding, int aspectBit) {
|
||||
_dbg_assert_(curRenderStep_ && curRenderStep_->stepType == GLRStepType::RENDER);
|
||||
_dbg_assert_(binding < MAX_GL_TEXTURE_SLOTS);
|
||||
GLRRenderData data{ GLRRenderCommand::BIND_FB_TEXTURE };
|
||||
@@ -595,18 +577,15 @@ void GLRenderManager::Run(int frame) {
|
||||
}
|
||||
}
|
||||
|
||||
if (IsVRBuild()) {
|
||||
int passes = 1;
|
||||
if (!IsMultiviewSupported() && g_Config.bEnableStereo) {
|
||||
passes = 2;
|
||||
}
|
||||
if (IsVREnabled()) {
|
||||
int passes = GetVRPassesCount();
|
||||
for (int i = 0; i < passes; i++) {
|
||||
PreVRFrameRender(i);
|
||||
queueRunner_.RunSteps(stepsOnThread, skipGLCalls_, i < passes - 1);
|
||||
queueRunner_.RunSteps(stepsOnThread, skipGLCalls_, i < passes - 1, true);
|
||||
PostVRFrameRender();
|
||||
}
|
||||
} else {
|
||||
queueRunner_.RunSteps(stepsOnThread, skipGLCalls_);
|
||||
queueRunner_.RunSteps(stepsOnThread, skipGLCalls_, false, false);
|
||||
}
|
||||
stepsOnThread.clear();
|
||||
|
||||
|
||||
@@ -526,7 +526,7 @@ public:
|
||||
void BindFramebufferAsRenderTarget(GLRFramebuffer *fb, GLRRenderPassAction color, GLRRenderPassAction depth, GLRRenderPassAction stencil, uint32_t clearColor, float clearDepth, uint8_t clearStencil, const char *tag);
|
||||
|
||||
// Binds a framebuffer as a texture, for the following draws.
|
||||
void BindFramebufferAsTexture(GLRFramebuffer *fb, int binding, int aspectBit, int attachment);
|
||||
void BindFramebufferAsTexture(GLRFramebuffer *fb, int binding, int aspectBit);
|
||||
|
||||
bool CopyFramebufferToMemorySync(GLRFramebuffer *src, int aspectBits, int x, int y, int w, int h, Draw::DataFormat destFormat, uint8_t *pixels, int pixelStride, const char *tag);
|
||||
void CopyImageToMemorySync(GLRTexture *texture, int mipLevel, int x, int y, int w, int h, Draw::DataFormat destFormat, uint8_t *pixels, int pixelStride, const char *tag);
|
||||
@@ -1051,7 +1051,6 @@ private:
|
||||
|
||||
bool nextFrame = false;
|
||||
bool firstFrame = true;
|
||||
bool vrRenderStarted = false;
|
||||
|
||||
GLDeleter deleter_;
|
||||
bool skipGLCalls_ = false;
|
||||
|
||||
@@ -355,10 +355,7 @@ public:
|
||||
|
||||
// These functions should be self explanatory.
|
||||
void BindFramebufferAsRenderTarget(Framebuffer *fbo, const RenderPassInfo &rp, const char *tag) override;
|
||||
Framebuffer *GetCurrentRenderTarget() override {
|
||||
return curRenderTarget_;
|
||||
}
|
||||
void BindFramebufferAsTexture(Framebuffer *fbo, int binding, FBChannel channelBit, int attachment) override;
|
||||
void BindFramebufferAsTexture(Framebuffer *fbo, int binding, FBChannel channelBit, int layer) override;
|
||||
|
||||
void GetFramebufferDimensions(Framebuffer *fbo, int *w, int *h) override;
|
||||
|
||||
@@ -400,7 +397,7 @@ public:
|
||||
curPipeline_->depthStencil->stencilPass);
|
||||
}
|
||||
|
||||
void BindTextures(int start, int count, Texture **textures) override;
|
||||
void BindTextures(int start, int count, Texture **textures, TextureBindFlags flags) override;
|
||||
void BindNativeTexture(int sampler, void *nativeTexture) override;
|
||||
|
||||
void BindPipeline(Pipeline *pipeline) override;
|
||||
@@ -551,7 +548,7 @@ OpenGLContext::OpenGLContext() {
|
||||
caps_.framebufferBlitSupported = gl_extensions.NV_framebuffer_blit || gl_extensions.ARB_framebuffer_object || gl_extensions.GLES3;
|
||||
caps_.framebufferDepthBlitSupported = caps_.framebufferBlitSupported;
|
||||
caps_.framebufferStencilBlitSupported = caps_.framebufferBlitSupported;
|
||||
caps_.depthClampSupported = gl_extensions.ARB_depth_clamp;
|
||||
caps_.depthClampSupported = gl_extensions.ARB_depth_clamp || gl_extensions.EXT_depth_clamp;
|
||||
caps_.blendMinMaxSupported = gl_extensions.EXT_blend_minmax;
|
||||
|
||||
if (gl_extensions.IsGLES) {
|
||||
@@ -1130,7 +1127,7 @@ Pipeline *OpenGLContext::CreateGraphicsPipeline(const PipelineDesc &desc, const
|
||||
}
|
||||
}
|
||||
|
||||
void OpenGLContext::BindTextures(int start, int count, Texture **textures) {
|
||||
void OpenGLContext::BindTextures(int start, int count, Texture **textures, TextureBindFlags flags) {
|
||||
_assert_(start + count <= MAX_TEXTURE_SLOTS);
|
||||
for (int i = start; i < start + count; i++) {
|
||||
OpenGLTexture *glTex = static_cast<OpenGLTexture *>(textures[i - start]);
|
||||
@@ -1203,6 +1200,7 @@ bool OpenGLPipeline::LinkShaders() {
|
||||
}
|
||||
|
||||
std::vector<GLRProgram::Semantic> semantics;
|
||||
semantics.reserve(8);
|
||||
// Bind all the common vertex data points. Mismatching ones will be ignored.
|
||||
semantics.push_back({ SEM_POSITION, "Position" });
|
||||
semantics.push_back({ SEM_COLOR0, "Color0" });
|
||||
@@ -1389,6 +1387,9 @@ void OpenGLInputLayout::Compile(const InputLayoutDesc &desc) {
|
||||
Framebuffer *OpenGLContext::CreateFramebuffer(const FramebufferDesc &desc) {
|
||||
CheckGLExtensions();
|
||||
|
||||
// TODO: Support multiview later. (It's our only use case for multi layers).
|
||||
_dbg_assert_(desc.numLayers == 1);
|
||||
|
||||
GLRFramebuffer *framebuffer = renderManager_.CreateFramebuffer(desc.width, desc.height, desc.z_stencil);
|
||||
OpenGLFramebuffer *fbo = new OpenGLFramebuffer(&renderManager_, framebuffer);
|
||||
return fbo;
|
||||
@@ -1435,7 +1436,7 @@ bool OpenGLContext::BlitFramebuffer(Framebuffer *fbsrc, int srcX1, int srcY1, in
|
||||
return true;
|
||||
}
|
||||
|
||||
void OpenGLContext::BindFramebufferAsTexture(Framebuffer *fbo, int binding, FBChannel channelBit, int color) {
|
||||
void OpenGLContext::BindFramebufferAsTexture(Framebuffer *fbo, int binding, FBChannel channelBit, int layer) {
|
||||
OpenGLFramebuffer *fb = (OpenGLFramebuffer *)fbo;
|
||||
_assert_(binding < MAX_TEXTURE_SLOTS);
|
||||
|
||||
@@ -1452,7 +1453,7 @@ void OpenGLContext::BindFramebufferAsTexture(Framebuffer *fbo, int binding, FBCh
|
||||
aspect |= GL_STENCIL_BUFFER_BIT;
|
||||
boundTextures_[binding] = &fb->framebuffer_->z_stencil_texture;
|
||||
}
|
||||
renderManager_.BindFramebufferAsTexture(fb->framebuffer_, binding, aspect, color);
|
||||
renderManager_.BindFramebufferAsTexture(fb->framebuffer_, binding, aspect);
|
||||
}
|
||||
|
||||
void OpenGLContext::GetFramebufferDimensions(Framebuffer *fbo, int *w, int *h) {
|
||||
|
||||
@@ -202,6 +202,7 @@ void init_resources(TBuiltInResource &Resources) {
|
||||
Resources.maxCullDistances = 8;
|
||||
Resources.maxCombinedClipAndCullDistances = 8;
|
||||
Resources.maxSamples = 4;
|
||||
Resources.maxDualSourceDrawBuffersEXT = 1;
|
||||
Resources.limits.nonInductiveForLoops = 1;
|
||||
Resources.limits.whileLoops = 1;
|
||||
Resources.limits.doWhileLoops = 1;
|
||||
|
||||
+10
-2
@@ -4,9 +4,12 @@
|
||||
#include <cstdint>
|
||||
#include <cstddef> // for size_t
|
||||
|
||||
#include "Common/Common.h"
|
||||
|
||||
// GLSL_1xx and GLSL_3xx each cover a lot of sub variants. All the little quirks
|
||||
// that differ are covered in ShaderLanguageDesc.
|
||||
// Defined as a bitmask so stuff like GetSupportedShaderLanguages can return combinations.
|
||||
// TODO: We can probably move away from this distinction soon, now that we mostly generate/translate shaders.
|
||||
enum ShaderLanguage {
|
||||
GLSL_1xx = 1,
|
||||
GLSL_3xx = 2,
|
||||
@@ -30,7 +33,6 @@ enum class ShaderStage {
|
||||
|
||||
const char *ShaderStageAsString(ShaderStage lang);
|
||||
|
||||
|
||||
struct ShaderLanguageDesc {
|
||||
ShaderLanguageDesc() {}
|
||||
explicit ShaderLanguageDesc(ShaderLanguage lang);
|
||||
@@ -91,12 +93,18 @@ struct UniformDef {
|
||||
int index;
|
||||
};
|
||||
|
||||
enum class SamplerFlags {
|
||||
ARRAY_ON_VULKAN = 1,
|
||||
};
|
||||
ENUM_CLASS_BITOPS(SamplerFlags);
|
||||
|
||||
struct SamplerDef {
|
||||
int binding; // Might only be used by some backends.
|
||||
const char *name;
|
||||
SamplerFlags flags;
|
||||
// TODO: Might need unsigned samplers, 3d samplers, or other types in the future.
|
||||
};
|
||||
|
||||
|
||||
// For passing error messages from shader compilation (and other critical issues) back to the host.
|
||||
// This can run on any thread - be aware!
|
||||
// TODO: See if we can find a less generic name for this.
|
||||
|
||||
@@ -98,7 +98,7 @@ R"(#version 450
|
||||
)";
|
||||
|
||||
static const char *vulkanUboDecl = R"(
|
||||
layout (std140, set = 0, binding = 0) uniform Data {
|
||||
layout (std140, set = 1, binding = 0) uniform Data {
|
||||
vec2 u_texelDelta;
|
||||
vec2 u_pixelDelta;
|
||||
vec4 u_time;
|
||||
@@ -187,11 +187,11 @@ bool ConvertToVulkanGLSL(std::string *dest, TranslatedShaderMetadata *destMetada
|
||||
continue;
|
||||
} else if (line.find("uniform sampler2D") == 0) {
|
||||
if (sscanf(line.c_str(), "uniform sampler2D sampler%d", &num) == 1)
|
||||
line = StringFromFormat("layout(set = 0, binding = %d) ", num + 1) + line;
|
||||
line = StringFromFormat("layout(set = 1, binding = %d) ", num + 1) + line;
|
||||
else if (line.find("sampler0") != line.npos)
|
||||
line = "layout(set = 0, binding = 1) " + line;
|
||||
line = "layout(set = 1, binding = 1) " + line;
|
||||
else
|
||||
line = "layout(set = 0, binding = 2) " + line;
|
||||
line = "layout(set = 1, binding = 2) " + line;
|
||||
} else if (line.find("uniform ") != std::string::npos) {
|
||||
continue;
|
||||
} else if (2 == sscanf(line.c_str(), "varying vec%d v_texcoord%d;", &vecSize, &num)) {
|
||||
@@ -235,7 +235,7 @@ bool TranslateShader(std::string *dest, ShaderLanguage destLang, const ShaderLan
|
||||
return false;
|
||||
#endif
|
||||
|
||||
*errorMessage = "";
|
||||
errorMessage->clear();
|
||||
|
||||
glslang::TProgram program;
|
||||
const char *shaderStrings[1]{};
|
||||
|
||||
+71
-28
@@ -7,7 +7,6 @@
|
||||
#include "Common/Log.h"
|
||||
|
||||
const char * const vulkan_glsl_preamble_fs =
|
||||
"#version 450\n"
|
||||
"#extension GL_ARB_separate_shader_objects : enable\n"
|
||||
"#extension GL_ARB_shading_language_420pack : enable\n"
|
||||
"#extension GL_ARB_conservative_depth : enable\n"
|
||||
@@ -45,7 +44,6 @@ static const char * const hlsl_d3d9_preamble_fs =
|
||||
"#define DISCARD_BELOW(x) clip(x)\n";
|
||||
|
||||
static const char * const vulkan_glsl_preamble_vs =
|
||||
"#version 450\n"
|
||||
"#extension GL_ARB_separate_shader_objects : enable\n"
|
||||
"#extension GL_ARB_shading_language_420pack : enable\n"
|
||||
"#define mul(x, y) ((x) * (y))\n"
|
||||
@@ -69,7 +67,6 @@ static const char * const hlsl_preamble_gs =
|
||||
"\n";
|
||||
|
||||
static const char * const vulkan_glsl_preamble_gs =
|
||||
"#version 450\n"
|
||||
"#extension GL_ARB_separate_shader_objects : enable\n"
|
||||
"#extension GL_ARB_shading_language_420pack : enable\n"
|
||||
"#define mul(x, y) ((x) * (y))\n"
|
||||
@@ -113,9 +110,17 @@ ShaderWriter & ShaderWriter::F(const char *format, ...) {
|
||||
return *this;
|
||||
}
|
||||
|
||||
void ShaderWriter::Preamble(const char **gl_extensions, size_t num_gl_extensions) {
|
||||
void ShaderWriter::Preamble(Slice<const char *> extensions) {
|
||||
switch (lang_.shaderLanguage) {
|
||||
case GLSL_VULKAN:
|
||||
C("#version 450\n");
|
||||
if (flags_ & ShaderWriterFlags::FS_AUTO_STEREO) {
|
||||
C("#extension GL_EXT_multiview : enable\n");
|
||||
}
|
||||
// IMPORTANT! Extensions must be the first thing after #version.
|
||||
for (size_t i = 0; i < extensions.size(); i++) {
|
||||
F("%s\n", extensions[i]);
|
||||
}
|
||||
switch (stage_) {
|
||||
case ShaderStage::Vertex:
|
||||
W(vulkan_glsl_preamble_vs);
|
||||
@@ -154,8 +159,8 @@ void ShaderWriter::Preamble(const char **gl_extensions, size_t num_gl_extensions
|
||||
default: // OpenGL
|
||||
F("#version %d%s\n", lang_.glslVersionNumber, lang_.gles && lang_.glslES30 ? " es" : "");
|
||||
// IMPORTANT! Extensions must be the first thing after #version.
|
||||
for (size_t i = 0; i < num_gl_extensions; i++) {
|
||||
F("%s\n", gl_extensions[i]);
|
||||
for (size_t i = 0; i < extensions.size(); i++) {
|
||||
F("%s\n", extensions[i]);
|
||||
}
|
||||
// Print some system info - useful to gather information directly from screenshots.
|
||||
if (strlen(lang_.driverInfo) != 0) {
|
||||
@@ -250,7 +255,7 @@ void ShaderWriter::BeginVSMain(Slice<InputDef> inputs, Slice<UniformDef> uniform
|
||||
}
|
||||
}
|
||||
|
||||
void ShaderWriter::BeginFSMain(Slice<UniformDef> uniforms, Slice<VaryingDef> varyings, FSFlags flags) {
|
||||
void ShaderWriter::BeginFSMain(Slice<UniformDef> uniforms, Slice<VaryingDef> varyings) {
|
||||
_assert_(this->stage_ == ShaderStage::Fragment);
|
||||
switch (lang_.shaderLanguage) {
|
||||
case HLSL_D3D11:
|
||||
@@ -264,13 +269,13 @@ void ShaderWriter::BeginFSMain(Slice<UniformDef> uniforms, Slice<VaryingDef> var
|
||||
C("};\n");
|
||||
}
|
||||
|
||||
if (flags & FSFLAG_WRITEDEPTH) {
|
||||
if (flags_ & ShaderWriterFlags::FS_WRITE_DEPTH) {
|
||||
C("float gl_FragDepth;\n");
|
||||
}
|
||||
|
||||
C("struct PS_OUT {\n");
|
||||
C(" vec4 target : SV_Target0;\n");
|
||||
if (flags & FSFLAG_WRITEDEPTH) {
|
||||
if (flags_ & ShaderWriterFlags::FS_WRITE_DEPTH) {
|
||||
C(" float depth : SV_Depth;\n");
|
||||
}
|
||||
C("};\n");
|
||||
@@ -285,14 +290,14 @@ void ShaderWriter::BeginFSMain(Slice<UniformDef> uniforms, Slice<VaryingDef> var
|
||||
|
||||
F(") {\n");
|
||||
C(" PS_OUT ps_out;\n");
|
||||
if (flags & FSFLAG_WRITEDEPTH) {
|
||||
if (flags_ & ShaderWriterFlags::FS_WRITE_DEPTH) {
|
||||
C(" float gl_FragDepth;\n");
|
||||
}
|
||||
break;
|
||||
case HLSL_D3D9:
|
||||
C("struct PS_OUT {\n");
|
||||
C(" vec4 target : SV_Target0;\n");
|
||||
if (flags & FSFLAG_WRITEDEPTH) {
|
||||
if (flags_ & ShaderWriterFlags::FS_WRITE_DEPTH) {
|
||||
C(" float depth : DEPTH;\n");
|
||||
}
|
||||
C("};\n");
|
||||
@@ -310,7 +315,7 @@ void ShaderWriter::BeginFSMain(Slice<UniformDef> uniforms, Slice<VaryingDef> var
|
||||
|
||||
F(") {\n");
|
||||
C(" PS_OUT ps_out;\n");
|
||||
if (flags & FSFLAG_WRITEDEPTH) {
|
||||
if (flags_ & ShaderWriterFlags::FS_WRITE_DEPTH) {
|
||||
C(" float gl_FragDepth;\n");
|
||||
}
|
||||
|
||||
@@ -321,7 +326,7 @@ void ShaderWriter::BeginFSMain(Slice<UniformDef> uniforms, Slice<VaryingDef> var
|
||||
}
|
||||
C("layout(location = 0, index = 0) out vec4 fragColor0;\n");
|
||||
if (!uniforms.is_empty()) {
|
||||
C("layout(std140, set = 0, binding = 0) uniform bufferVals {\n");
|
||||
C("layout(std140, set = 1, binding = 0) uniform bufferVals {\n");
|
||||
for (auto &uniform : uniforms) {
|
||||
F("%s %s;\n", uniform.type, uniform.name);
|
||||
}
|
||||
@@ -404,13 +409,13 @@ void ShaderWriter::EndVSMain(Slice<VaryingDef> varyings) {
|
||||
C("}\n");
|
||||
}
|
||||
|
||||
void ShaderWriter::EndFSMain(const char *vec4_color_variable, FSFlags flags) {
|
||||
void ShaderWriter::EndFSMain(const char *vec4_color_variable) {
|
||||
_assert_(this->stage_ == ShaderStage::Fragment);
|
||||
switch (lang_.shaderLanguage) {
|
||||
case HLSL_D3D11:
|
||||
case HLSL_D3D9:
|
||||
F(" ps_out.target = %s;\n", vec4_color_variable);
|
||||
if (flags & FSFLAG_WRITEDEPTH) {
|
||||
if (flags_ & ShaderWriterFlags::FS_WRITE_DEPTH) {
|
||||
C(" ps_out.depth = gl_FragDepth;\n");
|
||||
}
|
||||
C(" return ps_out;\n");
|
||||
@@ -454,34 +459,43 @@ void ShaderWriter::ConstFloat(const char *name, float value) {
|
||||
|
||||
void ShaderWriter::DeclareSamplers(Slice<SamplerDef> samplers) {
|
||||
for (int i = 0; i < (int)samplers.size(); i++) {
|
||||
DeclareTexture2D(samplers[i].name, i);
|
||||
DeclareSampler2D(samplers[i].name, i);
|
||||
DeclareTexture2D(samplers[i]);
|
||||
DeclareSampler2D(samplers[i]);
|
||||
}
|
||||
samplerDefs_ = samplers;
|
||||
}
|
||||
|
||||
void ShaderWriter::DeclareTexture2D(const char *name, int binding) {
|
||||
void ShaderWriter::ApplySamplerMetadata(Slice<SamplerDef> samplers) {
|
||||
samplerDefs_ = samplers;
|
||||
}
|
||||
|
||||
void ShaderWriter::DeclareTexture2D(const SamplerDef &def) {
|
||||
switch (lang_.shaderLanguage) {
|
||||
case HLSL_D3D11:
|
||||
F("Texture2D<float4> %s : register(t%d);\n", name, binding);
|
||||
F("Texture2D<float4> %s : register(t%d);\n", def.name, def.binding);
|
||||
break;
|
||||
case HLSL_D3D9:
|
||||
F("sampler %s: register(s%d);\n", name, binding);
|
||||
F("sampler %s: register(s%d);\n", def.name, def.binding);
|
||||
break;
|
||||
case GLSL_VULKAN:
|
||||
// In the thin3d descriptor set layout, textures start at 1 in set 0. Hence the +1.
|
||||
F("layout(set = 0, binding = %d) uniform sampler2D %s;\n", binding + 1, name);
|
||||
// texBindingBase_ is used for the thin3d descriptor set layout, where they start at 1.
|
||||
if (def.flags & SamplerFlags::ARRAY_ON_VULKAN) {
|
||||
F("layout(set = 1, binding = %d) uniform sampler2DArray %s;\n", def.binding + texBindingBase_, def.name);
|
||||
} else {
|
||||
F("layout(set = 1, binding = %d) uniform sampler2D %s;\n", def.binding + texBindingBase_, def.name);
|
||||
}
|
||||
break;
|
||||
default:
|
||||
F("uniform sampler2D %s;\n", name);
|
||||
F("uniform sampler2D %s;\n", def.name);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
void ShaderWriter::DeclareSampler2D(const char *name, int binding) {
|
||||
void ShaderWriter::DeclareSampler2D(const SamplerDef &def) {
|
||||
// We only use separate samplers in HLSL D3D11, where we have no choice.
|
||||
switch (lang_.shaderLanguage) {
|
||||
case HLSL_D3D11:
|
||||
F("SamplerState %sSamp : register(s%d);\n", name, binding);
|
||||
F("SamplerState %sSamp : register(s%d);\n", def.name, def.binding);
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
@@ -489,6 +503,7 @@ void ShaderWriter::DeclareSampler2D(const char *name, int binding) {
|
||||
}
|
||||
|
||||
ShaderWriter &ShaderWriter::SampleTexture2D(const char *sampName, const char *uv) {
|
||||
const SamplerDef *samp = GetSamplerDef(sampName);
|
||||
switch (lang_.shaderLanguage) {
|
||||
case HLSL_D3D11:
|
||||
F("%s.Sample(%sSamp, %s)", sampName, sampName, uv);
|
||||
@@ -498,13 +513,20 @@ ShaderWriter &ShaderWriter::SampleTexture2D(const char *sampName, const char *uv
|
||||
break;
|
||||
default:
|
||||
// Note: we ignore the sampler. make sure you bound samplers to the textures correctly.
|
||||
F("%s(%s, %s)", lang_.texture, sampName, uv);
|
||||
if (samp && (samp->flags & SamplerFlags::ARRAY_ON_VULKAN) && lang_.shaderLanguage == GLSL_VULKAN) {
|
||||
const char *index = (flags_ & ShaderWriterFlags::FS_AUTO_STEREO) ? "float(gl_ViewIndex)" : "0.0";
|
||||
F("%s(%s, vec3(%s, %s))", lang_.texture, sampName, uv, index);
|
||||
} else {
|
||||
F("%s(%s, %s)", lang_.texture, sampName, uv);
|
||||
}
|
||||
break;
|
||||
}
|
||||
return *this;
|
||||
}
|
||||
|
||||
ShaderWriter &ShaderWriter::SampleTexture2DOffset(const char *sampName, const char *uv, int offX, int offY) {
|
||||
const SamplerDef *samp = GetSamplerDef(sampName);
|
||||
|
||||
switch (lang_.shaderLanguage) {
|
||||
case HLSL_D3D11:
|
||||
F("%s.Sample(%sSamp, %s, int2(%d, %d))", sampName, sampName, uv, offX, offY);
|
||||
@@ -515,13 +537,20 @@ ShaderWriter &ShaderWriter::SampleTexture2DOffset(const char *sampName, const ch
|
||||
break;
|
||||
default:
|
||||
// Note: we ignore the sampler. make sure you bound samplers to the textures correctly.
|
||||
F("%sOffset(%s, %s, ivec2(%d, %d))", lang_.texture, sampName, uv, offX, offY);
|
||||
if (samp && (samp->flags & SamplerFlags::ARRAY_ON_VULKAN) && lang_.shaderLanguage == GLSL_VULKAN) {
|
||||
const char *index = (flags_ & ShaderWriterFlags::FS_AUTO_STEREO) ? "float(gl_ViewIndex)" : "0.0";
|
||||
F("%sOffset(%s, vec3(%s, %s), ivec2(%d, %d))", lang_.texture, sampName, uv, index, offX, offY);
|
||||
} else {
|
||||
F("%sOffset(%s, %s, ivec2(%d, %d))", lang_.texture, sampName, uv, offX, offY);
|
||||
}
|
||||
break;
|
||||
}
|
||||
return *this;
|
||||
}
|
||||
|
||||
ShaderWriter &ShaderWriter::LoadTexture2D(const char *sampName, const char *uv, int level) {
|
||||
const SamplerDef *samp = GetSamplerDef(sampName);
|
||||
|
||||
switch (lang_.shaderLanguage) {
|
||||
case HLSL_D3D11:
|
||||
F("%s.Load(ivec3(%s, %d))", sampName, uv, level);
|
||||
@@ -532,7 +561,12 @@ ShaderWriter &ShaderWriter::LoadTexture2D(const char *sampName, const char *uv,
|
||||
break;
|
||||
default:
|
||||
// Note: we ignore the sampler. make sure you bound samplers to the textures correctly.
|
||||
F("texelFetch(%s, %s, %d)", sampName, uv, level);
|
||||
if (samp && (samp->flags & SamplerFlags::ARRAY_ON_VULKAN) && lang_.shaderLanguage == GLSL_VULKAN) {
|
||||
const char *index = (flags_ & ShaderWriterFlags::FS_AUTO_STEREO) ? "gl_ViewIndex" : "0";
|
||||
F("texelFetch(%s, vec3(%s, %s), %d)", sampName, uv, index, level);
|
||||
} else {
|
||||
F("texelFetch(%s, %s, %d)", sampName, uv, level);
|
||||
}
|
||||
break;
|
||||
}
|
||||
return *this;
|
||||
@@ -553,3 +587,12 @@ ShaderWriter &ShaderWriter::GetTextureSize(const char *szVariable, const char *t
|
||||
}
|
||||
return *this;
|
||||
}
|
||||
|
||||
const SamplerDef *ShaderWriter::GetSamplerDef(const char *name) const {
|
||||
for (int i = 0; i < (int)samplerDefs_.size(); i++) {
|
||||
if (!strcmp(samplerDefs_[i].name, name)) {
|
||||
return &samplerDefs_[i];
|
||||
}
|
||||
}
|
||||
return nullptr;
|
||||
}
|
||||
+26
-10
@@ -30,15 +30,19 @@ struct VaryingDef {
|
||||
const char *precision;
|
||||
};
|
||||
|
||||
enum FSFlags {
|
||||
FSFLAG_NONE = 0,
|
||||
FSFLAG_WRITEDEPTH = 1,
|
||||
enum class ShaderWriterFlags {
|
||||
NONE = 0,
|
||||
FS_WRITE_DEPTH = 1,
|
||||
FS_AUTO_STEREO = 2, // Automatically indexes makes samplers tagged with `array` by gl_ViewIndex. Useful for stereo rendering.
|
||||
};
|
||||
ENUM_CLASS_BITOPS(ShaderWriterFlags);
|
||||
|
||||
class ShaderWriter {
|
||||
public:
|
||||
ShaderWriter(char *buffer, const ShaderLanguageDesc &lang, ShaderStage stage, const char **gl_extensions = nullptr, size_t num_gl_extensions = 0) : p_(buffer), lang_(lang), stage_(stage) {
|
||||
Preamble(gl_extensions, num_gl_extensions);
|
||||
// Extensions are supported for both OpenGL ES and Vulkan (though of course, they're different).
|
||||
ShaderWriter(char *buffer, const ShaderLanguageDesc &lang, ShaderStage stage, Slice<const char *> extensions = Slice<const char *>(), ShaderWriterFlags flags = ShaderWriterFlags::NONE) : p_(buffer), lang_(lang), stage_(stage), flags_(flags) {
|
||||
buffer[0] = '\0';
|
||||
Preamble(extensions);
|
||||
}
|
||||
ShaderWriter(const ShaderWriter &) = delete;
|
||||
|
||||
@@ -73,9 +77,16 @@ public:
|
||||
void HighPrecisionFloat();
|
||||
void LowPrecisionFloat();
|
||||
|
||||
// NOTE: samplers must live for the rest of ShaderWriter's lifetime. No way to express that in C++ though :(
|
||||
void DeclareSamplers(Slice<SamplerDef> samplers);
|
||||
|
||||
// Same as DeclareSamplers, but doesn't actually declare them.
|
||||
// This is currently only required by FragmentShaderGenerator.
|
||||
void ApplySamplerMetadata(Slice<SamplerDef> samplers);
|
||||
|
||||
void ConstFloat(const char *name, float value);
|
||||
void SetFlags(ShaderWriterFlags flags) { flags_ |= flags; }
|
||||
void SetTexBindingBase(int base) { texBindingBase_ = base; }
|
||||
|
||||
ShaderWriter &SampleTexture2D(const char *texName, const char *uv);
|
||||
ShaderWriter &SampleTexture2DOffset(const char *texName, const char *uv, int offX, int offY);
|
||||
@@ -84,12 +95,12 @@ public:
|
||||
|
||||
// Simple shaders with no special tricks.
|
||||
void BeginVSMain(Slice<InputDef> inputs, Slice<UniformDef> uniforms, Slice<VaryingDef> varyings);
|
||||
void BeginFSMain(Slice<UniformDef> uniforms, Slice<VaryingDef> varyings, FSFlags flags);
|
||||
void BeginFSMain(Slice<UniformDef> uniforms, Slice<VaryingDef> varyings);
|
||||
void BeginGSMain(Slice<VaryingDef> varyings, Slice<VaryingDef> outVaryings);
|
||||
|
||||
// For simple shaders that output a single color, we can deal with this generically.
|
||||
void EndVSMain(Slice<VaryingDef> varyings);
|
||||
void EndFSMain(const char *vec4_color_variable, FSFlags flags);
|
||||
void EndFSMain(const char *vec4_color_variable);
|
||||
void EndGSMain();
|
||||
|
||||
const ShaderLanguageDesc &Lang() const {
|
||||
@@ -107,12 +118,17 @@ public:
|
||||
|
||||
private:
|
||||
// Several of the shader languages ignore samplers, beware of that.
|
||||
void DeclareSampler2D(const char *name, int binding);
|
||||
void DeclareTexture2D(const char *name, int binding);
|
||||
void DeclareSampler2D(const SamplerDef &def);
|
||||
void DeclareTexture2D(const SamplerDef &def);
|
||||
const SamplerDef *GetSamplerDef(const char *name) const;
|
||||
|
||||
void Preamble(const char **gl_extensions, size_t num_gl_extensions);
|
||||
void Preamble(Slice<const char *> extensions);
|
||||
|
||||
char *p_;
|
||||
const ShaderLanguageDesc &lang_;
|
||||
const ShaderStage stage_;
|
||||
Slice<SamplerDef> samplers_;
|
||||
ShaderWriterFlags flags_ = ShaderWriterFlags::NONE;
|
||||
Slice<SamplerDef> samplerDefs_;
|
||||
int texBindingBase_ = 1;
|
||||
};
|
||||
@@ -14,7 +14,7 @@ class VulkanContext;
|
||||
class VulkanBarrier {
|
||||
public:
|
||||
void TransitionImage(
|
||||
VkImage image, int baseMip, int numMipLevels, VkImageAspectFlags aspectMask,
|
||||
VkImage image, int baseMip, int numMipLevels, int numLayers, VkImageAspectFlags aspectMask,
|
||||
VkImageLayout oldImageLayout, VkImageLayout newImageLayout,
|
||||
VkAccessFlags srcAccessMask, VkAccessFlags dstAccessMask,
|
||||
VkPipelineStageFlags srcStageMask, VkPipelineStageFlags dstStageMask
|
||||
@@ -36,7 +36,7 @@ public:
|
||||
imageBarrier.subresourceRange.aspectMask = aspectMask;
|
||||
imageBarrier.subresourceRange.baseMipLevel = baseMip;
|
||||
imageBarrier.subresourceRange.levelCount = numMipLevels;
|
||||
imageBarrier.subresourceRange.layerCount = 1; // We never use more than one layer, and old Mali drivers have problems with VK_REMAINING_ARRAY_LAYERS/VK_REMAINING_MIP_LEVELS.
|
||||
imageBarrier.subresourceRange.layerCount = numLayers; // NOTE: We could usually use VK_REMAINING_ARRAY_LAYERS/VK_REMAINING_MIP_LEVELS, but really old Mali drivers have problems with those.
|
||||
imageBarrier.subresourceRange.baseArrayLayer = 0;
|
||||
imageBarrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
|
||||
imageBarrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
|
||||
@@ -46,7 +46,7 @@ public:
|
||||
// Automatically determines access and stage masks from layouts.
|
||||
// Not universally usable, but works for PPSSPP's use.
|
||||
void TransitionImageAuto(
|
||||
VkImage image, int baseMip, int numMipLevels, VkImageAspectFlags aspectMask, VkImageLayout oldImageLayout, VkImageLayout newImageLayout
|
||||
VkImage image, int baseMip, int numMipLevels, int numLayers, VkImageAspectFlags aspectMask, VkImageLayout oldImageLayout, VkImageLayout newImageLayout
|
||||
) {
|
||||
_dbg_assert_(image != VK_NULL_HANDLE);
|
||||
|
||||
@@ -104,7 +104,7 @@ public:
|
||||
imageBarrier.subresourceRange.aspectMask = aspectMask;
|
||||
imageBarrier.subresourceRange.baseMipLevel = baseMip;
|
||||
imageBarrier.subresourceRange.levelCount = numMipLevels;
|
||||
imageBarrier.subresourceRange.layerCount = 1; // We never use more than one layer, and old Mali drivers have problems with VK_REMAINING_ARRAY_LAYERS/VK_REMAINING_MIP_LEVELS.
|
||||
imageBarrier.subresourceRange.layerCount = numLayers; // NOTE: We could usually use VK_REMAINING_ARRAY_LAYERS/VK_REMAINING_MIP_LEVELS, but really old Mali drivers have problems with those.
|
||||
imageBarrier.subresourceRange.baseArrayLayer = 0;
|
||||
imageBarrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
|
||||
imageBarrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
|
||||
|
||||
@@ -585,24 +585,31 @@ void VulkanContext::ChooseDevice(int physical_device) {
|
||||
// Optional features
|
||||
if (extensionsLookup_.KHR_get_physical_device_properties2) {
|
||||
VkPhysicalDeviceFeatures2 features2{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2_KHR};
|
||||
// Add to chain even if not supported, GetPhysicalDeviceFeatures is supposed to ignore unknown structs.
|
||||
VkPhysicalDeviceMultiviewFeatures multiViewFeatures{ VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MULTIVIEW_FEATURES };
|
||||
features2.pNext = &multiViewFeatures;
|
||||
vkGetPhysicalDeviceFeatures2KHR(physical_devices_[physical_device_], &features2);
|
||||
deviceFeatures_.available = features2.features;
|
||||
deviceFeatures_.available.standard = features2.features;
|
||||
deviceFeatures_.available.multiview = multiViewFeatures;
|
||||
} else {
|
||||
vkGetPhysicalDeviceFeatures(physical_devices_[physical_device_], &deviceFeatures_.available);
|
||||
vkGetPhysicalDeviceFeatures(physical_devices_[physical_device_], &deviceFeatures_.available.standard);
|
||||
deviceFeatures_.available.multiview = {};
|
||||
}
|
||||
|
||||
deviceFeatures_.enabled = {};
|
||||
// Enable a few safe ones if they are available.
|
||||
deviceFeatures_.enabled.dualSrcBlend = deviceFeatures_.available.dualSrcBlend;
|
||||
deviceFeatures_.enabled.logicOp = deviceFeatures_.available.logicOp;
|
||||
deviceFeatures_.enabled.depthClamp = deviceFeatures_.available.depthClamp;
|
||||
deviceFeatures_.enabled.depthBounds = deviceFeatures_.available.depthBounds;
|
||||
deviceFeatures_.enabled.samplerAnisotropy = deviceFeatures_.available.samplerAnisotropy;
|
||||
deviceFeatures_.enabled.shaderClipDistance = deviceFeatures_.available.shaderClipDistance;
|
||||
deviceFeatures_.enabled.shaderCullDistance = deviceFeatures_.available.shaderCullDistance;
|
||||
// For easy wireframe mode, someday.
|
||||
deviceFeatures_.enabled.fillModeNonSolid = deviceFeatures_.available.fillModeNonSolid;
|
||||
deviceFeatures_.enabled.geometryShader = deviceFeatures_.available.geometryShader;
|
||||
deviceFeatures_.enabled.standard.dualSrcBlend = deviceFeatures_.available.standard.dualSrcBlend;
|
||||
deviceFeatures_.enabled.standard.logicOp = deviceFeatures_.available.standard.logicOp;
|
||||
deviceFeatures_.enabled.standard.depthClamp = deviceFeatures_.available.standard.depthClamp;
|
||||
deviceFeatures_.enabled.standard.depthBounds = deviceFeatures_.available.standard.depthBounds;
|
||||
deviceFeatures_.enabled.standard.samplerAnisotropy = deviceFeatures_.available.standard.samplerAnisotropy;
|
||||
deviceFeatures_.enabled.standard.shaderClipDistance = deviceFeatures_.available.standard.shaderClipDistance;
|
||||
deviceFeatures_.enabled.standard.shaderCullDistance = deviceFeatures_.available.standard.shaderCullDistance;
|
||||
deviceFeatures_.enabled.standard.geometryShader = deviceFeatures_.available.standard.geometryShader;
|
||||
|
||||
deviceFeatures_.enabled.multiview = { VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MULTIVIEW_FEATURES };
|
||||
deviceFeatures_.enabled.multiview.multiview = deviceFeatures_.available.multiview.multiview;
|
||||
// deviceFeatures_.enabled.multiview.multiviewGeometryShader = deviceFeatures_.available.multiview.multiviewGeometryShader;
|
||||
|
||||
GetDeviceLayerExtensionList(nullptr, device_extension_properties_);
|
||||
|
||||
@@ -673,6 +680,8 @@ VkResult VulkanContext::CreateDevice() {
|
||||
extensionsLookup_.EXT_fragment_shader_interlock = EnableDeviceExtension(VK_EXT_FRAGMENT_SHADER_INTERLOCK_EXTENSION_NAME);
|
||||
extensionsLookup_.ARM_rasterization_order_attachment_access = EnableDeviceExtension(VK_ARM_RASTERIZATION_ORDER_ATTACHMENT_ACCESS_EXTENSION_NAME);
|
||||
|
||||
VkPhysicalDeviceFeatures2 features2{ VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2 };
|
||||
|
||||
VkDeviceCreateInfo device_info{ VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO };
|
||||
device_info.queueCreateInfoCount = 1;
|
||||
device_info.pQueueCreateInfos = &queue_info;
|
||||
@@ -680,7 +689,14 @@ VkResult VulkanContext::CreateDevice() {
|
||||
device_info.ppEnabledLayerNames = device_info.enabledLayerCount ? device_layer_names_.data() : nullptr;
|
||||
device_info.enabledExtensionCount = (uint32_t)device_extensions_enabled_.size();
|
||||
device_info.ppEnabledExtensionNames = device_info.enabledExtensionCount ? device_extensions_enabled_.data() : nullptr;
|
||||
device_info.pEnabledFeatures = &deviceFeatures_.enabled;
|
||||
|
||||
if (extensionsLookup_.KHR_get_physical_device_properties2) {
|
||||
device_info.pNext = &features2;
|
||||
features2.features = deviceFeatures_.enabled.standard;
|
||||
features2.pNext = &deviceFeatures_.enabled.multiview;
|
||||
} else {
|
||||
device_info.pEnabledFeatures = &deviceFeatures_.enabled.standard;
|
||||
}
|
||||
|
||||
VkResult res = vkCreateDevice(physical_devices_[physical_device_], &device_info, nullptr, &device_);
|
||||
if (res != VK_SUCCESS) {
|
||||
@@ -1013,12 +1029,21 @@ bool VulkanContext::InitSwapchain() {
|
||||
res = vkGetPhysicalDeviceSurfacePresentModesKHR(physical_devices_[physical_device_], surface_, &presentModeCount, presentModes);
|
||||
_dbg_assert_(res == VK_SUCCESS);
|
||||
|
||||
VkExtent2D currentExtent { surfCapabilities_.currentExtent };
|
||||
// https://registry.khronos.org/vulkan/specs/1.3-extensions/man/html/VkSurfaceCapabilitiesKHR.html
|
||||
// currentExtent is the current width and height of the surface, or the special value (0xFFFFFFFF, 0xFFFFFFFF) indicating that the surface size will be determined by the extent of a swapchain targeting the surface.
|
||||
if (currentExtent.width == 0xFFFFFFFFu || currentExtent.height == 0xFFFFFFFFu) {
|
||||
_dbg_assert_((bool)cbGetDrawSize_)
|
||||
if (cbGetDrawSize_) {
|
||||
currentExtent = cbGetDrawSize_();
|
||||
}
|
||||
}
|
||||
|
||||
swapChainExtent_.width = clamp(surfCapabilities_.currentExtent.width, surfCapabilities_.minImageExtent.width, surfCapabilities_.maxImageExtent.width);
|
||||
swapChainExtent_.height = clamp(surfCapabilities_.currentExtent.height, surfCapabilities_.minImageExtent.height, surfCapabilities_.maxImageExtent.height);
|
||||
swapChainExtent_.width = clamp(currentExtent.width, surfCapabilities_.minImageExtent.width, surfCapabilities_.maxImageExtent.width);
|
||||
swapChainExtent_.height = clamp(currentExtent.height, surfCapabilities_.minImageExtent.height, surfCapabilities_.maxImageExtent.height);
|
||||
|
||||
INFO_LOG(G3D, "surfCapabilities_.current: %dx%d min: %dx%d max: %dx%d computed: %dx%d",
|
||||
surfCapabilities_.currentExtent.width, surfCapabilities_.currentExtent.height,
|
||||
currentExtent.width, currentExtent.height,
|
||||
surfCapabilities_.minImageExtent.width, surfCapabilities_.minImageExtent.height,
|
||||
surfCapabilities_.maxImageExtent.width, surfCapabilities_.maxImageExtent.height,
|
||||
swapChainExtent_.width, swapChainExtent_.height);
|
||||
@@ -1163,6 +1188,10 @@ bool VulkanContext::InitSwapchain() {
|
||||
return true;
|
||||
}
|
||||
|
||||
void VulkanContext::SetCbGetDrawSize(std::function<VkExtent2D()> cb) {
|
||||
cbGetDrawSize_ = cb;
|
||||
}
|
||||
|
||||
VkFence VulkanContext::CreateFence(bool presignalled) {
|
||||
VkFence fence;
|
||||
VkFenceCreateInfo fenceInfo{ VK_STRUCTURE_TYPE_FENCE_CREATE_INFO };
|
||||
@@ -1216,7 +1245,7 @@ bool VulkanContext::CreateShaderModule(const std::vector<uint32_t> &spirv, VkSha
|
||||
}
|
||||
}
|
||||
|
||||
void TransitionImageLayout2(VkCommandBuffer cmd, VkImage image, int baseMip, int numMipLevels, VkImageAspectFlags aspectMask,
|
||||
void TransitionImageLayout2(VkCommandBuffer cmd, VkImage image, int baseMip, int numMipLevels, int numLayers, VkImageAspectFlags aspectMask,
|
||||
VkImageLayout oldImageLayout, VkImageLayout newImageLayout,
|
||||
VkPipelineStageFlags srcStageMask, VkPipelineStageFlags dstStageMask,
|
||||
VkAccessFlags srcAccessMask, VkAccessFlags dstAccessMask) {
|
||||
@@ -1229,7 +1258,7 @@ void TransitionImageLayout2(VkCommandBuffer cmd, VkImage image, int baseMip, int
|
||||
image_memory_barrier.subresourceRange.aspectMask = aspectMask;
|
||||
image_memory_barrier.subresourceRange.baseMipLevel = baseMip;
|
||||
image_memory_barrier.subresourceRange.levelCount = numMipLevels;
|
||||
image_memory_barrier.subresourceRange.layerCount = 1; // We never use more than one layer, and old Mali drivers have problems with VK_REMAINING_ARRAY_LAYERS/VK_REMAINING_MIP_LEVELS.
|
||||
image_memory_barrier.subresourceRange.layerCount = numLayers; // We never use more than one layer, and old Mali drivers have problems with VK_REMAINING_ARRAY_LAYERS/VK_REMAINING_MIP_LEVELS.
|
||||
image_memory_barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
|
||||
image_memory_barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
|
||||
vkCmdPipelineBarrier(cmd, srcStageMask, dstStageMask, 0, 0, nullptr, 0, nullptr, 1, &image_memory_barrier);
|
||||
@@ -1343,37 +1372,6 @@ void finalize_glslang() {
|
||||
glslang::FinalizeProcess();
|
||||
}
|
||||
|
||||
const char *VulkanResultToString(VkResult res) {
|
||||
switch (res) {
|
||||
case VK_NOT_READY: return "VK_NOT_READY";
|
||||
case VK_TIMEOUT: return "VK_TIMEOUT";
|
||||
case VK_EVENT_SET: return "VK_EVENT_SET";
|
||||
case VK_EVENT_RESET: return "VK_EVENT_RESET";
|
||||
case VK_INCOMPLETE: return "VK_INCOMPLETE";
|
||||
case VK_ERROR_OUT_OF_HOST_MEMORY: return "VK_ERROR_OUT_OF_HOST_MEMORY";
|
||||
case VK_ERROR_OUT_OF_DEVICE_MEMORY: return "VK_ERROR_OUT_OF_DEVICE_MEMORY";
|
||||
case VK_ERROR_INITIALIZATION_FAILED: return "VK_ERROR_INITIALIZATION_FAILED";
|
||||
case VK_ERROR_DEVICE_LOST: return "VK_ERROR_DEVICE_LOST";
|
||||
case VK_ERROR_MEMORY_MAP_FAILED: return "VK_ERROR_MEMORY_MAP_FAILED";
|
||||
case VK_ERROR_LAYER_NOT_PRESENT: return "VK_ERROR_LAYER_NOT_PRESENT";
|
||||
case VK_ERROR_EXTENSION_NOT_PRESENT: return "VK_ERROR_EXTENSION_NOT_PRESENT";
|
||||
case VK_ERROR_FEATURE_NOT_PRESENT: return "VK_ERROR_FEATURE_NOT_PRESENT";
|
||||
case VK_ERROR_INCOMPATIBLE_DRIVER: return "VK_ERROR_INCOMPATIBLE_DRIVER";
|
||||
case VK_ERROR_TOO_MANY_OBJECTS: return "VK_ERROR_TOO_MANY_OBJECTS";
|
||||
case VK_ERROR_FORMAT_NOT_SUPPORTED: return "VK_ERROR_FORMAT_NOT_SUPPORTED";
|
||||
case VK_ERROR_SURFACE_LOST_KHR: return "VK_ERROR_SURFACE_LOST_KHR";
|
||||
case VK_SUBOPTIMAL_KHR: return "VK_SUBOPTIMAL_KHR";
|
||||
case VK_ERROR_OUT_OF_DATE_KHR: return "VK_ERROR_OUT_OF_DATE_KHR";
|
||||
case VK_ERROR_INCOMPATIBLE_DISPLAY_KHR: return "VK_ERROR_INCOMPATIBLE_DISPLAY_KHR";
|
||||
case VK_ERROR_NATIVE_WINDOW_IN_USE_KHR: return "VK_ERROR_NATIVE_WINDOW_IN_USE_KHR";
|
||||
case VK_ERROR_OUT_OF_POOL_MEMORY_KHR: return "VK_ERROR_OUT_OF_POOL_MEMORY_KHR";
|
||||
case VK_ERROR_INVALID_EXTERNAL_HANDLE_KHR: return "VK_ERROR_INVALID_EXTERNAL_HANDLE_KHR";
|
||||
|
||||
default:
|
||||
return "VK_ERROR_...(unknown)";
|
||||
}
|
||||
}
|
||||
|
||||
void VulkanDeleteList::Take(VulkanDeleteList &del) {
|
||||
_dbg_assert_(cmdPools_.empty());
|
||||
_dbg_assert_(descPools_.empty());
|
||||
@@ -1565,6 +1563,7 @@ const char *VulkanFormatToString(VkFormat format) {
|
||||
switch (format) {
|
||||
case VK_FORMAT_A1R5G5B5_UNORM_PACK16: return "A1R5G5B5_UNORM_PACK16";
|
||||
case VK_FORMAT_A2B10G10R10_UNORM_PACK32: return "A2B10G10R10_UNORM_PACK32";
|
||||
case VK_FORMAT_A2R10G10B10_UNORM_PACK32: return "A2R10G10B10_UNORM_PACK32";
|
||||
case VK_FORMAT_A8B8G8R8_SNORM_PACK32: return "A8B8G8R8_SNORM_PACK32";
|
||||
case VK_FORMAT_A8B8G8R8_SRGB_PACK32: return "A8B8G8R8_SRGB_PACK32";
|
||||
case VK_FORMAT_A8B8G8R8_UNORM_PACK32: return "A8B8G8R8_UNORM_PACK32";
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <utility>
|
||||
#include <functional>
|
||||
|
||||
#include "Common/Log.h"
|
||||
#include "Common/GPU/Vulkan/VulkanLoader.h"
|
||||
@@ -190,6 +191,7 @@ public:
|
||||
VkResult ReinitSurface();
|
||||
|
||||
bool InitSwapchain();
|
||||
void SetCbGetDrawSize(std::function<VkExtent2D()>);
|
||||
|
||||
void DestroySwapchain();
|
||||
void DestroySurface();
|
||||
@@ -220,6 +222,9 @@ public:
|
||||
SetDebugNameImpl((uint64_t)handle, type, name);
|
||||
}
|
||||
}
|
||||
bool DebugLayerEnabled() const {
|
||||
return extensionsLookup_.EXT_debug_utils;
|
||||
}
|
||||
|
||||
bool MemoryTypeFromProperties(uint32_t typeBits, VkFlags requirements_mask, uint32_t *typeIndex);
|
||||
|
||||
@@ -250,6 +255,11 @@ public:
|
||||
VkPhysicalDeviceExternalMemoryHostPropertiesEXT externalMemoryHostProperties;
|
||||
};
|
||||
|
||||
struct AllPhysicalDeviceFeatures {
|
||||
VkPhysicalDeviceFeatures standard;
|
||||
VkPhysicalDeviceMultiviewFeatures multiview;
|
||||
};
|
||||
|
||||
const PhysicalDeviceProps &GetPhysicalDeviceProperties(int i = -1) const {
|
||||
if (i < 0)
|
||||
i = GetCurrentPhysicalDeviceIndex();
|
||||
@@ -274,8 +284,8 @@ public:
|
||||
}
|
||||
|
||||
struct PhysicalDeviceFeatures {
|
||||
VkPhysicalDeviceFeatures available{};
|
||||
VkPhysicalDeviceFeatures enabled{};
|
||||
AllPhysicalDeviceFeatures available{};
|
||||
AllPhysicalDeviceFeatures enabled{};
|
||||
};
|
||||
|
||||
const PhysicalDeviceFeatures &GetDeviceFeatures() const { return deviceFeatures_; }
|
||||
@@ -363,6 +373,7 @@ private:
|
||||
// that we really don't want in everything that uses VulkanContext.
|
||||
void *winsysData1_;
|
||||
void *winsysData2_;
|
||||
std::function<VkExtent2D()> cbGetDrawSize_;
|
||||
|
||||
VkInstance instance_ = VK_NULL_HANDLE;
|
||||
VkDevice device_ = VK_NULL_HANDLE;
|
||||
@@ -433,7 +444,7 @@ private:
|
||||
};
|
||||
|
||||
// Detailed control.
|
||||
void TransitionImageLayout2(VkCommandBuffer cmd, VkImage image, int baseMip, int mipLevels, VkImageAspectFlags aspectMask,
|
||||
void TransitionImageLayout2(VkCommandBuffer cmd, VkImage image, int baseMip, int mipLevels, int numLayers, VkImageAspectFlags aspectMask,
|
||||
VkImageLayout oldImageLayout, VkImageLayout newImageLayout,
|
||||
VkPipelineStageFlags srcStageMask, VkPipelineStageFlags dstStageMask,
|
||||
VkAccessFlags srcAccessMask, VkAccessFlags dstAccessMask);
|
||||
@@ -450,7 +461,6 @@ enum class GLSLVariant {
|
||||
|
||||
bool GLSLtoSPV(const VkShaderStageFlagBits shader_type, const char *sourceCode, GLSLVariant variant, std::vector<uint32_t> &spirv, std::string *errorMessage);
|
||||
|
||||
const char *VulkanResultToString(VkResult res);
|
||||
const char *VulkanColorSpaceToString(VkColorSpaceKHR colorSpace);
|
||||
const char *VulkanFormatToString(VkFormat format);
|
||||
|
||||
|
||||
@@ -110,6 +110,11 @@ VkCommandBuffer FrameData::GetInitCmd(VulkanContext *vulkan) {
|
||||
if (res != VK_SUCCESS) {
|
||||
return VK_NULL_HANDLE;
|
||||
}
|
||||
|
||||
// Good spot to reset the query pool.
|
||||
vkCmdResetQueryPool(initCmd, profile.queryPool, 0, MAX_TIMESTAMP_QUERIES);
|
||||
vkCmdWriteTimestamp(initCmd, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, profile.queryPool, 0);
|
||||
|
||||
hasInitCommands = true;
|
||||
}
|
||||
return initCmd;
|
||||
|
||||
@@ -80,6 +80,8 @@ struct FrameData {
|
||||
|
||||
void AcquireNextImage(VulkanContext *vulkan, FrameDataShared &shared);
|
||||
VkResult QueuePresent(VulkanContext *vulkan, FrameDataShared &shared);
|
||||
|
||||
// Generally called from the main thread, unlike most of the rest.
|
||||
VkCommandBuffer GetInitCmd(VulkanContext *vulkan);
|
||||
|
||||
// This will only submit if we are actually recording init commands.
|
||||
|
||||
@@ -87,7 +87,7 @@ bool VulkanTexture::CreateDirect(VkCommandBuffer cmd, int w, int h, int depth, i
|
||||
switch (initialLayout) {
|
||||
case VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL:
|
||||
case VK_IMAGE_LAYOUT_GENERAL:
|
||||
TransitionImageLayout2(cmd, image_, 0, numMips, VK_IMAGE_ASPECT_COLOR_BIT,
|
||||
TransitionImageLayout2(cmd, image_, 0, numMips, 1, VK_IMAGE_ASPECT_COLOR_BIT,
|
||||
VK_IMAGE_LAYOUT_UNDEFINED, initialLayout,
|
||||
VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT,
|
||||
0, VK_ACCESS_TRANSFER_WRITE_BIT);
|
||||
@@ -123,6 +123,16 @@ bool VulkanTexture::CreateDirect(VkCommandBuffer cmd, int w, int h, int depth, i
|
||||
_assert_(res == VK_ERROR_OUT_OF_HOST_MEMORY || res == VK_ERROR_OUT_OF_DEVICE_MEMORY || res == VK_ERROR_TOO_MANY_OBJECTS);
|
||||
return false;
|
||||
}
|
||||
vulkan_->SetDebugName(view_, VK_OBJECT_TYPE_IMAGE_VIEW, tag_.c_str());
|
||||
|
||||
// Additionally, create an array view, but only if it's a 2D texture.
|
||||
if (view_info.viewType == VK_IMAGE_VIEW_TYPE_2D) {
|
||||
view_info.viewType = VK_IMAGE_VIEW_TYPE_2D_ARRAY;
|
||||
res = vkCreateImageView(vulkan_->GetDevice(), &view_info, NULL, &arrayView_);
|
||||
_assert_(res == VK_SUCCESS);
|
||||
vulkan_->SetDebugName(arrayView_, VK_OBJECT_TYPE_IMAGE_VIEW, tag_.c_str());
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -164,7 +174,7 @@ void VulkanTexture::GenerateMips(VkCommandBuffer cmd, int firstMipToGenerate, bo
|
||||
_assert_msg_(firstMipToGenerate < numMips_, "Can't generate levels beyond storage");
|
||||
|
||||
// Transition the pre-set levels to GENERAL.
|
||||
TransitionImageLayout2(cmd, image_, 0, firstMipToGenerate, VK_IMAGE_ASPECT_COLOR_BIT,
|
||||
TransitionImageLayout2(cmd, image_, 0, firstMipToGenerate, 1, VK_IMAGE_ASPECT_COLOR_BIT,
|
||||
fromCompute ? VK_IMAGE_LAYOUT_GENERAL : VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
|
||||
VK_IMAGE_LAYOUT_GENERAL,
|
||||
fromCompute ? VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT : VK_PIPELINE_STAGE_TRANSFER_BIT,
|
||||
@@ -173,7 +183,7 @@ void VulkanTexture::GenerateMips(VkCommandBuffer cmd, int firstMipToGenerate, bo
|
||||
VK_ACCESS_TRANSFER_READ_BIT);
|
||||
|
||||
// Do the same with the uninitialized levels.
|
||||
TransitionImageLayout2(cmd, image_, firstMipToGenerate, numMips_ - firstMipToGenerate,
|
||||
TransitionImageLayout2(cmd, image_, firstMipToGenerate, numMips_ - firstMipToGenerate, 1,
|
||||
VK_IMAGE_ASPECT_COLOR_BIT,
|
||||
VK_IMAGE_LAYOUT_UNDEFINED,
|
||||
VK_IMAGE_LAYOUT_GENERAL,
|
||||
@@ -206,7 +216,7 @@ void VulkanTexture::GenerateMips(VkCommandBuffer cmd, int firstMipToGenerate, bo
|
||||
|
||||
vkCmdBlitImage(cmd, image_, VK_IMAGE_LAYOUT_GENERAL, image_, VK_IMAGE_LAYOUT_GENERAL, 1, &blit, VK_FILTER_LINEAR);
|
||||
|
||||
TransitionImageLayout2(cmd, image_, mip, 1, VK_IMAGE_ASPECT_COLOR_BIT,
|
||||
TransitionImageLayout2(cmd, image_, mip, 1, 1, VK_IMAGE_ASPECT_COLOR_BIT,
|
||||
VK_IMAGE_LAYOUT_GENERAL, VK_IMAGE_LAYOUT_GENERAL,
|
||||
VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT,
|
||||
VK_ACCESS_TRANSFER_WRITE_BIT, VK_ACCESS_TRANSFER_READ_BIT);
|
||||
@@ -214,7 +224,7 @@ void VulkanTexture::GenerateMips(VkCommandBuffer cmd, int firstMipToGenerate, bo
|
||||
}
|
||||
|
||||
void VulkanTexture::EndCreate(VkCommandBuffer cmd, bool vertexTexture, VkPipelineStageFlags prevStage, VkImageLayout layout) {
|
||||
TransitionImageLayout2(cmd, image_, 0, numMips_,
|
||||
TransitionImageLayout2(cmd, image_, 0, numMips_, 1,
|
||||
VK_IMAGE_ASPECT_COLOR_BIT,
|
||||
layout, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL,
|
||||
prevStage, vertexTexture ? VK_PIPELINE_STAGE_VERTEX_SHADER_BIT : VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT,
|
||||
@@ -237,6 +247,7 @@ VkImageView VulkanTexture::CreateViewForMip(int mip) {
|
||||
view_info.subresourceRange.layerCount = 1;
|
||||
VkImageView view;
|
||||
VkResult res = vkCreateImageView(vulkan_->GetDevice(), &view_info, NULL, &view);
|
||||
vulkan_->SetDebugName(view, VK_OBJECT_TYPE_IMAGE_VIEW, "mipview");
|
||||
_assert_(res == VK_SUCCESS);
|
||||
return view;
|
||||
}
|
||||
@@ -245,6 +256,9 @@ void VulkanTexture::Destroy() {
|
||||
if (view_ != VK_NULL_HANDLE) {
|
||||
vulkan_->Delete().QueueDeleteImageView(view_);
|
||||
}
|
||||
if (arrayView_ != VK_NULL_HANDLE) {
|
||||
vulkan_->Delete().QueueDeleteImageView(arrayView_);
|
||||
}
|
||||
if (image_ != VK_NULL_HANDLE) {
|
||||
_dbg_assert_(allocation_ != VK_NULL_HANDLE);
|
||||
vulkan_->Delete().QueueDeleteImageAllocation(image_, allocation_);
|
||||
|
||||
@@ -51,6 +51,9 @@ public:
|
||||
// Used for sampling, generally.
|
||||
VkImageView GetImageView() const { return view_; }
|
||||
|
||||
// For use with some shaders, we might want to view it as a single entry array for convenience.
|
||||
VkImageView GetImageArrayView() const { return arrayView_; }
|
||||
|
||||
int32_t GetWidth() const { return width_; }
|
||||
int32_t GetHeight() const { return height_; }
|
||||
int32_t GetNumMips() const { return numMips_; }
|
||||
@@ -62,6 +65,7 @@ private:
|
||||
VulkanContext *vulkan_;
|
||||
VkImage image_ = VK_NULL_HANDLE;
|
||||
VkImageView view_ = VK_NULL_HANDLE;
|
||||
VkImageView arrayView_ = VK_NULL_HANDLE;
|
||||
VmaAllocation allocation_ = VK_NULL_HANDLE;
|
||||
|
||||
int16_t width_ = 0;
|
||||
|
||||
@@ -239,7 +239,6 @@ static VulkanLibraryHandle vulkanLibrary;
|
||||
typedef void *VulkanLibraryHandle;
|
||||
static VulkanLibraryHandle vulkanLibrary;
|
||||
#endif
|
||||
const char *VulkanResultToString(VkResult res);
|
||||
|
||||
bool g_vulkanAvailabilityChecked = false;
|
||||
bool g_vulkanMayBeAvailable = false;
|
||||
@@ -274,6 +273,8 @@ static VulkanLibraryHandle VulkanLoadLibrary(const char *logname) {
|
||||
#if PPSSPP_PLATFORM(SWITCH)
|
||||
// Always unavailable, for now.
|
||||
return nullptr;
|
||||
#elif PPSSPP_PLATFORM(UWP)
|
||||
return nullptr;
|
||||
#elif PPSSPP_PLATFORM(WINDOWS)
|
||||
return LoadLibrary(L"vulkan-1.dll");
|
||||
#else
|
||||
@@ -308,9 +309,8 @@ void VulkanSetAvailable(bool available) {
|
||||
}
|
||||
|
||||
bool VulkanMayBeAvailable() {
|
||||
|
||||
//unsupported in VR at the moment
|
||||
if (IsVRBuild()) {
|
||||
// Unsupported in VR at the moment
|
||||
if (IsVREnabled()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -725,3 +725,34 @@ void VulkanLoadDeviceFunctions(VkDevice device, const VulkanExtensions &enabledE
|
||||
void VulkanFree() {
|
||||
VulkanFreeLibrary(vulkanLibrary);
|
||||
}
|
||||
|
||||
const char *VulkanResultToString(VkResult res) {
|
||||
switch (res) {
|
||||
case VK_NOT_READY: return "VK_NOT_READY";
|
||||
case VK_TIMEOUT: return "VK_TIMEOUT";
|
||||
case VK_EVENT_SET: return "VK_EVENT_SET";
|
||||
case VK_EVENT_RESET: return "VK_EVENT_RESET";
|
||||
case VK_INCOMPLETE: return "VK_INCOMPLETE";
|
||||
case VK_ERROR_OUT_OF_HOST_MEMORY: return "VK_ERROR_OUT_OF_HOST_MEMORY";
|
||||
case VK_ERROR_OUT_OF_DEVICE_MEMORY: return "VK_ERROR_OUT_OF_DEVICE_MEMORY";
|
||||
case VK_ERROR_INITIALIZATION_FAILED: return "VK_ERROR_INITIALIZATION_FAILED";
|
||||
case VK_ERROR_DEVICE_LOST: return "VK_ERROR_DEVICE_LOST";
|
||||
case VK_ERROR_MEMORY_MAP_FAILED: return "VK_ERROR_MEMORY_MAP_FAILED";
|
||||
case VK_ERROR_LAYER_NOT_PRESENT: return "VK_ERROR_LAYER_NOT_PRESENT";
|
||||
case VK_ERROR_EXTENSION_NOT_PRESENT: return "VK_ERROR_EXTENSION_NOT_PRESENT";
|
||||
case VK_ERROR_FEATURE_NOT_PRESENT: return "VK_ERROR_FEATURE_NOT_PRESENT";
|
||||
case VK_ERROR_INCOMPATIBLE_DRIVER: return "VK_ERROR_INCOMPATIBLE_DRIVER";
|
||||
case VK_ERROR_TOO_MANY_OBJECTS: return "VK_ERROR_TOO_MANY_OBJECTS";
|
||||
case VK_ERROR_FORMAT_NOT_SUPPORTED: return "VK_ERROR_FORMAT_NOT_SUPPORTED";
|
||||
case VK_ERROR_SURFACE_LOST_KHR: return "VK_ERROR_SURFACE_LOST_KHR";
|
||||
case VK_SUBOPTIMAL_KHR: return "VK_SUBOPTIMAL_KHR";
|
||||
case VK_ERROR_OUT_OF_DATE_KHR: return "VK_ERROR_OUT_OF_DATE_KHR";
|
||||
case VK_ERROR_INCOMPATIBLE_DISPLAY_KHR: return "VK_ERROR_INCOMPATIBLE_DISPLAY_KHR";
|
||||
case VK_ERROR_NATIVE_WINDOW_IN_USE_KHR: return "VK_ERROR_NATIVE_WINDOW_IN_USE_KHR";
|
||||
case VK_ERROR_OUT_OF_POOL_MEMORY_KHR: return "VK_ERROR_OUT_OF_POOL_MEMORY_KHR";
|
||||
case VK_ERROR_INVALID_EXTERNAL_HANDLE_KHR: return "VK_ERROR_INVALID_EXTERNAL_HANDLE_KHR";
|
||||
|
||||
default:
|
||||
return "VK_ERROR_...(unknown)";
|
||||
}
|
||||
}
|
||||
@@ -254,3 +254,5 @@ bool VulkanLoad();
|
||||
void VulkanLoadInstanceFunctions(VkInstance instance, const VulkanExtensions &enabledExtensions);
|
||||
void VulkanLoadDeviceFunctions(VkDevice device, const VulkanExtensions &enabledExtensions);
|
||||
void VulkanFree();
|
||||
|
||||
const char *VulkanResultToString(VkResult res);
|
||||
@@ -153,7 +153,7 @@ void VulkanDescSetPool::Create(VulkanContext *vulkan, const VkDescriptorPoolCrea
|
||||
_assert_msg_(res == VK_SUCCESS, "Could not create VulkanDescSetPool %s", tag_);
|
||||
}
|
||||
|
||||
VkDescriptorSet VulkanDescSetPool::Allocate(int n, const VkDescriptorSetLayout *layouts) {
|
||||
VkDescriptorSet VulkanDescSetPool::Allocate(int n, const VkDescriptorSetLayout *layouts, const char *tag) {
|
||||
if (descPool_ == VK_NULL_HANDLE || usage_ + n >= info_.maxSets) {
|
||||
// Missing or out of space, need to recreate.
|
||||
VkResult res = Recreate(grow_);
|
||||
@@ -180,9 +180,12 @@ VkDescriptorSet VulkanDescSetPool::Allocate(int n, const VkDescriptorSetLayout *
|
||||
_assert_msg_(result == VK_SUCCESS, "Ran out of descriptor space (frag?) and failed to allocate after recreating a descriptor pool. res=%d", (int)result);
|
||||
}
|
||||
|
||||
if (result == VK_SUCCESS)
|
||||
return desc;
|
||||
return VK_NULL_HANDLE;
|
||||
if (result != VK_SUCCESS) {
|
||||
return VK_NULL_HANDLE;
|
||||
}
|
||||
|
||||
vulkan_->SetDebugName(desc, VK_OBJECT_TYPE_DESCRIPTOR_SET, tag);
|
||||
return desc;
|
||||
}
|
||||
|
||||
void VulkanDescSetPool::Reset() {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
#pragma once
|
||||
|
||||
#include <cstdint>
|
||||
#include <cstring>
|
||||
#include <functional>
|
||||
#include <vector>
|
||||
|
||||
@@ -121,6 +122,15 @@ public:
|
||||
return writePtr_ + off;
|
||||
}
|
||||
|
||||
template<class T>
|
||||
void PushUBOData(const T &data, VkDescriptorBufferInfo *info) {
|
||||
uint32_t bindOffset;
|
||||
void *ptr = PushAligned(sizeof(T), &bindOffset, &info->buffer, vulkan_->GetPhysicalDeviceProperties().properties.limits.minUniformBufferOffsetAlignment);
|
||||
memcpy(ptr, &data, sizeof(T));
|
||||
info->offset = bindOffset;
|
||||
info->range = sizeof(T);
|
||||
}
|
||||
|
||||
size_t GetTotalSize() const;
|
||||
|
||||
private:
|
||||
@@ -153,7 +163,7 @@ public:
|
||||
void Create(VulkanContext *vulkan, const VkDescriptorPoolCreateInfo &info, const std::vector<VkDescriptorPoolSize> &sizes);
|
||||
// Allocate a new set, which may resize and empty the current sets.
|
||||
// Use only for the current frame, unless in a cache cleared by clear_.
|
||||
VkDescriptorSet Allocate(int n, const VkDescriptorSetLayout *layouts);
|
||||
VkDescriptorSet Allocate(int n, const VkDescriptorSetLayout *layouts, const char *tag);
|
||||
void Reset();
|
||||
void Destroy();
|
||||
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
#include "Common/GPU/DataFormat.h"
|
||||
#include "Common/GPU/Vulkan/VulkanQueueRunner.h"
|
||||
#include "Common/GPU/Vulkan/VulkanRenderManager.h"
|
||||
#include "Common/VR/PPSSPPVR.h"
|
||||
#include "Common/Log.h"
|
||||
#include "Common/TimeUtil.h"
|
||||
|
||||
@@ -31,11 +32,13 @@ static void MergeRenderAreaRectInto(VkRect2D *dest, VkRect2D &src) {
|
||||
RenderPassType MergeRPTypes(RenderPassType a, RenderPassType b) {
|
||||
// Either both are backbuffer type, or neither are.
|
||||
// These can't merge with other renderpasses
|
||||
if (a == RP_TYPE_BACKBUFFER || b == RP_TYPE_BACKBUFFER) {
|
||||
if (a == RenderPassType::BACKBUFFER || b == RenderPassType::BACKBUFFER) {
|
||||
_dbg_assert_(a == b);
|
||||
return a;
|
||||
}
|
||||
|
||||
_dbg_assert_((a & RenderPassType::MULTIVIEW) == (b & RenderPassType::MULTIVIEW));
|
||||
|
||||
// The rest we can just OR together to get the maximum feature set.
|
||||
return (RenderPassType)((u32)a | (u32)b);
|
||||
}
|
||||
@@ -165,7 +168,7 @@ bool VulkanQueueRunner::CreateSwapchain(VkCommandBuffer cmdInit) {
|
||||
color_image_view.subresourceRange.baseMipLevel = 0;
|
||||
color_image_view.subresourceRange.levelCount = 1;
|
||||
color_image_view.subresourceRange.baseArrayLayer = 0;
|
||||
color_image_view.subresourceRange.layerCount = 1;
|
||||
color_image_view.subresourceRange.layerCount = 1; // TODO: Investigate hw-assisted stereo.
|
||||
color_image_view.viewType = VK_IMAGE_VIEW_TYPE_2D;
|
||||
color_image_view.flags = 0;
|
||||
color_image_view.image = sc_buffer.image;
|
||||
@@ -175,6 +178,7 @@ bool VulkanQueueRunner::CreateSwapchain(VkCommandBuffer cmdInit) {
|
||||
// Also, turns out it's illegal to transition un-acquired images, thanks Hans-Kristian. See #11417.
|
||||
|
||||
res = vkCreateImageView(vulkan_->GetDevice(), &color_image_view, nullptr, &sc_buffer.view);
|
||||
vulkan_->SetDebugName(sc_buffer.view, VK_OBJECT_TYPE_IMAGE_VIEW, "swapchain_view");
|
||||
swapchainImages_.push_back(sc_buffer);
|
||||
_dbg_assert_(res == VK_SUCCESS);
|
||||
}
|
||||
@@ -194,7 +198,7 @@ bool VulkanQueueRunner::InitBackbufferFramebuffers(int width, int height) {
|
||||
VkImageView attachments[2] = { VK_NULL_HANDLE, depth_.view };
|
||||
|
||||
VkFramebufferCreateInfo fb_info = { VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO };
|
||||
fb_info.renderPass = GetCompatibleRenderPass()->Get(vulkan_, RP_TYPE_BACKBUFFER);
|
||||
fb_info.renderPass = GetCompatibleRenderPass()->Get(vulkan_, RenderPassType::BACKBUFFER);
|
||||
fb_info.attachmentCount = 2;
|
||||
fb_info.pAttachments = attachments;
|
||||
fb_info.width = width;
|
||||
@@ -248,7 +252,7 @@ bool VulkanQueueRunner::InitDepthStencilBuffer(VkCommandBuffer cmd) {
|
||||
|
||||
vulkan_->SetDebugName(depth_.image, VK_OBJECT_TYPE_IMAGE, "BackbufferDepth");
|
||||
|
||||
TransitionImageLayout2(cmd, depth_.image, 0, 1,
|
||||
TransitionImageLayout2(cmd, depth_.image, 0, 1, 1,
|
||||
aspectMask,
|
||||
VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL,
|
||||
VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT | VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT,
|
||||
@@ -273,6 +277,7 @@ bool VulkanQueueRunner::InitDepthStencilBuffer(VkCommandBuffer cmd) {
|
||||
VkDevice device = vulkan_->GetDevice();
|
||||
|
||||
res = vkCreateImageView(device, &depth_view_info, NULL, &depth_.view);
|
||||
vulkan_->SetDebugName(depth_.view, VK_OBJECT_TYPE_IMAGE_VIEW, "depth_stencil_backbuffer");
|
||||
_dbg_assert_(res == VK_SUCCESS);
|
||||
if (res != VK_SUCCESS)
|
||||
return false;
|
||||
@@ -325,9 +330,14 @@ static VkAttachmentStoreOp ConvertStoreAction(VKRRenderPassStoreAction action) {
|
||||
// Also see https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#synchronization-pipeline-barriers-subpass-self-dependencies
|
||||
|
||||
VkRenderPass CreateRenderPass(VulkanContext *vulkan, const RPKey &key, RenderPassType rpType) {
|
||||
bool selfDependency = rpType == RP_TYPE_COLOR_INPUT || rpType == RP_TYPE_COLOR_DEPTH_INPUT;
|
||||
bool isBackbuffer = rpType == RP_TYPE_BACKBUFFER;
|
||||
bool hasDepth = rpType == RP_TYPE_BACKBUFFER || rpType == RP_TYPE_COLOR_DEPTH || rpType == RP_TYPE_COLOR_DEPTH_INPUT;
|
||||
bool selfDependency = RenderPassTypeHasInput(rpType);
|
||||
bool isBackbuffer = rpType == RenderPassType::BACKBUFFER;
|
||||
bool hasDepth = RenderPassTypeHasDepth(rpType);
|
||||
bool multiview = RenderPassTypeHasMultiView(rpType);
|
||||
|
||||
if (multiview) {
|
||||
// TODO: Assert that the device has multiview support enabled.
|
||||
}
|
||||
|
||||
VkAttachmentDescription attachments[2] = {};
|
||||
attachments[0].format = isBackbuffer ? vulkan->GetSwapchainFormat() : VK_FORMAT_R8G8B8A8_UNORM;
|
||||
@@ -389,6 +399,19 @@ VkRenderPass CreateRenderPass(VulkanContext *vulkan, const RPKey &key, RenderPas
|
||||
rp.subpassCount = 1;
|
||||
rp.pSubpasses = &subpass;
|
||||
|
||||
VkRenderPassMultiviewCreateInfoKHR mv{ VK_STRUCTURE_TYPE_RENDER_PASS_MULTIVIEW_CREATE_INFO_KHR };
|
||||
uint32_t viewMask = 0x3; // Must be outside the 'if (multiview)' scope!
|
||||
int viewOffset = 0;
|
||||
if (multiview) {
|
||||
rp.pNext = &mv;
|
||||
mv.subpassCount = 1;
|
||||
mv.pViewMasks = &viewMask;
|
||||
mv.dependencyCount = 0;
|
||||
mv.pCorrelationMasks = &viewMask; // same masks
|
||||
mv.correlationMaskCount = 1;
|
||||
mv.pViewOffsets = &viewOffset;
|
||||
}
|
||||
|
||||
if (isBackbuffer) {
|
||||
deps[numDeps].srcSubpass = VK_SUBPASS_EXTERNAL;
|
||||
deps[numDeps].dstSubpass = 0;
|
||||
@@ -456,6 +479,7 @@ void VulkanQueueRunner::SelfDependencyBarrier(VKRImage &img, VkImageAspectFlags
|
||||
img.image,
|
||||
0,
|
||||
1,
|
||||
img.numLayers,
|
||||
aspect,
|
||||
VK_IMAGE_LAYOUT_GENERAL,
|
||||
VK_IMAGE_LAYOUT_GENERAL,
|
||||
@@ -515,6 +539,8 @@ void VulkanQueueRunner::PreprocessSteps(std::vector<VKRStep *> &steps) {
|
||||
}
|
||||
MergeRenderAreaRectInto(&steps[i]->render.renderArea, steps[j]->render.renderArea);
|
||||
steps[i]->render.renderPassType = MergeRPTypes(steps[i]->render.renderPassType, steps[j]->render.renderPassType);
|
||||
steps[i]->render.numDraws += steps[j]->render.numDraws;
|
||||
steps[i]->render.numReads += steps[j]->render.numReads;
|
||||
// Cheaply skip the first step.
|
||||
steps[j]->stepType = VKRStepType::RENDER_SKIP;
|
||||
break;
|
||||
@@ -544,7 +570,7 @@ void VulkanQueueRunner::PreprocessSteps(std::vector<VKRStep *> &steps) {
|
||||
}
|
||||
}
|
||||
|
||||
void VulkanQueueRunner::RunSteps(std::vector<VKRStep *> &steps, FrameData &frameData, FrameDataShared &frameDataShared) {
|
||||
void VulkanQueueRunner::RunSteps(std::vector<VKRStep *> &steps, FrameData &frameData, FrameDataShared &frameDataShared, bool keepSteps) {
|
||||
QueueProfileContext *profile = frameData.profilingEnabled_ ? &frameData.profile : nullptr;
|
||||
|
||||
if (profile)
|
||||
@@ -622,12 +648,13 @@ void VulkanQueueRunner::RunSteps(std::vector<VKRStep *> &steps, FrameData &frame
|
||||
|
||||
// Deleting all in one go should be easier on the instruction cache than deleting
|
||||
// them as we go - and easier to debug because we can look backwards in the frame.
|
||||
for (auto step : steps) {
|
||||
delete step;
|
||||
if (!keepSteps) {
|
||||
for (auto step : steps) {
|
||||
delete step;
|
||||
}
|
||||
steps.clear();
|
||||
}
|
||||
|
||||
steps.clear();
|
||||
|
||||
if (profile)
|
||||
profile->cpuEndTime = time_now_d();
|
||||
}
|
||||
@@ -871,6 +898,18 @@ const char *AspectToString(VkImageAspectFlags aspect) {
|
||||
}
|
||||
}
|
||||
|
||||
static const char *rpTypeDebugNames[] = {
|
||||
"RENDER",
|
||||
"RENDER_DEPTH",
|
||||
"RENDER_INPUT",
|
||||
"RENDER_DEPTH_INPUT",
|
||||
"MV_RENDER",
|
||||
"MV_RENDER_DEPTH",
|
||||
"MV_RENDER_INPUT",
|
||||
"MV_RENDER_DEPTH_INPUT",
|
||||
"BACKBUF",
|
||||
};
|
||||
|
||||
std::string VulkanQueueRunner::StepToString(const VKRStep &step) const {
|
||||
char buffer[256];
|
||||
switch (step.stepType) {
|
||||
@@ -880,16 +919,8 @@ std::string VulkanQueueRunner::StepToString(const VKRStep &step) const {
|
||||
int h = step.render.framebuffer ? step.render.framebuffer->height : vulkan_->GetBackbufferHeight();
|
||||
int actual_w = step.render.renderArea.extent.width;
|
||||
int actual_h = step.render.renderArea.extent.height;
|
||||
const char *renderCmd;
|
||||
switch (step.render.renderPassType) {
|
||||
case RP_TYPE_BACKBUFFER: renderCmd = "BACKBUF"; break;
|
||||
case RP_TYPE_COLOR: renderCmd = "RENDER"; break;
|
||||
case RP_TYPE_COLOR_DEPTH: renderCmd = "RENDER_DEPTH"; break;
|
||||
case RP_TYPE_COLOR_INPUT: renderCmd = "RENDER_INPUT"; break;
|
||||
case RP_TYPE_COLOR_DEPTH_INPUT: renderCmd = "RENDER_DEPTH_INPUT"; break;
|
||||
default: renderCmd = "N/A";
|
||||
}
|
||||
snprintf(buffer, sizeof(buffer), "%s %s (draws: %d, %dx%d/%dx%d, fb: %p, )", renderCmd, step.tag, step.render.numDraws, actual_w, actual_h, w, h, step.render.framebuffer);
|
||||
const char *renderCmd = rpTypeDebugNames[(size_t)step.render.renderPassType];
|
||||
snprintf(buffer, sizeof(buffer), "%s %s %s (draws: %d, %dx%d/%dx%d)", renderCmd, step.tag, step.render.framebuffer ? step.render.framebuffer->Tag() : "", step.render.numDraws, actual_w, actual_h, w, h);
|
||||
break;
|
||||
}
|
||||
case VKRStepType::COPY:
|
||||
@@ -899,7 +930,7 @@ std::string VulkanQueueRunner::StepToString(const VKRStep &step) const {
|
||||
snprintf(buffer, sizeof(buffer), "BLIT '%s' %s -> %s (%dx%d->%dx%d, %s)", step.tag, step.copy.src->Tag(), step.copy.dst->Tag(), step.blit.srcRect.extent.width, step.blit.srcRect.extent.height, step.blit.dstRect.extent.width, step.blit.dstRect.extent.height, AspectToString(step.blit.aspectMask));
|
||||
break;
|
||||
case VKRStepType::READBACK:
|
||||
snprintf(buffer, sizeof(buffer), "READBACK '%s' %s (%dx%d, %s)", step.tag, step.readback.src->Tag(), step.readback.srcRect.extent.width, step.readback.srcRect.extent.height, AspectToString(step.readback.aspectMask));
|
||||
snprintf(buffer, sizeof(buffer), "READBACK '%s' %s (%dx%d, %s)", step.tag, step.readback.src ? step.readback.src->Tag() : "(backbuffer)", step.readback.srcRect.extent.width, step.readback.srcRect.extent.height, AspectToString(step.readback.aspectMask));
|
||||
break;
|
||||
case VKRStepType::READBACK_IMAGE:
|
||||
snprintf(buffer, sizeof(buffer), "READBACK_IMAGE '%s' (%dx%d)", step.tag, step.readback_image.srcRect.extent.width, step.readback_image.srcRect.extent.height);
|
||||
@@ -936,6 +967,8 @@ void VulkanQueueRunner::ApplyRenderPassMerge(std::vector<VKRStep *> &steps) {
|
||||
// So we don't consider it for other things, maybe doesn't matter.
|
||||
src->dependencies.clear();
|
||||
src->stepType = VKRStepType::RENDER_SKIP;
|
||||
dst->render.numDraws += src->render.numDraws;
|
||||
dst->render.numReads += src->render.numReads;
|
||||
dst->render.pipelineFlags |= src->render.pipelineFlags;
|
||||
dst->render.renderPassType = MergeRPTypes(dst->render.renderPassType, src->render.renderPassType);
|
||||
};
|
||||
@@ -1109,6 +1142,12 @@ void VulkanQueueRunner::LogRenderPass(const VKRStep &pass, bool verbose) {
|
||||
case VKRRenderCommand::PUSH_CONSTANTS:
|
||||
INFO_LOG(G3D, " PushConstants(%d)", cmd.push.size);
|
||||
break;
|
||||
case VKRRenderCommand::DEBUG_ANNOTATION:
|
||||
INFO_LOG(G3D, " DebugAnnotation(%s)", cmd.debugAnnotation.annotation);
|
||||
break;
|
||||
case VKRRenderCommand::BIND_DESCRIPTOR_SET:
|
||||
INFO_LOG(G3D, " BindDescSet(%d)", cmd.bindDescSet.setNumber);
|
||||
break;
|
||||
|
||||
case VKRRenderCommand::NUM_RENDER_COMMANDS:
|
||||
break;
|
||||
@@ -1136,7 +1175,7 @@ void VulkanQueueRunner::LogReadbackImage(const VKRStep &step) {
|
||||
INFO_LOG(G3D, "%s", StepToString(step).c_str());
|
||||
}
|
||||
|
||||
void TransitionToOptimal(VkCommandBuffer cmd, VkImage colorImage, VkImageLayout colorLayout, VkImage depthStencilImage, VkImageLayout depthStencilLayout, VulkanBarrier *recordBarrier) {
|
||||
void TransitionToOptimal(VkCommandBuffer cmd, VkImage colorImage, VkImageLayout colorLayout, VkImage depthStencilImage, VkImageLayout depthStencilLayout, int numLayers, VulkanBarrier *recordBarrier) {
|
||||
if (colorLayout != VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL) {
|
||||
VkPipelineStageFlags srcStageMask = 0;
|
||||
VkAccessFlags srcAccessMask = 0;
|
||||
@@ -1169,7 +1208,7 @@ void TransitionToOptimal(VkCommandBuffer cmd, VkImage colorImage, VkImageLayout
|
||||
break;
|
||||
}
|
||||
recordBarrier->TransitionImage(
|
||||
colorImage, 0, 1, VK_IMAGE_ASPECT_COLOR_BIT,
|
||||
colorImage, 0, 1, numLayers, VK_IMAGE_ASPECT_COLOR_BIT,
|
||||
colorLayout,
|
||||
VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL,
|
||||
srcAccessMask,
|
||||
@@ -1205,7 +1244,7 @@ void TransitionToOptimal(VkCommandBuffer cmd, VkImage colorImage, VkImageLayout
|
||||
break;
|
||||
}
|
||||
recordBarrier->TransitionImage(
|
||||
depthStencilImage, 0, 1, VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT,
|
||||
depthStencilImage, 0, 1, numLayers, VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT,
|
||||
depthStencilLayout,
|
||||
VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL,
|
||||
srcAccessMask,
|
||||
@@ -1215,7 +1254,7 @@ void TransitionToOptimal(VkCommandBuffer cmd, VkImage colorImage, VkImageLayout
|
||||
}
|
||||
}
|
||||
|
||||
void TransitionFromOptimal(VkCommandBuffer cmd, VkImage colorImage, VkImageLayout colorLayout, VkImage depthStencilImage, VkImageLayout depthStencilLayout) {
|
||||
void TransitionFromOptimal(VkCommandBuffer cmd, VkImage colorImage, VkImageLayout colorLayout, VkImage depthStencilImage, int numLayers, VkImageLayout depthStencilLayout) {
|
||||
VkPipelineStageFlags srcStageMask = 0;
|
||||
VkPipelineStageFlags dstStageMask = 0;
|
||||
|
||||
@@ -1257,7 +1296,7 @@ void TransitionFromOptimal(VkCommandBuffer cmd, VkImage colorImage, VkImageLayou
|
||||
barrier[0].subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
|
||||
barrier[0].subresourceRange.baseMipLevel = 0;
|
||||
barrier[0].subresourceRange.levelCount = 1;
|
||||
barrier[0].subresourceRange.layerCount = 1;
|
||||
barrier[0].subresourceRange.layerCount = numLayers;
|
||||
barrier[0].srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
|
||||
barrier[0].dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
|
||||
barrierCount++;
|
||||
@@ -1296,7 +1335,7 @@ void TransitionFromOptimal(VkCommandBuffer cmd, VkImage colorImage, VkImageLayou
|
||||
barrier[barrierCount].subresourceRange.aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT;
|
||||
barrier[barrierCount].subresourceRange.baseMipLevel = 0;
|
||||
barrier[barrierCount].subresourceRange.levelCount = 1;
|
||||
barrier[barrierCount].subresourceRange.layerCount = 1;
|
||||
barrier[barrierCount].subresourceRange.layerCount = numLayers;
|
||||
barrier[barrierCount].srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
|
||||
barrier[barrierCount].dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
|
||||
barrierCount++;
|
||||
@@ -1314,6 +1353,7 @@ void VulkanQueueRunner::PerformRenderPass(const VKRStep &step, VkCommandBuffer c
|
||||
iter.fb->color.image,
|
||||
0,
|
||||
1,
|
||||
iter.fb->numLayers,
|
||||
VK_IMAGE_ASPECT_COLOR_BIT,
|
||||
iter.fb->color.layout,
|
||||
iter.targetLayout
|
||||
@@ -1324,6 +1364,7 @@ void VulkanQueueRunner::PerformRenderPass(const VKRStep &step, VkCommandBuffer c
|
||||
iter.fb->depth.image,
|
||||
0,
|
||||
1,
|
||||
iter.fb->numLayers,
|
||||
VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT,
|
||||
iter.fb->depth.layout,
|
||||
iter.targetLayout
|
||||
@@ -1348,12 +1389,12 @@ void VulkanQueueRunner::PerformRenderPass(const VKRStep &step, VkCommandBuffer c
|
||||
int n = 0;
|
||||
int stage = 0;
|
||||
|
||||
VkImageMemoryBarrier barriers[2]{};
|
||||
if (step.render.framebuffer->color.layout == VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL) {
|
||||
recordBarrier_.TransitionImage(
|
||||
step.render.framebuffer->color.image,
|
||||
0,
|
||||
1,
|
||||
step.render.framebuffer->numLayers,
|
||||
VK_IMAGE_ASPECT_COLOR_BIT,
|
||||
VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL,
|
||||
VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL,
|
||||
@@ -1368,6 +1409,7 @@ void VulkanQueueRunner::PerformRenderPass(const VKRStep &step, VkCommandBuffer c
|
||||
step.render.framebuffer->depth.image,
|
||||
0,
|
||||
1,
|
||||
step.render.framebuffer->numLayers,
|
||||
VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT,
|
||||
VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL,
|
||||
VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL,
|
||||
@@ -1407,7 +1449,8 @@ void VulkanQueueRunner::PerformRenderPass(const VKRStep &step, VkCommandBuffer c
|
||||
|
||||
const RenderPassType rpType = step.render.renderPassType;
|
||||
|
||||
for (const auto &c : commands) {
|
||||
for (size_t i = 0; i < commands.size(); i++) {
|
||||
const VkRenderData &c = commands[i];
|
||||
switch (c.cmd) {
|
||||
case VKRRenderCommand::REMOVED:
|
||||
break;
|
||||
@@ -1416,17 +1459,17 @@ void VulkanQueueRunner::PerformRenderPass(const VKRStep &step, VkCommandBuffer c
|
||||
{
|
||||
VKRGraphicsPipeline *graphicsPipeline = c.graphics_pipeline.pipeline;
|
||||
if (graphicsPipeline != lastGraphicsPipeline) {
|
||||
if (!graphicsPipeline->pipeline[rpType]) {
|
||||
if (!graphicsPipeline->pipeline[(size_t)rpType]) {
|
||||
// NOTE: If render steps got merged, it can happen that, as they ended during recording,
|
||||
// they didn't know their final render pass type so they created the wrong pipelines in EndCurRenderStep().
|
||||
// Unfortunately I don't know if we can fix it in any more sensible place than here.
|
||||
// Maybe a middle pass. But let's try to just block and compile here for now, this doesn't
|
||||
// happen all that much.
|
||||
graphicsPipeline->pipeline[rpType] = Promise<VkPipeline>::CreateEmpty();
|
||||
graphicsPipeline->pipeline[(size_t)rpType] = Promise<VkPipeline>::CreateEmpty();
|
||||
graphicsPipeline->Create(vulkan_, renderPass->Get(vulkan_, rpType), rpType);
|
||||
}
|
||||
|
||||
VkPipeline pipeline = graphicsPipeline->pipeline[rpType]->BlockUntilReady();
|
||||
VkPipeline pipeline = graphicsPipeline->pipeline[(size_t)rpType]->BlockUntilReady();
|
||||
if (pipeline != VK_NULL_HANDLE) {
|
||||
vkCmdBindPipeline(cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline);
|
||||
pipelineLayout = c.pipeline.pipelineLayout;
|
||||
@@ -1527,7 +1570,7 @@ void VulkanQueueRunner::PerformRenderPass(const VKRStep &step, VkCommandBuffer c
|
||||
|
||||
case VKRRenderCommand::DRAW_INDEXED:
|
||||
{
|
||||
vkCmdBindDescriptorSets(cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, pipelineLayout, 0, 1, &c.drawIndexed.ds, c.drawIndexed.numUboOffsets, c.drawIndexed.uboOffsets);
|
||||
vkCmdBindDescriptorSets(cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, pipelineLayout, 1, 1, &c.drawIndexed.ds, c.drawIndexed.numUboOffsets, c.drawIndexed.uboOffsets);
|
||||
vkCmdBindIndexBuffer(cmd, c.drawIndexed.ibuffer, c.drawIndexed.ioffset, (VkIndexType)c.drawIndexed.indexType);
|
||||
VkDeviceSize voffset = c.drawIndexed.voffset;
|
||||
vkCmdBindVertexBuffers(cmd, 0, 1, &c.drawIndexed.vbuffer, &voffset);
|
||||
@@ -1536,7 +1579,7 @@ void VulkanQueueRunner::PerformRenderPass(const VKRStep &step, VkCommandBuffer c
|
||||
}
|
||||
|
||||
case VKRRenderCommand::DRAW:
|
||||
vkCmdBindDescriptorSets(cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, pipelineLayout, 0, 1, &c.draw.ds, c.draw.numUboOffsets, c.draw.uboOffsets);
|
||||
vkCmdBindDescriptorSets(cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, pipelineLayout, 1, 1, &c.draw.ds, c.draw.numUboOffsets, c.draw.uboOffsets);
|
||||
if (c.draw.vbuffer) {
|
||||
vkCmdBindVertexBuffers(cmd, 0, 1, &c.draw.vbuffer, &c.draw.voffset);
|
||||
}
|
||||
@@ -1549,7 +1592,7 @@ void VulkanQueueRunner::PerformRenderPass(const VKRStep &step, VkCommandBuffer c
|
||||
int numAttachments = 0;
|
||||
VkClearRect rc{};
|
||||
rc.baseArrayLayer = 0;
|
||||
rc.layerCount = 1;
|
||||
rc.layerCount = 1; // In multiview mode, 1 means to replicate to all the active layers.
|
||||
rc.rect.extent.width = (uint32_t)curWidth;
|
||||
rc.rect.extent.height = (uint32_t)curHeight;
|
||||
VkClearAttachment attachments[2]{};
|
||||
@@ -1576,15 +1619,29 @@ void VulkanQueueRunner::PerformRenderPass(const VKRStep &step, VkCommandBuffer c
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
case VKRRenderCommand::DEBUG_ANNOTATION:
|
||||
if (vulkan_->Extensions().EXT_debug_utils) {
|
||||
VkDebugUtilsLabelEXT labelInfo{ VK_STRUCTURE_TYPE_DEBUG_UTILS_LABEL_EXT };
|
||||
labelInfo.pLabelName = c.debugAnnotation.annotation;
|
||||
vkCmdInsertDebugUtilsLabelEXT(cmd, &labelInfo);
|
||||
}
|
||||
break;
|
||||
|
||||
case VKRRenderCommand::BIND_DESCRIPTOR_SET:
|
||||
vkCmdBindDescriptorSets(cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, c.bindDescSet.pipelineLayout, c.bindDescSet.setNumber, 1, &c.bindDescSet.set, 0, nullptr);
|
||||
break;
|
||||
|
||||
default:
|
||||
ERROR_LOG(G3D, "Unimpl queue command");
|
||||
break;
|
||||
}
|
||||
}
|
||||
vkCmdEndRenderPass(cmd);
|
||||
|
||||
if (fb) {
|
||||
// If the desired final layout aren't the optimal layout for rendering, transition.
|
||||
TransitionFromOptimal(cmd, fb->color.image, step.render.finalColorLayout, fb->depth.image, step.render.finalDepthStencilLayout);
|
||||
TransitionFromOptimal(cmd, fb->color.image, step.render.finalColorLayout, fb->depth.image, fb->numLayers, step.render.finalDepthStencilLayout);
|
||||
|
||||
fb->color.layout = step.render.finalColorLayout;
|
||||
fb->depth.layout = step.render.finalDepthStencilLayout;
|
||||
@@ -1613,6 +1670,7 @@ VKRRenderPass *VulkanQueueRunner::PerformBindFramebufferAsRenderTarget(const VKR
|
||||
|
||||
VKRFramebuffer *fb = step.render.framebuffer;
|
||||
framebuf = fb->Get(renderPass, step.render.renderPassType);
|
||||
_dbg_assert_(framebuf != VK_NULL_HANDLE);
|
||||
w = fb->width;
|
||||
h = fb->height;
|
||||
|
||||
@@ -1624,7 +1682,7 @@ VKRRenderPass *VulkanQueueRunner::PerformBindFramebufferAsRenderTarget(const VKR
|
||||
step.render.colorLoad == VKRRenderPassLoadAction::CLEAR &&
|
||||
vulkan_->GetPhysicalDeviceProperties().properties.driverVersion == 0xaa9c4b29;
|
||||
if (maliBugWorkaround) {
|
||||
recordBarrier_.TransitionImage(step.render.framebuffer->color.image, 0, 1, VK_IMAGE_ASPECT_COLOR_BIT,
|
||||
recordBarrier_.TransitionImage(fb->color.image, 0, 1, fb->numLayers, VK_IMAGE_ASPECT_COLOR_BIT,
|
||||
fb->color.layout, VK_IMAGE_LAYOUT_GENERAL,
|
||||
VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT,
|
||||
VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT,
|
||||
@@ -1632,7 +1690,7 @@ VKRRenderPass *VulkanQueueRunner::PerformBindFramebufferAsRenderTarget(const VKR
|
||||
fb->color.layout = VK_IMAGE_LAYOUT_GENERAL;
|
||||
}
|
||||
|
||||
TransitionToOptimal(cmd, fb->color.image, fb->color.layout, fb->depth.image, fb->depth.layout, &recordBarrier_);
|
||||
TransitionToOptimal(cmd, fb->color.image, fb->color.layout, fb->depth.image, fb->depth.layout, fb->numLayers, &recordBarrier_);
|
||||
|
||||
// The transition from the optimal format happens after EndRenderPass, now that we don't
|
||||
// do it as part of the renderpass itself anymore.
|
||||
@@ -1653,7 +1711,11 @@ VKRRenderPass *VulkanQueueRunner::PerformBindFramebufferAsRenderTarget(const VKR
|
||||
};
|
||||
renderPass = GetRenderPass(key);
|
||||
|
||||
framebuf = backbuffer_;
|
||||
if (IsVREnabled()) {
|
||||
framebuf = (VkFramebuffer)BindVRFramebuffer();
|
||||
} else {
|
||||
framebuf = backbuffer_;
|
||||
}
|
||||
|
||||
// Raw, rotated backbuffer size.
|
||||
w = vulkan_->GetBackbufferWidth();
|
||||
@@ -1698,20 +1760,11 @@ void VulkanQueueRunner::PerformCopy(const VKRStep &step, VkCommandBuffer cmd) {
|
||||
VKRFramebuffer *src = step.copy.src;
|
||||
VKRFramebuffer *dst = step.copy.dst;
|
||||
|
||||
VkImageCopy copy{};
|
||||
copy.srcOffset.x = step.copy.srcRect.offset.x;
|
||||
copy.srcOffset.y = step.copy.srcRect.offset.y;
|
||||
copy.srcOffset.z = 0;
|
||||
copy.srcSubresource.mipLevel = 0;
|
||||
copy.srcSubresource.layerCount = 1;
|
||||
copy.dstOffset.x = step.copy.dstPos.x;
|
||||
copy.dstOffset.y = step.copy.dstPos.y;
|
||||
copy.dstOffset.z = 0;
|
||||
copy.dstSubresource.mipLevel = 0;
|
||||
copy.dstSubresource.layerCount = 1;
|
||||
copy.extent.width = step.copy.srcRect.extent.width;
|
||||
copy.extent.height = step.copy.srcRect.extent.height;
|
||||
copy.extent.depth = 1;
|
||||
int layerCount = std::min(step.copy.src->numLayers, step.copy.dst->numLayers);
|
||||
_dbg_assert_(step.copy.src->numLayers >= step.copy.dst->numLayers);
|
||||
|
||||
// TODO: If dst covers exactly the whole destination, we can set up a UNDEFINED->TRANSFER_DST_OPTIMAL transition,
|
||||
// which can potentially be more efficient.
|
||||
|
||||
// First source barriers.
|
||||
if (step.copy.aspectMask & VK_IMAGE_ASPECT_COLOR_BIT) {
|
||||
@@ -1725,6 +1778,8 @@ void VulkanQueueRunner::PerformCopy(const VKRStep &step, VkCommandBuffer cmd) {
|
||||
|
||||
// We can't copy only depth or only stencil unfortunately - or can we?.
|
||||
if (step.copy.aspectMask & (VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT)) {
|
||||
_dbg_assert_(src->depth.image != VK_NULL_HANDLE);
|
||||
|
||||
if (src->depth.layout != VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL) {
|
||||
SetupTransitionToTransferSrc(src->depth, VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT, &recordBarrier_);
|
||||
}
|
||||
@@ -1740,6 +1795,21 @@ void VulkanQueueRunner::PerformCopy(const VKRStep &step, VkCommandBuffer cmd) {
|
||||
|
||||
recordBarrier_.Flush(cmd);
|
||||
|
||||
VkImageCopy copy{};
|
||||
copy.srcOffset.x = step.copy.srcRect.offset.x;
|
||||
copy.srcOffset.y = step.copy.srcRect.offset.y;
|
||||
copy.srcOffset.z = 0;
|
||||
copy.srcSubresource.mipLevel = 0;
|
||||
copy.srcSubresource.layerCount = layerCount;
|
||||
copy.dstOffset.x = step.copy.dstPos.x;
|
||||
copy.dstOffset.y = step.copy.dstPos.y;
|
||||
copy.dstOffset.z = 0;
|
||||
copy.dstSubresource.mipLevel = 0;
|
||||
copy.dstSubresource.layerCount = layerCount;
|
||||
copy.extent.width = step.copy.srcRect.extent.width;
|
||||
copy.extent.height = step.copy.srcRect.extent.height;
|
||||
copy.extent.depth = 1;
|
||||
|
||||
if (step.copy.aspectMask & VK_IMAGE_ASPECT_COLOR_BIT) {
|
||||
copy.srcSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
|
||||
copy.dstSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
|
||||
@@ -1758,38 +1828,12 @@ void VulkanQueueRunner::PerformBlit(const VKRStep &step, VkCommandBuffer cmd) {
|
||||
// The barrier code doesn't handle this case. We'd need to transition to GENERAL to do an intra-image copy.
|
||||
_dbg_assert_(step.blit.src != step.blit.dst);
|
||||
|
||||
VkImageMemoryBarrier srcBarriers[2]{};
|
||||
VkImageMemoryBarrier dstBarriers[2]{};
|
||||
int layerCount = std::min(step.blit.src->numLayers, step.blit.dst->numLayers);
|
||||
_dbg_assert_(step.blit.src->numLayers >= step.blit.dst->numLayers);
|
||||
|
||||
VKRFramebuffer *src = step.blit.src;
|
||||
VKRFramebuffer *dst = step.blit.dst;
|
||||
|
||||
// If any validation needs to be performed here, it should probably have been done
|
||||
// already when the blit was queued. So don't validate here.
|
||||
VkImageBlit blit{};
|
||||
blit.srcOffsets[0].x = step.blit.srcRect.offset.x;
|
||||
blit.srcOffsets[0].y = step.blit.srcRect.offset.y;
|
||||
blit.srcOffsets[0].z = 0;
|
||||
blit.srcOffsets[1].x = step.blit.srcRect.offset.x + step.blit.srcRect.extent.width;
|
||||
blit.srcOffsets[1].y = step.blit.srcRect.offset.y + step.blit.srcRect.extent.height;
|
||||
blit.srcOffsets[1].z = 1;
|
||||
blit.srcSubresource.mipLevel = 0;
|
||||
blit.srcSubresource.layerCount = 1;
|
||||
blit.dstOffsets[0].x = step.blit.dstRect.offset.x;
|
||||
blit.dstOffsets[0].y = step.blit.dstRect.offset.y;
|
||||
blit.dstOffsets[0].z = 0;
|
||||
blit.dstOffsets[1].x = step.blit.dstRect.offset.x + step.blit.dstRect.extent.width;
|
||||
blit.dstOffsets[1].y = step.blit.dstRect.offset.y + step.blit.dstRect.extent.height;
|
||||
blit.dstOffsets[1].z = 1;
|
||||
blit.dstSubresource.mipLevel = 0;
|
||||
blit.dstSubresource.layerCount = 1;
|
||||
|
||||
VkPipelineStageFlags srcStage = 0;
|
||||
VkPipelineStageFlags dstStage = 0;
|
||||
|
||||
int srcCount = 0;
|
||||
int dstCount = 0;
|
||||
|
||||
// First source barriers.
|
||||
if (step.blit.aspectMask & VK_IMAGE_ASPECT_COLOR_BIT) {
|
||||
if (src->color.layout != VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL) {
|
||||
@@ -1815,6 +1859,26 @@ void VulkanQueueRunner::PerformBlit(const VKRStep &step, VkCommandBuffer cmd) {
|
||||
|
||||
recordBarrier_.Flush(cmd);
|
||||
|
||||
// If any validation needs to be performed here, it should probably have been done
|
||||
// already when the blit was queued. So don't validate here.
|
||||
VkImageBlit blit{};
|
||||
blit.srcOffsets[0].x = step.blit.srcRect.offset.x;
|
||||
blit.srcOffsets[0].y = step.blit.srcRect.offset.y;
|
||||
blit.srcOffsets[0].z = 0;
|
||||
blit.srcOffsets[1].x = step.blit.srcRect.offset.x + step.blit.srcRect.extent.width;
|
||||
blit.srcOffsets[1].y = step.blit.srcRect.offset.y + step.blit.srcRect.extent.height;
|
||||
blit.srcOffsets[1].z = 1;
|
||||
blit.srcSubresource.mipLevel = 0;
|
||||
blit.srcSubresource.layerCount = layerCount;
|
||||
blit.dstOffsets[0].x = step.blit.dstRect.offset.x;
|
||||
blit.dstOffsets[0].y = step.blit.dstRect.offset.y;
|
||||
blit.dstOffsets[0].z = 0;
|
||||
blit.dstOffsets[1].x = step.blit.dstRect.offset.x + step.blit.dstRect.extent.width;
|
||||
blit.dstOffsets[1].y = step.blit.dstRect.offset.y + step.blit.dstRect.extent.height;
|
||||
blit.dstOffsets[1].z = 1;
|
||||
blit.dstSubresource.mipLevel = 0;
|
||||
blit.dstSubresource.layerCount = layerCount;
|
||||
|
||||
if (step.blit.aspectMask & VK_IMAGE_ASPECT_COLOR_BIT) {
|
||||
blit.srcSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
|
||||
blit.dstSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
|
||||
@@ -1875,6 +1939,7 @@ void VulkanQueueRunner::SetupTransitionToTransferSrc(VKRImage &img, VkImageAspec
|
||||
img.image,
|
||||
0,
|
||||
1,
|
||||
img.numLayers,
|
||||
imageAspect,
|
||||
img.layout,
|
||||
VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
|
||||
@@ -1923,6 +1988,7 @@ void VulkanQueueRunner::SetupTransitionToTransferDst(VKRImage &img, VkImageAspec
|
||||
img.image,
|
||||
0,
|
||||
1,
|
||||
img.numLayers,
|
||||
aspect,
|
||||
img.layout,
|
||||
VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
|
||||
@@ -1952,6 +2018,7 @@ void VulkanQueueRunner::SetupTransferDstWriteAfterWrite(VKRImage &img, VkImageAs
|
||||
img.image,
|
||||
0,
|
||||
1,
|
||||
img.numLayers,
|
||||
aspect,
|
||||
VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
|
||||
VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
|
||||
@@ -1980,7 +2047,8 @@ void VulkanQueueRunner::PerformReadback(const VKRStep &step, VkCommandBuffer cmd
|
||||
if (step.readback.src == nullptr) {
|
||||
// We only take screenshots after the main render pass (anything else would be stupid) so we need to transition out of PRESENT,
|
||||
// and then back into it.
|
||||
TransitionImageLayout2(cmd, backbufferImage_, 0, 1, VK_IMAGE_ASPECT_COLOR_BIT,
|
||||
// Regarding layers, backbuffer currently only has one layer.
|
||||
TransitionImageLayout2(cmd, backbufferImage_, 0, 1, 1, VK_IMAGE_ASPECT_COLOR_BIT,
|
||||
VK_IMAGE_LAYOUT_PRESENT_SRC_KHR, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
|
||||
VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT,
|
||||
0, VK_ACCESS_TRANSFER_READ_BIT);
|
||||
@@ -1992,6 +2060,7 @@ void VulkanQueueRunner::PerformReadback(const VKRStep &step, VkCommandBuffer cmd
|
||||
srcImage = &step.readback.src->color;
|
||||
} else if (step.readback.aspectMask & (VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT)) {
|
||||
srcImage = &step.readback.src->depth;
|
||||
_dbg_assert_(srcImage->image != VK_NULL_HANDLE);
|
||||
} else {
|
||||
_dbg_assert_msg_(false, "No image aspect to readback?");
|
||||
return;
|
||||
@@ -2013,7 +2082,8 @@ void VulkanQueueRunner::PerformReadback(const VKRStep &step, VkCommandBuffer cmd
|
||||
if (step.readback.src == nullptr) {
|
||||
// We only take screenshots after the main render pass (anything else would be stupid) so we need to transition out of PRESENT,
|
||||
// and then back into it.
|
||||
TransitionImageLayout2(cmd, backbufferImage_, 0, 1, VK_IMAGE_ASPECT_COLOR_BIT,
|
||||
// Regarding layers, backbuffer currently only has one layer.
|
||||
TransitionImageLayout2(cmd, backbufferImage_, 0, 1, 1, VK_IMAGE_ASPECT_COLOR_BIT,
|
||||
VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, VK_IMAGE_LAYOUT_PRESENT_SRC_KHR,
|
||||
VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT,
|
||||
VK_ACCESS_TRANSFER_READ_BIT, 0);
|
||||
@@ -2044,7 +2114,7 @@ void VulkanQueueRunner::PerformReadbackImage(const VKRStep &step, VkCommandBuffe
|
||||
vkCmdCopyImageToBuffer(cmd, step.readback_image.image, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, readbackBuffer_, 1, ®ion);
|
||||
|
||||
// Now transfer it back to a texture.
|
||||
TransitionImageLayout2(cmd, step.readback_image.image, 0, 1,
|
||||
TransitionImageLayout2(cmd, step.readback_image.image, 0, 1, 1, // I don't think we have any multilayer cases for regular textures. Above in PerformReadback, though..
|
||||
VK_IMAGE_ASPECT_COLOR_BIT,
|
||||
VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL,
|
||||
VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT,
|
||||
|
||||
@@ -38,40 +38,52 @@ enum class VKRRenderCommand : uint8_t {
|
||||
DRAW_INDEXED,
|
||||
PUSH_CONSTANTS,
|
||||
SELF_DEPENDENCY_BARRIER,
|
||||
DEBUG_ANNOTATION,
|
||||
BIND_DESCRIPTOR_SET,
|
||||
NUM_RENDER_COMMANDS,
|
||||
};
|
||||
|
||||
enum class PipelineFlags {
|
||||
enum class PipelineFlags : u8 {
|
||||
NONE = 0,
|
||||
USES_BLEND_CONSTANT = (1 << 1),
|
||||
USES_DEPTH_STENCIL = (1 << 2), // Reads or writes the depth or stencil buffers.
|
||||
USES_INPUT_ATTACHMENT = (1 << 3),
|
||||
USES_GEOMETRY_SHADER = (1 << 4),
|
||||
USES_MULTIVIEW = (1 << 5), // Inherited from the render pass it was created with.
|
||||
};
|
||||
ENUM_CLASS_BITOPS(PipelineFlags);
|
||||
|
||||
// Pipelines need to be created for the right type of render pass.
|
||||
enum RenderPassType {
|
||||
// These four are organized so that bit 0 is DEPTH and bit 1 is INPUT, so
|
||||
// TODO: Rename to RenderPassFlags?
|
||||
// When you add more flags, don't forget to update rpTypeDebugNames[].
|
||||
enum class RenderPassType {
|
||||
DEFAULT = 0,
|
||||
// These eight are organized so that bit 0 is DEPTH and bit 1 is INPUT and bit 2 is MULTIVIEW, so
|
||||
// they can be OR-ed together in MergeRPTypes.
|
||||
RP_TYPE_COLOR,
|
||||
RP_TYPE_COLOR_DEPTH,
|
||||
RP_TYPE_COLOR_INPUT,
|
||||
RP_TYPE_COLOR_DEPTH_INPUT,
|
||||
HAS_DEPTH = 1,
|
||||
COLOR_INPUT = 2, // input attachment
|
||||
MULTIVIEW = 4,
|
||||
|
||||
// This is the odd one out, and gets special handling in MergeRPTypes.
|
||||
RP_TYPE_BACKBUFFER, // For the backbuffer we can always use CLEAR/DONT_CARE, so bandwidth cost for a depth channel is negligible.
|
||||
// If this flag is set, none of the other flags can be set.
|
||||
// For the backbuffer we can always use CLEAR/DONT_CARE, so bandwidth cost for a depth channel is negligible
|
||||
// so we don't bother with a non-depth version.
|
||||
BACKBUFFER = 8,
|
||||
|
||||
// Later will add pure-color render passes.
|
||||
RP_TYPE_COUNT,
|
||||
TYPE_COUNT = BACKBUFFER + 1,
|
||||
};
|
||||
ENUM_CLASS_BITOPS(RenderPassType);
|
||||
|
||||
inline bool RenderPassTypeHasDepth(RenderPassType type) {
|
||||
return type == RP_TYPE_BACKBUFFER || type == RP_TYPE_COLOR_DEPTH || type == RP_TYPE_COLOR_DEPTH_INPUT;
|
||||
return (type & RenderPassType::HAS_DEPTH) || type == RenderPassType::BACKBUFFER;
|
||||
}
|
||||
|
||||
inline bool RenderPassTypeHasInput(RenderPassType type) {
|
||||
return type == RP_TYPE_COLOR_INPUT || type == RP_TYPE_COLOR_DEPTH_INPUT;
|
||||
return (type & RenderPassType::COLOR_INPUT) != 0;
|
||||
}
|
||||
|
||||
inline bool RenderPassTypeHasMultiView(RenderPassType type) {
|
||||
return (type & RenderPassType::MULTIVIEW) != 0;
|
||||
}
|
||||
|
||||
struct VkRenderData {
|
||||
@@ -102,7 +114,7 @@ struct VkRenderData {
|
||||
VkDescriptorSet ds;
|
||||
int numUboOffsets;
|
||||
uint32_t uboOffsets[3];
|
||||
VkBuffer vbuffer; // might need to increase at some point
|
||||
VkBuffer vbuffer;
|
||||
VkBuffer ibuffer;
|
||||
uint32_t voffset;
|
||||
uint32_t ioffset;
|
||||
@@ -136,6 +148,14 @@ struct VkRenderData {
|
||||
uint8_t size;
|
||||
uint8_t data[40]; // Should be enough for now.
|
||||
} push;
|
||||
struct {
|
||||
const char *annotation;
|
||||
} debugAnnotation;
|
||||
struct {
|
||||
int setNumber;
|
||||
VkDescriptorSet set;
|
||||
VkPipelineLayout pipelineLayout;
|
||||
} bindDescSet;
|
||||
};
|
||||
};
|
||||
|
||||
@@ -248,7 +268,7 @@ public:
|
||||
|
||||
VkRenderPass Get(VulkanContext *vulkan, RenderPassType rpType);
|
||||
void Destroy(VulkanContext *vulkan) {
|
||||
for (int i = 0; i < RP_TYPE_COUNT; i++) {
|
||||
for (size_t i = 0; i < (size_t)RenderPassType::TYPE_COUNT; i++) {
|
||||
if (pass[i]) {
|
||||
vulkan->Delete().QueueDeleteRenderPass(pass[i]);
|
||||
}
|
||||
@@ -256,7 +276,8 @@ public:
|
||||
}
|
||||
|
||||
private:
|
||||
VkRenderPass pass[RP_TYPE_COUNT]{};
|
||||
// TODO: Might be better off with a hashmap once the render pass type count grows really large..
|
||||
VkRenderPass pass[(size_t)RenderPassType::TYPE_COUNT]{};
|
||||
RPKey key_;
|
||||
};
|
||||
|
||||
@@ -278,7 +299,7 @@ public:
|
||||
}
|
||||
|
||||
void PreprocessSteps(std::vector<VKRStep *> &steps);
|
||||
void RunSteps(std::vector<VKRStep *> &steps, FrameData &frameData, FrameDataShared &frameDataShared);
|
||||
void RunSteps(std::vector<VKRStep *> &steps, FrameData &frameData, FrameDataShared &frameDataShared, bool keepSteps = false);
|
||||
void LogSteps(const std::vector<VKRStep *> &steps, bool verbose);
|
||||
|
||||
std::string StepToString(const VKRStep &step) const;
|
||||
|
||||
@@ -12,6 +12,7 @@
|
||||
#include "Common/GPU/Vulkan/VulkanRenderManager.h"
|
||||
|
||||
#include "Common/Thread/ThreadUtil.h"
|
||||
#include "Common/VR/PPSSPPVR.h"
|
||||
|
||||
#if 0 // def _DEBUG
|
||||
#define VLOG(...) NOTICE_LOG(G3D, __VA_ARGS__)
|
||||
@@ -30,8 +31,9 @@ bool VKRGraphicsPipeline::Create(VulkanContext *vulkan, VkRenderPass compatibleR
|
||||
// Fill in the last part of the desc since now it's time to block.
|
||||
VkShaderModule vs = desc->vertexShader->BlockUntilReady();
|
||||
VkShaderModule fs = desc->fragmentShader->BlockUntilReady();
|
||||
VkShaderModule gs = desc->geometryShader ? desc->geometryShader->BlockUntilReady() : VK_NULL_HANDLE;
|
||||
|
||||
if (!vs || !fs) {
|
||||
if (!vs || !fs || (!gs && desc->geometryShader)) {
|
||||
ERROR_LOG(G3D, "Failed creating graphics pipeline - missing shader modules");
|
||||
// We're kinda screwed here?
|
||||
return false;
|
||||
@@ -49,6 +51,14 @@ bool VKRGraphicsPipeline::Create(VulkanContext *vulkan, VkRenderPass compatibleR
|
||||
ss[1].pSpecializationInfo = nullptr;
|
||||
ss[1].module = fs;
|
||||
ss[1].pName = "main";
|
||||
if (gs) {
|
||||
stageCount++;
|
||||
ss[2].sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;
|
||||
ss[2].stage = VK_SHADER_STAGE_GEOMETRY_BIT;
|
||||
ss[2].pSpecializationInfo = nullptr;
|
||||
ss[2].module = gs;
|
||||
ss[2].pName = "main";
|
||||
}
|
||||
|
||||
VkGraphicsPipelineCreateInfo pipe{ VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO };
|
||||
pipe.pStages = ss;
|
||||
@@ -83,10 +93,10 @@ bool VKRGraphicsPipeline::Create(VulkanContext *vulkan, VkRenderPass compatibleR
|
||||
// Would really like to log more here, we could probably attach more info to desc.
|
||||
//
|
||||
// At least create a null placeholder to avoid creating over and over if something is broken.
|
||||
pipeline[rpType]->Post(VK_NULL_HANDLE);
|
||||
pipeline[(size_t)rpType]->Post(VK_NULL_HANDLE);
|
||||
success = false;
|
||||
} else if (result != VK_SUCCESS) {
|
||||
pipeline[rpType]->Post(VK_NULL_HANDLE);
|
||||
pipeline[(size_t)rpType]->Post(VK_NULL_HANDLE);
|
||||
ERROR_LOG(G3D, "Failed creating graphics pipeline! result='%s'", VulkanResultToString(result));
|
||||
success = false;
|
||||
} else {
|
||||
@@ -94,14 +104,14 @@ bool VKRGraphicsPipeline::Create(VulkanContext *vulkan, VkRenderPass compatibleR
|
||||
if (!tag.empty()) {
|
||||
vulkan->SetDebugName(vkpipeline, VK_OBJECT_TYPE_PIPELINE, tag.c_str());
|
||||
}
|
||||
pipeline[rpType]->Post(vkpipeline);
|
||||
pipeline[(size_t)rpType]->Post(vkpipeline);
|
||||
}
|
||||
|
||||
return success;
|
||||
}
|
||||
|
||||
void VKRGraphicsPipeline::QueueForDeletion(VulkanContext *vulkan) {
|
||||
for (int i = 0; i < RP_TYPE_COUNT; i++) {
|
||||
for (size_t i = 0; i < (size_t)RenderPassType::TYPE_COUNT; i++) {
|
||||
if (!pipeline[i])
|
||||
continue;
|
||||
VkPipeline pipeline = this->pipeline[i]->BlockUntilReady();
|
||||
@@ -115,7 +125,7 @@ void VKRGraphicsPipeline::QueueForDeletion(VulkanContext *vulkan) {
|
||||
|
||||
u32 VKRGraphicsPipeline::GetVariantsBitmask() const {
|
||||
u32 bitmask = 0;
|
||||
for (int i = 0; i < RP_TYPE_COUNT; i++) {
|
||||
for (size_t i = 0; i < (size_t)RenderPassType::TYPE_COUNT; i++) {
|
||||
if (pipeline[i]) {
|
||||
bitmask |= 1 << i;
|
||||
}
|
||||
@@ -145,15 +155,14 @@ bool VKRComputePipeline::Create(VulkanContext *vulkan) {
|
||||
return success;
|
||||
}
|
||||
|
||||
VKRFramebuffer::VKRFramebuffer(VulkanContext *vk, VkCommandBuffer initCmd, VKRRenderPass *compatibleRenderPass, int _width, int _height, bool createDepthStencilBuffer, const char *tag) : vulkan_(vk), tag_(tag) {
|
||||
width = _width;
|
||||
height = _height;
|
||||
VKRFramebuffer::VKRFramebuffer(VulkanContext *vk, VkCommandBuffer initCmd, VKRRenderPass *compatibleRenderPass, int _width, int _height, int _numLayers, bool createDepthStencilBuffer, const char *tag)
|
||||
: vulkan_(vk), tag_(tag), width(_width), height(_height), numLayers(_numLayers) {
|
||||
|
||||
_dbg_assert_(tag);
|
||||
|
||||
CreateImage(vulkan_, initCmd, color, width, height, VK_FORMAT_R8G8B8A8_UNORM, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, true, tag);
|
||||
CreateImage(vulkan_, initCmd, color, width, height, numLayers, VK_FORMAT_R8G8B8A8_UNORM, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, true, tag);
|
||||
if (createDepthStencilBuffer) {
|
||||
CreateImage(vulkan_, initCmd, depth, width, height, vulkan_->GetDeviceInfo().preferredDepthStencilFormat, VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL, false, tag);
|
||||
CreateImage(vulkan_, initCmd, depth, width, height, numLayers, vulkan_->GetDeviceInfo().preferredDepthStencilFormat, VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL, false, tag);
|
||||
}
|
||||
|
||||
UpdateTag(tag);
|
||||
@@ -166,13 +175,13 @@ void VKRFramebuffer::UpdateTag(const char *newTag) {
|
||||
char name[128];
|
||||
snprintf(name, sizeof(name), "fb_color_%s", tag_.c_str());
|
||||
vulkan_->SetDebugName(color.image, VK_OBJECT_TYPE_IMAGE, name);
|
||||
vulkan_->SetDebugName(color.imageView, VK_OBJECT_TYPE_IMAGE_VIEW, name);
|
||||
vulkan_->SetDebugName(color.rtView, VK_OBJECT_TYPE_IMAGE_VIEW, name);
|
||||
if (depth.image) {
|
||||
snprintf(name, sizeof(name), "fb_depth_%s", tag_.c_str());
|
||||
vulkan_->SetDebugName(depth.image, VK_OBJECT_TYPE_IMAGE, name);
|
||||
vulkan_->SetDebugName(depth.imageView, VK_OBJECT_TYPE_IMAGE_VIEW, name);
|
||||
vulkan_->SetDebugName(depth.rtView, VK_OBJECT_TYPE_IMAGE_VIEW, name);
|
||||
}
|
||||
for (int rpType = 0; rpType < RP_TYPE_COUNT; rpType++) {
|
||||
for (size_t rpType = 0; rpType < (size_t)RenderPassType::TYPE_COUNT; rpType++) {
|
||||
if (framebuf[rpType]) {
|
||||
snprintf(name, sizeof(name), "fb_%s", tag_.c_str());
|
||||
vulkan_->SetDebugName(framebuf[(int)rpType], VK_OBJECT_TYPE_FRAMEBUFFER, name);
|
||||
@@ -181,6 +190,8 @@ void VKRFramebuffer::UpdateTag(const char *newTag) {
|
||||
}
|
||||
|
||||
VkFramebuffer VKRFramebuffer::Get(VKRRenderPass *compatibleRenderPass, RenderPassType rpType) {
|
||||
bool multiview = RenderPassTypeHasMultiView(rpType);
|
||||
|
||||
if (framebuf[(int)rpType]) {
|
||||
return framebuf[(int)rpType];
|
||||
}
|
||||
@@ -188,19 +199,17 @@ VkFramebuffer VKRFramebuffer::Get(VKRRenderPass *compatibleRenderPass, RenderPas
|
||||
VkFramebufferCreateInfo fbci{ VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO };
|
||||
VkImageView views[2]{};
|
||||
|
||||
bool hasDepth = rpType == RP_TYPE_BACKBUFFER || rpType == RP_TYPE_COLOR_DEPTH || rpType == RP_TYPE_COLOR_DEPTH_INPUT;
|
||||
|
||||
views[0] = color.imageView;
|
||||
bool hasDepth = RenderPassTypeHasDepth(rpType);
|
||||
views[0] = color.rtView; // 2D array texture if multilayered.
|
||||
if (hasDepth) {
|
||||
_dbg_assert_(depth.imageView != VK_NULL_HANDLE);
|
||||
views[1] = depth.imageView;
|
||||
views[1] = depth.rtView;
|
||||
}
|
||||
fbci.renderPass = compatibleRenderPass->Get(vulkan_, rpType);
|
||||
fbci.attachmentCount = hasDepth ? 2 : 1;
|
||||
fbci.pAttachments = views;
|
||||
fbci.width = width;
|
||||
fbci.height = height;
|
||||
fbci.layers = 1;
|
||||
fbci.layers = 1; // With multiview, this should be set as 1.
|
||||
|
||||
VkResult res = vkCreateFramebuffer(vulkan_->GetDevice(), &fbci, nullptr, &framebuf[(int)rpType]);
|
||||
_assert_(res == VK_SUCCESS);
|
||||
@@ -213,10 +222,24 @@ VkFramebuffer VKRFramebuffer::Get(VKRRenderPass *compatibleRenderPass, RenderPas
|
||||
}
|
||||
|
||||
VKRFramebuffer::~VKRFramebuffer() {
|
||||
if (color.imageView)
|
||||
vulkan_->Delete().QueueDeleteImageView(color.imageView);
|
||||
if (depth.imageView)
|
||||
vulkan_->Delete().QueueDeleteImageView(depth.imageView);
|
||||
// Get rid of the views first, feels cleaner (but in reality doesn't matter).
|
||||
if (color.rtView)
|
||||
vulkan_->Delete().QueueDeleteImageView(color.rtView);
|
||||
if (depth.rtView)
|
||||
vulkan_->Delete().QueueDeleteImageView(depth.rtView);
|
||||
if (color.texAllLayersView)
|
||||
vulkan_->Delete().QueueDeleteImageView(color.texAllLayersView);
|
||||
if (depth.texAllLayersView)
|
||||
vulkan_->Delete().QueueDeleteImageView(depth.texAllLayersView);
|
||||
for (int i = 0; i < 2; i++) {
|
||||
if (color.texLayerViews[i]) {
|
||||
vulkan_->Delete().QueueDeleteImageView(color.texLayerViews[i]);
|
||||
}
|
||||
if (depth.texLayerViews[i]) {
|
||||
vulkan_->Delete().QueueDeleteImageView(depth.texLayerViews[i]);
|
||||
}
|
||||
}
|
||||
|
||||
if (color.image) {
|
||||
_dbg_assert_(color.alloc);
|
||||
vulkan_->Delete().QueueDeleteImageAllocation(color.image, color.alloc);
|
||||
@@ -225,17 +248,19 @@ VKRFramebuffer::~VKRFramebuffer() {
|
||||
_dbg_assert_(depth.alloc);
|
||||
vulkan_->Delete().QueueDeleteImageAllocation(depth.image, depth.alloc);
|
||||
}
|
||||
if (depth.depthSampleView)
|
||||
vulkan_->Delete().QueueDeleteImageView(depth.depthSampleView);
|
||||
for (auto &fb : framebuf) {
|
||||
if (fb)
|
||||
if (fb) {
|
||||
vulkan_->Delete().QueueDeleteFramebuffer(fb);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void CreateImage(VulkanContext *vulkan, VkCommandBuffer cmd, VKRImage &img, int width, int height, VkFormat format, VkImageLayout initialLayout, bool color, const char *tag) {
|
||||
void CreateImage(VulkanContext *vulkan, VkCommandBuffer cmd, VKRImage &img, int width, int height, int numLayers, VkFormat format, VkImageLayout initialLayout, bool color, const char *tag) {
|
||||
// We don't support more exotic layer setups for now. Mono or stereo.
|
||||
_dbg_assert_(numLayers == 1 || numLayers == 2);
|
||||
|
||||
VkImageCreateInfo ici{ VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO };
|
||||
ici.arrayLayers = 1;
|
||||
ici.arrayLayers = numLayers;
|
||||
ici.mipLevels = 1;
|
||||
ici.extent.width = width;
|
||||
ici.extent.height = height;
|
||||
@@ -266,20 +291,37 @@ void CreateImage(VulkanContext *vulkan, VkCommandBuffer cmd, VKRImage &img, int
|
||||
ivci.components = { VK_COMPONENT_SWIZZLE_IDENTITY, VK_COMPONENT_SWIZZLE_IDENTITY, VK_COMPONENT_SWIZZLE_IDENTITY, VK_COMPONENT_SWIZZLE_IDENTITY };
|
||||
ivci.format = ici.format;
|
||||
ivci.image = img.image;
|
||||
ivci.viewType = VK_IMAGE_VIEW_TYPE_2D;
|
||||
ivci.viewType = numLayers == 1 ? VK_IMAGE_VIEW_TYPE_2D : VK_IMAGE_VIEW_TYPE_2D_ARRAY;
|
||||
ivci.subresourceRange.aspectMask = aspects;
|
||||
ivci.subresourceRange.layerCount = 1;
|
||||
ivci.subresourceRange.layerCount = numLayers;
|
||||
ivci.subresourceRange.levelCount = 1;
|
||||
res = vkCreateImageView(vulkan->GetDevice(), &ivci, nullptr, &img.imageView);
|
||||
res = vkCreateImageView(vulkan->GetDevice(), &ivci, nullptr, &img.rtView);
|
||||
vulkan->SetDebugName(img.rtView, VK_OBJECT_TYPE_IMAGE_VIEW, tag);
|
||||
|
||||
_dbg_assert_(res == VK_SUCCESS);
|
||||
|
||||
// Separate view for texture sampling that only exposes depth.
|
||||
// Separate view for texture sampling all layers together.
|
||||
if (!color) {
|
||||
ivci.subresourceRange.aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT;
|
||||
res = vkCreateImageView(vulkan->GetDevice(), &ivci, nullptr, &img.depthSampleView);
|
||||
}
|
||||
|
||||
ivci.viewType = VK_IMAGE_VIEW_TYPE_2D_ARRAY; // layered for consistency, even if single image.
|
||||
res = vkCreateImageView(vulkan->GetDevice(), &ivci, nullptr, &img.texAllLayersView);
|
||||
vulkan->SetDebugName(img.texAllLayersView, VK_OBJECT_TYPE_IMAGE_VIEW, tag);
|
||||
|
||||
// Create 2D views for both layers.
|
||||
// Useful when multipassing shaders that don't yet exist in a single-pass-stereo version.
|
||||
for (int i = 0; i < numLayers; i++) {
|
||||
ivci.viewType = VK_IMAGE_VIEW_TYPE_2D;
|
||||
ivci.subresourceRange.layerCount = 1;
|
||||
ivci.subresourceRange.baseArrayLayer = i;
|
||||
res = vkCreateImageView(vulkan->GetDevice(), &ivci, nullptr, &img.texLayerViews[i]);
|
||||
if (vulkan->DebugLayerEnabled()) {
|
||||
char temp[128];
|
||||
snprintf(temp, sizeof(temp), "%s_layer%d", tag, i);
|
||||
vulkan->SetDebugName(img.texLayerViews[i], VK_OBJECT_TYPE_IMAGE_VIEW, temp);
|
||||
}
|
||||
_dbg_assert_(res == VK_SUCCESS);
|
||||
} else {
|
||||
img.depthSampleView = VK_NULL_HANDLE;
|
||||
}
|
||||
|
||||
VkPipelineStageFlags dstStage;
|
||||
@@ -302,17 +344,22 @@ void CreateImage(VulkanContext *vulkan, VkCommandBuffer cmd, VKRImage &img, int
|
||||
return;
|
||||
}
|
||||
|
||||
TransitionImageLayout2(cmd, img.image, 0, 1, aspects,
|
||||
TransitionImageLayout2(cmd, img.image, 0, 1, numLayers, aspects,
|
||||
VK_IMAGE_LAYOUT_UNDEFINED, initialLayout,
|
||||
VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, dstStage,
|
||||
0, dstAccessMask);
|
||||
img.layout = initialLayout;
|
||||
|
||||
img.format = format;
|
||||
img.tag = tag ? tag : "N/A";
|
||||
img.numLayers = numLayers;
|
||||
}
|
||||
|
||||
VulkanRenderManager::VulkanRenderManager(VulkanContext *vulkan) : vulkan_(vulkan), queueRunner_(vulkan) {
|
||||
VulkanRenderManager::VulkanRenderManager(VulkanContext *vulkan)
|
||||
: vulkan_(vulkan), queueRunner_(vulkan),
|
||||
initTimeMs_("initTimeMs"),
|
||||
totalGPUTimeMs_("totalGPUTimeMs"),
|
||||
renderCPUTimeMs_("renderCPUTimeMs")
|
||||
{
|
||||
inflightFramesAtStart_ = vulkan_->GetInflightFrames();
|
||||
|
||||
frameDataShared_.Init(vulkan);
|
||||
@@ -564,14 +611,25 @@ void VulkanRenderManager::BeginFrame(bool enableProfiling, bool enableLogProfile
|
||||
std::stringstream str;
|
||||
|
||||
char line[256];
|
||||
snprintf(line, sizeof(line), "Total GPU time: %0.3f ms\n", ((double)((queryResults[numQueries - 1] - queryResults[0]) & timestampDiffMask) * timestampConversionFactor));
|
||||
totalGPUTimeMs_.Update(((double)((queryResults[numQueries - 1] - queryResults[0]) & timestampDiffMask) * timestampConversionFactor));
|
||||
totalGPUTimeMs_.Format(line, sizeof(line));
|
||||
str << line;
|
||||
snprintf(line, sizeof(line), "Render CPU time: %0.3f ms\n", (frameData.profile.cpuEndTime - frameData.profile.cpuStartTime) * 1000.0);
|
||||
renderCPUTimeMs_.Update((frameData.profile.cpuEndTime - frameData.profile.cpuStartTime) * 1000.0);
|
||||
renderCPUTimeMs_.Format(line, sizeof(line));
|
||||
str << line;
|
||||
for (int i = 0; i < numQueries - 1; i++) {
|
||||
uint64_t diff = (queryResults[i + 1] - queryResults[i]) & timestampDiffMask;
|
||||
double milliseconds = (double)diff * timestampConversionFactor;
|
||||
snprintf(line, sizeof(line), "%s: %0.3f ms\n", frameData.profile.timestampDescriptions[i + 1].c_str(), milliseconds);
|
||||
|
||||
// Can't use SimpleStat for these very easily since these are dynamic per frame.
|
||||
// Only the first one is static, the initCmd.
|
||||
// Could try some hashtable tracking for the rest, later.
|
||||
if (i == 0) {
|
||||
initTimeMs_.Update(milliseconds);
|
||||
initTimeMs_.Format(line, sizeof(line));
|
||||
} else {
|
||||
snprintf(line, sizeof(line), "%s: %0.3f ms\n", frameData.profile.timestampDescriptions[i + 1].c_str(), milliseconds);
|
||||
}
|
||||
str << line;
|
||||
}
|
||||
frameData.profile.profileSummary = str.str();
|
||||
@@ -586,9 +644,9 @@ void VulkanRenderManager::BeginFrame(bool enableProfiling, bool enableLogProfile
|
||||
// Must be after the fence - this performs deletes.
|
||||
VLOG("PUSH: BeginFrame %d", curFrame);
|
||||
|
||||
insideFrame_ = true;
|
||||
vulkan_->BeginFrame(enableLogProfiler ? GetInitCmd() : VK_NULL_HANDLE);
|
||||
|
||||
insideFrame_ = true;
|
||||
renderStepOffset_ = 0;
|
||||
|
||||
frameData.profile.timestampDescriptions.clear();
|
||||
@@ -600,8 +658,6 @@ void VulkanRenderManager::BeginFrame(bool enableProfiling, bool enableLogProfile
|
||||
frameData.profile.timestampDescriptions.push_back("initCmd Begin");
|
||||
frameData.profile.timestampDescriptions.push_back("initCmd");
|
||||
VkCommandBuffer initCmd = GetInitCmd();
|
||||
vkCmdResetQueryPool(initCmd, frameData.profile.queryPool, 0, MAX_TIMESTAMP_QUERIES);
|
||||
vkCmdWriteTimestamp(initCmd, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, frameData.profile.queryPool, 0);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -632,7 +688,7 @@ VKRGraphicsPipeline *VulkanRenderManager::CreateGraphicsPipeline(VKRGraphicsPipe
|
||||
VKRRenderPass *compatibleRenderPass = queueRunner_.GetRenderPass(key);
|
||||
compileMutex_.lock();
|
||||
bool needsCompile = false;
|
||||
for (int i = 0; i < RP_TYPE_COUNT; i++) {
|
||||
for (size_t i = 0; i < (size_t)RenderPassType::TYPE_COUNT; i++) {
|
||||
if (!(variantBitmask & (1 << i)))
|
||||
continue;
|
||||
RenderPassType rpType = (RenderPassType)i;
|
||||
@@ -651,7 +707,7 @@ VKRGraphicsPipeline *VulkanRenderManager::CreateGraphicsPipeline(VKRGraphicsPipe
|
||||
}
|
||||
}
|
||||
|
||||
pipeline->pipeline[rpType] = Promise<VkPipeline>::CreateEmpty();
|
||||
pipeline->pipeline[i] = Promise<VkPipeline>::CreateEmpty();
|
||||
compileQueue_.push_back(CompileQueueEntry(pipeline, compatibleRenderPass->Get(vulkan_, rpType), rpType));
|
||||
needsCompile = true;
|
||||
}
|
||||
@@ -684,13 +740,22 @@ void VulkanRenderManager::EndCurRenderStep() {
|
||||
// We'll often be able to avoid loading/saving the depth/stencil buffer.
|
||||
curRenderStep_->render.pipelineFlags = curPipelineFlags_;
|
||||
bool depthStencil = (curPipelineFlags_ & PipelineFlags::USES_DEPTH_STENCIL) != 0;
|
||||
RenderPassType rpType = depthStencil ? RP_TYPE_COLOR_DEPTH : RP_TYPE_COLOR;
|
||||
RenderPassType rpType = depthStencil ? RenderPassType::HAS_DEPTH : RenderPassType::DEFAULT;
|
||||
if (!curRenderStep_->render.framebuffer) {
|
||||
rpType = RP_TYPE_BACKBUFFER;
|
||||
} else if (curPipelineFlags_ & PipelineFlags::USES_INPUT_ATTACHMENT) {
|
||||
// Not allowed on backbuffers.
|
||||
rpType = depthStencil ? RP_TYPE_COLOR_DEPTH_INPUT : RP_TYPE_COLOR_INPUT;
|
||||
rpType = RenderPassType::BACKBUFFER;
|
||||
} else {
|
||||
if (curPipelineFlags_ & PipelineFlags::USES_INPUT_ATTACHMENT) {
|
||||
// Not allowed on backbuffers.
|
||||
rpType = depthStencil ? (RenderPassType::HAS_DEPTH | RenderPassType::COLOR_INPUT) : RenderPassType::COLOR_INPUT;
|
||||
}
|
||||
// Framebuffers can be stereo, and if so, will control the render pass type to match.
|
||||
// Pipelines can be mono and render fine to stereo etc, so not checking them here.
|
||||
// Note that we don't support rendering to just one layer of a multilayer framebuffer!
|
||||
if (curRenderStep_->render.framebuffer->numLayers > 1) {
|
||||
rpType = (RenderPassType)(rpType | RenderPassType::MULTIVIEW);
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: Also add render pass types for depth/stencil-less.
|
||||
|
||||
VKRRenderPass *renderPass = queueRunner_.GetRenderPass(key);
|
||||
@@ -699,8 +764,8 @@ void VulkanRenderManager::EndCurRenderStep() {
|
||||
compileMutex_.lock();
|
||||
bool needsCompile = false;
|
||||
for (VKRGraphicsPipeline *pipeline : pipelinesToCheck_) {
|
||||
if (!pipeline->pipeline[rpType]) {
|
||||
pipeline->pipeline[rpType] = Promise<VkPipeline>::CreateEmpty();
|
||||
if (!pipeline->pipeline[(size_t)rpType]) {
|
||||
pipeline->pipeline[(size_t)rpType] = Promise<VkPipeline>::CreateEmpty();
|
||||
compileQueue_.push_back(CompileQueueEntry(pipeline, renderPass->Get(vulkan_, rpType), rpType));
|
||||
needsCompile = true;
|
||||
}
|
||||
@@ -1152,7 +1217,7 @@ void VulkanRenderManager::BlitFramebuffer(VKRFramebuffer *src, VkRect2D srcRect,
|
||||
steps_.push_back(step);
|
||||
}
|
||||
|
||||
VkImageView VulkanRenderManager::BindFramebufferAsTexture(VKRFramebuffer *fb, int binding, VkImageAspectFlags aspectBit, int attachment) {
|
||||
VkImageView VulkanRenderManager::BindFramebufferAsTexture(VKRFramebuffer *fb, int binding, VkImageAspectFlags aspectBit, int layer) {
|
||||
_dbg_assert_(curRenderStep_ != nullptr);
|
||||
|
||||
// We don't support texturing from stencil, neither do we support texturing from depth|stencil together (nonsensical).
|
||||
@@ -1187,7 +1252,12 @@ VkImageView VulkanRenderManager::BindFramebufferAsTexture(VKRFramebuffer *fb, in
|
||||
// Add this pretransition unless we already have it.
|
||||
TransitionRequest rq{ fb, aspectBit, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL };
|
||||
curRenderStep_->preTransitions.insert(rq); // Note that insert avoids inserting duplicates.
|
||||
return aspectBit == VK_IMAGE_ASPECT_COLOR_BIT ? fb->color.imageView : fb->depth.depthSampleView;
|
||||
|
||||
if (layer == -1) {
|
||||
return aspectBit == VK_IMAGE_ASPECT_COLOR_BIT ? fb->color.texAllLayersView : fb->depth.texAllLayersView;
|
||||
} else {
|
||||
return aspectBit == VK_IMAGE_ASPECT_COLOR_BIT ? fb->color.texLayerViews[layer] : fb->depth.texLayerViews[layer];
|
||||
}
|
||||
}
|
||||
|
||||
// Called on main thread.
|
||||
@@ -1255,7 +1325,16 @@ void VulkanRenderManager::Run(VKRRenderThreadTask &task) {
|
||||
if (task.steps.empty() && !frameData.hasAcquired)
|
||||
frameData.skipSwap = true;
|
||||
//queueRunner_.LogSteps(stepsOnThread, false);
|
||||
queueRunner_.RunSteps(task.steps, frameData, frameDataShared_);
|
||||
if (IsVREnabled()) {
|
||||
int passes = GetVRPassesCount();
|
||||
for (int i = 0; i < passes; i++) {
|
||||
PreVRFrameRender(i);
|
||||
queueRunner_.RunSteps(task.steps, frameData, frameDataShared_, i < passes - 1);
|
||||
PostVRFrameRender();
|
||||
}
|
||||
} else {
|
||||
queueRunner_.RunSteps(task.steps, frameData, frameDataShared_);
|
||||
}
|
||||
|
||||
switch (task.runType) {
|
||||
case VKRRunType::PRESENT:
|
||||
@@ -1331,3 +1410,9 @@ void VulkanRenderManager::FlushSync() {
|
||||
frameData.syncDone = false;
|
||||
}
|
||||
}
|
||||
|
||||
void VulkanRenderManager::ResetStats() {
|
||||
initTimeMs_.Reset();
|
||||
totalGPUTimeMs_.Reset();
|
||||
renderCPUTimeMs_.Reset();
|
||||
}
|
||||
@@ -12,6 +12,7 @@
|
||||
#include <thread>
|
||||
#include <queue>
|
||||
|
||||
#include "Common/Math/Statistics.h"
|
||||
#include "Common/Thread/Promise.h"
|
||||
#include "Common/System/Display.h"
|
||||
#include "Common/GPU/Vulkan/VulkanContext.h"
|
||||
@@ -23,33 +24,47 @@
|
||||
// Forward declaration
|
||||
VK_DEFINE_HANDLE(VmaAllocation);
|
||||
|
||||
// Simple independent framebuffer image. Gets its own allocation, we don't have that many framebuffers so it's fine
|
||||
// to let them have individual non-pooled allocations. Until it's not fine. We'll see.
|
||||
// Simple independent framebuffer image.
|
||||
struct VKRImage {
|
||||
// These four are "immutable".
|
||||
VkImage image;
|
||||
VkImageView imageView;
|
||||
VkImageView depthSampleView;
|
||||
|
||||
VkImageView rtView; // Used for rendering to, and readbacks of stencil. 2D if single layer, 2D_ARRAY if multiple. Includes both depth and stencil if depth/stencil.
|
||||
|
||||
// This is for texturing all layers at once. If aspect is depth/stencil, does not include stencil.
|
||||
VkImageView texAllLayersView;
|
||||
|
||||
// If it's a layered image (for stereo), this is two 2D views of it, to make it compatible with shaders that don't yet support stereo.
|
||||
// If there's only one layer, layerViews[0] only is initialized.
|
||||
VkImageView texLayerViews[2]{};
|
||||
|
||||
VmaAllocation alloc;
|
||||
VkFormat format;
|
||||
|
||||
// This one is used by QueueRunner's Perform functions to keep track. CANNOT be used anywhere else due to sync issues.
|
||||
VkImageLayout layout;
|
||||
|
||||
int numLayers;
|
||||
|
||||
// For debugging.
|
||||
std::string tag;
|
||||
};
|
||||
void CreateImage(VulkanContext *vulkan, VkCommandBuffer cmd, VKRImage &img, int width, int height, VkFormat format, VkImageLayout initialLayout, bool color, const char *tag);
|
||||
|
||||
// NOTE: If numLayers > 1, it will create an array texture, rather than a normal 2D texture.
|
||||
// This requires a different sampling path!
|
||||
void CreateImage(VulkanContext *vulkan, VkCommandBuffer cmd, VKRImage &img, int width, int height, int numLayers, VkFormat format, VkImageLayout initialLayout, bool color, const char *tag);
|
||||
|
||||
class VKRFramebuffer {
|
||||
public:
|
||||
VKRFramebuffer(VulkanContext *vk, VkCommandBuffer initCmd, VKRRenderPass *compatibleRenderPass, int _width, int _height, bool createDepthStencilBuffer, const char *tag);
|
||||
VKRFramebuffer(VulkanContext *vk, VkCommandBuffer initCmd, VKRRenderPass *compatibleRenderPass, int _width, int _height, int _numLayers, bool createDepthStencilBuffer, const char *tag);
|
||||
~VKRFramebuffer();
|
||||
|
||||
VkFramebuffer Get(VKRRenderPass *compatibleRenderPass, RenderPassType rpType);
|
||||
|
||||
int width = 0;
|
||||
int height = 0;
|
||||
int numLayers = 0;
|
||||
|
||||
VKRImage color{}; // color.image is always there.
|
||||
VKRImage depth{}; // depth.image is allowed to be VK_NULL_HANDLE.
|
||||
|
||||
@@ -62,7 +77,7 @@ public:
|
||||
// TODO: Hide.
|
||||
VulkanContext *vulkan_;
|
||||
private:
|
||||
VkFramebuffer framebuf[RP_TYPE_COUNT]{};
|
||||
VkFramebuffer framebuf[(size_t)RenderPassType::TYPE_COUNT]{};
|
||||
|
||||
std::string tag_;
|
||||
};
|
||||
@@ -128,6 +143,7 @@ struct VKRGraphicsPipelineDesc {
|
||||
// Replaced the ShaderStageInfo with promises here so we can wait for compiles to finish.
|
||||
Promise<VkShaderModule> *vertexShader = nullptr;
|
||||
Promise<VkShaderModule> *fragmentShader = nullptr;
|
||||
Promise<VkShaderModule> *geometryShader = nullptr;
|
||||
|
||||
VkPipelineInputAssemblyStateCreateInfo inputAssembly{ VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO };
|
||||
VkVertexInputAttributeDescription attrs[8]{};
|
||||
@@ -151,7 +167,7 @@ struct VKRComputePipelineDesc {
|
||||
// Wrapped pipeline. Doesn't own desc.
|
||||
struct VKRGraphicsPipeline {
|
||||
~VKRGraphicsPipeline() {
|
||||
for (int i = 0; i < RP_TYPE_COUNT; i++) {
|
||||
for (size_t i = 0; i < (size_t)RenderPassType::TYPE_COUNT; i++) {
|
||||
delete pipeline[i];
|
||||
}
|
||||
}
|
||||
@@ -164,7 +180,7 @@ struct VKRGraphicsPipeline {
|
||||
u32 GetVariantsBitmask() const;
|
||||
|
||||
VKRGraphicsPipelineDesc *desc = nullptr; // not owned!
|
||||
Promise<VkPipeline> *pipeline[RP_TYPE_COUNT]{};
|
||||
Promise<VkPipeline> *pipeline[(size_t)RenderPassType::TYPE_COUNT]{};
|
||||
std::string tag;
|
||||
};
|
||||
|
||||
@@ -185,7 +201,7 @@ struct VKRComputePipeline {
|
||||
struct CompileQueueEntry {
|
||||
CompileQueueEntry(VKRGraphicsPipeline *p, VkRenderPass _compatibleRenderPass, RenderPassType _renderPassType)
|
||||
: type(Type::GRAPHICS), graphics(p), compatibleRenderPass(_compatibleRenderPass), renderPassType(_renderPassType) {}
|
||||
CompileQueueEntry(VKRComputePipeline *p) : type(Type::COMPUTE), compute(p), renderPassType(RP_TYPE_COLOR_DEPTH) {}
|
||||
CompileQueueEntry(VKRComputePipeline *p) : type(Type::COMPUTE), compute(p), renderPassType(RenderPassType::HAS_DEPTH) {} // renderpasstype here shouldn't matter
|
||||
enum class Type {
|
||||
GRAPHICS,
|
||||
COMPUTE,
|
||||
@@ -209,7 +225,7 @@ public:
|
||||
// Zaps queued up commands. Use if you know there's a risk you've queued up stuff that has already been deleted. Can happen during in-game shutdown.
|
||||
void Wipe();
|
||||
|
||||
// This starts a new step containing a render pass.
|
||||
// This starts a new step containing a render pass (unless it can be trivially merged into the previous one, which is pretty common).
|
||||
//
|
||||
// After a "CopyFramebuffer" or the other functions that start "steps", you need to call this beforce
|
||||
// making any new render state changes or draw calls.
|
||||
@@ -228,7 +244,9 @@ public:
|
||||
|
||||
// Returns an ImageView corresponding to a framebuffer. Is called BindFramebufferAsTexture to maintain a similar interface
|
||||
// as the other backends, even though there's no actual binding happening here.
|
||||
VkImageView BindFramebufferAsTexture(VKRFramebuffer *fb, int binding, VkImageAspectFlags aspectBits, int attachment);
|
||||
// For layer, we use the same convention as thin3d, where layer = -1 means all layers together. For texturing, that means that you
|
||||
// get an array texture view.
|
||||
VkImageView BindFramebufferAsTexture(VKRFramebuffer *fb, int binding, VkImageAspectFlags aspectBits, int layer);
|
||||
|
||||
void BindCurrentFramebufferAsInputAttachment0(VkImageAspectFlags aspectBits);
|
||||
|
||||
@@ -252,6 +270,16 @@ public:
|
||||
compileMutex_.unlock();
|
||||
}
|
||||
|
||||
// Mainly used to bind the frame-global desc set.
|
||||
// Can be done before binding a pipeline, so not asserting on that.
|
||||
void BindDescriptorSet(int setNumber, VkDescriptorSet set, VkPipelineLayout pipelineLayout) {
|
||||
VkRenderData data{ VKRRenderCommand::BIND_DESCRIPTOR_SET };
|
||||
data.bindDescSet.setNumber = setNumber;
|
||||
data.bindDescSet.set = set;
|
||||
data.bindDescSet.pipelineLayout = pipelineLayout;
|
||||
curRenderStep_->commands.push_back(data);
|
||||
}
|
||||
|
||||
void BindPipeline(VKRGraphicsPipeline *pipeline, PipelineFlags flags, VkPipelineLayout pipelineLayout) {
|
||||
_dbg_assert_(curRenderStep_ && curRenderStep_->stepType == VKRStepType::RENDER);
|
||||
_dbg_assert_(pipeline != nullptr);
|
||||
@@ -424,6 +452,13 @@ public:
|
||||
curRenderStep_->render.numDraws++;
|
||||
}
|
||||
|
||||
// These can be useful both when inspecting in RenderDoc, and when manually inspecting recorded commands
|
||||
// in the debugger.
|
||||
void DebugAnnotate(const char *annotation) {
|
||||
VkRenderData data{ VKRRenderCommand::DEBUG_ANNOTATION };
|
||||
data.debugAnnotation.annotation = annotation;
|
||||
}
|
||||
|
||||
VkCommandBuffer GetInitCmd();
|
||||
|
||||
// Gets a frame-unique ID of the current step being recorded. Can be used to figure out
|
||||
@@ -461,6 +496,8 @@ public:
|
||||
return outOfDateFrames_ > VulkanContext::MAX_INFLIGHT_FRAMES;
|
||||
}
|
||||
|
||||
void ResetStats();
|
||||
|
||||
private:
|
||||
void EndCurRenderStep();
|
||||
|
||||
@@ -531,4 +568,9 @@ private:
|
||||
|
||||
// pipelines to check and possibly create at the end of the current render pass.
|
||||
std::vector<VKRGraphicsPipeline *> pipelinesToCheck_;
|
||||
|
||||
// For nicer output in the little internal GPU profiler.
|
||||
SimpleStat initTimeMs_;
|
||||
SimpleStat totalGPUTimeMs_;
|
||||
SimpleStat renderCPUTimeMs_;
|
||||
};
|
||||
@@ -35,15 +35,22 @@
|
||||
|
||||
#include "Core/Config.h"
|
||||
|
||||
// We use a simple descriptor set for all rendering: 1 sampler, 1 texture, 1 UBO binding point.
|
||||
// binding 0 - uniform data
|
||||
// binding 1 - sampler
|
||||
// binding 2 - sampler
|
||||
//
|
||||
// Vertex data lives in a separate namespace (location = 0, 1, etc)
|
||||
|
||||
#include "Common/GPU/Vulkan/VulkanLoader.h"
|
||||
|
||||
// We support a frame-global descriptor set, which can be optionally used by other code,
|
||||
// but is not directly used by thin3d. It has to be defined here though, be in set 0
|
||||
// and specified in every pipeline layout, otherwise it can't sit undisturbed when other
|
||||
// descriptor sets are bound on top.
|
||||
|
||||
// For descriptor set 1, we use a simple descriptor set for all thin3d rendering: 1 UBO binding point, 3 combined texture/samples.
|
||||
//
|
||||
// binding 0 - uniform buffer
|
||||
// binding 1 - texture/sampler
|
||||
// binding 2 - texture/sampler
|
||||
// binding 3 - texture/sampler
|
||||
//
|
||||
// Vertex data lives in a separate namespace (location = 0, 1, etc).
|
||||
|
||||
using namespace PPSSPP_VK;
|
||||
|
||||
namespace Draw {
|
||||
@@ -177,9 +184,9 @@ VkShaderStageFlagBits StageToVulkan(ShaderStage stage) {
|
||||
case ShaderStage::Vertex: return VK_SHADER_STAGE_VERTEX_BIT;
|
||||
case ShaderStage::Geometry: return VK_SHADER_STAGE_GEOMETRY_BIT;
|
||||
case ShaderStage::Compute: return VK_SHADER_STAGE_COMPUTE_BIT;
|
||||
default:
|
||||
case ShaderStage::Fragment: return VK_SHADER_STAGE_FRAGMENT_BIT;
|
||||
}
|
||||
return VK_SHADER_STAGE_FRAGMENT_BIT;
|
||||
}
|
||||
|
||||
// Not registering this as a resource holder, instead the pipeline is registered. It will
|
||||
@@ -270,6 +277,7 @@ public:
|
||||
}
|
||||
|
||||
void SetDynamicUniformData(const void *data, size_t size) {
|
||||
_dbg_assert_(size <= uboSize_);
|
||||
memcpy(ubo_, data, size);
|
||||
}
|
||||
|
||||
@@ -337,10 +345,16 @@ public:
|
||||
if (vkTex_) {
|
||||
vkTex_->Touch();
|
||||
return vkTex_->GetImageView();
|
||||
} else {
|
||||
// This would be bad.
|
||||
return VK_NULL_HANDLE;
|
||||
}
|
||||
return VK_NULL_HANDLE; // This would be bad.
|
||||
}
|
||||
|
||||
VkImageView GetImageArrayView() {
|
||||
if (vkTex_) {
|
||||
vkTex_->Touch();
|
||||
return vkTex_->GetImageArrayView();
|
||||
}
|
||||
return VK_NULL_HANDLE; // This would be bad.
|
||||
}
|
||||
|
||||
private:
|
||||
@@ -367,6 +381,8 @@ public:
|
||||
VKContext(VulkanContext *vulkan);
|
||||
virtual ~VKContext();
|
||||
|
||||
void DebugAnnotate(const char *annotation) override;
|
||||
|
||||
const DeviceCaps &GetDeviceCaps() const override {
|
||||
return caps_;
|
||||
}
|
||||
@@ -403,10 +419,7 @@ public:
|
||||
|
||||
// These functions should be self explanatory.
|
||||
void BindFramebufferAsRenderTarget(Framebuffer *fbo, const RenderPassInfo &rp, const char *tag) override;
|
||||
Framebuffer *GetCurrentRenderTarget() override {
|
||||
return (Framebuffer *)curFramebuffer_.ptr;
|
||||
}
|
||||
void BindFramebufferAsTexture(Framebuffer *fbo, int binding, FBChannel channelBit, int attachment) override;
|
||||
void BindFramebufferAsTexture(Framebuffer *fbo, int binding, FBChannel channelBit, int layer) override;
|
||||
void BindCurrentFramebufferForColorInput() override;
|
||||
|
||||
void GetFramebufferDimensions(Framebuffer *fbo, int *w, int *h) override;
|
||||
@@ -417,7 +430,7 @@ public:
|
||||
void SetStencilParams(uint8_t refValue, uint8_t writeMask, uint8_t compareMask) override;
|
||||
|
||||
void BindSamplerStates(int start, int count, SamplerState **state) override;
|
||||
void BindTextures(int start, int count, Texture **textures) override;
|
||||
void BindTextures(int start, int count, Texture **textures, TextureBindFlags flags) override;
|
||||
void BindNativeTexture(int sampler, void *nativeTexture) override;
|
||||
|
||||
void BindPipeline(Pipeline *pipeline) override {
|
||||
@@ -455,6 +468,10 @@ public:
|
||||
|
||||
void FlushState() override {}
|
||||
|
||||
void ResetStats() override {
|
||||
renderManager_.ResetStats();
|
||||
}
|
||||
|
||||
std::string GetInfoString(InfoField info) const override {
|
||||
// TODO: Make these actually query the right information
|
||||
switch (info) {
|
||||
@@ -504,6 +521,7 @@ private:
|
||||
int curIBufferOffset_ = 0;
|
||||
|
||||
VkDescriptorSetLayout descriptorSetLayout_ = VK_NULL_HANDLE;
|
||||
VkDescriptorSetLayout frameDescSetLayout_ = VK_NULL_HANDLE;
|
||||
VkPipelineLayout pipelineLayout_ = VK_NULL_HANDLE;
|
||||
VkPipelineCache pipelineCache_ = VK_NULL_HANDLE;
|
||||
AutoRef<VKFramebuffer> curFramebuffer_;
|
||||
@@ -518,6 +536,7 @@ private:
|
||||
AutoRef<VKTexture> boundTextures_[MAX_BOUND_TEXTURES];
|
||||
AutoRef<VKSamplerState> boundSamplers_[MAX_BOUND_TEXTURES];
|
||||
VkImageView boundImageView_[MAX_BOUND_TEXTURES]{};
|
||||
TextureBindFlags boundTextureFlags_[MAX_BOUND_TEXTURES];
|
||||
|
||||
struct FrameData {
|
||||
FrameData() : descriptorPool("VKContext", false) {
|
||||
@@ -771,14 +790,13 @@ VKContext::VKContext(VulkanContext *vulkan)
|
||||
|
||||
VkFormat depthStencilFormat = vulkan->GetDeviceInfo().preferredDepthStencilFormat;
|
||||
|
||||
caps_.anisoSupported = vulkan->GetDeviceFeatures().enabled.samplerAnisotropy != 0;
|
||||
caps_.geometryShaderSupported = vulkan->GetDeviceFeatures().enabled.geometryShader != 0;
|
||||
caps_.tesselationShaderSupported = vulkan->GetDeviceFeatures().enabled.tessellationShader != 0;
|
||||
caps_.multiViewport = vulkan->GetDeviceFeatures().enabled.multiViewport != 0;
|
||||
caps_.dualSourceBlend = vulkan->GetDeviceFeatures().enabled.dualSrcBlend != 0;
|
||||
caps_.depthClampSupported = vulkan->GetDeviceFeatures().enabled.depthClamp != 0;
|
||||
caps_.clipDistanceSupported = vulkan->GetDeviceFeatures().enabled.shaderClipDistance != 0;
|
||||
caps_.cullDistanceSupported = vulkan->GetDeviceFeatures().enabled.shaderCullDistance != 0;
|
||||
caps_.anisoSupported = vulkan->GetDeviceFeatures().enabled.standard.samplerAnisotropy != 0;
|
||||
caps_.geometryShaderSupported = vulkan->GetDeviceFeatures().enabled.standard.geometryShader != 0;
|
||||
caps_.tesselationShaderSupported = vulkan->GetDeviceFeatures().enabled.standard.tessellationShader != 0;
|
||||
caps_.dualSourceBlend = vulkan->GetDeviceFeatures().enabled.standard.dualSrcBlend != 0;
|
||||
caps_.depthClampSupported = vulkan->GetDeviceFeatures().enabled.standard.depthClamp != 0;
|
||||
caps_.clipDistanceSupported = vulkan->GetDeviceFeatures().enabled.standard.shaderClipDistance != 0;
|
||||
caps_.cullDistanceSupported = vulkan->GetDeviceFeatures().enabled.standard.shaderCullDistance != 0;
|
||||
caps_.framebufferBlitSupported = true;
|
||||
caps_.framebufferCopySupported = true;
|
||||
caps_.framebufferDepthBlitSupported = vulkan->GetDeviceInfo().canBlitToPreferredDepthStencilFormat;
|
||||
@@ -792,7 +810,8 @@ VKContext::VKContext(VulkanContext *vulkan)
|
||||
caps_.textureNPOTFullySupported = true;
|
||||
caps_.fragmentShaderDepthWriteSupported = true;
|
||||
caps_.blendMinMaxSupported = true;
|
||||
caps_.logicOpSupported = vulkan->GetDeviceFeatures().enabled.logicOp != 0;
|
||||
caps_.logicOpSupported = vulkan->GetDeviceFeatures().enabled.standard.logicOp != 0;
|
||||
caps_.multiViewSupported = vulkan->GetDeviceFeatures().enabled.multiview.multiview != 0;
|
||||
|
||||
auto deviceProps = vulkan->GetPhysicalDeviceProperties(vulkan_->GetCurrentPhysicalDeviceIndex()).properties;
|
||||
|
||||
@@ -846,6 +865,12 @@ VKContext::VKContext(VulkanContext *vulkan)
|
||||
if (majorVersion >= 32) {
|
||||
bugs_.Infest(Bugs::MALI_CONSTANT_LOAD_BUG); // See issue #15661
|
||||
}
|
||||
|
||||
// Older ARM devices have very slow geometry shaders, not worth using. At least before 15.
|
||||
// Also seen to cause weird issues on 18, so let's lump it in.
|
||||
if (majorVersion <= 18) {
|
||||
bugs_.Infest(Bugs::GEOMETRY_SHADERS_SLOW_OR_BROKEN);
|
||||
}
|
||||
}
|
||||
|
||||
// Limited, through input attachments and self-dependencies.
|
||||
@@ -904,13 +929,25 @@ VKContext::VKContext(VulkanContext *vulkan)
|
||||
VkResult res = vkCreateDescriptorSetLayout(device_, &dsl, nullptr, &descriptorSetLayout_);
|
||||
_assert_(VK_SUCCESS == res);
|
||||
|
||||
VkDescriptorSetLayoutBinding frameBindings[1]{};
|
||||
frameBindings[0].descriptorCount = 1;
|
||||
frameBindings[0].descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
|
||||
frameBindings[0].stageFlags = VK_SHADER_STAGE_VERTEX_BIT;
|
||||
frameBindings[0].binding = 0;
|
||||
|
||||
dsl.bindingCount = ARRAY_SIZE(frameBindings);
|
||||
dsl.pBindings = frameBindings;
|
||||
res = vkCreateDescriptorSetLayout(device_, &dsl, nullptr, &frameDescSetLayout_);
|
||||
_dbg_assert_(VK_SUCCESS == res);
|
||||
|
||||
vulkan_->SetDebugName(descriptorSetLayout_, VK_OBJECT_TYPE_DESCRIPTOR_SET_LAYOUT, "thin3d_d_layout");
|
||||
|
||||
VkPipelineLayoutCreateInfo pl = { VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO };
|
||||
pl.pPushConstantRanges = nullptr;
|
||||
pl.pushConstantRangeCount = 0;
|
||||
pl.setLayoutCount = 1;
|
||||
pl.pSetLayouts = &descriptorSetLayout_;
|
||||
VkDescriptorSetLayout setLayouts[2] = { frameDescSetLayout_, descriptorSetLayout_ };
|
||||
pl.setLayoutCount = ARRAY_SIZE(setLayouts);
|
||||
pl.pSetLayouts = setLayouts;
|
||||
res = vkCreatePipelineLayout(device_, &pl, nullptr, &pipelineLayout_);
|
||||
_assert_(VK_SUCCESS == res);
|
||||
|
||||
@@ -930,6 +967,7 @@ VKContext::~VKContext() {
|
||||
delete frame_[i].pushBuffer;
|
||||
}
|
||||
vulkan_->Delete().QueueDeleteDescriptorSetLayout(descriptorSetLayout_);
|
||||
vulkan_->Delete().QueueDeleteDescriptorSetLayout(frameDescSetLayout_);
|
||||
vulkan_->Delete().QueueDeletePipelineLayout(pipelineLayout_);
|
||||
vulkan_->Delete().QueueDeletePipelineCache(pipelineCache_);
|
||||
}
|
||||
@@ -984,7 +1022,11 @@ VkDescriptorSet VKContext::GetOrCreateDescriptorSet(VkBuffer buf) {
|
||||
FrameData *frame = &frame_[vulkan_->GetCurFrame()];
|
||||
|
||||
for (int i = 0; i < MAX_BOUND_TEXTURES; ++i) {
|
||||
key.imageViews_[i] = boundTextures_[i] ? boundTextures_[i]->GetImageView() : boundImageView_[i];
|
||||
if (boundTextures_[i]) {
|
||||
key.imageViews_[i] = (boundTextureFlags_[i] & TextureBindFlags::VULKAN_BIND_ARRAY) ? boundTextures_[i]->GetImageArrayView() : boundTextures_[i]->GetImageView();
|
||||
} else {
|
||||
key.imageViews_[i] = boundImageView_[i];
|
||||
}
|
||||
key.samplers_[i] = boundSamplers_[i];
|
||||
}
|
||||
key.buffer_ = buf;
|
||||
@@ -994,12 +1036,14 @@ VkDescriptorSet VKContext::GetOrCreateDescriptorSet(VkBuffer buf) {
|
||||
return iter->second;
|
||||
}
|
||||
|
||||
VkDescriptorSet descSet = frame->descriptorPool.Allocate(1, &descriptorSetLayout_);
|
||||
VkDescriptorSet descSet = frame->descriptorPool.Allocate(1, &descriptorSetLayout_, "thin3d_descset");
|
||||
if (descSet == VK_NULL_HANDLE) {
|
||||
ERROR_LOG(G3D, "GetOrCreateDescriptorSet failed");
|
||||
return VK_NULL_HANDLE;
|
||||
}
|
||||
|
||||
vulkan_->SetDebugName(descSet, VK_OBJECT_TYPE_DESCRIPTOR_SET, "(thin3d desc set)");
|
||||
|
||||
VkDescriptorBufferInfo bufferDesc;
|
||||
bufferDesc.buffer = buf;
|
||||
bufferDesc.offset = 0;
|
||||
@@ -1078,6 +1122,7 @@ Pipeline *VKContext::CreateGraphicsPipeline(const PipelineDesc &desc, const char
|
||||
gDesc.fragmentShader = vkshader->Get();
|
||||
} else {
|
||||
ERROR_LOG(G3D, "Bad stage");
|
||||
delete pipeline;
|
||||
return nullptr;
|
||||
}
|
||||
}
|
||||
@@ -1133,7 +1178,7 @@ Pipeline *VKContext::CreateGraphicsPipeline(const PipelineDesc &desc, const char
|
||||
VkPipelineRasterizationStateCreateInfo rs{ VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO };
|
||||
raster->ToVulkan(&gDesc.rs);
|
||||
|
||||
pipeline->pipeline = renderManager_.CreateGraphicsPipeline(&gDesc, pipelineFlags, 1 << RP_TYPE_BACKBUFFER, tag ? tag : "thin3d");
|
||||
pipeline->pipeline = renderManager_.CreateGraphicsPipeline(&gDesc, pipelineFlags, 1 << (size_t)RenderPassType::BACKBUFFER, tag ? tag : "thin3d");
|
||||
|
||||
if (desc.uniformDesc) {
|
||||
pipeline->dynamicUniformSize = (int)desc.uniformDesc->uniformBufferSize;
|
||||
@@ -1283,15 +1328,32 @@ void VKContext::UpdateBuffer(Buffer *buffer, const uint8_t *data, size_t offset,
|
||||
memcpy(buf->data_ + offset, data, size);
|
||||
}
|
||||
|
||||
void VKContext::BindTextures(int start, int count, Texture **textures) {
|
||||
void VKContext::BindTextures(int start, int count, Texture **textures, TextureBindFlags flags) {
|
||||
_assert_(start + count <= MAX_BOUND_TEXTURES);
|
||||
for (int i = start; i < start + count; i++) {
|
||||
_dbg_assert_(i >= 0 && i < MAX_BOUND_TEXTURES);
|
||||
boundTextures_[i] = static_cast<VKTexture *>(textures[i - start]);
|
||||
boundImageView_[i] = boundTextures_[i] ? boundTextures_[i]->GetImageView() : GetNullTexture()->GetImageView();
|
||||
boundTextureFlags_[i] = flags;
|
||||
if (boundTextures_[i]) {
|
||||
// If a texture is bound, we set these up in GetOrCreateDescriptorSet too.
|
||||
// But we might need to set the view here anyway so it can be queried using GetNativeObject.
|
||||
if (flags & TextureBindFlags::VULKAN_BIND_ARRAY) {
|
||||
boundImageView_[i] = boundTextures_[i]->GetImageArrayView();
|
||||
} else {
|
||||
boundImageView_[i] = boundTextures_[i]->GetImageView();
|
||||
}
|
||||
} else {
|
||||
if (flags & TextureBindFlags::VULKAN_BIND_ARRAY) {
|
||||
boundImageView_[i] = GetNullTexture()->GetImageArrayView();
|
||||
} else {
|
||||
boundImageView_[i] = GetNullTexture()->GetImageView();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void VKContext::BindNativeTexture(int sampler, void *nativeTexture) {
|
||||
_dbg_assert_(sampler >= 0 && sampler < MAX_BOUND_TEXTURES);
|
||||
boundTextures_[sampler] = nullptr;
|
||||
boundImageView_[sampler] = (VkImageView)nativeTexture;
|
||||
}
|
||||
@@ -1399,8 +1461,8 @@ void AddFeature(std::vector<std::string> &features, const char *name, VkBool32 a
|
||||
}
|
||||
|
||||
std::vector<std::string> VKContext::GetFeatureList() const {
|
||||
const VkPhysicalDeviceFeatures &available = vulkan_->GetDeviceFeatures().available;
|
||||
const VkPhysicalDeviceFeatures &enabled = vulkan_->GetDeviceFeatures().enabled;
|
||||
const VkPhysicalDeviceFeatures &available = vulkan_->GetDeviceFeatures().available.standard;
|
||||
const VkPhysicalDeviceFeatures &enabled = vulkan_->GetDeviceFeatures().enabled.standard;
|
||||
|
||||
std::vector<std::string> features;
|
||||
AddFeature(features, "dualSrcBlend", available.dualSrcBlend, enabled.dualSrcBlend);
|
||||
@@ -1419,7 +1481,10 @@ std::vector<std::string> VKContext::GetFeatureList() const {
|
||||
AddFeature(features, "occlusionQueryPrecise", available.occlusionQueryPrecise, enabled.occlusionQueryPrecise);
|
||||
AddFeature(features, "multiDrawIndirect", available.multiDrawIndirect, enabled.multiDrawIndirect);
|
||||
|
||||
features.push_back(std::string("Preferred depth buffer format: ") + VulkanFormatToString(vulkan_->GetDeviceInfo().preferredDepthStencilFormat));
|
||||
AddFeature(features, "multiview", vulkan_->GetDeviceFeatures().available.multiview.multiview, vulkan_->GetDeviceFeatures().enabled.multiview.multiview);
|
||||
AddFeature(features, "multiviewGeometryShader", vulkan_->GetDeviceFeatures().available.multiview.multiviewGeometryShader, vulkan_->GetDeviceFeatures().enabled.multiview.multiviewGeometryShader);
|
||||
|
||||
features.emplace_back(std::string("Preferred depth buffer format: ") + VulkanFormatToString(vulkan_->GetDeviceInfo().preferredDepthStencilFormat));
|
||||
|
||||
return features;
|
||||
}
|
||||
@@ -1468,6 +1533,7 @@ public:
|
||||
_assert_msg_(fb, "Null fb in VKFramebuffer constructor");
|
||||
width_ = fb->width;
|
||||
height_ = fb->height;
|
||||
layers_ = fb->numLayers;
|
||||
}
|
||||
~VKFramebuffer() {
|
||||
_assert_msg_(buf_, "Null buf_ in VKFramebuffer - double delete?");
|
||||
@@ -1487,7 +1553,7 @@ private:
|
||||
|
||||
Framebuffer *VKContext::CreateFramebuffer(const FramebufferDesc &desc) {
|
||||
VkCommandBuffer cmd = renderManager_.GetInitCmd();
|
||||
VKRFramebuffer *vkrfb = new VKRFramebuffer(vulkan_, cmd, renderManager_.GetQueueRunner()->GetCompatibleRenderPass(), desc.width, desc.height, desc.z_stencil, desc.tag);
|
||||
VKRFramebuffer *vkrfb = new VKRFramebuffer(vulkan_, cmd, renderManager_.GetQueueRunner()->GetCompatibleRenderPass(), desc.width, desc.height, desc.numLayers, desc.z_stencil, desc.tag);
|
||||
return new VKFramebuffer(vkrfb);
|
||||
}
|
||||
|
||||
@@ -1548,9 +1614,9 @@ void VKContext::BindFramebufferAsRenderTarget(Framebuffer *fbo, const RenderPass
|
||||
curFramebuffer_ = fb;
|
||||
}
|
||||
|
||||
void VKContext::BindFramebufferAsTexture(Framebuffer *fbo, int binding, FBChannel channelBit, int attachment) {
|
||||
void VKContext::BindFramebufferAsTexture(Framebuffer *fbo, int binding, FBChannel channelBit, int layer) {
|
||||
VKFramebuffer *fb = (VKFramebuffer *)fbo;
|
||||
_assert_(binding < MAX_BOUND_TEXTURES);
|
||||
_assert_(binding >= 0 && binding < MAX_BOUND_TEXTURES);
|
||||
|
||||
// TODO: There are cases where this is okay, actually. But requires layout transitions and stuff -
|
||||
// we're not ready for this.
|
||||
@@ -1568,8 +1634,9 @@ void VKContext::BindFramebufferAsTexture(Framebuffer *fbo, int binding, FBChanne
|
||||
_assert_(false);
|
||||
break;
|
||||
}
|
||||
boundTextures_[binding] = nullptr;
|
||||
boundImageView_[binding] = renderManager_.BindFramebufferAsTexture(fb->GetFB(), binding, aspect, attachment);
|
||||
|
||||
boundTextures_[binding].clear();
|
||||
boundImageView_[binding] = renderManager_.BindFramebufferAsTexture(fb->GetFB(), binding, aspect, layer);
|
||||
}
|
||||
|
||||
void VKContext::BindCurrentFramebufferForColorInput() {
|
||||
@@ -1630,14 +1697,30 @@ uint64_t VKContext::GetNativeObject(NativeObject obj, void *srcObject) {
|
||||
return (uint64_t)(uintptr_t)&renderManager_;
|
||||
case NativeObject::NULL_IMAGEVIEW:
|
||||
return (uint64_t)GetNullTexture()->GetImageView();
|
||||
case NativeObject::NULL_IMAGEVIEW_ARRAY:
|
||||
return (uint64_t)GetNullTexture()->GetImageArrayView();
|
||||
case NativeObject::TEXTURE_VIEW:
|
||||
return (uint64_t)(((VKTexture *)srcObject)->GetImageView());
|
||||
case NativeObject::BOUND_FRAMEBUFFER_COLOR_IMAGEVIEW:
|
||||
return (uint64_t)curFramebuffer_->GetFB()->color.imageView;
|
||||
case NativeObject::BOUND_FRAMEBUFFER_COLOR_IMAGEVIEW_ALL_LAYERS:
|
||||
return (uint64_t)curFramebuffer_->GetFB()->color.texAllLayersView;
|
||||
case NativeObject::BOUND_FRAMEBUFFER_COLOR_IMAGEVIEW_LAYER: {
|
||||
size_t layer = (size_t)srcObject;
|
||||
_dbg_assert_(layer < curFramebuffer_->Layers());
|
||||
return (uint64_t)curFramebuffer_->GetFB()->color.texLayerViews[layer];
|
||||
}
|
||||
case NativeObject::FRAME_DATA_DESC_SET_LAYOUT:
|
||||
return (uint64_t)frameDescSetLayout_;
|
||||
case NativeObject::THIN3D_PIPELINE_LAYOUT:
|
||||
return (uint64_t)pipelineLayout_;
|
||||
|
||||
default:
|
||||
Crash();
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
void VKContext::DebugAnnotate(const char *annotation) {
|
||||
renderManager_.DebugAnnotate(annotation);
|
||||
}
|
||||
|
||||
} // namespace Draw
|
||||
+34
-5
@@ -137,7 +137,7 @@ static const std::vector<ShaderSource> fsTexCol = {
|
||||
"layout(location = 0) in vec4 oColor0;\n"
|
||||
"layout(location = 1) in vec2 oTexCoord0;\n"
|
||||
"layout(location = 0) out vec4 fragColor0;\n"
|
||||
"layout(set = 0, binding = 1) uniform sampler2D Sampler0;\n"
|
||||
"layout(set = 1, binding = 1) uniform sampler2D Sampler0;\n"
|
||||
"void main() { fragColor0 = texture(Sampler0, oTexCoord0) * oColor0; }\n"
|
||||
}
|
||||
};
|
||||
@@ -181,7 +181,7 @@ static const std::vector<ShaderSource> fsTexColRBSwizzle = {
|
||||
"layout(location = 0) in vec4 oColor0;\n"
|
||||
"layout(location = 1) in vec2 oTexCoord0;\n"
|
||||
"layout(location = 0) out vec4 fragColor0\n;"
|
||||
"layout(set = 0, binding = 1) uniform sampler2D Sampler0;\n"
|
||||
"layout(set = 1, binding = 1) uniform sampler2D Sampler0;\n"
|
||||
"void main() { fragColor0 = texture(Sampler0, oTexCoord0).bgra * oColor0; }\n"
|
||||
}
|
||||
};
|
||||
@@ -270,7 +270,7 @@ static const std::vector<ShaderSource> vsCol = {
|
||||
R"(#version 450
|
||||
#extension GL_ARB_separate_shader_objects : enable
|
||||
#extension GL_ARB_shading_language_420pack : enable
|
||||
layout (std140, set = 0, binding = 0) uniform bufferVals {
|
||||
layout (std140, set = 1, binding = 0) uniform bufferVals {
|
||||
mat4 WorldViewProj;
|
||||
vec2 TintSaturation;
|
||||
} myBufferVals;
|
||||
@@ -416,7 +416,7 @@ VS_OUTPUT main(VS_INPUT input) {
|
||||
R"(#version 450
|
||||
#extension GL_ARB_separate_shader_objects : enable
|
||||
#extension GL_ARB_shading_language_420pack : enable
|
||||
layout (std140, set = 0, binding = 0) uniform bufferVals {
|
||||
layout (std140, set = 1, binding = 0) uniform bufferVals {
|
||||
mat4 WorldViewProj;
|
||||
vec2 TintSaturation;
|
||||
} myBufferVals;
|
||||
@@ -586,7 +586,36 @@ void ConvertFromBGRA8888(uint8_t *dst, const uint8_t *src, uint32_t dstStride, u
|
||||
dst += dstStride * 3;
|
||||
}
|
||||
} else {
|
||||
WARN_LOG(G3D, "Unable to convert from format to BGRA: %d", (int)format);
|
||||
// But here it shouldn't matter if they do intersect
|
||||
uint16_t *dst16 = (uint16_t *)dst;
|
||||
switch (format) {
|
||||
case Draw::DataFormat::R5G6B5_UNORM_PACK16: // BGR 565
|
||||
for (uint32_t y = 0; y < height; ++y) {
|
||||
ConvertBGRA8888ToRGB565(dst16, src32, width);
|
||||
src32 += srcStride;
|
||||
dst16 += dstStride;
|
||||
}
|
||||
break;
|
||||
case Draw::DataFormat::A1R5G5B5_UNORM_PACK16: // ABGR 1555
|
||||
for (uint32_t y = 0; y < height; ++y) {
|
||||
ConvertBGRA8888ToRGBA5551(dst16, src32, width);
|
||||
src32 += srcStride;
|
||||
dst16 += dstStride;
|
||||
}
|
||||
break;
|
||||
case Draw::DataFormat::A4R4G4B4_UNORM_PACK16: // ABGR 4444
|
||||
for (uint32_t y = 0; y < height; ++y) {
|
||||
ConvertBGRA8888ToRGBA4444(dst16, src32, width);
|
||||
src32 += srcStride;
|
||||
dst16 += dstStride;
|
||||
}
|
||||
break;
|
||||
case Draw::DataFormat::R8G8B8A8_UNORM:
|
||||
case Draw::DataFormat::UNDEFINED:
|
||||
default:
|
||||
WARN_LOG(G3D, "Unable to convert from format to BGRA: %d", (int)format);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+45
-9
@@ -13,6 +13,7 @@
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "Common/Common.h"
|
||||
#include "Common/GPU/DataFormat.h"
|
||||
#include "Common/GPU/Shader.h"
|
||||
#include "Common/Data/Collections/Slice.h"
|
||||
@@ -241,12 +242,16 @@ enum class NativeObject {
|
||||
BACKBUFFER_DEPTH_TEX,
|
||||
FEATURE_LEVEL,
|
||||
INIT_COMMANDBUFFER,
|
||||
BOUND_TEXTURE0_IMAGEVIEW,
|
||||
BOUND_TEXTURE1_IMAGEVIEW,
|
||||
BOUND_FRAMEBUFFER_COLOR_IMAGEVIEW,
|
||||
BOUND_TEXTURE0_IMAGEVIEW, // Layer etc depends on how you bound it...
|
||||
BOUND_TEXTURE1_IMAGEVIEW, // Layer etc depends on how you bound it...
|
||||
BOUND_FRAMEBUFFER_COLOR_IMAGEVIEW_ALL_LAYERS,
|
||||
BOUND_FRAMEBUFFER_COLOR_IMAGEVIEW_LAYER, // use an int cast to void *srcObject to specify layer.
|
||||
RENDER_MANAGER,
|
||||
TEXTURE_VIEW,
|
||||
NULL_IMAGEVIEW,
|
||||
NULL_IMAGEVIEW_ARRAY,
|
||||
FRAME_DATA_DESC_SET_LAYOUT,
|
||||
THIN3D_PIPELINE_LAYOUT,
|
||||
};
|
||||
|
||||
enum FBChannel {
|
||||
@@ -293,7 +298,7 @@ struct FramebufferDesc {
|
||||
int width;
|
||||
int height;
|
||||
int depth;
|
||||
int numColorAttachments;
|
||||
int numLayers;
|
||||
bool z_stencil;
|
||||
const char *tag; // For graphics debuggers
|
||||
};
|
||||
@@ -333,11 +338,14 @@ public:
|
||||
RASPBERRY_SHADER_COMP_HANG = 8,
|
||||
MALI_CONSTANT_LOAD_BUG = 9,
|
||||
SUBPASS_FEEDBACK_BROKEN = 10,
|
||||
GEOMETRY_SHADERS_SLOW_OR_BROKEN = 11,
|
||||
MAX_BUG,
|
||||
};
|
||||
|
||||
protected:
|
||||
uint32_t flags_ = 0;
|
||||
|
||||
static_assert(sizeof(flags_) * 8 > MAX_BUG, "Ran out of space for bugs.");
|
||||
};
|
||||
|
||||
class RefCountedObject {
|
||||
@@ -385,6 +393,9 @@ struct AutoRef {
|
||||
*this = p.ptr;
|
||||
return *this;
|
||||
}
|
||||
bool operator !=(const AutoRef<T> &p) const {
|
||||
return ptr != p.ptr;
|
||||
}
|
||||
|
||||
T *operator->() const {
|
||||
return ptr;
|
||||
@@ -392,6 +403,16 @@ struct AutoRef {
|
||||
operator T *() {
|
||||
return ptr;
|
||||
}
|
||||
operator bool() const {
|
||||
return ptr != nullptr;
|
||||
}
|
||||
|
||||
void clear() {
|
||||
if (ptr) {
|
||||
ptr->Release();
|
||||
ptr = nullptr;
|
||||
}
|
||||
}
|
||||
|
||||
T *ptr = nullptr;
|
||||
};
|
||||
@@ -412,9 +433,11 @@ class Framebuffer : public RefCountedObject {
|
||||
public:
|
||||
int Width() { return width_; }
|
||||
int Height() { return height_; }
|
||||
int Layers() { return layers_; }
|
||||
|
||||
virtual void UpdateTag(const char *tag) {}
|
||||
protected:
|
||||
int width_ = -1, height_ = -1;
|
||||
int width_ = -1, height_ = -1, layers_ = 1;
|
||||
};
|
||||
|
||||
class Buffer : public RefCountedObject {
|
||||
@@ -531,7 +554,6 @@ struct DeviceCaps {
|
||||
bool depthRangeMinusOneToOne; // OpenGL style depth
|
||||
bool geometryShaderSupported;
|
||||
bool tesselationShaderSupported;
|
||||
bool multiViewport;
|
||||
bool dualSourceBlend;
|
||||
bool logicOpSupported;
|
||||
bool depthClampSupported;
|
||||
@@ -550,6 +572,7 @@ struct DeviceCaps {
|
||||
bool fragmentShaderDepthWriteSupported;
|
||||
bool textureDepthSupported;
|
||||
bool blendMinMaxSupported;
|
||||
bool multiViewSupported;
|
||||
|
||||
std::string deviceName; // The device name to use when creating the thin3d context, to get the same one.
|
||||
};
|
||||
@@ -590,6 +613,14 @@ struct RenderPassInfo {
|
||||
const char *tag;
|
||||
};
|
||||
|
||||
const int ALL_LAYERS = -1;
|
||||
|
||||
enum class TextureBindFlags {
|
||||
NONE = 0,
|
||||
VULKAN_BIND_ARRAY = 1,
|
||||
};
|
||||
ENUM_CLASS_BITOPS(TextureBindFlags);
|
||||
|
||||
class DrawContext {
|
||||
public:
|
||||
virtual ~DrawContext();
|
||||
@@ -613,6 +644,8 @@ public:
|
||||
|
||||
virtual void SetErrorCallback(ErrorCallbackFn callback, void *userdata) {}
|
||||
|
||||
virtual void DebugAnnotate(const char *annotation) {}
|
||||
|
||||
// Partial pipeline state, used to create pipelines. (in practice, in d3d11 they'll use the native state objects directly).
|
||||
// TODO: Possibly ditch these and just put the descs directly in PipelineDesc since only D3D11 benefits.
|
||||
virtual DepthStencilState *CreateDepthStencilState(const DepthStencilStateDesc &desc) = 0;
|
||||
@@ -649,11 +682,11 @@ public:
|
||||
|
||||
// These functions should be self explanatory.
|
||||
// Binding a zero render target means binding the backbuffer.
|
||||
// If an fbo has two layers, we bind for stereo rendering ALWAYS. There's no rendering to one layer anymore.
|
||||
virtual void BindFramebufferAsRenderTarget(Framebuffer *fbo, const RenderPassInfo &rp, const char *tag) = 0;
|
||||
virtual Framebuffer *GetCurrentRenderTarget() = 0;
|
||||
|
||||
// binding must be < MAX_TEXTURE_SLOTS (0, 1 are okay if it's 2).
|
||||
virtual void BindFramebufferAsTexture(Framebuffer *fbo, int binding, FBChannel channelBit, int attachment) = 0;
|
||||
virtual void BindFramebufferAsTexture(Framebuffer *fbo, int binding, FBChannel channelBit, int layer) = 0;
|
||||
|
||||
// Framebuffer fetch / input attachment support, needs to be explicit in Vulkan.
|
||||
virtual void BindCurrentFramebufferForColorInput() {}
|
||||
@@ -678,7 +711,7 @@ public:
|
||||
virtual void SetStencilParams(uint8_t refValue, uint8_t writeMask, uint8_t compareMask) = 0;
|
||||
|
||||
virtual void BindSamplerStates(int start, int count, SamplerState **state) = 0;
|
||||
virtual void BindTextures(int start, int count, Texture **textures) = 0;
|
||||
virtual void BindTextures(int start, int count, Texture **textures, TextureBindFlags flags = TextureBindFlags::NONE) = 0;
|
||||
virtual void BindVertexBuffers(int start, int count, Buffer **buffers, const int *offsets) = 0;
|
||||
virtual void BindIndexBuffer(Buffer *indexBuffer, int offset) = 0;
|
||||
|
||||
@@ -732,6 +765,9 @@ public:
|
||||
// Flush state like scissors etc so the caller can do its own custom drawing.
|
||||
virtual void FlushState() {}
|
||||
|
||||
// This is called when we launch a new game, so any collected internal stats in the backends don't carry over.
|
||||
virtual void ResetStats() {}
|
||||
|
||||
virtual int GetCurrentStepId() const = 0;
|
||||
|
||||
protected:
|
||||
|
||||
@@ -261,7 +261,14 @@ typedef enum _keycode_t {
|
||||
NKCODE_EXT_MOUSEBUTTON_4 = 1006,
|
||||
NKCODE_EXT_MOUSEBUTTON_5 = 1007,
|
||||
NKCODE_EXT_MOUSEWHEEL_UP = 1008,
|
||||
NKCODE_EXT_MOUSEWHEEL_DOWN = 1009
|
||||
NKCODE_EXT_MOUSEWHEEL_DOWN = 1009,
|
||||
|
||||
// Virtual reality controller motion
|
||||
NKCODE_EXT_MOTION_UP = 1101,
|
||||
NKCODE_EXT_MOTION_DOWN = 1102,
|
||||
NKCODE_EXT_MOTION_LEFT = 1103,
|
||||
NKCODE_EXT_MOTION_RIGHT = 1104,
|
||||
NKCODE_EXT_MOTION_FORWARD = 1105,
|
||||
} keycode_t;
|
||||
|
||||
enum AndroidJoystickAxis {
|
||||
|
||||
@@ -35,7 +35,7 @@ bool ShouldLogNTimes(const char *identifier, int count) {
|
||||
std::lock_guard<std::mutex> lock(logNTimesLock);
|
||||
auto iter = logNTimes.find(identifier);
|
||||
if (iter == logNTimes.end()) {
|
||||
logNTimes.insert(std::pair<const char*, int>(identifier, 1));
|
||||
logNTimes.emplace(identifier, 1);
|
||||
return true;
|
||||
} else {
|
||||
if (iter->second >= count) {
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
#include <cstdio>
|
||||
|
||||
#include "Common/Math/Statistics.h"
|
||||
|
||||
void SimpleStat::Format(char *buffer, size_t sz) {
|
||||
if (min_ == INFINITY) {
|
||||
snprintf(buffer, sz, "%s: N/A\n", name_);
|
||||
} else {
|
||||
snprintf(buffer, sz, "%s: %0.2f (%0.2f..%0.2f, avg %0.2f)\n", name_, value_, min_, max_, smoothed_);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
#pragma once
|
||||
|
||||
#include <cmath>
|
||||
|
||||
// Very simple stat for convenience. Keeps track of min, max, smoothed.
|
||||
struct SimpleStat {
|
||||
SimpleStat(const char *name) : name_(name) { Reset(); }
|
||||
|
||||
void Update(double value) {
|
||||
value_ = value;
|
||||
if (min_ == INFINITY) {
|
||||
smoothed_ = value;
|
||||
} else {
|
||||
// TODO: Make factor adjustable?
|
||||
smoothed_ = 0.99 * smoothed_ + 0.01 * value;
|
||||
}
|
||||
if (value < min_) {
|
||||
min_ = value;
|
||||
}
|
||||
if (value > max_) {
|
||||
max_ = value;
|
||||
}
|
||||
}
|
||||
|
||||
void Reset() {
|
||||
value_ = 0.0;
|
||||
smoothed_ = 0.0; // doens't really need init
|
||||
min_ = INFINITY;
|
||||
max_ = -INFINITY;
|
||||
}
|
||||
|
||||
void Format(char *buffer, size_t sz);
|
||||
|
||||
private:
|
||||
const char *name_;
|
||||
|
||||
// These are initialized in Reset().
|
||||
double value_;
|
||||
double min_;
|
||||
double max_;
|
||||
double smoothed_;
|
||||
};
|
||||
+22
-3
@@ -273,7 +273,7 @@ void SplitString(const std::string& str, const char delim, std::vector<std::stri
|
||||
size_t next = 0;
|
||||
for (size_t pos = 0, len = str.length(); pos < len; ++pos) {
|
||||
if (str[pos] == delim) {
|
||||
output.push_back(str.substr(next, pos - next));
|
||||
output.emplace_back(str.substr(next, pos - next));
|
||||
// Skip the delimiter itself.
|
||||
next = pos + 1;
|
||||
}
|
||||
@@ -282,10 +282,29 @@ void SplitString(const std::string& str, const char delim, std::vector<std::stri
|
||||
if (next == 0) {
|
||||
output.push_back(str);
|
||||
} else if (next < str.length()) {
|
||||
output.push_back(str.substr(next));
|
||||
output.emplace_back(str.substr(next));
|
||||
}
|
||||
}
|
||||
|
||||
static std::string ApplyHtmlEscapes(std::string str) {
|
||||
struct Repl {
|
||||
const char *a;
|
||||
const char *b;
|
||||
};
|
||||
|
||||
static const Repl replacements[] = {
|
||||
{ "&", "&" },
|
||||
// Easy to add more cases.
|
||||
};
|
||||
|
||||
for (const Repl &r : replacements) {
|
||||
str = ReplaceAll(str, r.a, r.b);
|
||||
}
|
||||
|
||||
return str;
|
||||
}
|
||||
|
||||
// Meant for HTML listings and similar, so supports some HTML escapes.
|
||||
void GetQuotedStrings(const std::string& str, std::vector<std::string>& output)
|
||||
{
|
||||
size_t next = 0;
|
||||
@@ -294,7 +313,7 @@ void GetQuotedStrings(const std::string& str, std::vector<std::string>& output)
|
||||
if (str[pos] == '\"' || str[pos] == '\'') {
|
||||
if (even) {
|
||||
//quoted text
|
||||
output.push_back(str.substr(next, pos - next));
|
||||
output.emplace_back(ApplyHtmlEscapes(str.substr(next, pos - next)));
|
||||
even = 0;
|
||||
} else {
|
||||
//non quoted text
|
||||
|
||||
@@ -21,8 +21,6 @@
|
||||
|
||||
// TODO: https://github.com/floooh/sokol/blob/9a6237fcdf213e6da48e4f9201f144bcb2dcb46f/sokol_time.h#L229-L248
|
||||
|
||||
static double curtime = 0;
|
||||
|
||||
#ifdef _WIN32
|
||||
|
||||
static LARGE_INTEGER frequency;
|
||||
@@ -33,7 +31,6 @@ double time_now_d() {
|
||||
if (frequency.QuadPart == 0) {
|
||||
QueryPerformanceFrequency(&frequency);
|
||||
QueryPerformanceCounter(&startTime);
|
||||
curtime = 0.0;
|
||||
frequencyMult = 1.0 / static_cast<double>(frequency.QuadPart);
|
||||
}
|
||||
LARGE_INTEGER time;
|
||||
|
||||
@@ -12,7 +12,6 @@
|
||||
#include "Common/UI/Root.h"
|
||||
#include "Common/Data/Text/I18n.h"
|
||||
#include "Common/Render/DrawBuffer.h"
|
||||
#include "Common/VR/PPSSPPVR.h"
|
||||
|
||||
#include "Common/Log.h"
|
||||
#include "Common/StringUtils.h"
|
||||
@@ -89,10 +88,6 @@ void UIScreen::preRender() {
|
||||
draw->BindFramebufferAsRenderTarget(nullptr, { RPAction::CLEAR, RPAction::CLEAR, RPAction::CLEAR, 0xFF000000 }, "UI");
|
||||
screenManager()->getUIContext()->BeginFrame();
|
||||
|
||||
if (IsVRBuild()) {
|
||||
BindVRFramebuffer();
|
||||
}
|
||||
|
||||
Draw::Viewport viewport;
|
||||
viewport.TopLeftX = 0;
|
||||
viewport.TopLeftY = 0;
|
||||
|
||||
@@ -0,0 +1,160 @@
|
||||
#include "Common/VR/OpenXRLoader.h"
|
||||
#ifdef _WIN32
|
||||
#include "Common/CommonWindows.h"
|
||||
#endif
|
||||
|
||||
#ifdef XR_NO_PROTOTYPES
|
||||
|
||||
PFN_xrGetInstanceProcAddr xrGetInstanceProcAddr;
|
||||
PFN_xrEnumerateApiLayerProperties xrEnumerateApiLayerProperties;
|
||||
PFN_xrEnumerateInstanceExtensionProperties xrEnumerateInstanceExtensionProperties;
|
||||
PFN_xrCreateInstance xrCreateInstance;
|
||||
PFN_xrDestroyInstance xrDestroyInstance;
|
||||
PFN_xrGetInstanceProperties xrGetInstanceProperties;
|
||||
PFN_xrPollEvent xrPollEvent;
|
||||
PFN_xrResultToString xrResultToString;
|
||||
PFN_xrStructureTypeToString xrStructureTypeToString;
|
||||
PFN_xrGetSystem xrGetSystem;
|
||||
PFN_xrGetSystemProperties xrGetSystemProperties;
|
||||
PFN_xrEnumerateEnvironmentBlendModes xrEnumerateEnvironmentBlendModes;
|
||||
PFN_xrCreateSession xrCreateSession;
|
||||
PFN_xrDestroySession xrDestroySession;
|
||||
PFN_xrEnumerateReferenceSpaces xrEnumerateReferenceSpaces;
|
||||
PFN_xrCreateReferenceSpace xrCreateReferenceSpace;
|
||||
PFN_xrGetReferenceSpaceBoundsRect xrGetReferenceSpaceBoundsRect;
|
||||
PFN_xrCreateActionSpace xrCreateActionSpace;
|
||||
PFN_xrLocateSpace xrLocateSpace;
|
||||
PFN_xrDestroySpace xrDestroySpace;
|
||||
PFN_xrEnumerateViewConfigurations xrEnumerateViewConfigurations;
|
||||
PFN_xrGetViewConfigurationProperties xrGetViewConfigurationProperties;
|
||||
PFN_xrEnumerateViewConfigurationViews xrEnumerateViewConfigurationViews;
|
||||
PFN_xrEnumerateSwapchainFormats xrEnumerateSwapchainFormats;
|
||||
PFN_xrCreateSwapchain xrCreateSwapchain;
|
||||
PFN_xrDestroySwapchain xrDestroySwapchain;
|
||||
PFN_xrEnumerateSwapchainImages xrEnumerateSwapchainImages;
|
||||
PFN_xrAcquireSwapchainImage xrAcquireSwapchainImage;
|
||||
PFN_xrWaitSwapchainImage xrWaitSwapchainImage;
|
||||
PFN_xrReleaseSwapchainImage xrReleaseSwapchainImage;
|
||||
PFN_xrBeginSession xrBeginSession;
|
||||
PFN_xrEndSession xrEndSession;
|
||||
PFN_xrRequestExitSession xrRequestExitSession;
|
||||
PFN_xrWaitFrame xrWaitFrame;
|
||||
PFN_xrBeginFrame xrBeginFrame;
|
||||
PFN_xrEndFrame xrEndFrame;
|
||||
PFN_xrLocateViews xrLocateViews;
|
||||
PFN_xrStringToPath xrStringToPath;
|
||||
PFN_xrPathToString xrPathToString;
|
||||
PFN_xrCreateActionSet xrCreateActionSet;
|
||||
PFN_xrDestroyActionSet xrDestroyActionSet;
|
||||
PFN_xrCreateAction xrCreateAction;
|
||||
PFN_xrDestroyAction xrDestroyAction;
|
||||
PFN_xrSuggestInteractionProfileBindings xrSuggestInteractionProfileBindings;
|
||||
PFN_xrAttachSessionActionSets xrAttachSessionActionSets;
|
||||
PFN_xrGetCurrentInteractionProfile xrGetCurrentInteractionProfile;
|
||||
PFN_xrGetActionStateBoolean xrGetActionStateBoolean;
|
||||
PFN_xrGetActionStateFloat xrGetActionStateFloat;
|
||||
PFN_xrGetActionStateVector2f xrGetActionStateVector2f;
|
||||
PFN_xrGetActionStatePose xrGetActionStatePose;
|
||||
PFN_xrSyncActions xrSyncActions;
|
||||
PFN_xrEnumerateBoundSourcesForAction xrEnumerateBoundSourcesForAction;
|
||||
PFN_xrGetInputSourceLocalizedName xrGetInputSourceLocalizedName;
|
||||
PFN_xrApplyHapticFeedback xrApplyHapticFeedback;
|
||||
PFN_xrStopHapticFeedback xrStopHapticFeedback;
|
||||
|
||||
#ifdef XR_USE_PLATFORM_WIN32
|
||||
#define dlsym(x, y) GetProcAddress(x, y)
|
||||
static HMODULE g_xrLibrary;
|
||||
#else
|
||||
#define dlsym(x, y) nullptr
|
||||
void *g_xrLibrary;
|
||||
#endif
|
||||
|
||||
#define LOAD_INSTANCE_FUNC(name) (PFN_ ## name)xrGetInstanceProcAddr(instance, #name, (PFN_xrVoidFunction *)(&name))
|
||||
|
||||
|
||||
bool XRLoad() {
|
||||
if (g_xrLibrary) {
|
||||
// Already loaded. That's OK.
|
||||
return true;
|
||||
}
|
||||
|
||||
#ifdef XR_USE_PLATFORM_WIN32
|
||||
g_xrLibrary = LoadLibrary(L"openxr_loader.dll");
|
||||
if (!g_xrLibrary) {
|
||||
return false;
|
||||
}
|
||||
#else
|
||||
return false;
|
||||
#endif
|
||||
|
||||
// Load the three basic functions.
|
||||
xrGetInstanceProcAddr = (PFN_xrGetInstanceProcAddr)dlsym(g_xrLibrary, "xrGetInstanceProcAddr");
|
||||
xrEnumerateApiLayerProperties = (PFN_xrEnumerateApiLayerProperties)dlsym(g_xrLibrary, "xrEnumerateApiLayerProperties");
|
||||
xrEnumerateInstanceExtensionProperties = (PFN_xrEnumerateInstanceExtensionProperties)dlsym(g_xrLibrary, "xrEnumerateInstanceExtensionProperties");
|
||||
|
||||
// Load the rest.
|
||||
return true;
|
||||
}
|
||||
|
||||
void XRLoadInstanceFunctions(XrInstance instance) {
|
||||
LOAD_INSTANCE_FUNC(xrCreateInstance);
|
||||
LOAD_INSTANCE_FUNC(xrGetInstanceProcAddr);
|
||||
LOAD_INSTANCE_FUNC(xrEnumerateApiLayerProperties);
|
||||
LOAD_INSTANCE_FUNC(xrEnumerateInstanceExtensionProperties);
|
||||
LOAD_INSTANCE_FUNC(xrCreateInstance);
|
||||
LOAD_INSTANCE_FUNC(xrDestroyInstance);
|
||||
LOAD_INSTANCE_FUNC(xrGetInstanceProperties);
|
||||
LOAD_INSTANCE_FUNC(xrPollEvent);
|
||||
LOAD_INSTANCE_FUNC(xrResultToString);
|
||||
LOAD_INSTANCE_FUNC(xrStructureTypeToString);
|
||||
LOAD_INSTANCE_FUNC(xrGetSystem);
|
||||
LOAD_INSTANCE_FUNC(xrGetSystemProperties);
|
||||
LOAD_INSTANCE_FUNC(xrEnumerateEnvironmentBlendModes);
|
||||
LOAD_INSTANCE_FUNC(xrCreateSession);
|
||||
LOAD_INSTANCE_FUNC(xrDestroySession);
|
||||
LOAD_INSTANCE_FUNC(xrEnumerateReferenceSpaces);
|
||||
LOAD_INSTANCE_FUNC(xrCreateReferenceSpace);
|
||||
LOAD_INSTANCE_FUNC(xrGetReferenceSpaceBoundsRect);
|
||||
LOAD_INSTANCE_FUNC(xrCreateActionSpace);
|
||||
LOAD_INSTANCE_FUNC(xrLocateSpace);
|
||||
LOAD_INSTANCE_FUNC(xrDestroySpace);
|
||||
LOAD_INSTANCE_FUNC(xrEnumerateViewConfigurations);
|
||||
LOAD_INSTANCE_FUNC(xrGetViewConfigurationProperties);
|
||||
LOAD_INSTANCE_FUNC(xrEnumerateViewConfigurationViews);
|
||||
LOAD_INSTANCE_FUNC(xrEnumerateSwapchainFormats);
|
||||
LOAD_INSTANCE_FUNC(xrCreateSwapchain);
|
||||
LOAD_INSTANCE_FUNC(xrDestroySwapchain);
|
||||
LOAD_INSTANCE_FUNC(xrEnumerateSwapchainImages);
|
||||
LOAD_INSTANCE_FUNC(xrAcquireSwapchainImage);
|
||||
LOAD_INSTANCE_FUNC(xrWaitSwapchainImage);
|
||||
LOAD_INSTANCE_FUNC(xrReleaseSwapchainImage);
|
||||
LOAD_INSTANCE_FUNC(xrBeginSession);
|
||||
LOAD_INSTANCE_FUNC(xrEndSession);
|
||||
LOAD_INSTANCE_FUNC(xrRequestExitSession);
|
||||
LOAD_INSTANCE_FUNC(xrWaitFrame);
|
||||
LOAD_INSTANCE_FUNC(xrBeginFrame);
|
||||
LOAD_INSTANCE_FUNC(xrEndFrame);
|
||||
LOAD_INSTANCE_FUNC(xrLocateViews);
|
||||
LOAD_INSTANCE_FUNC(xrStringToPath);
|
||||
LOAD_INSTANCE_FUNC(xrPathToString);
|
||||
LOAD_INSTANCE_FUNC(xrCreateActionSet);
|
||||
LOAD_INSTANCE_FUNC(xrDestroyActionSet);
|
||||
LOAD_INSTANCE_FUNC(xrCreateAction);
|
||||
LOAD_INSTANCE_FUNC(xrDestroyAction);
|
||||
LOAD_INSTANCE_FUNC(xrSuggestInteractionProfileBindings);
|
||||
LOAD_INSTANCE_FUNC(xrAttachSessionActionSets);
|
||||
LOAD_INSTANCE_FUNC(xrGetCurrentInteractionProfile);
|
||||
LOAD_INSTANCE_FUNC(xrGetActionStateBoolean);
|
||||
LOAD_INSTANCE_FUNC(xrGetActionStateFloat);
|
||||
LOAD_INSTANCE_FUNC(xrGetActionStateVector2f);
|
||||
LOAD_INSTANCE_FUNC(xrGetActionStatePose);
|
||||
LOAD_INSTANCE_FUNC(xrSyncActions);
|
||||
LOAD_INSTANCE_FUNC(xrEnumerateBoundSourcesForAction);
|
||||
LOAD_INSTANCE_FUNC(xrGetInputSourceLocalizedName);
|
||||
LOAD_INSTANCE_FUNC(xrApplyHapticFeedback);
|
||||
LOAD_INSTANCE_FUNC(xrStopHapticFeedback);
|
||||
|
||||
// TODO: Load any extensions we need, too.
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,122 @@
|
||||
#pragma once
|
||||
|
||||
//Vulkan
|
||||
#ifdef VK_USE_NATIVE_LIB
|
||||
#include <vulkan/vulkan.h>
|
||||
#else
|
||||
#include "Common/GPU/Vulkan/VulkanLoader.h"
|
||||
using namespace PPSSPP_VK;
|
||||
#endif
|
||||
|
||||
#ifdef ANDROID
|
||||
#include <jni.h>
|
||||
#define XR_USE_PLATFORM_ANDROID 1
|
||||
#define XR_USE_GRAPHICS_API_OPENGL_ES 1
|
||||
#define XR_USE_GRAPHICS_API_VULKAN 1
|
||||
#include <EGL/egl.h>
|
||||
#include <EGL/eglext.h>
|
||||
|
||||
#if OPENXR
|
||||
// One of the Android-based headsets. We're linking with a static OpenXR loader.
|
||||
#else
|
||||
// Normal Android app, we don't have a loader so use our own dynamic loader, which won't load anything.
|
||||
#define XR_NO_PROTOTYPES 1
|
||||
#endif
|
||||
|
||||
#elif defined(_WIN32)
|
||||
#include "Common/CommonWindows.h"
|
||||
#if defined(WINAPI_FAMILY) && defined(WINAPI_FAMILY_PARTITION)
|
||||
#if WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_APP) && WINAPI_FAMILY == WINAPI_FAMILY_DESKTOP_APP
|
||||
#if defined(_M_IX86) || defined(_M_X64)
|
||||
#include "Common/GPU/OpenGL/GLCommon.h"
|
||||
#define XR_USE_GRAPHICS_API_OPENGL 1
|
||||
#endif
|
||||
#define XR_USE_PLATFORM_WIN32 1
|
||||
#endif
|
||||
#endif
|
||||
#define XR_USE_GRAPHICS_API_VULKAN 1
|
||||
#include "Common/VR/OpenXRLoader.h"
|
||||
#include <unknwn.h>
|
||||
#define XR_NO_PROTOTYPES 1
|
||||
#else
|
||||
#define XR_USE_GRAPHICS_API_VULKAN 1
|
||||
#define XR_NO_PROTOTYPES 1
|
||||
#endif
|
||||
|
||||
#include <openxr.h>
|
||||
#include <openxr_platform.h>
|
||||
|
||||
#ifdef XR_NO_PROTOTYPES
|
||||
|
||||
extern PFN_xrGetInstanceProcAddr xrGetInstanceProcAddr;
|
||||
extern PFN_xrEnumerateApiLayerProperties xrEnumerateApiLayerProperties;
|
||||
extern PFN_xrEnumerateInstanceExtensionProperties xrEnumerateInstanceExtensionProperties;
|
||||
extern PFN_xrCreateInstance xrCreateInstance;
|
||||
extern PFN_xrDestroyInstance xrDestroyInstance;
|
||||
extern PFN_xrGetInstanceProperties xrGetInstanceProperties;
|
||||
extern PFN_xrPollEvent xrPollEvent;
|
||||
extern PFN_xrResultToString xrResultToString;
|
||||
extern PFN_xrStructureTypeToString xrStructureTypeToString;
|
||||
extern PFN_xrGetSystem xrGetSystem;
|
||||
extern PFN_xrGetSystemProperties xrGetSystemProperties;
|
||||
extern PFN_xrEnumerateEnvironmentBlendModes xrEnumerateEnvironmentBlendModes;
|
||||
extern PFN_xrCreateSession xrCreateSession;
|
||||
extern PFN_xrDestroySession xrDestroySession;
|
||||
extern PFN_xrEnumerateReferenceSpaces xrEnumerateReferenceSpaces;
|
||||
extern PFN_xrCreateReferenceSpace xrCreateReferenceSpace;
|
||||
extern PFN_xrGetReferenceSpaceBoundsRect xrGetReferenceSpaceBoundsRect;
|
||||
extern PFN_xrCreateActionSpace xrCreateActionSpace;
|
||||
extern PFN_xrLocateSpace xrLocateSpace;
|
||||
extern PFN_xrDestroySpace xrDestroySpace;
|
||||
extern PFN_xrEnumerateViewConfigurations xrEnumerateViewConfigurations;
|
||||
extern PFN_xrGetViewConfigurationProperties xrGetViewConfigurationProperties;
|
||||
extern PFN_xrEnumerateViewConfigurationViews xrEnumerateViewConfigurationViews;
|
||||
extern PFN_xrEnumerateSwapchainFormats xrEnumerateSwapchainFormats;
|
||||
extern PFN_xrCreateSwapchain xrCreateSwapchain;
|
||||
extern PFN_xrDestroySwapchain xrDestroySwapchain;
|
||||
extern PFN_xrEnumerateSwapchainImages xrEnumerateSwapchainImages;
|
||||
extern PFN_xrAcquireSwapchainImage xrAcquireSwapchainImage;
|
||||
extern PFN_xrWaitSwapchainImage xrWaitSwapchainImage;
|
||||
extern PFN_xrReleaseSwapchainImage xrReleaseSwapchainImage;
|
||||
extern PFN_xrBeginSession xrBeginSession;
|
||||
extern PFN_xrEndSession xrEndSession;
|
||||
extern PFN_xrRequestExitSession xrRequestExitSession;
|
||||
extern PFN_xrWaitFrame xrWaitFrame;
|
||||
extern PFN_xrBeginFrame xrBeginFrame;
|
||||
extern PFN_xrEndFrame xrEndFrame;
|
||||
extern PFN_xrLocateViews xrLocateViews;
|
||||
extern PFN_xrStringToPath xrStringToPath;
|
||||
extern PFN_xrPathToString xrPathToString;
|
||||
extern PFN_xrCreateActionSet xrCreateActionSet;
|
||||
extern PFN_xrDestroyActionSet xrDestroyActionSet;
|
||||
extern PFN_xrCreateAction xrCreateAction;
|
||||
extern PFN_xrDestroyAction xrDestroyAction;
|
||||
extern PFN_xrSuggestInteractionProfileBindings xrSuggestInteractionProfileBindings;
|
||||
extern PFN_xrAttachSessionActionSets xrAttachSessionActionSets;
|
||||
extern PFN_xrGetCurrentInteractionProfile xrGetCurrentInteractionProfile;
|
||||
extern PFN_xrGetActionStateBoolean xrGetActionStateBoolean;
|
||||
extern PFN_xrGetActionStateFloat xrGetActionStateFloat;
|
||||
extern PFN_xrGetActionStateVector2f xrGetActionStateVector2f;
|
||||
extern PFN_xrGetActionStatePose xrGetActionStatePose;
|
||||
extern PFN_xrSyncActions xrSyncActions;
|
||||
extern PFN_xrEnumerateBoundSourcesForAction xrEnumerateBoundSourcesForAction;
|
||||
extern PFN_xrGetInputSourceLocalizedName xrGetInputSourceLocalizedName;
|
||||
extern PFN_xrApplyHapticFeedback xrApplyHapticFeedback;
|
||||
extern PFN_xrStopHapticFeedback xrStopHapticFeedback;
|
||||
|
||||
// Dynamic loader for OpenXR on desktop platforms.
|
||||
// On Quest/Pico, we use statically linked loaders provided by the platform owners.
|
||||
// On Windows (and Linux etc), we're not so lucky - we could link to static libraries, but we really
|
||||
// don't want to as we still want to function when one is not present.
|
||||
//
|
||||
// Similar to our dynamic Vulkan loader.
|
||||
|
||||
bool XRLoad();
|
||||
void XRLoadInstanceFunctions(XrInstance instance);
|
||||
|
||||
#else
|
||||
|
||||
inline bool XRLoad() { return true; }
|
||||
inline void XRLoadInstanceFunctions(XrInstance instance) {}
|
||||
|
||||
#endif
|
||||
+298
-47
@@ -1,11 +1,13 @@
|
||||
#include "Common/GPU/OpenGL/GLRenderManager.h"
|
||||
|
||||
#include "Common/VR/PPSSPPVR.h"
|
||||
#include "Common/VR/VRBase.h"
|
||||
#include "Common/VR/VRInput.h"
|
||||
#include "Common/VR/VRMath.h"
|
||||
#include "Common/VR/VRRenderer.h"
|
||||
#include "Common/VR/VRTweaks.h"
|
||||
|
||||
#if XR_USE_GRAPHICS_API_OPENGL
|
||||
#include "Common/GPU/OpenGL/GLRenderManager.h"
|
||||
#endif
|
||||
#include "Common/GPU/Vulkan/VulkanContext.h"
|
||||
|
||||
#include "Core/HLE/sceDisplay.h"
|
||||
#include "Core/Config.h"
|
||||
@@ -76,6 +78,7 @@ static std::vector<ButtonMapping> controllerMapping[2] = {
|
||||
leftControllerMapping,
|
||||
rightControllerMapping
|
||||
};
|
||||
static bool controllerMotion[2][5] = {};
|
||||
static int mouseController = -1;
|
||||
static bool mousePressed[] = {false, false};
|
||||
|
||||
@@ -95,25 +98,65 @@ VR app flow integration
|
||||
================================================================================
|
||||
*/
|
||||
|
||||
bool IsVRBuild() {
|
||||
bool IsVREnabled() {
|
||||
// For now, let the OPENXR build flag control enablement.
|
||||
// This will change.
|
||||
#ifdef OPENXR
|
||||
return true;
|
||||
#else
|
||||
return false;
|
||||
#endif
|
||||
}
|
||||
|
||||
void InitVROnAndroid(void* vm, void* activity, int version, const char* name) {
|
||||
#if PPSSPP_PLATFORM(ANDROID)
|
||||
void InitVROnAndroid(void* vm, void* activity, const char* system, int version, const char* name) {
|
||||
|
||||
//Get device vendor (uppercase)
|
||||
char vendor[64];
|
||||
sscanf(system, "%[^:]", vendor);
|
||||
for (unsigned int i = 0; i < strlen(vendor); i++) {
|
||||
if ((vendor[i] >= 'a') && (vendor[i] <= 'z')) {
|
||||
vendor[i] = vendor[i] - 'a' + 'A';
|
||||
}
|
||||
}
|
||||
|
||||
//Set platform flags
|
||||
if (strcmp(vendor, "PICO") == 0) {
|
||||
VR_SetPlatformFLag(VR_PLATFORM_CONTROLLER_PICO, true);
|
||||
VR_SetPlatformFLag(VR_PLATFORM_PICO_INIT, true);
|
||||
} else if ((strcmp(vendor, "META") == 0) || (strcmp(vendor, "OCULUS") == 0)) {
|
||||
VR_SetPlatformFLag(VR_PLATFORM_CONTROLLER_QUEST, true);
|
||||
VR_SetPlatformFLag(VR_PLATFORM_PERFORMANCE_EXT, true);
|
||||
}
|
||||
VR_SetPlatformFLag(VR_PLATFORM_RENDERER_VULKAN, (GPUBackend)g_Config.iGPUBackend == GPUBackend::VULKAN);
|
||||
|
||||
//Init VR
|
||||
ovrJava java;
|
||||
java.Vm = (JavaVM*)vm;
|
||||
java.ActivityObject = (jobject)activity;
|
||||
java.AppVersion = version;
|
||||
strcpy(java.AppName, name);
|
||||
VR_Init(java);
|
||||
|
||||
__DisplaySetFramerate(72);
|
||||
VR_Init(&java, name, version);
|
||||
}
|
||||
#endif
|
||||
|
||||
void EnterVR(bool firstStart) {
|
||||
void EnterVR(bool firstStart, void* vulkanContext) {
|
||||
if (firstStart) {
|
||||
VR_EnterVR(VR_GetEngine());
|
||||
IN_VRInit(VR_GetEngine());
|
||||
engine_t* engine = VR_GetEngine();
|
||||
bool useVulkan = (GPUBackend)g_Config.iGPUBackend == GPUBackend::VULKAN;
|
||||
if (useVulkan) {
|
||||
auto* context = (VulkanContext*)vulkanContext;
|
||||
engine->graphicsBindingVulkan = {};
|
||||
engine->graphicsBindingVulkan.type = XR_TYPE_GRAPHICS_BINDING_VULKAN_KHR;
|
||||
engine->graphicsBindingVulkan.next = NULL;
|
||||
engine->graphicsBindingVulkan.device = context->GetDevice();
|
||||
engine->graphicsBindingVulkan.instance = context->GetInstance();
|
||||
engine->graphicsBindingVulkan.physicalDevice = context->GetCurrentPhysicalDevice();
|
||||
engine->graphicsBindingVulkan.queueFamilyIndex = context->GetGraphicsQueueFamilyIndex();
|
||||
engine->graphicsBindingVulkan.queueIndex = 0;
|
||||
VR_EnterVR(engine, &engine->graphicsBindingVulkan);
|
||||
} else {
|
||||
VR_EnterVR(engine, nullptr);
|
||||
}
|
||||
IN_VRInit(engine);
|
||||
}
|
||||
VR_SetConfig(VR_CONFIG_VIEWPORT_VALID, false);
|
||||
}
|
||||
@@ -129,22 +172,42 @@ void UpdateVRInput(bool(*NativeKey)(const KeyInput &key), bool(*NativeTouch)(con
|
||||
KeyInput keyInput = {};
|
||||
for (int j = 0; j < 2; j++) {
|
||||
int status = IN_VRGetButtonState(j);
|
||||
bool cameraControl = VR_GetConfig(VR_CONFIG_CAMERA_CONTROL);
|
||||
for (ButtonMapping& m : controllerMapping[j]) {
|
||||
|
||||
//check if camera key was pressed
|
||||
bool cameraKey = false;
|
||||
std::vector<int> nativeKeys;
|
||||
if (KeyMap::KeyToPspButton(controllerIds[j], m.keycode, &nativeKeys)) {
|
||||
for (int& nativeKey : nativeKeys) {
|
||||
if (nativeKey == VIRTKEY_VR_CAMERA_ADJUST) {
|
||||
cameraKey = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//fill KeyInput structure
|
||||
bool pressed = status & m.ovr;
|
||||
keyInput.flags = pressed ? KEY_DOWN : KEY_UP;
|
||||
keyInput.keyCode = m.keycode;
|
||||
keyInput.deviceId = controllerIds[j];
|
||||
|
||||
//process the key action
|
||||
if (m.pressed != pressed) {
|
||||
if (pressed && haptics) {
|
||||
INVR_Vibrate(100, j, 1000);
|
||||
}
|
||||
NativeKey(keyInput);
|
||||
if (!cameraControl || cameraKey) {
|
||||
NativeKey(keyInput);
|
||||
}
|
||||
m.pressed = pressed;
|
||||
m.repeat = 0;
|
||||
} else if (pressed && (m.repeat > 30)) {
|
||||
keyInput.flags |= KEY_IS_REPEAT;
|
||||
NativeKey(keyInput);
|
||||
if (!cameraControl || cameraKey) {
|
||||
NativeKey(keyInput);
|
||||
}
|
||||
m.repeat = 0;
|
||||
} else {
|
||||
m.repeat++;
|
||||
@@ -162,6 +225,58 @@ void UpdateVRInput(bool(*NativeKey)(const KeyInput &key), bool(*NativeTouch)(con
|
||||
}
|
||||
}
|
||||
|
||||
//motion control
|
||||
if (g_Config.bEnableMotions) {
|
||||
for (int j = 0; j < 2; j++) {
|
||||
bool activate;
|
||||
float limit = g_Config.fMotionLength; //length of needed movement in meters
|
||||
XrVector3f axis = {0, 1, 0};
|
||||
float center = ToRadians(VR_GetConfigFloat(VR_CONFIG_MENU_YAW));
|
||||
XrQuaternionf orientation = XrQuaternionf_CreateFromVectorAngle(axis, center);
|
||||
XrVector3f position = XrQuaternionf_Rotate(orientation, IN_VRGetPose(j).position);
|
||||
|
||||
//up
|
||||
activate = position.y > limit;
|
||||
keyInput.flags = activate ? KEY_DOWN : KEY_UP;
|
||||
keyInput.keyCode = NKCODE_EXT_MOTION_UP;
|
||||
keyInput.deviceId = controllerIds[j];
|
||||
if (controllerMotion[j][0] != activate) NativeKey(keyInput);
|
||||
controllerMotion[j][0] = activate;
|
||||
|
||||
//down
|
||||
activate = position.y < -limit * 1.5f;
|
||||
keyInput.flags = activate ? KEY_DOWN : KEY_UP;
|
||||
keyInput.keyCode = NKCODE_EXT_MOTION_DOWN;
|
||||
keyInput.deviceId = controllerIds[j];
|
||||
if (controllerMotion[j][1] != activate) NativeKey(keyInput);
|
||||
controllerMotion[j][1] = activate;
|
||||
|
||||
//left
|
||||
activate = position.x < -limit * (j == 0 ? 1.0f : 0.25f);
|
||||
keyInput.flags = activate ? KEY_DOWN : KEY_UP;
|
||||
keyInput.keyCode = NKCODE_EXT_MOTION_LEFT;
|
||||
keyInput.deviceId = controllerIds[j];
|
||||
if (controllerMotion[j][2] != activate) NativeKey(keyInput);
|
||||
controllerMotion[j][2] = activate;
|
||||
|
||||
//right
|
||||
activate = position.x > limit * (j == 1 ? 1.0f : 0.25f);
|
||||
keyInput.flags = activate ? KEY_DOWN : KEY_UP;
|
||||
keyInput.keyCode = NKCODE_EXT_MOTION_RIGHT;
|
||||
keyInput.deviceId = controllerIds[j];
|
||||
if (controllerMotion[j][3] != activate) NativeKey(keyInput);
|
||||
controllerMotion[j][3] = activate;
|
||||
|
||||
//forward
|
||||
activate = position.z < -limit;
|
||||
keyInput.flags = activate ? KEY_DOWN : KEY_UP;
|
||||
keyInput.keyCode = NKCODE_EXT_MOTION_FORWARD;
|
||||
keyInput.deviceId = controllerIds[j];
|
||||
if (controllerMotion[j][4] != activate) NativeKey(keyInput);
|
||||
controllerMotion[j][4] = activate;
|
||||
}
|
||||
}
|
||||
|
||||
//mouse cursor
|
||||
if (mouseController >= 0) {
|
||||
//get position on screen
|
||||
@@ -172,13 +287,13 @@ void UpdateVRInput(bool(*NativeKey)(const KeyInput &key), bool(*NativeTouch)(con
|
||||
float cx = width / 2;
|
||||
float cy = height / 2;
|
||||
float speed = (cx + cy) / 2;
|
||||
float x = cx - tan(ToRadians(angles.y - (float)VR_GetConfig(VR_CONFIG_MENU_YAW))) * speed;
|
||||
float x = cx - tan(ToRadians(angles.y - VR_GetConfigFloat(VR_CONFIG_MENU_YAW))) * speed;
|
||||
float y = cy - tan(ToRadians(angles.x)) * speed;
|
||||
|
||||
//set renderer
|
||||
VR_SetConfig(VR_CONFIG_MOUSE_X, (int)x);
|
||||
VR_SetConfig(VR_CONFIG_MOUSE_Y, (int)y);
|
||||
VR_SetConfig(VR_CONFIG_MOUSE_SIZE, 6 * (int)pow(VR_GetConfig(VR_CONFIG_CANVAS_DISTANCE), 0.25f));
|
||||
VR_SetConfig(VR_CONFIG_MOUSE_SIZE, 6 * (int)pow(VR_GetConfigFloat(VR_CONFIG_CANVAS_DISTANCE), 0.25f));
|
||||
|
||||
//inform engine about the status
|
||||
TouchInput touch;
|
||||
@@ -200,11 +315,16 @@ void UpdateVRInput(bool(*NativeKey)(const KeyInput &key), bool(*NativeTouch)(con
|
||||
}
|
||||
}
|
||||
|
||||
void UpdateVRScreenKey(const KeyInput &key) {
|
||||
void UpdateVRSpecialKeys(const KeyInput &key) {
|
||||
std::vector<int> nativeKeys;
|
||||
if (KeyMap::KeyToPspButton(key.deviceId, key.keyCode, &nativeKeys)) {
|
||||
for (int& nativeKey : nativeKeys) {
|
||||
if (nativeKey == CTRL_SCREEN) {
|
||||
// adjust camera parameters
|
||||
if (nativeKey == VIRTKEY_VR_CAMERA_ADJUST) {
|
||||
VR_SetConfig(VR_CONFIG_CAMERA_CONTROL, key.flags & KEY_DOWN);
|
||||
}
|
||||
// force 2D rendering
|
||||
else if (nativeKey == CTRL_SCREEN) {
|
||||
VR_SetConfig(VR_CONFIG_FORCE_2D, key.flags & KEY_DOWN);
|
||||
}
|
||||
}
|
||||
@@ -219,6 +339,8 @@ void UpdateVRScreenKey(const KeyInput &key) {
|
||||
================================================================================
|
||||
*/
|
||||
|
||||
#if XR_USE_GRAPHICS_API_OPENGL
|
||||
|
||||
void PreprocessSkyplane(GLRStep* step) {
|
||||
|
||||
// Do not do anything if the scene is not in VR.
|
||||
@@ -260,6 +382,12 @@ void PreprocessStepVR(void* step) {
|
||||
if (vrCompat[VR_COMPAT_SKYPLANE]) PreprocessSkyplane(glrStep);
|
||||
}
|
||||
|
||||
#else
|
||||
|
||||
void PreprocessStepVR(void* step) {}
|
||||
|
||||
#endif
|
||||
|
||||
void SetVRCompat(VRCompatFlag flag, long value) {
|
||||
vrCompat[flag] = value;
|
||||
}
|
||||
@@ -272,8 +400,14 @@ VR rendering integration
|
||||
================================================================================
|
||||
*/
|
||||
|
||||
void BindVRFramebuffer() {
|
||||
VR_BindFramebuffer(VR_GetEngine());
|
||||
void* BindVRFramebuffer() {
|
||||
return VR_BindFramebuffer(VR_GetEngine());
|
||||
}
|
||||
|
||||
inline float clampFloat(float x, float minValue, float maxValue) {
|
||||
if (x < minValue) return minValue;
|
||||
if (x > maxValue) return maxValue;
|
||||
return x;
|
||||
}
|
||||
|
||||
bool StartVRRender() {
|
||||
@@ -286,20 +420,58 @@ bool StartVRRender() {
|
||||
|
||||
// Decide if the scene is 3D or not
|
||||
if (g_Config.bEnableVR && !VR_GetConfig(VR_CONFIG_FORCE_2D) && (VR_GetConfig(VR_CONFIG_3D_GEOMETRY_COUNT) > 15)) {
|
||||
bool stereo = VR_GetConfig(VR_CONFIG_6DOF_PRECISE) && g_Config.bEnableStereo;
|
||||
bool stereo = VR_GetConfig(VR_CONFIG_HAS_UNIT_SCALE) && g_Config.bEnableStereo;
|
||||
VR_SetConfig(VR_CONFIG_MODE, stereo ? VR_MODE_STEREO_6DOF : VR_MODE_MONO_6DOF);
|
||||
} else {
|
||||
VR_SetConfig(VR_CONFIG_MODE, VR_MODE_FLAT_SCREEN);
|
||||
VR_SetConfig(VR_CONFIG_MODE, g_Config.bEnableStereo ? VR_MODE_STEREO_SCREEN : VR_MODE_MONO_SCREEN);
|
||||
}
|
||||
VR_SetConfig(VR_CONFIG_3D_GEOMETRY_COUNT, VR_GetConfig(VR_CONFIG_3D_GEOMETRY_COUNT) / 2);
|
||||
|
||||
// Set compatibility
|
||||
vrCompat[VR_COMPAT_SKYPLANE] = PSP_CoreParameter().compat.vrCompat().Skyplane;
|
||||
|
||||
// Camera control
|
||||
if (VR_GetConfig(VR_CONFIG_CAMERA_CONTROL)) {
|
||||
//left joystick controls height and side
|
||||
float height = g_Config.fCameraHeight;
|
||||
float side = g_Config.fCameraSide;
|
||||
int status = IN_VRGetButtonState(0);
|
||||
if (status & ovrButton_Left) side -= 0.05f;
|
||||
if (status & ovrButton_Right) side += 0.05f;
|
||||
if (status & ovrButton_Down) height -= 0.05f;
|
||||
if (status & ovrButton_Up) height += 0.05f;
|
||||
if (status & ovrButton_LThumb) {
|
||||
height = 0;
|
||||
side = 0;
|
||||
}
|
||||
g_Config.fCameraHeight = clampFloat(height, -10.0f, 10.0f);
|
||||
g_Config.fCameraSide = clampFloat(side, -10.0f, 10.0f);
|
||||
|
||||
//right joystick controls distance and fov
|
||||
float dst = g_Config.fCameraDistance;
|
||||
float fov = g_Config.fFieldOfViewPercentage;
|
||||
status = IN_VRGetButtonState(1);
|
||||
if (status & ovrButton_Left) fov -= 1.0f;
|
||||
if (status & ovrButton_Right) fov += 1.0f;
|
||||
if (status & ovrButton_Down) dst -= 0.1f;
|
||||
if (status & ovrButton_Up) dst += 0.1f;
|
||||
if (status & ovrButton_RThumb) {
|
||||
fov = 100;
|
||||
dst = 0;
|
||||
}
|
||||
g_Config.fCameraDistance = clampFloat(dst, -10.0f, 10.0f);
|
||||
g_Config.fFieldOfViewPercentage = clampFloat(fov, 100.0f, 200.0f);
|
||||
}
|
||||
|
||||
// Set customizations
|
||||
__DisplaySetFramerate(g_Config.bForce72Hz ? 72 : 60);
|
||||
VR_SetConfig(VR_CONFIG_6DOF_ENABLED, g_Config.bEnable6DoF);
|
||||
VR_SetConfig(VR_CONFIG_CANVAS_DISTANCE, g_Config.iCanvasDistance);
|
||||
VR_SetConfig(VR_CONFIG_FOV_SCALE, g_Config.iFieldOfViewPercentage);
|
||||
VR_SetConfigFloat(VR_CONFIG_CAMERA_DISTANCE, g_Config.fCameraDistance);
|
||||
VR_SetConfigFloat(VR_CONFIG_CAMERA_HEIGHT, g_Config.fCameraHeight);
|
||||
VR_SetConfigFloat(VR_CONFIG_CAMERA_SIDE, g_Config.fCameraSide);
|
||||
VR_SetConfigFloat(VR_CONFIG_CANVAS_DISTANCE, g_Config.fCanvasDistance);
|
||||
VR_SetConfigFloat(VR_CONFIG_FOV_SCALE, g_Config.fFieldOfViewPercentage);
|
||||
VR_SetConfig(VR_CONFIG_MIRROR_UPDATED, false);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
@@ -322,43 +494,122 @@ int GetVRFBOIndex() {
|
||||
return VR_GetConfig(VR_CONFIG_CURRENT_FBO);
|
||||
}
|
||||
|
||||
int GetVRPassesCount() {
|
||||
if (!IsMultiviewSupported() && g_Config.bEnableStereo) {
|
||||
return 2;
|
||||
} else {
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
|
||||
bool IsMultiviewSupported() {
|
||||
return false;
|
||||
}
|
||||
|
||||
bool IsFlatVRScene() {
|
||||
return VR_GetConfig(VR_CONFIG_MODE) == VR_MODE_FLAT_SCREEN;
|
||||
int vrMode = VR_GetConfig(VR_CONFIG_MODE);
|
||||
return (vrMode == VR_MODE_MONO_SCREEN) || (vrMode == VR_MODE_STEREO_SCREEN);
|
||||
}
|
||||
|
||||
bool Is2DVRObject(float* projMatrix, bool ortho) {
|
||||
bool is2D = VR_TweakIsMatrixBigScale(projMatrix) ||
|
||||
VR_TweakIsMatrixIdentity(projMatrix) ||
|
||||
VR_TweakIsMatrixOneOrtho(projMatrix) ||
|
||||
VR_TweakIsMatrixOneScale(projMatrix) ||
|
||||
VR_TweakIsMatrixOneTransform(projMatrix);
|
||||
if (!is2D && !ortho) {
|
||||
|
||||
// Quick analyze if the object is in 2D
|
||||
if ((fabs(fabs(projMatrix[12]) - 1.0f) < EPSILON) && (fabs(fabs(projMatrix[13]) - 1.0f) < EPSILON) && (fabs(fabs(projMatrix[14]) - 1.0f) < EPSILON)) {
|
||||
return true;
|
||||
} else if ((fabs(projMatrix[0]) > 10.0f) && (fabs(projMatrix[5]) > 10.0f)) {
|
||||
return true;
|
||||
} else if (fabs(projMatrix[15] - 1) < EPSILON) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// Chceck if the projection matrix is identity
|
||||
bool identity = true;
|
||||
for (int i = 0; i < 4; i++) {
|
||||
for (int j = 0; j < 4; j++) {
|
||||
float value = projMatrix[i * 4 + j];
|
||||
|
||||
// Other number than zero on non-diagonale
|
||||
if ((i != j) && (fabs(value) > EPSILON)) identity = false;
|
||||
// Other number than one on diagonale
|
||||
if ((i == j) && (fabs(value - 1.0f) > EPSILON)) identity = false;
|
||||
}
|
||||
}
|
||||
|
||||
// Update 3D geometry count
|
||||
if (!identity && !ortho) {
|
||||
VR_SetConfig(VR_CONFIG_3D_GEOMETRY_COUNT, VR_GetConfig(VR_CONFIG_3D_GEOMETRY_COUNT) + 1);
|
||||
}
|
||||
return is2D;
|
||||
return identity;
|
||||
}
|
||||
|
||||
void UpdateVRParams(float* projMatrix) {
|
||||
|
||||
// Set mirroring of axes
|
||||
if (!VR_GetConfig(VR_CONFIG_MIRROR_UPDATED)) {
|
||||
VR_SetConfig(VR_CONFIG_MIRROR_UPDATED, true);
|
||||
VR_SetConfig(VR_CONFIG_MIRROR_AXIS_X, projMatrix[0] < 0);
|
||||
VR_SetConfig(VR_CONFIG_MIRROR_AXIS_Y, projMatrix[5] < 0);
|
||||
VR_SetConfig(VR_CONFIG_MIRROR_AXIS_Z, projMatrix[10] > 0);
|
||||
if ((projMatrix[0] < 0) && (projMatrix[10] < 0)) { //e.g. Dante's inferno
|
||||
VR_SetConfig(VR_CONFIG_MIRROR_PITCH, true);
|
||||
VR_SetConfig(VR_CONFIG_MIRROR_YAW, true);
|
||||
VR_SetConfig(VR_CONFIG_MIRROR_ROLL, false);
|
||||
} else if (projMatrix[10] < 0) { //e.g. GTA - Liberty city
|
||||
VR_SetConfig(VR_CONFIG_MIRROR_PITCH, false);
|
||||
VR_SetConfig(VR_CONFIG_MIRROR_YAW, false);
|
||||
VR_SetConfig(VR_CONFIG_MIRROR_ROLL, false);
|
||||
} else if (projMatrix[5] < 0) { //e.g. PES 2014
|
||||
VR_SetConfig(VR_CONFIG_MIRROR_PITCH, true);
|
||||
VR_SetConfig(VR_CONFIG_MIRROR_YAW, true);
|
||||
VR_SetConfig(VR_CONFIG_MIRROR_ROLL, false);
|
||||
} else { //e.g. Lego Pirates
|
||||
VR_SetConfig(VR_CONFIG_MIRROR_PITCH, false);
|
||||
VR_SetConfig(VR_CONFIG_MIRROR_YAW, true);
|
||||
VR_SetConfig(VR_CONFIG_MIRROR_ROLL, true);
|
||||
}
|
||||
}
|
||||
|
||||
// Set 6DoF scale
|
||||
float scale = 1.0f;
|
||||
if (PSP_CoreParameter().compat.vrCompat().UnitsPerMeter > 0) {
|
||||
scale = PSP_CoreParameter().compat.vrCompat().UnitsPerMeter;
|
||||
VR_SetConfig(VR_CONFIG_HAS_UNIT_SCALE, true);
|
||||
} else {
|
||||
VR_SetConfig(VR_CONFIG_HAS_UNIT_SCALE, false);
|
||||
}
|
||||
VR_SetConfigFloat(VR_CONFIG_6DOF_SCALE, scale);
|
||||
}
|
||||
|
||||
void UpdateVRProjection(float* projMatrix, float* leftEye, float* rightEye) {
|
||||
VR_TweakProjection(projMatrix, leftEye, VR_PROJECTION_MATRIX_LEFT_EYE);
|
||||
VR_TweakProjection(projMatrix, rightEye, VR_PROJECTION_MATRIX_RIGHT_EYE);
|
||||
VR_TweakMirroring(projMatrix);
|
||||
|
||||
// Set 6DoF scale
|
||||
float scale = pow(fabs(projMatrix[14]), 1.15f);
|
||||
if (PSP_CoreParameter().compat.vrCompat().UnitsPerMeter > 0) {
|
||||
scale = PSP_CoreParameter().compat.vrCompat().UnitsPerMeter;
|
||||
VR_SetConfig(VR_CONFIG_6DOF_PRECISE, true);
|
||||
} else {
|
||||
VR_SetConfig(VR_CONFIG_6DOF_PRECISE, false);
|
||||
float* dst[] = {leftEye, rightEye};
|
||||
VRMatrix enums[] = {VR_PROJECTION_MATRIX_LEFT_EYE, VR_PROJECTION_MATRIX_RIGHT_EYE};
|
||||
for (int index = 0; index < 2; index++) {
|
||||
ovrMatrix4f hmdProjection = VR_GetMatrix(enums[index]);
|
||||
for (int i = 0; i < 4; i++) {
|
||||
for (int j = 0; j < 4; j++) {
|
||||
if ((hmdProjection.M[i][j] > 0) != (projMatrix[i * 4 + j] > 0)) {
|
||||
hmdProjection.M[i][j] *= -1.0f;
|
||||
}
|
||||
}
|
||||
}
|
||||
memcpy(dst[index], hmdProjection.M, 16 * sizeof(float));
|
||||
}
|
||||
VR_SetConfig(VR_CONFIG_6DOF_SCALE, (int)(scale * 1000000));
|
||||
}
|
||||
|
||||
void UpdateVRView(float* leftEye, float* rightEye) {
|
||||
VR_TweakView(leftEye, VR_VIEW_MATRIX_LEFT_EYE);
|
||||
VR_TweakView(rightEye, VR_VIEW_MATRIX_RIGHT_EYE);
|
||||
float* dst[] = {leftEye, rightEye};
|
||||
VRMatrix enums[] = {VR_VIEW_MATRIX_LEFT_EYE, VR_VIEW_MATRIX_RIGHT_EYE};
|
||||
for (int index = 0; index < 2; index++) {
|
||||
|
||||
// Get view matrix from the game
|
||||
ovrMatrix4f gameView;
|
||||
memcpy(gameView.M, dst[index], 16 * sizeof(float));
|
||||
|
||||
// Get view matrix from the headset
|
||||
ovrMatrix4f hmdView = VR_GetMatrix(enums[index]);
|
||||
|
||||
// Combine the matrices
|
||||
ovrMatrix4f renderView = ovrMatrix4f_Multiply(&hmdView, &gameView);
|
||||
memcpy(dst[index], renderView.M, 16 * sizeof(float));
|
||||
}
|
||||
}
|
||||
+7
-36
@@ -17,58 +17,29 @@ enum VRCompatFlag {
|
||||
VR_COMPAT_MAX
|
||||
};
|
||||
|
||||
#ifdef OPENXR
|
||||
|
||||
// VR app flow integration
|
||||
bool IsVRBuild();
|
||||
void InitVROnAndroid(void* vm, void* activity, int version, const char* name);
|
||||
void EnterVR(bool firstStart);
|
||||
bool IsVREnabled();
|
||||
void InitVROnAndroid(void* vm, void* activity, const char* system, int version, const char* name);
|
||||
void EnterVR(bool firstStart, void* vulkanContext);
|
||||
void GetVRResolutionPerEye(int* width, int* height);
|
||||
void UpdateVRInput(bool(*NativeKey)(const KeyInput &key), bool(*NativeTouch)(const TouchInput &touch), bool haptics, float dp_xscale, float dp_yscale);
|
||||
void UpdateVRScreenKey(const KeyInput &key);
|
||||
void UpdateVRSpecialKeys(const KeyInput &key);
|
||||
|
||||
// VR games compatibility
|
||||
void PreprocessStepVR(void* step);
|
||||
void SetVRCompat(VRCompatFlag flag, long value);
|
||||
|
||||
// VR rendering integration
|
||||
void BindVRFramebuffer();
|
||||
void* BindVRFramebuffer();
|
||||
bool StartVRRender();
|
||||
void FinishVRRender();
|
||||
void PreVRFrameRender(int fboIndex);
|
||||
void PostVRFrameRender();
|
||||
int GetVRFBOIndex();
|
||||
int GetVRPassesCount();
|
||||
bool IsMultiviewSupported();
|
||||
bool IsFlatVRScene();
|
||||
bool Is2DVRObject(float* projMatrix, bool ortho);
|
||||
void UpdateVRParams(float* projMatrix);
|
||||
void UpdateVRProjection(float* projMatrix, float* leftEye, float* rightEye);
|
||||
void UpdateVRView(float* leftEye, float* rightEye);
|
||||
|
||||
#else //dummy integration
|
||||
|
||||
// VR app flow integration
|
||||
inline bool IsVRBuild() { return false; }
|
||||
inline void InitVROnAndroid(void* vm, void* activity, int version, const char* name) {}
|
||||
inline void EnterVR(bool firstTime) {}
|
||||
inline void GetVRResolutionPerEye(int* width, int* height) {}
|
||||
inline void UpdateVRInput(bool(*NativeKey)(const KeyInput &key), bool(*NativeTouch)(const TouchInput &touch), bool haptics, float dp_xscale, float dp_yscale) {}
|
||||
inline void UpdateVRScreenKey(const KeyInput &key) {}
|
||||
|
||||
// VR games compatibility
|
||||
inline void PreprocessStepVR(void* step) {}
|
||||
inline void SetVRCompat(VRCompatFlag flag, long value) {}
|
||||
|
||||
// VR rendering integration
|
||||
inline void BindVRFramebuffer() {}
|
||||
inline bool StartVRRender() { return false; }
|
||||
inline void FinishVRRender() {}
|
||||
inline void PreVRFrameRender(int fboIndex) {}
|
||||
inline void PostVRFrameRender() {}
|
||||
inline int GetVRFBOIndex() { return 0; }
|
||||
inline bool IsMultiviewSupported() { return false; }
|
||||
inline bool IsFlatVRScene() { return true; }
|
||||
inline bool Is2DVRObject(float* projMatrix, bool ortho) { return false; }
|
||||
inline void UpdateVRProjection(float* projMatrix, float* leftEye, float* rightEye) {}
|
||||
inline void UpdateVRView(float* leftEye, float* rightEye) {}
|
||||
|
||||
#endif
|
||||
+132
-78
@@ -3,9 +3,12 @@
|
||||
#include <assert.h>
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
#include <vector>
|
||||
|
||||
#ifndef _WIN32
|
||||
#include <unistd.h>
|
||||
#endif
|
||||
|
||||
#ifdef OPENXR_PLATFORM_PICO
|
||||
enum ConfigsSetEXT {
|
||||
UNREAL_VERSION = 0,
|
||||
TRACKING_ORIGIN,
|
||||
@@ -27,80 +30,95 @@ enum PxrTrackingDof {
|
||||
typedef XrResult (XRAPI_PTR *PFN_xrSetEngineVersionPico)(XrInstance instance,const char* version);
|
||||
typedef XrResult (XRAPI_PTR *PFN_xrStartCVControllerThreadPico)(XrInstance instance,int headSensorState, int handSensorState);
|
||||
typedef XrResult (XRAPI_PTR *PFN_xrStopCVControllerThreadPico)(XrInstance instance,int headSensorState, int handSensorState);
|
||||
typedef XrResult (XRAPI_PTR *PFN_xrSetConfigPICO) (XrSession instance, enum ConfigsSetEXT configIndex, char* configData);
|
||||
typedef XrResult (XRAPI_PTR *PFN_xrSetConfigPICO) (XrSession instance, enum ConfigsSetEXT configIndex, const char *configData);
|
||||
|
||||
PFN_xrSetConfigPICO pfnXrSetConfigPICO = nullptr;
|
||||
PFN_xrSetEngineVersionPico pfnXrSetEngineVersionPico = nullptr;
|
||||
PFN_xrStartCVControllerThreadPico pfnXrStartCVControllerThreadPico = nullptr;
|
||||
PFN_xrStopCVControllerThreadPico pfnXrStopCVControllerThreadPico = nullptr;
|
||||
#endif
|
||||
|
||||
static bool vr_platform[VR_PLATFORM_MAX];
|
||||
static engine_t vr_engine;
|
||||
int vr_initialized = 0;
|
||||
|
||||
const char* const requiredExtensionNames[] = {
|
||||
XR_KHR_OPENGL_ES_ENABLE_EXTENSION_NAME,
|
||||
#ifdef OPENXR_HAS_PERFORMANCE_EXTENSION
|
||||
XR_EXT_PERFORMANCE_SETTINGS_EXTENSION_NAME,
|
||||
XR_KHR_ANDROID_THREAD_SETTINGS_EXTENSION_NAME,
|
||||
#endif
|
||||
#ifdef OPENXR_PLATFORM_PICO
|
||||
XR_KHR_ANDROID_CREATE_INSTANCE_EXTENSION_NAME,
|
||||
"XR_PICO_android_controller_function_ext_enable",
|
||||
"XR_PICO_view_state_ext_enable",
|
||||
"XR_PICO_frame_end_info_ext",
|
||||
"XR_PICO_configs_ext",
|
||||
"XR_PICO_reset_sensor",
|
||||
#endif
|
||||
XR_KHR_COMPOSITION_LAYER_CYLINDER_EXTENSION_NAME};
|
||||
const uint32_t numRequiredExtensions =
|
||||
sizeof(requiredExtensionNames) / sizeof(requiredExtensionNames[0]);
|
||||
|
||||
void VR_Init( ovrJava java ) {
|
||||
void VR_Init( void* system, const char* name, int version ) {
|
||||
if (vr_initialized)
|
||||
return;
|
||||
|
||||
if (!XRLoad()) {
|
||||
return;
|
||||
}
|
||||
|
||||
ovrApp_Clear(&vr_engine.appState);
|
||||
|
||||
#ifdef ANDROID
|
||||
PFN_xrInitializeLoaderKHR xrInitializeLoaderKHR;
|
||||
xrGetInstanceProcAddr(
|
||||
XR_NULL_HANDLE, "xrInitializeLoaderKHR", (PFN_xrVoidFunction*)&xrInitializeLoaderKHR);
|
||||
xrGetInstanceProcAddr(XR_NULL_HANDLE, "xrInitializeLoaderKHR", (PFN_xrVoidFunction*)&xrInitializeLoaderKHR);
|
||||
if (xrInitializeLoaderKHR != NULL) {
|
||||
XrLoaderInitInfoAndroidKHR loaderInitializeInfoAndroid;
|
||||
memset(&loaderInitializeInfoAndroid, 0, sizeof(loaderInitializeInfoAndroid));
|
||||
loaderInitializeInfoAndroid.type = XR_TYPE_LOADER_INIT_INFO_ANDROID_KHR;
|
||||
loaderInitializeInfoAndroid.next = NULL;
|
||||
loaderInitializeInfoAndroid.applicationVM = java.Vm;
|
||||
loaderInitializeInfoAndroid.applicationContext = java.ActivityObject;
|
||||
xrInitializeLoaderKHR((XrLoaderInitInfoBaseHeaderKHR*)&loaderInitializeInfoAndroid);
|
||||
ovrJava* java = (ovrJava*)system;
|
||||
XrLoaderInitInfoAndroidKHR loaderInitializeInfo;
|
||||
memset(&loaderInitializeInfo, 0, sizeof(loaderInitializeInfo));
|
||||
loaderInitializeInfo.type = XR_TYPE_LOADER_INIT_INFO_ANDROID_KHR;
|
||||
loaderInitializeInfo.next = NULL;
|
||||
loaderInitializeInfo.applicationVM = java->Vm;
|
||||
loaderInitializeInfo.applicationContext = java->ActivityObject;
|
||||
xrInitializeLoaderKHR((XrLoaderInitInfoBaseHeaderKHR*)&loaderInitializeInfo);
|
||||
}
|
||||
#endif
|
||||
|
||||
std::vector<const char *> extensions;
|
||||
if (VR_GetPlatformFlag(VR_PLATFORM_RENDERER_VULKAN)) {
|
||||
extensions.push_back(XR_KHR_VULKAN_ENABLE_EXTENSION_NAME);
|
||||
} else {
|
||||
#ifdef XR_USE_GRAPHICS_API_OPENGL_ES
|
||||
extensions.push_back(XR_KHR_OPENGL_ES_ENABLE_EXTENSION_NAME);
|
||||
#endif
|
||||
}
|
||||
extensions.push_back(XR_KHR_COMPOSITION_LAYER_CYLINDER_EXTENSION_NAME);
|
||||
#ifdef ANDROID
|
||||
if (VR_GetPlatformFlag(VR_PLATFORM_PERFORMANCE_EXT)) {
|
||||
extensions.push_back(XR_EXT_PERFORMANCE_SETTINGS_EXTENSION_NAME);
|
||||
extensions.push_back(XR_KHR_ANDROID_THREAD_SETTINGS_EXTENSION_NAME);
|
||||
}
|
||||
if (VR_GetPlatformFlag(VR_PLATFORM_PICO_INIT)) {
|
||||
extensions.push_back(XR_KHR_ANDROID_CREATE_INSTANCE_EXTENSION_NAME);
|
||||
extensions.push_back("XR_PICO_android_controller_function_ext_enable");
|
||||
extensions.push_back("XR_PICO_view_state_ext_enable");
|
||||
extensions.push_back("XR_PICO_frame_end_info_ext");
|
||||
extensions.push_back("XR_PICO_configs_ext");
|
||||
extensions.push_back("XR_PICO_reset_sensor");
|
||||
}
|
||||
#endif
|
||||
|
||||
// Create the OpenXR instance.
|
||||
XrApplicationInfo appInfo;
|
||||
memset(&appInfo, 0, sizeof(appInfo));
|
||||
strcpy(appInfo.applicationName, java.AppName);
|
||||
strcpy(appInfo.engineName, java.AppName);
|
||||
appInfo.applicationVersion = java.AppVersion;
|
||||
appInfo.engineVersion = java.AppVersion;
|
||||
strcpy(appInfo.applicationName, name);
|
||||
strcpy(appInfo.engineName, name);
|
||||
appInfo.applicationVersion = version;
|
||||
appInfo.engineVersion = version;
|
||||
appInfo.apiVersion = XR_CURRENT_API_VERSION;
|
||||
|
||||
XrInstanceCreateInfo instanceCreateInfo;
|
||||
memset(&instanceCreateInfo, 0, sizeof(instanceCreateInfo));
|
||||
instanceCreateInfo.type = XR_TYPE_INSTANCE_CREATE_INFO;
|
||||
#ifdef OPENXR_PLATFORM_PICO
|
||||
XrInstanceCreateInfoAndroidKHR instanceCreateInfoAndroid = {XR_TYPE_INSTANCE_CREATE_INFO_ANDROID_KHR};
|
||||
instanceCreateInfoAndroid.applicationVM = java.Vm;
|
||||
instanceCreateInfoAndroid.applicationActivity = java.ActivityObject;
|
||||
instanceCreateInfo.next = (XrBaseInStructure*)&instanceCreateInfoAndroid;
|
||||
#else
|
||||
instanceCreateInfo.next = NULL;
|
||||
#endif
|
||||
instanceCreateInfo.createFlags = 0;
|
||||
instanceCreateInfo.applicationInfo = appInfo;
|
||||
instanceCreateInfo.enabledApiLayerCount = 0;
|
||||
instanceCreateInfo.enabledApiLayerNames = NULL;
|
||||
instanceCreateInfo.enabledExtensionCount = numRequiredExtensions;
|
||||
instanceCreateInfo.enabledExtensionNames = requiredExtensionNames;
|
||||
instanceCreateInfo.enabledExtensionCount = (uint32_t)extensions.size();
|
||||
instanceCreateInfo.enabledExtensionNames = extensions.data();
|
||||
|
||||
#ifdef ANDROID
|
||||
XrInstanceCreateInfoAndroidKHR instanceCreateInfoAndroid = {XR_TYPE_INSTANCE_CREATE_INFO_ANDROID_KHR};
|
||||
if (VR_GetPlatformFlag(VR_PLATFORM_PICO_INIT)) {
|
||||
ovrJava* java = (ovrJava*)system;
|
||||
instanceCreateInfoAndroid.applicationVM = java->Vm;
|
||||
instanceCreateInfoAndroid.applicationActivity = java->ActivityObject;
|
||||
instanceCreateInfo.next = (XrBaseInStructure*)&instanceCreateInfoAndroid;
|
||||
}
|
||||
#endif
|
||||
|
||||
XrResult initResult;
|
||||
OXR(initResult = xrCreateInstance(&instanceCreateInfo, &vr_engine.appState.Instance));
|
||||
@@ -109,14 +127,16 @@ void VR_Init( ovrJava java ) {
|
||||
exit(1);
|
||||
}
|
||||
|
||||
#ifdef OPENXR_PLATFORM_PICO
|
||||
xrGetInstanceProcAddr(vr_engine.appState.Instance, "xrSetEngineVersionPico", (PFN_xrVoidFunction*)(&pfnXrSetEngineVersionPico));
|
||||
xrGetInstanceProcAddr(vr_engine.appState.Instance, "xrStartCVControllerThreadPico", (PFN_xrVoidFunction*)(&pfnXrStartCVControllerThreadPico));
|
||||
xrGetInstanceProcAddr(vr_engine.appState.Instance, "xrStopCVControllerThreadPico", (PFN_xrVoidFunction*)(&pfnXrStopCVControllerThreadPico));
|
||||
xrGetInstanceProcAddr(vr_engine.appState.Instance,"xrSetConfigPICO", (PFN_xrVoidFunction*)(&pfnXrSetConfigPICO));
|
||||
if (pfnXrSetEngineVersionPico != nullptr) pfnXrSetEngineVersionPico(vr_engine.appState.Instance, "2.8.0.1");
|
||||
if (pfnXrStartCVControllerThreadPico != nullptr) pfnXrStartCVControllerThreadPico(vr_engine.appState.Instance, PXR_TRACKING_6DOF, PXR_TRACKING_6DOF);
|
||||
#endif
|
||||
XRLoadInstanceFunctions(vr_engine.appState.Instance);
|
||||
|
||||
if (VR_GetPlatformFlag(VR_PLATFORM_PICO_INIT)) {
|
||||
xrGetInstanceProcAddr(vr_engine.appState.Instance, "xrSetEngineVersionPico", (PFN_xrVoidFunction*)(&pfnXrSetEngineVersionPico));
|
||||
xrGetInstanceProcAddr(vr_engine.appState.Instance, "xrStartCVControllerThreadPico", (PFN_xrVoidFunction*)(&pfnXrStartCVControllerThreadPico));
|
||||
xrGetInstanceProcAddr(vr_engine.appState.Instance, "xrStopCVControllerThreadPico", (PFN_xrVoidFunction*)(&pfnXrStopCVControllerThreadPico));
|
||||
xrGetInstanceProcAddr(vr_engine.appState.Instance,"xrSetConfigPICO", (PFN_xrVoidFunction*)(&pfnXrSetConfigPICO));
|
||||
if (pfnXrSetEngineVersionPico != nullptr) pfnXrSetEngineVersionPico(vr_engine.appState.Instance, "2.8.0.1");
|
||||
if (pfnXrStartCVControllerThreadPico != nullptr) pfnXrStartCVControllerThreadPico(vr_engine.appState.Instance, PXR_TRACKING_6DOF, PXR_TRACKING_6DOF);
|
||||
}
|
||||
|
||||
XrInstanceProperties instanceInfo;
|
||||
instanceInfo.type = XR_TYPE_INSTANCE_PROPERTIES;
|
||||
@@ -143,36 +163,51 @@ void VR_Init( ovrJava java ) {
|
||||
}
|
||||
|
||||
// Get the graphics requirements.
|
||||
PFN_xrGetOpenGLESGraphicsRequirementsKHR pfnGetOpenGLESGraphicsRequirementsKHR = NULL;
|
||||
OXR(xrGetInstanceProcAddr(
|
||||
vr_engine.appState.Instance,
|
||||
"xrGetOpenGLESGraphicsRequirementsKHR",
|
||||
(PFN_xrVoidFunction*)(&pfnGetOpenGLESGraphicsRequirementsKHR)));
|
||||
if (VR_GetPlatformFlag(VR_PLATFORM_RENDERER_VULKAN)) {
|
||||
PFN_xrGetVulkanGraphicsRequirementsKHR pfnGetVulkanGraphicsRequirementsKHR = NULL;
|
||||
OXR(xrGetInstanceProcAddr(
|
||||
vr_engine.appState.Instance,
|
||||
"xrGetVulkanGraphicsRequirementsKHR",
|
||||
(PFN_xrVoidFunction*)(&pfnGetVulkanGraphicsRequirementsKHR)));
|
||||
|
||||
XrGraphicsRequirementsOpenGLESKHR graphicsRequirements = {};
|
||||
graphicsRequirements.type = XR_TYPE_GRAPHICS_REQUIREMENTS_OPENGL_ES_KHR;
|
||||
OXR(pfnGetOpenGLESGraphicsRequirementsKHR(vr_engine.appState.Instance, systemId, &graphicsRequirements));
|
||||
XrGraphicsRequirementsVulkanKHR graphicsRequirements = {};
|
||||
graphicsRequirements.type = XR_TYPE_GRAPHICS_REQUIREMENTS_VULKAN_KHR;
|
||||
OXR(pfnGetVulkanGraphicsRequirementsKHR(vr_engine.appState.Instance, systemId, &graphicsRequirements));
|
||||
} else {
|
||||
#ifdef XR_USE_GRAPHICS_API_OPENGL_ES
|
||||
PFN_xrGetOpenGLESGraphicsRequirementsKHR pfnGetOpenGLESGraphicsRequirementsKHR = NULL;
|
||||
OXR(xrGetInstanceProcAddr(
|
||||
vr_engine.appState.Instance,
|
||||
"xrGetOpenGLESGraphicsRequirementsKHR",
|
||||
(PFN_xrVoidFunction*)(&pfnGetOpenGLESGraphicsRequirementsKHR)));
|
||||
|
||||
XrGraphicsRequirementsOpenGLESKHR graphicsRequirements = {};
|
||||
graphicsRequirements.type = XR_TYPE_GRAPHICS_REQUIREMENTS_OPENGL_ES_KHR;
|
||||
OXR(pfnGetOpenGLESGraphicsRequirementsKHR(vr_engine.appState.Instance, systemId, &graphicsRequirements));
|
||||
#endif
|
||||
}
|
||||
|
||||
#ifdef ANDROID
|
||||
vr_engine.appState.MainThreadTid = gettid();
|
||||
#endif
|
||||
vr_engine.appState.SystemId = systemId;
|
||||
|
||||
vr_engine.java = java;
|
||||
vr_initialized = 1;
|
||||
}
|
||||
|
||||
void VR_Destroy( engine_t* engine ) {
|
||||
if (engine == &vr_engine) {
|
||||
#ifdef OPENXR_PLATFORM_PICO
|
||||
if (pfnXrStopCVControllerThreadPico != nullptr) {
|
||||
pfnXrStopCVControllerThreadPico(engine->appState.Instance, PXR_TRACKING_6DOF, PXR_TRACKING_6DOF);
|
||||
if (VR_GetPlatformFlag(VR_PLATFORM_PICO_INIT)) {
|
||||
if (pfnXrStopCVControllerThreadPico != nullptr) {
|
||||
pfnXrStopCVControllerThreadPico(engine->appState.Instance, PXR_TRACKING_6DOF, PXR_TRACKING_6DOF);
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
xrDestroyInstance(engine->appState.Instance);
|
||||
ovrApp_Destroy(&engine->appState);
|
||||
}
|
||||
}
|
||||
|
||||
void VR_EnterVR( engine_t* engine ) {
|
||||
void VR_EnterVR( engine_t* engine, XrGraphicsBindingVulkanKHR* graphicsBindingVulkan ) {
|
||||
|
||||
if (engine->appState.Session) {
|
||||
ALOGE("VR_EnterVR called with existing session");
|
||||
@@ -180,17 +215,28 @@ void VR_EnterVR( engine_t* engine ) {
|
||||
}
|
||||
|
||||
// Create the OpenXR Session.
|
||||
XrGraphicsBindingOpenGLESAndroidKHR graphicsBindingAndroidGLES = {};
|
||||
graphicsBindingAndroidGLES.type = XR_TYPE_GRAPHICS_BINDING_OPENGL_ES_ANDROID_KHR;
|
||||
graphicsBindingAndroidGLES.next = NULL;
|
||||
graphicsBindingAndroidGLES.display = eglGetCurrentDisplay();
|
||||
graphicsBindingAndroidGLES.config = eglGetCurrentSurface(EGL_DRAW);
|
||||
graphicsBindingAndroidGLES.context = eglGetCurrentContext();
|
||||
|
||||
XrSessionCreateInfo sessionCreateInfo = {};
|
||||
#ifdef ANDROID
|
||||
XrGraphicsBindingOpenGLESAndroidKHR graphicsBindingGL = {};
|
||||
#elif XR_USE_GRAPHICS_API_OPENGL
|
||||
XrGraphicsBindingOpenGLWin32KHR graphicsBindingGL = {};
|
||||
#endif
|
||||
memset(&sessionCreateInfo, 0, sizeof(sessionCreateInfo));
|
||||
if (VR_GetPlatformFlag(VR_PLATFORM_RENDERER_VULKAN)) {
|
||||
sessionCreateInfo.next = graphicsBindingVulkan;
|
||||
} else {
|
||||
#ifdef ANDROID
|
||||
graphicsBindingGL.type = XR_TYPE_GRAPHICS_BINDING_OPENGL_ES_ANDROID_KHR;
|
||||
graphicsBindingGL.next = NULL;
|
||||
graphicsBindingGL.display = eglGetCurrentDisplay();
|
||||
graphicsBindingGL.config = eglGetCurrentSurface(EGL_DRAW);
|
||||
graphicsBindingGL.context = eglGetCurrentContext();
|
||||
sessionCreateInfo.next = &graphicsBindingGL;
|
||||
#else
|
||||
//TODO:PCVR definition
|
||||
#endif
|
||||
}
|
||||
sessionCreateInfo.type = XR_TYPE_SESSION_CREATE_INFO;
|
||||
sessionCreateInfo.next = &graphicsBindingAndroidGLES;
|
||||
sessionCreateInfo.createFlags = 0;
|
||||
sessionCreateInfo.systemId = engine->appState.SystemId;
|
||||
|
||||
@@ -200,9 +246,9 @@ void VR_EnterVR( engine_t* engine ) {
|
||||
ALOGE("Failed to create XR session: %d.", initResult);
|
||||
exit(1);
|
||||
}
|
||||
#ifdef OPENXR_PLATFORM_PICO
|
||||
pfnXrSetConfigPICO(engine->appState.Session, TRACKING_ORIGIN, "1");
|
||||
#endif
|
||||
if (VR_GetPlatformFlag(VR_PLATFORM_PICO_INIT)) {
|
||||
pfnXrSetConfigPICO(engine->appState.Session, TRACKING_ORIGIN, "1");
|
||||
}
|
||||
|
||||
// Create a space to the first path
|
||||
XrReferenceSpaceCreateInfo spaceCreateInfo = {};
|
||||
@@ -229,3 +275,11 @@ void VR_LeaveVR( engine_t* engine ) {
|
||||
engine_t* VR_GetEngine( void ) {
|
||||
return &vr_engine;
|
||||
}
|
||||
|
||||
bool VR_GetPlatformFlag(VRPlatformFlag flag) {
|
||||
return vr_platform[flag];
|
||||
}
|
||||
|
||||
void VR_SetPlatformFLag(VRPlatformFlag flag, bool value) {
|
||||
vr_platform[flag] = value;
|
||||
}
|
||||
+38
-24
@@ -5,23 +5,24 @@
|
||||
#define ALOGE(...) __android_log_print(ANDROID_LOG_ERROR, "OpenXR", __VA_ARGS__);
|
||||
#define ALOGV(...) __android_log_print(ANDROID_LOG_VERBOSE, "OpenXR", __VA_ARGS__);
|
||||
#else
|
||||
#include <cstdio>
|
||||
#define ALOGE(...) printf(__VA_ARGS__)
|
||||
#define ALOGV(...) printf(__VA_ARGS__)
|
||||
#endif
|
||||
|
||||
//OpenXR
|
||||
#define XR_USE_PLATFORM_ANDROID 1
|
||||
#define XR_USE_GRAPHICS_API_OPENGL_ES 1
|
||||
#include <EGL/egl.h>
|
||||
#include <EGL/eglext.h>
|
||||
#include <jni.h>
|
||||
#include <math.h>
|
||||
#include <openxr.h>
|
||||
#include <openxr_platform.h>
|
||||
#include "Common/VR/OpenXRLoader.h"
|
||||
|
||||
#define _USE_MATH_DEFINES
|
||||
#include <cmath>
|
||||
|
||||
#ifdef ANDROID
|
||||
|
||||
#include <GLES3/gl3.h>
|
||||
#include <GLES3/gl3ext.h>
|
||||
|
||||
#ifdef _DEBUG
|
||||
#endif
|
||||
|
||||
#if defined(_DEBUG) && defined(ANDROID)
|
||||
static const char* GlErrorString(GLenum error) {
|
||||
switch (error) {
|
||||
case GL_NO_ERROR:
|
||||
@@ -73,11 +74,7 @@ static void OXR_CheckErrors(XrInstance instance, XrResult result, const char* fu
|
||||
#define OXR(func) func;
|
||||
#endif
|
||||
|
||||
#ifdef OPENXR_PLATFORM_QUEST
|
||||
#define OPENXR_HAS_PERFORMANCE_EXTENSION
|
||||
#endif
|
||||
|
||||
enum { ovrMaxLayerCount = 1 };
|
||||
enum { ovrMaxLayerCount = 2 };
|
||||
enum { ovrMaxNumEyes = 2 };
|
||||
|
||||
typedef union {
|
||||
@@ -98,10 +95,15 @@ typedef struct {
|
||||
uint32_t TextureSwapChainIndex;
|
||||
ovrSwapChain ColorSwapChain;
|
||||
ovrSwapChain DepthSwapChain;
|
||||
XrSwapchainImageOpenGLESKHR* ColorSwapChainImage;
|
||||
XrSwapchainImageOpenGLESKHR* DepthSwapChainImage;
|
||||
unsigned int* FrameBuffers;
|
||||
void* ColorSwapChainImage;
|
||||
void* DepthSwapChainImage;
|
||||
unsigned int* GLFrameBuffers;
|
||||
VkFramebuffer* VKFrameBuffers;
|
||||
VkImageView* VKColorImages;
|
||||
VkImageView* VKDepthImages;
|
||||
|
||||
bool Acquired;
|
||||
XrGraphicsBindingVulkanKHR* VKContext;
|
||||
} ovrFramebuffer;
|
||||
|
||||
typedef struct {
|
||||
@@ -133,27 +135,39 @@ typedef struct {
|
||||
ovrRenderer Renderer;
|
||||
} ovrApp;
|
||||
|
||||
#ifdef ANDROID
|
||||
typedef struct {
|
||||
JavaVM* Vm;
|
||||
jobject ActivityObject;
|
||||
JNIEnv* Env;
|
||||
char AppName[64];
|
||||
int AppVersion;
|
||||
} ovrJava;
|
||||
#endif
|
||||
|
||||
typedef struct {
|
||||
uint64_t frameIndex;
|
||||
ovrApp appState;
|
||||
ovrJava java;
|
||||
float predictedDisplayTime;
|
||||
XrTime predictedDisplayTime;
|
||||
XrGraphicsBindingVulkanKHR graphicsBindingVulkan;
|
||||
} engine_t;
|
||||
|
||||
void VR_Init( ovrJava java );
|
||||
enum VRPlatformFlag {
|
||||
VR_PLATFORM_CONTROLLER_PICO,
|
||||
VR_PLATFORM_CONTROLLER_QUEST,
|
||||
VR_PLATFORM_PERFORMANCE_EXT,
|
||||
VR_PLATFORM_PICO_INIT,
|
||||
VR_PLATFORM_RENDERER_VULKAN,
|
||||
VR_PLATFORM_TRACKING_FLOOR,
|
||||
VR_PLATFORM_MAX
|
||||
};
|
||||
|
||||
void VR_Init( void* system, const char* name, int version );
|
||||
void VR_Destroy( engine_t* engine );
|
||||
void VR_EnterVR( engine_t* engine );
|
||||
void VR_EnterVR( engine_t* engine, XrGraphicsBindingVulkanKHR* graphicsBindingVulkan );
|
||||
void VR_LeaveVR( engine_t* engine );
|
||||
|
||||
engine_t* VR_GetEngine( void );
|
||||
bool VR_GetPlatformFlag(VRPlatformFlag flag);
|
||||
void VR_SetPlatformFLag(VRPlatformFlag flag, bool value);
|
||||
|
||||
void ovrApp_Clear(ovrApp* app);
|
||||
void ovrApp_Destroy(ovrApp* app);
|
||||
|
||||
+217
-47
@@ -1,16 +1,16 @@
|
||||
#include "VRFramebuffer.h"
|
||||
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <stdbool.h>
|
||||
#include <string.h>
|
||||
#include <math.h>
|
||||
#include <time.h>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstdbool>
|
||||
#include <cstring>
|
||||
#include <cmath>
|
||||
#include <ctime>
|
||||
#include <cassert>
|
||||
|
||||
#if !defined(_WIN32)
|
||||
#include <pthread.h>
|
||||
#include <sys/prctl.h>
|
||||
#include <assert.h>
|
||||
#include <GLES3/gl3.h>
|
||||
#include <GLES3/gl3ext.h>
|
||||
#endif
|
||||
|
||||
double FromXrTime(const XrTime time) {
|
||||
return (time * 1e-9);
|
||||
@@ -39,11 +39,13 @@ void ovrFramebuffer_Clear(ovrFramebuffer* frameBuffer) {
|
||||
frameBuffer->DepthSwapChain.Height = 0;
|
||||
frameBuffer->DepthSwapChainImage = NULL;
|
||||
|
||||
frameBuffer->FrameBuffers = NULL;
|
||||
frameBuffer->GLFrameBuffers = NULL;
|
||||
frameBuffer->Acquired = false;
|
||||
}
|
||||
|
||||
bool ovrFramebuffer_Create(XrSession session, ovrFramebuffer* frameBuffer, int width, int height, bool multiview) {
|
||||
#if XR_USE_GRAPHICS_API_OPENGL_ES
|
||||
|
||||
static bool ovrFramebuffer_CreateGLES(XrSession session, ovrFramebuffer* frameBuffer, int width, int height, bool multiview) {
|
||||
|
||||
frameBuffer->Width = width;
|
||||
frameBuffer->Height = height;
|
||||
@@ -54,12 +56,11 @@ bool ovrFramebuffer_Create(XrSession session, ovrFramebuffer* frameBuffer, int w
|
||||
}
|
||||
|
||||
typedef void (*PFNGLFRAMEBUFFERTEXTUREMULTIVIEWOVR)(GLenum, GLenum, GLuint, GLint, GLint, GLsizei);
|
||||
auto glFramebufferTextureMultiviewOVR = (PFNGLFRAMEBUFFERTEXTUREMULTIVIEWOVR)eglGetProcAddress ("glFramebufferTextureMultiviewOVR");
|
||||
if (!glFramebufferTextureMultiviewOVR)
|
||||
{
|
||||
PFNGLFRAMEBUFFERTEXTUREMULTIVIEWOVR glFramebufferTextureMultiviewOVR = nullptr;
|
||||
glFramebufferTextureMultiviewOVR = (PFNGLFRAMEBUFFERTEXTUREMULTIVIEWOVR)eglGetProcAddress ("glFramebufferTextureMultiviewOVR");
|
||||
if (!glFramebufferTextureMultiviewOVR) {
|
||||
ALOGE("Can not get proc address for glFramebufferTextureMultiviewOVR.\n");
|
||||
}
|
||||
|
||||
XrSwapchainCreateInfo swapChainCreateInfo;
|
||||
memset(&swapChainCreateInfo, 0, sizeof(swapChainCreateInfo));
|
||||
swapChainCreateInfo.type = XR_TYPE_SWAPCHAIN_CREATE_INFO;
|
||||
@@ -80,20 +81,20 @@ bool ovrFramebuffer_Create(XrSession session, ovrFramebuffer* frameBuffer, int w
|
||||
swapChainCreateInfo.usageFlags = XR_SWAPCHAIN_USAGE_COLOR_ATTACHMENT_BIT;
|
||||
OXR(xrCreateSwapchain(session, &swapChainCreateInfo, &frameBuffer->ColorSwapChain.Handle));
|
||||
OXR(xrEnumerateSwapchainImages(frameBuffer->ColorSwapChain.Handle, 0, &frameBuffer->TextureSwapChainLength, NULL));
|
||||
frameBuffer->ColorSwapChainImage = (XrSwapchainImageOpenGLESKHR*)malloc(frameBuffer->TextureSwapChainLength * sizeof(XrSwapchainImageOpenGLESKHR));
|
||||
frameBuffer->ColorSwapChainImage = malloc(frameBuffer->TextureSwapChainLength * sizeof(XrSwapchainImageOpenGLESKHR));
|
||||
|
||||
// Create the depth swapchain.
|
||||
swapChainCreateInfo.format = GL_DEPTH24_STENCIL8;
|
||||
swapChainCreateInfo.usageFlags = XR_SWAPCHAIN_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT;
|
||||
OXR(xrCreateSwapchain(session, &swapChainCreateInfo, &frameBuffer->DepthSwapChain.Handle));
|
||||
frameBuffer->DepthSwapChainImage = (XrSwapchainImageOpenGLESKHR*)malloc(frameBuffer->TextureSwapChainLength * sizeof(XrSwapchainImageOpenGLESKHR));
|
||||
frameBuffer->DepthSwapChainImage = malloc(frameBuffer->TextureSwapChainLength * sizeof(XrSwapchainImageOpenGLESKHR));
|
||||
|
||||
// Populate the swapchain image array.
|
||||
for (uint32_t i = 0; i < frameBuffer->TextureSwapChainLength; i++) {
|
||||
frameBuffer->ColorSwapChainImage[i].type = XR_TYPE_SWAPCHAIN_IMAGE_OPENGL_ES_KHR;
|
||||
frameBuffer->ColorSwapChainImage[i].next = NULL;
|
||||
frameBuffer->DepthSwapChainImage[i].type = XR_TYPE_SWAPCHAIN_IMAGE_OPENGL_ES_KHR;
|
||||
frameBuffer->DepthSwapChainImage[i].next = NULL;
|
||||
((XrSwapchainImageOpenGLESKHR*)frameBuffer->ColorSwapChainImage)[i].type = XR_TYPE_SWAPCHAIN_IMAGE_OPENGL_ES_KHR;
|
||||
((XrSwapchainImageOpenGLESKHR*)frameBuffer->ColorSwapChainImage)[i].next = NULL;
|
||||
((XrSwapchainImageOpenGLESKHR*)frameBuffer->DepthSwapChainImage)[i].type = XR_TYPE_SWAPCHAIN_IMAGE_OPENGL_ES_KHR;
|
||||
((XrSwapchainImageOpenGLESKHR*)frameBuffer->DepthSwapChainImage)[i].next = NULL;
|
||||
}
|
||||
OXR(xrEnumerateSwapchainImages(
|
||||
frameBuffer->ColorSwapChain.Handle,
|
||||
@@ -106,14 +107,14 @@ bool ovrFramebuffer_Create(XrSession session, ovrFramebuffer* frameBuffer, int w
|
||||
&frameBuffer->TextureSwapChainLength,
|
||||
(XrSwapchainImageBaseHeader*)frameBuffer->DepthSwapChainImage));
|
||||
|
||||
frameBuffer->FrameBuffers = (GLuint*)malloc(frameBuffer->TextureSwapChainLength * sizeof(GLuint));
|
||||
frameBuffer->GLFrameBuffers = (GLuint*)malloc(frameBuffer->TextureSwapChainLength * sizeof(GLuint));
|
||||
for (uint32_t i = 0; i < frameBuffer->TextureSwapChainLength; i++) {
|
||||
const GLuint colorTexture = frameBuffer->ColorSwapChainImage[i].image;
|
||||
const GLuint depthTexture = frameBuffer->DepthSwapChainImage[i].image;
|
||||
const GLuint colorTexture = ((XrSwapchainImageOpenGLESKHR*)frameBuffer->ColorSwapChainImage)[i].image;
|
||||
const GLuint depthTexture = ((XrSwapchainImageOpenGLESKHR*)frameBuffer->DepthSwapChainImage)[i].image;
|
||||
|
||||
// Create the frame buffer.
|
||||
GL(glGenFramebuffers(1, &frameBuffer->FrameBuffers[i]));
|
||||
GL(glBindFramebuffer(GL_DRAW_FRAMEBUFFER, frameBuffer->FrameBuffers[i]));
|
||||
GL(glGenFramebuffers(1, &frameBuffer->GLFrameBuffers[i]));
|
||||
GL(glBindFramebuffer(GL_DRAW_FRAMEBUFFER, frameBuffer->GLFrameBuffers[i]));
|
||||
if (multiview) {
|
||||
GL(glFramebufferTextureMultiviewOVR(GL_DRAW_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, depthTexture, 0, 0, 2));
|
||||
GL(glFramebufferTextureMultiviewOVR(GL_DRAW_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, depthTexture, 0, 0, 2));
|
||||
@@ -134,29 +135,148 @@ bool ovrFramebuffer_Create(XrSession session, ovrFramebuffer* frameBuffer, int w
|
||||
return true;
|
||||
}
|
||||
|
||||
#endif
|
||||
|
||||
#if XR_USE_GRAPHICS_API_VULKAN
|
||||
|
||||
static bool ovrFramebuffer_CreateVK(XrSession session, ovrFramebuffer* frameBuffer, int width, int height,
|
||||
bool multiview, void* context) {
|
||||
|
||||
frameBuffer->Width = width;
|
||||
frameBuffer->Height = height;
|
||||
frameBuffer->VKContext = (XrGraphicsBindingVulkanKHR*)context;
|
||||
|
||||
XrSwapchainCreateInfo swapChainCreateInfo;
|
||||
memset(&swapChainCreateInfo, 0, sizeof(swapChainCreateInfo));
|
||||
swapChainCreateInfo.type = XR_TYPE_SWAPCHAIN_CREATE_INFO;
|
||||
swapChainCreateInfo.sampleCount = 1;
|
||||
swapChainCreateInfo.width = width;
|
||||
swapChainCreateInfo.height = height;
|
||||
swapChainCreateInfo.faceCount = 1;
|
||||
swapChainCreateInfo.mipCount = 1;
|
||||
swapChainCreateInfo.arraySize = multiview ? 2 : 1;
|
||||
|
||||
frameBuffer->ColorSwapChain.Width = swapChainCreateInfo.width;
|
||||
frameBuffer->ColorSwapChain.Height = swapChainCreateInfo.height;
|
||||
frameBuffer->DepthSwapChain.Width = swapChainCreateInfo.width;
|
||||
frameBuffer->DepthSwapChain.Height = swapChainCreateInfo.height;
|
||||
|
||||
// Create the color swapchain.
|
||||
swapChainCreateInfo.format = VK_FORMAT_R8G8B8A8_UNORM;
|
||||
swapChainCreateInfo.usageFlags = XR_SWAPCHAIN_USAGE_COLOR_ATTACHMENT_BIT;
|
||||
OXR(xrCreateSwapchain(session, &swapChainCreateInfo, &frameBuffer->ColorSwapChain.Handle));
|
||||
OXR(xrEnumerateSwapchainImages(frameBuffer->ColorSwapChain.Handle, 0, &frameBuffer->TextureSwapChainLength, NULL));
|
||||
frameBuffer->ColorSwapChainImage = malloc(frameBuffer->TextureSwapChainLength * sizeof(XrSwapchainImageVulkanKHR));
|
||||
|
||||
// Create the depth swapchain.
|
||||
swapChainCreateInfo.format = VK_FORMAT_D24_UNORM_S8_UINT;
|
||||
swapChainCreateInfo.usageFlags = XR_SWAPCHAIN_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT;
|
||||
OXR(xrCreateSwapchain(session, &swapChainCreateInfo, &frameBuffer->DepthSwapChain.Handle));
|
||||
frameBuffer->DepthSwapChainImage = malloc(frameBuffer->TextureSwapChainLength * sizeof(XrSwapchainImageVulkanKHR));
|
||||
|
||||
// Populate the swapchain image array.
|
||||
for (uint32_t i = 0; i < frameBuffer->TextureSwapChainLength; i++) {
|
||||
((XrSwapchainImageVulkanKHR*)frameBuffer->ColorSwapChainImage)[i].type = XR_TYPE_SWAPCHAIN_IMAGE_VULKAN_KHR;
|
||||
((XrSwapchainImageVulkanKHR*)frameBuffer->ColorSwapChainImage)[i].next = NULL;
|
||||
((XrSwapchainImageVulkanKHR*)frameBuffer->DepthSwapChainImage)[i].type = XR_TYPE_SWAPCHAIN_IMAGE_VULKAN_KHR;
|
||||
((XrSwapchainImageVulkanKHR*)frameBuffer->DepthSwapChainImage)[i].next = NULL;
|
||||
}
|
||||
OXR(xrEnumerateSwapchainImages(
|
||||
frameBuffer->ColorSwapChain.Handle,
|
||||
frameBuffer->TextureSwapChainLength,
|
||||
&frameBuffer->TextureSwapChainLength,
|
||||
(XrSwapchainImageBaseHeader*)frameBuffer->ColorSwapChainImage));
|
||||
OXR(xrEnumerateSwapchainImages(
|
||||
frameBuffer->DepthSwapChain.Handle,
|
||||
frameBuffer->TextureSwapChainLength,
|
||||
&frameBuffer->TextureSwapChainLength,
|
||||
(XrSwapchainImageBaseHeader*)frameBuffer->DepthSwapChainImage));
|
||||
|
||||
frameBuffer->VKColorImages = new VkImageView[frameBuffer->TextureSwapChainLength];
|
||||
frameBuffer->VKDepthImages = new VkImageView[frameBuffer->TextureSwapChainLength];
|
||||
frameBuffer->VKFrameBuffers = new VkFramebuffer[frameBuffer->TextureSwapChainLength];
|
||||
for (uint32_t i = 0; i < frameBuffer->TextureSwapChainLength; i++) {
|
||||
VkImageViewCreateInfo createInfo{};
|
||||
createInfo.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
|
||||
createInfo.image = ((XrSwapchainImageVulkanKHR*)frameBuffer->ColorSwapChainImage)[i].image;
|
||||
createInfo.viewType = VK_IMAGE_VIEW_TYPE_2D;
|
||||
createInfo.format = VK_FORMAT_R8G8B8A8_UNORM;
|
||||
createInfo.components.r = VK_COMPONENT_SWIZZLE_IDENTITY;
|
||||
createInfo.components.g = VK_COMPONENT_SWIZZLE_IDENTITY;
|
||||
createInfo.components.b = VK_COMPONENT_SWIZZLE_IDENTITY;
|
||||
createInfo.components.a = VK_COMPONENT_SWIZZLE_IDENTITY;
|
||||
createInfo.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
|
||||
createInfo.subresourceRange.baseMipLevel = 0;
|
||||
createInfo.subresourceRange.levelCount = 1;
|
||||
createInfo.subresourceRange.baseArrayLayer = 0;
|
||||
createInfo.subresourceRange.layerCount = swapChainCreateInfo.arraySize;
|
||||
if (vkCreateImageView(frameBuffer->VKContext->device, &createInfo, nullptr, &frameBuffer->VKColorImages[i]) != VK_SUCCESS) {
|
||||
ALOGE("failed to create color image view!");
|
||||
return false;
|
||||
}
|
||||
|
||||
createInfo.image = ((XrSwapchainImageVulkanKHR*)frameBuffer->DepthSwapChainImage)[i].image;
|
||||
createInfo.format = VK_FORMAT_D24_UNORM_S8_UINT;
|
||||
createInfo.subresourceRange.aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT;
|
||||
if (vkCreateImageView(frameBuffer->VKContext->device, &createInfo, nullptr, &frameBuffer->VKDepthImages[i]) != VK_SUCCESS) {
|
||||
ALOGE("failed to create depth image view!");
|
||||
return false;
|
||||
}
|
||||
|
||||
// Create the frame buffer.
|
||||
VkImageView attachments[] = { frameBuffer->VKColorImages[i], frameBuffer->VKDepthImages[i] };
|
||||
VkFramebufferCreateInfo framebufferInfo{};
|
||||
framebufferInfo.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO;
|
||||
framebufferInfo.renderPass = VK_NULL_HANDLE; //TODO:This is probably wrong
|
||||
framebufferInfo.attachmentCount = 2;
|
||||
framebufferInfo.pAttachments = attachments;
|
||||
framebufferInfo.width = width;
|
||||
framebufferInfo.height = height;
|
||||
framebufferInfo.layers = swapChainCreateInfo.arraySize;
|
||||
if (vkCreateFramebuffer(frameBuffer->VKContext->device, &framebufferInfo, nullptr, &frameBuffer->VKFrameBuffers[i]) != VK_SUCCESS) {
|
||||
ALOGE("failed to create framebuffer!");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
#endif
|
||||
|
||||
void ovrFramebuffer_Destroy(ovrFramebuffer* frameBuffer) {
|
||||
GL(glDeleteFramebuffers(frameBuffer->TextureSwapChainLength, frameBuffer->FrameBuffers));
|
||||
if (VR_GetPlatformFlag(VR_PLATFORM_RENDERER_VULKAN)) {
|
||||
for (int i = 0; i < (int)frameBuffer->TextureSwapChainLength; i++) {
|
||||
vkDestroyImageView(frameBuffer->VKContext->device, frameBuffer->VKColorImages[i], nullptr);
|
||||
vkDestroyImageView(frameBuffer->VKContext->device, frameBuffer->VKDepthImages[i], nullptr);
|
||||
vkDestroyFramebuffer(frameBuffer->VKContext->device, frameBuffer->VKFrameBuffers[i], nullptr);
|
||||
}
|
||||
delete[] frameBuffer->VKColorImages;
|
||||
delete[] frameBuffer->VKDepthImages;
|
||||
delete[] frameBuffer->VKFrameBuffers;
|
||||
} else {
|
||||
#if XR_USE_GRAPHICS_API_OPENGL_ES || XR_USE_GRAPHICS_API_OPENGL
|
||||
GL(glDeleteFramebuffers(frameBuffer->TextureSwapChainLength, frameBuffer->GLFrameBuffers));
|
||||
free(frameBuffer->GLFrameBuffers);
|
||||
#endif
|
||||
}
|
||||
OXR(xrDestroySwapchain(frameBuffer->ColorSwapChain.Handle));
|
||||
OXR(xrDestroySwapchain(frameBuffer->DepthSwapChain.Handle));
|
||||
free(frameBuffer->ColorSwapChainImage);
|
||||
free(frameBuffer->DepthSwapChainImage);
|
||||
free(frameBuffer->FrameBuffers);
|
||||
|
||||
ovrFramebuffer_Clear(frameBuffer);
|
||||
}
|
||||
|
||||
void ovrFramebuffer_SetCurrent(ovrFramebuffer* frameBuffer) {
|
||||
GL(glBindFramebuffer(GL_DRAW_FRAMEBUFFER, frameBuffer->FrameBuffers[frameBuffer->TextureSwapChainIndex]));
|
||||
}
|
||||
|
||||
void ovrFramebuffer_SetNone() {
|
||||
GL(glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0));
|
||||
}
|
||||
|
||||
void ovrFramebuffer_Resolve(ovrFramebuffer* frameBuffer) {
|
||||
// Discard the depth buffer, so the tiler won't need to write it back out to memory.
|
||||
const GLenum depthAttachment[1] = {GL_DEPTH_ATTACHMENT};
|
||||
glInvalidateFramebuffer(GL_DRAW_FRAMEBUFFER, 1, depthAttachment);
|
||||
void* ovrFramebuffer_SetCurrent(ovrFramebuffer* frameBuffer) {
|
||||
if (VR_GetPlatformFlag(VR_PLATFORM_RENDERER_VULKAN)) {
|
||||
return (void *)frameBuffer->VKFrameBuffers[frameBuffer->TextureSwapChainIndex];
|
||||
} else {
|
||||
#if XR_USE_GRAPHICS_API_OPENGL_ES || XR_USE_GRAPHICS_API_OPENGL
|
||||
GL(glBindFramebuffer(GL_DRAW_FRAMEBUFFER, frameBuffer->GLFrameBuffers[frameBuffer->TextureSwapChainIndex]));
|
||||
#endif
|
||||
return nullptr;
|
||||
}
|
||||
}
|
||||
|
||||
void ovrFramebuffer_Acquire(ovrFramebuffer* frameBuffer) {
|
||||
@@ -178,6 +298,22 @@ void ovrFramebuffer_Acquire(ovrFramebuffer* frameBuffer) {
|
||||
waitInfo.timeout * (1E-9));
|
||||
}
|
||||
frameBuffer->Acquired = res == XR_SUCCESS;
|
||||
|
||||
ovrFramebuffer_SetCurrent(frameBuffer);
|
||||
|
||||
if (VR_GetPlatformFlag(VR_PLATFORM_RENDERER_VULKAN)) {
|
||||
//TODO:implement
|
||||
} else {
|
||||
#if XR_USE_GRAPHICS_API_OPENGL_ES || XR_USE_GRAPHICS_API_OPENGL
|
||||
GL(glEnable( GL_SCISSOR_TEST ));
|
||||
GL(glViewport( 0, 0, frameBuffer->Width, frameBuffer->Height ));
|
||||
GL(glClearColor( 0.0f, 0.0f, 0.0f, 1.0f ));
|
||||
GL(glScissor( 0, 0, frameBuffer->Width, frameBuffer->Height ));
|
||||
GL(glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT ));
|
||||
GL(glScissor( 0, 0, 0, 0 ));
|
||||
GL(glDisable( GL_SCISSOR_TEST ));
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
||||
void ovrFramebuffer_Release(ovrFramebuffer* frameBuffer) {
|
||||
@@ -185,6 +321,18 @@ void ovrFramebuffer_Release(ovrFramebuffer* frameBuffer) {
|
||||
XrSwapchainImageReleaseInfo releaseInfo = {XR_TYPE_SWAPCHAIN_IMAGE_RELEASE_INFO, NULL};
|
||||
OXR(xrReleaseSwapchainImage(frameBuffer->ColorSwapChain.Handle, &releaseInfo));
|
||||
frameBuffer->Acquired = false;
|
||||
|
||||
// Clear the alpha channel, other way OpenXR would not transfer the framebuffer fully
|
||||
if (VR_GetPlatformFlag(VR_PLATFORM_RENDERER_VULKAN)) {
|
||||
//TODO:implement
|
||||
} else {
|
||||
#if XR_USE_GRAPHICS_API_OPENGL_ES || XR_USE_GRAPHICS_API_OPENGL
|
||||
GL(glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_TRUE));
|
||||
GL(glClearColor(0.0f, 0.0f, 0.0f, 1.0f));
|
||||
GL(glClear(GL_COLOR_BUFFER_BIT));
|
||||
GL(glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE));
|
||||
#endif
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -202,11 +350,19 @@ void ovrRenderer_Clear(ovrRenderer* renderer) {
|
||||
}
|
||||
}
|
||||
|
||||
void ovrRenderer_Create(XrSession session, ovrRenderer* renderer, int width, int height, bool multiview) {
|
||||
void ovrRenderer_Create(XrSession session, ovrRenderer* renderer, int width, int height, bool multiview, void* vulkanContext) {
|
||||
renderer->Multiview = multiview;
|
||||
int instances = renderer->Multiview ? 1 : ovrMaxNumEyes;
|
||||
for (int i = 0; i < instances; i++) {
|
||||
ovrFramebuffer_Create(session, &renderer->FrameBuffer[i], width, height, multiview);
|
||||
if (vulkanContext) {
|
||||
ovrFramebuffer_CreateVK(session, &renderer->FrameBuffer[i], width, height, multiview, vulkanContext);
|
||||
} else {
|
||||
#if XR_USE_GRAPHICS_API_OPENGL_ES
|
||||
ovrFramebuffer_CreateGLES(session, &renderer->FrameBuffer[i], width, height, multiview);
|
||||
#elif XR_USE_GRAPHICS_API_OPENGL
|
||||
// TODO
|
||||
#endif
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -217,6 +373,21 @@ void ovrRenderer_Destroy(ovrRenderer* renderer) {
|
||||
}
|
||||
}
|
||||
|
||||
void ovrRenderer_MouseCursor(ovrRenderer* renderer, int x, int y, int size) {
|
||||
if (VR_GetPlatformFlag(VR_PLATFORM_RENDERER_VULKAN)) {
|
||||
//TODO:implement
|
||||
} else {
|
||||
#if XR_USE_GRAPHICS_API_OPENGL_ES || XR_USE_GRAPHICS_API_OPENGL
|
||||
GL(glEnable(GL_SCISSOR_TEST));
|
||||
GL(glScissor(x, y, size, size));
|
||||
GL(glViewport(x, y, size, size));
|
||||
GL(glClearColor(1.0f, 1.0f, 1.0f, 1.0f));
|
||||
GL(glClear(GL_COLOR_BUFFER_BIT));
|
||||
GL(glDisable(GL_SCISSOR_TEST));
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
================================================================================
|
||||
|
||||
@@ -250,6 +421,7 @@ void ovrApp_Destroy(ovrApp* app) {
|
||||
ovrApp_Clear(app);
|
||||
}
|
||||
|
||||
|
||||
void ovrApp_HandleSessionStateChanges(ovrApp* app, XrSessionState state) {
|
||||
if (state == XR_SESSION_STATE_READY) {
|
||||
assert(app->SessionActive == false);
|
||||
@@ -262,12 +434,10 @@ void ovrApp_HandleSessionStateChanges(ovrApp* app, XrSessionState state) {
|
||||
|
||||
XrResult result;
|
||||
OXR(result = xrBeginSession(app->Session, &sessionBeginInfo));
|
||||
|
||||
app->SessionActive = (result == XR_SUCCESS);
|
||||
|
||||
// Set session state once we have entered VR mode and have a valid session object.
|
||||
#ifdef OPENXR_HAS_PERFORMANCE_EXTENSION
|
||||
if (app->SessionActive) {
|
||||
#ifdef ANDROID
|
||||
if (app->SessionActive && VR_GetPlatformFlag(VR_PLATFORM_PERFORMANCE_EXT)) {
|
||||
XrPerfSettingsLevelEXT cpuPerfLevel = XR_PERF_SETTINGS_LEVEL_BOOST_EXT;
|
||||
XrPerfSettingsLevelEXT gpuPerfLevel = XR_PERF_SETTINGS_LEVEL_BOOST_EXT;
|
||||
|
||||
|
||||
@@ -1,16 +1,15 @@
|
||||
#pragma once
|
||||
|
||||
#include "VR/VRBase.h"
|
||||
#include "VRBase.h"
|
||||
|
||||
void ovrApp_Clear(ovrApp* app);
|
||||
void ovrApp_Destroy(ovrApp* app);
|
||||
int ovrApp_HandleXrEvents(ovrApp* app);
|
||||
|
||||
void ovrFramebuffer_Acquire(ovrFramebuffer* frameBuffer);
|
||||
void ovrFramebuffer_Resolve(ovrFramebuffer* frameBuffer);
|
||||
void ovrFramebuffer_Release(ovrFramebuffer* frameBuffer);
|
||||
void ovrFramebuffer_SetCurrent(ovrFramebuffer* frameBuffer);
|
||||
void ovrFramebuffer_SetNone();
|
||||
void* ovrFramebuffer_SetCurrent(ovrFramebuffer* frameBuffer);
|
||||
|
||||
void ovrRenderer_Create(XrSession session, ovrRenderer* renderer, int width, int height, bool multiview);
|
||||
void ovrRenderer_Create(XrSession session, ovrRenderer* renderer, int width, int height, bool multiview, void* vulkanContext);
|
||||
void ovrRenderer_Destroy(ovrRenderer* renderer);
|
||||
void ovrRenderer_MouseCursor(ovrRenderer* renderer, int x, int y, int size);
|
||||
+45
-24
@@ -1,6 +1,5 @@
|
||||
#include "VRInput.h"
|
||||
#include <string.h>
|
||||
#include <sys/time.h>
|
||||
#include <cstring>
|
||||
|
||||
//OpenXR
|
||||
XrPath leftHandPath;
|
||||
@@ -38,6 +37,8 @@ XrActionStateVector2f moveJoystickState[2];
|
||||
float vibration_channel_duration[2] = {0.0f, 0.0f};
|
||||
float vibration_channel_intensity[2] = {0.0f, 0.0f};
|
||||
|
||||
#if !defined(_WIN32)
|
||||
#include <sys/time.h>
|
||||
|
||||
unsigned long sys_timeBase = 0;
|
||||
int milliseconds(void) {
|
||||
@@ -47,14 +48,33 @@ int milliseconds(void) {
|
||||
|
||||
if (!sys_timeBase) {
|
||||
sys_timeBase = tp.tv_sec;
|
||||
return tp.tv_usec/1000;
|
||||
return tp.tv_usec / 1000;
|
||||
}
|
||||
|
||||
return (tp.tv_sec - sys_timeBase)*1000 + tp.tv_usec/1000;
|
||||
return (tp.tv_sec - sys_timeBase) * 1000 + tp.tv_usec / 1000;
|
||||
}
|
||||
#else
|
||||
|
||||
static LARGE_INTEGER frequency;
|
||||
static double frequencyMult;
|
||||
static LARGE_INTEGER startTime;
|
||||
|
||||
int milliseconds() {
|
||||
if (frequency.QuadPart == 0) {
|
||||
QueryPerformanceFrequency(&frequency);
|
||||
QueryPerformanceCounter(&startTime);
|
||||
frequencyMult = 1.0 / static_cast<double>(frequency.QuadPart);
|
||||
}
|
||||
LARGE_INTEGER time;
|
||||
QueryPerformanceCounter(&time);
|
||||
double elapsed = static_cast<double>(time.QuadPart - startTime.QuadPart);
|
||||
return (int)(elapsed * frequencyMult * 1000.0);
|
||||
}
|
||||
|
||||
#endif
|
||||
|
||||
XrTime ToXrTime(const double timeInSeconds) {
|
||||
return (timeInSeconds * 1e9);
|
||||
return (XrTime)(timeInSeconds * 1e9);
|
||||
}
|
||||
|
||||
void INVR_Vibrate( int duration, int chan, float intensity ) {
|
||||
@@ -67,16 +87,15 @@ void INVR_Vibrate( int duration, int chan, float intensity ) {
|
||||
if (vibration_channel_duration[channel] == -1.0f && duration != 0.0f)
|
||||
return;
|
||||
|
||||
vibration_channel_duration[channel] = duration;
|
||||
vibration_channel_duration[channel] = (float)duration;
|
||||
vibration_channel_intensity[channel] = intensity;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
void VR_processHaptics() {
|
||||
float lastFrameTime = 0.0f;
|
||||
float timestamp = (float)(milliseconds( ));
|
||||
float timestamp = (float)(milliseconds());
|
||||
float frametime = timestamp - lastFrameTime;
|
||||
lastFrameTime = timestamp;
|
||||
|
||||
@@ -247,25 +266,27 @@ void IN_VRInit( engine_t *engine ) {
|
||||
handPoseRightAction = CreateAction(runningActionSet, XR_ACTION_TYPE_POSE_INPUT, "hand_pose_right", NULL, 1, &rightHandPath);
|
||||
|
||||
XrPath interactionProfilePath = XR_NULL_PATH;
|
||||
#ifdef OPENXR_PLATFORM_QUEST
|
||||
OXR(xrStringToPath(engine->appState.Instance, "/interaction_profiles/oculus/touch_controller", &interactionProfilePath));
|
||||
#elif OPENXR_PLATFORM_PICO
|
||||
OXR(xrStringToPath(engine->appState.Instance, "/interaction_profiles/pico/neo3_controller", &interactionProfilePath));
|
||||
#endif
|
||||
if (VR_GetPlatformFlag(VR_PLATFORM_CONTROLLER_QUEST)) {
|
||||
OXR(xrStringToPath(engine->appState.Instance, "/interaction_profiles/oculus/touch_controller", &interactionProfilePath));
|
||||
} else if (VR_GetPlatformFlag(VR_PLATFORM_CONTROLLER_PICO)) {
|
||||
OXR(xrStringToPath(engine->appState.Instance, "/interaction_profiles/pico/neo3_controller", &interactionProfilePath));
|
||||
}
|
||||
|
||||
// Map bindings
|
||||
XrActionSuggestedBinding bindings[32]; // large enough for all profiles
|
||||
int currBinding = 0;
|
||||
|
||||
#ifdef OPENXR_PLATFORM_QUEST
|
||||
bindings[currBinding++] = ActionSuggestedBinding(indexLeftAction, "/user/hand/left/input/trigger");
|
||||
bindings[currBinding++] = ActionSuggestedBinding(indexRightAction, "/user/hand/right/input/trigger");
|
||||
bindings[currBinding++] = ActionSuggestedBinding(menuAction, "/user/hand/left/input/menu/click");
|
||||
#elif OPENXR_PLATFORM_PICO
|
||||
bindings[currBinding++] = ActionSuggestedBinding(indexLeftAction, "/user/hand/left/input/trigger/click");
|
||||
bindings[currBinding++] = ActionSuggestedBinding(indexRightAction, "/user/hand/right/input/trigger/click");
|
||||
bindings[currBinding++] = ActionSuggestedBinding(menuAction, "/user/hand/left/input/back/click");
|
||||
bindings[currBinding++] = ActionSuggestedBinding(menuAction, "/user/hand/right/input/back/click");
|
||||
#endif
|
||||
|
||||
if (VR_GetPlatformFlag(VR_PLATFORM_CONTROLLER_QUEST)) {
|
||||
bindings[currBinding++] = ActionSuggestedBinding(indexLeftAction, "/user/hand/left/input/trigger");
|
||||
bindings[currBinding++] = ActionSuggestedBinding(indexRightAction, "/user/hand/right/input/trigger");
|
||||
bindings[currBinding++] = ActionSuggestedBinding(menuAction, "/user/hand/left/input/menu/click");
|
||||
} else if (VR_GetPlatformFlag(VR_PLATFORM_CONTROLLER_PICO)) {
|
||||
bindings[currBinding++] = ActionSuggestedBinding(indexLeftAction, "/user/hand/left/input/trigger/click");
|
||||
bindings[currBinding++] = ActionSuggestedBinding(indexRightAction, "/user/hand/right/input/trigger/click");
|
||||
bindings[currBinding++] = ActionSuggestedBinding(menuAction, "/user/hand/left/input/back/click");
|
||||
bindings[currBinding++] = ActionSuggestedBinding(menuAction, "/user/hand/right/input/back/click");
|
||||
}
|
||||
bindings[currBinding++] = ActionSuggestedBinding(buttonXAction, "/user/hand/left/input/x/click");
|
||||
bindings[currBinding++] = ActionSuggestedBinding(buttonYAction, "/user/hand/left/input/y/click");
|
||||
bindings[currBinding++] = ActionSuggestedBinding(buttonAAction, "/user/hand/right/input/a/click");
|
||||
@@ -438,6 +459,6 @@ XrPosef IN_VRGetPose( int controllerIndex ) {
|
||||
XrSpaceLocation loc = {};
|
||||
loc.type = XR_TYPE_SPACE_LOCATION;
|
||||
XrSpace aimSpace[] = { leftControllerAimSpace, rightControllerAimSpace };
|
||||
xrLocateSpace(aimSpace[controllerIndex], engine->appState.CurrentSpace, engine->predictedDisplayTime, &loc);
|
||||
xrLocateSpace(aimSpace[controllerIndex], engine->appState.CurrentSpace, (XrTime)(engine->predictedDisplayTime), &loc);
|
||||
return loc.pose;
|
||||
}
|
||||
@@ -1,3 +1,7 @@
|
||||
#define _USE_MATH_DEFINES
|
||||
|
||||
#include <cmath>
|
||||
|
||||
#include "VRMath.h"
|
||||
|
||||
float ToDegrees(float rad) {
|
||||
|
||||
+179
-148
@@ -1,21 +1,24 @@
|
||||
#define _USE_MATH_DEFINES
|
||||
#include <cmath>
|
||||
|
||||
#include "VRBase.h"
|
||||
#include "VRInput.h"
|
||||
#include "VRRenderer.h"
|
||||
#include "OpenXRLoader.h"
|
||||
|
||||
#include <assert.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
#include <GLES3/gl3.h>
|
||||
#include <GLES3/gl3ext.h>
|
||||
#include <cassert>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
|
||||
XrFovf fov;
|
||||
XrView* projections;
|
||||
XrPosef invViewTransform[2];
|
||||
XrFrameState frameState = {};
|
||||
GLboolean initialized = GL_FALSE;
|
||||
GLboolean stageSupported = GL_FALSE;
|
||||
bool initialized = false;
|
||||
bool stageSupported = false;
|
||||
ovrMatrix4f vrMatrix[VR_MATRIX_COUNT];
|
||||
int vrConfig[VR_CONFIG_MAX] = {};
|
||||
float vrConfigFloat[VR_CONFIG_FLOAT_MAX] = {};
|
||||
|
||||
XrVector3f hmdorientation;
|
||||
XrVector3f hmdposition;
|
||||
@@ -133,12 +136,12 @@ void VR_Recenter(engine_t* engine) {
|
||||
OXR(xrLocateSpace(engine->appState.HeadSpace, engine->appState.CurrentSpace, engine->predictedDisplayTime, &loc));
|
||||
hmdorientation = XrQuaternionf_ToEulerAngles(loc.pose.orientation);
|
||||
|
||||
vrConfig[VR_CONFIG_RECENTER_YAW] += (int)hmdorientation.y;
|
||||
float recenterYaw = ToRadians((float)vrConfig[VR_CONFIG_RECENTER_YAW]);
|
||||
VR_SetConfigFloat(VR_CONFIG_RECENTER_YAW, VR_GetConfigFloat(VR_CONFIG_RECENTER_YAW) + hmdorientation.y);
|
||||
float recenterYaw = ToRadians(VR_GetConfigFloat(VR_CONFIG_RECENTER_YAW));
|
||||
spaceCreateInfo.poseInReferenceSpace.orientation.x = 0;
|
||||
spaceCreateInfo.poseInReferenceSpace.orientation.y = sin(recenterYaw / 2);
|
||||
spaceCreateInfo.poseInReferenceSpace.orientation.y = sinf(recenterYaw / 2);
|
||||
spaceCreateInfo.poseInReferenceSpace.orientation.z = 0;
|
||||
spaceCreateInfo.poseInReferenceSpace.orientation.w = cos(recenterYaw / 2);
|
||||
spaceCreateInfo.poseInReferenceSpace.orientation.w = cosf(recenterYaw / 2);
|
||||
}
|
||||
|
||||
// Delete previous space instances
|
||||
@@ -152,9 +155,9 @@ void VR_Recenter(engine_t* engine) {
|
||||
// Create a default stage space to use if SPACE_TYPE_STAGE is not
|
||||
// supported, or calls to xrGetReferenceSpaceBoundsRect fail.
|
||||
spaceCreateInfo.referenceSpaceType = XR_REFERENCE_SPACE_TYPE_LOCAL;
|
||||
#ifdef OPENXR_FLOOR_STAGE
|
||||
spaceCreateInfo.poseInReferenceSpace.position.y = -1.6750f;
|
||||
#endif
|
||||
if (VR_GetPlatformFlag(VR_PLATFORM_TRACKING_FLOOR)) {
|
||||
spaceCreateInfo.poseInReferenceSpace.position.y = -1.6750f;
|
||||
}
|
||||
OXR(xrCreateReferenceSpace(engine->appState.Session, &spaceCreateInfo, &engine->appState.FakeStageSpace));
|
||||
ALOGV("Created fake stage space from local space with offset");
|
||||
engine->appState.CurrentSpace = engine->appState.FakeStageSpace;
|
||||
@@ -164,14 +167,14 @@ void VR_Recenter(engine_t* engine) {
|
||||
spaceCreateInfo.poseInReferenceSpace.position.y = 0.0;
|
||||
OXR(xrCreateReferenceSpace(engine->appState.Session, &spaceCreateInfo, &engine->appState.StageSpace));
|
||||
ALOGV("Created stage space");
|
||||
#ifdef OPENXR_FLOOR_STAGE
|
||||
engine->appState.CurrentSpace = engine->appState.StageSpace;
|
||||
#endif
|
||||
if (VR_GetPlatformFlag(VR_PLATFORM_TRACKING_FLOOR)) {
|
||||
engine->appState.CurrentSpace = engine->appState.StageSpace;
|
||||
}
|
||||
}
|
||||
|
||||
// Update menu orientation
|
||||
vrConfig[VR_CONFIG_MENU_PITCH] = (int)hmdorientation.x;
|
||||
vrConfig[VR_CONFIG_MENU_YAW] = 0;
|
||||
VR_SetConfigFloat(VR_CONFIG_MENU_PITCH, hmdorientation.x);
|
||||
VR_SetConfigFloat(VR_CONFIG_MENU_YAW, 0.0f);
|
||||
}
|
||||
|
||||
void VR_InitRenderer( engine_t* engine, bool multiview ) {
|
||||
@@ -181,8 +184,8 @@ void VR_InitRenderer( engine_t* engine, bool multiview ) {
|
||||
|
||||
int eyeW, eyeH;
|
||||
VR_GetResolution(engine, &eyeW, &eyeH);
|
||||
vrConfig[VR_CONFIG_VIEWPORT_WIDTH] = eyeW;
|
||||
vrConfig[VR_CONFIG_VIEWPORT_HEIGHT] = eyeH;
|
||||
VR_SetConfig(VR_CONFIG_VIEWPORT_WIDTH, eyeW);
|
||||
VR_SetConfig(VR_CONFIG_VIEWPORT_HEIGHT, eyeH);
|
||||
|
||||
// Get the viewport configuration info for the chosen viewport configuration type.
|
||||
engine->appState.ViewportConfig.type = XR_TYPE_VIEW_CONFIGURATION_PROPERTIES;
|
||||
@@ -195,7 +198,7 @@ void VR_InitRenderer( engine_t* engine, bool multiview ) {
|
||||
|
||||
for (uint32_t i = 0; i < numOutputSpaces; i++) {
|
||||
if (referenceSpaces[i] == XR_REFERENCE_SPACE_TYPE_STAGE) {
|
||||
stageSupported = GL_TRUE;
|
||||
stageSupported = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
@@ -208,46 +211,35 @@ void VR_InitRenderer( engine_t* engine, bool multiview ) {
|
||||
|
||||
projections = (XrView*)(malloc(ovrMaxNumEyes * sizeof(XrView)));
|
||||
|
||||
ovrRenderer_Create(
|
||||
engine->appState.Session,
|
||||
&engine->appState.Renderer,
|
||||
void* vulkanContext = nullptr;
|
||||
if (VR_GetPlatformFlag(VR_PLATFORM_RENDERER_VULKAN)) {
|
||||
vulkanContext = &engine->graphicsBindingVulkan;
|
||||
}
|
||||
ovrRenderer_Create(engine->appState.Session, &engine->appState.Renderer,
|
||||
engine->appState.ViewConfigurationView[0].recommendedImageRectWidth,
|
||||
engine->appState.ViewConfigurationView[0].recommendedImageRectHeight,
|
||||
multiview);
|
||||
initialized = GL_TRUE;
|
||||
multiview, vulkanContext);
|
||||
initialized = true;
|
||||
}
|
||||
|
||||
void VR_DestroyRenderer( engine_t* engine ) {
|
||||
ovrRenderer_Destroy(&engine->appState.Renderer);
|
||||
free(projections);
|
||||
initialized = GL_FALSE;
|
||||
}
|
||||
|
||||
void VR_ClearFrameBuffer( int width, int height) {
|
||||
glEnable( GL_SCISSOR_TEST );
|
||||
glViewport( 0, 0, width, height );
|
||||
|
||||
glClearColor( 0.0f, 0.0f, 0.0f, 1.0f );
|
||||
|
||||
glScissor( 0, 0, width, height );
|
||||
glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
|
||||
|
||||
glScissor( 0, 0, 0, 0 );
|
||||
glDisable( GL_SCISSOR_TEST );
|
||||
initialized = false;
|
||||
}
|
||||
|
||||
bool VR_InitFrame( engine_t* engine ) {
|
||||
GLboolean stageBoundsDirty = GL_TRUE;
|
||||
bool stageBoundsDirty = true;
|
||||
if (ovrApp_HandleXrEvents(&engine->appState)) {
|
||||
VR_Recenter(engine);
|
||||
}
|
||||
if (engine->appState.SessionActive == GL_FALSE) {
|
||||
if (engine->appState.SessionActive == false) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (stageBoundsDirty) {
|
||||
VR_UpdateStageBounds(&engine->appState);
|
||||
stageBoundsDirty = GL_FALSE;
|
||||
stageBoundsDirty = false;
|
||||
}
|
||||
|
||||
// NOTE: OpenXR does not use the concept of frame indices. Instead,
|
||||
@@ -310,43 +302,114 @@ bool VR_InitFrame( engine_t* engine ) {
|
||||
|
||||
engine->appState.LayerCount = 0;
|
||||
memset(engine->appState.Layers, 0, sizeof(ovrCompositorLayer_Union) * ovrMaxLayerCount);
|
||||
|
||||
// Update matrices
|
||||
for (int matrix = 0; matrix < VR_MATRIX_COUNT; matrix++) {
|
||||
if ((matrix == VR_PROJECTION_MATRIX_LEFT_EYE) || (matrix == VR_PROJECTION_MATRIX_RIGHT_EYE)) {
|
||||
float nearPlane = VR_GetConfigFloat(VR_CONFIG_FOV_SCALE) / 200.0f;
|
||||
vrMatrix[matrix] = ovrMatrix4f_CreateProjectionFov(fov.angleLeft, fov.angleRight, fov.angleUp, fov.angleDown, nearPlane, 0.0f );
|
||||
} else if ((matrix == VR_VIEW_MATRIX_LEFT_EYE) || (matrix == VR_VIEW_MATRIX_RIGHT_EYE)) {
|
||||
bool flatScreen = false;
|
||||
XrPosef invView = invViewTransform[0];
|
||||
int vrMode = vrConfig[VR_CONFIG_MODE];
|
||||
if ((vrMode == VR_MODE_MONO_SCREEN) || (vrMode == VR_MODE_STEREO_SCREEN)) {
|
||||
invView = XrPosef_Identity();
|
||||
flatScreen = true;
|
||||
}
|
||||
|
||||
// get axis mirroring configuration
|
||||
float mx = vrConfig[VR_CONFIG_MIRROR_PITCH] ? -1.0f : 1.0f;
|
||||
float my = vrConfig[VR_CONFIG_MIRROR_YAW] ? -1.0f : 1.0f;
|
||||
float mz = vrConfig[VR_CONFIG_MIRROR_ROLL] ? -1.0f : 1.0f;
|
||||
|
||||
// ensure there is maximally one axis to mirror rotation
|
||||
if (mx + my + mz < 0) {
|
||||
mx *= -1.0f;
|
||||
my *= -1.0f;
|
||||
mz *= -1.0f;
|
||||
} else {
|
||||
invView = XrPosef_Inverse(invView);
|
||||
}
|
||||
|
||||
// create updated quaternion
|
||||
if (mx + my + mz < 3 - EPSILON) {
|
||||
XrVector3f rotation = XrQuaternionf_ToEulerAngles(invView.orientation);
|
||||
XrQuaternionf pitch = XrQuaternionf_CreateFromVectorAngle({1, 0, 0}, mx * ToRadians(rotation.x));
|
||||
XrQuaternionf yaw = XrQuaternionf_CreateFromVectorAngle({0, 1, 0}, my * ToRadians(rotation.y));
|
||||
XrQuaternionf roll = XrQuaternionf_CreateFromVectorAngle({0, 0, 1}, mz * ToRadians(rotation.z));
|
||||
invView.orientation = XrQuaternionf_Multiply(roll, XrQuaternionf_Multiply(pitch, yaw));
|
||||
}
|
||||
|
||||
vrMatrix[matrix] = ovrMatrix4f_CreateFromQuaternion(&invView.orientation);
|
||||
float scale = VR_GetConfigFloat(VR_CONFIG_6DOF_SCALE);
|
||||
if (!flatScreen && vrConfig[VR_CONFIG_6DOF_ENABLED]) {
|
||||
vrMatrix[matrix].M[0][3] -= hmdposition.x * (vrConfig[VR_CONFIG_MIRROR_AXIS_X] ? -1.0f : 1.0f) * scale;
|
||||
vrMatrix[matrix].M[1][3] -= hmdposition.y * (vrConfig[VR_CONFIG_MIRROR_AXIS_Y] ? -1.0f : 1.0f) * scale;
|
||||
vrMatrix[matrix].M[2][3] -= hmdposition.z * (vrConfig[VR_CONFIG_MIRROR_AXIS_Z] ? -1.0f : 1.0f) * scale;
|
||||
}
|
||||
if (fabsf(VR_GetConfigFloat(VR_CONFIG_CAMERA_DISTANCE)) > 0.0f) {
|
||||
XrVector3f forward = {0.0f, 0.0f, VR_GetConfigFloat(VR_CONFIG_CAMERA_DISTANCE) * scale};
|
||||
forward = XrQuaternionf_Rotate(invView.orientation, forward);
|
||||
forward = XrVector3f_ScalarMultiply(forward, vrConfig[VR_CONFIG_MIRROR_AXIS_Z] ? -1.0f : 1.0f);
|
||||
vrMatrix[matrix].M[0][3] += forward.x;
|
||||
vrMatrix[matrix].M[1][3] += forward.y;
|
||||
vrMatrix[matrix].M[2][3] += forward.z;
|
||||
}
|
||||
if (fabsf(VR_GetConfigFloat(VR_CONFIG_CAMERA_HEIGHT)) > 0.0f) {
|
||||
XrVector3f up = {0.0f, -VR_GetConfigFloat(VR_CONFIG_CAMERA_HEIGHT) * scale, 0.0f};
|
||||
up = XrQuaternionf_Rotate(invView.orientation, up);
|
||||
up = XrVector3f_ScalarMultiply(up, vrConfig[VR_CONFIG_MIRROR_AXIS_Y] ? -1.0f : 1.0f);
|
||||
vrMatrix[matrix].M[0][3] += up.x;
|
||||
vrMatrix[matrix].M[1][3] += up.y;
|
||||
vrMatrix[matrix].M[2][3] += up.z;
|
||||
}
|
||||
if (fabsf(VR_GetConfigFloat(VR_CONFIG_CAMERA_SIDE)) > 0.0f) {
|
||||
XrVector3f side = {-VR_GetConfigFloat(VR_CONFIG_CAMERA_SIDE) * scale, 0.0f, 0.0f};
|
||||
side = XrQuaternionf_Rotate(invView.orientation, side);
|
||||
side = XrVector3f_ScalarMultiply(side, vrConfig[VR_CONFIG_MIRROR_AXIS_X] ? -1.0f : 1.0f);
|
||||
vrMatrix[matrix].M[0][3] += side.x;
|
||||
vrMatrix[matrix].M[1][3] += side.y;
|
||||
vrMatrix[matrix].M[2][3] += side.z;
|
||||
}
|
||||
if (vrConfig[VR_CONFIG_HAS_UNIT_SCALE] && (matrix == VR_VIEW_MATRIX_RIGHT_EYE)) {
|
||||
float dx = fabs(invViewTransform[1].position.x - invViewTransform[0].position.x);
|
||||
float dy = fabs(invViewTransform[1].position.y - invViewTransform[0].position.y);
|
||||
float dz = fabs(invViewTransform[1].position.z - invViewTransform[0].position.z);
|
||||
float ipd = sqrt(dx * dx + dy * dy + dz * dz);
|
||||
XrVector3f separation = {ipd * scale, 0.0f, 0.0f};
|
||||
separation = XrQuaternionf_Rotate(invView.orientation, separation);
|
||||
separation = XrVector3f_ScalarMultiply(separation, vrConfig[VR_CONFIG_MIRROR_AXIS_Z] ? -1.0f : 1.0f);
|
||||
vrMatrix[matrix].M[0][3] -= separation.x;
|
||||
vrMatrix[matrix].M[1][3] -= separation.y;
|
||||
vrMatrix[matrix].M[2][3] -= separation.z;
|
||||
}
|
||||
} else {
|
||||
assert(false);
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
void VR_BeginFrame( engine_t* engine, int fboIndex ) {
|
||||
vrConfig[VR_CONFIG_CURRENT_FBO] = fboIndex;
|
||||
ovrFramebuffer* frameBuffer = &engine->appState.Renderer.FrameBuffer[fboIndex];
|
||||
ovrFramebuffer_Acquire(frameBuffer);
|
||||
ovrFramebuffer_SetCurrent(frameBuffer);
|
||||
VR_ClearFrameBuffer(frameBuffer->ColorSwapChain.Width, frameBuffer->ColorSwapChain.Height);
|
||||
ovrFramebuffer_Acquire(&engine->appState.Renderer.FrameBuffer[fboIndex]);
|
||||
}
|
||||
|
||||
void VR_EndFrame( engine_t* engine ) {
|
||||
|
||||
int fboIndex = vrConfig[VR_CONFIG_CURRENT_FBO];
|
||||
|
||||
// Clear the alpha channel, other way OpenXR would not transfer the framebuffer fully
|
||||
VR_BindFramebuffer(engine);
|
||||
glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_TRUE);
|
||||
glClearColor(0.0, 0.0, 0.0, 1.0);
|
||||
glClear(GL_COLOR_BUFFER_BIT);
|
||||
glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
|
||||
|
||||
// Show mouse cursor
|
||||
int size = vrConfig[VR_CONFIG_MOUSE_SIZE];
|
||||
if ((vrConfig[VR_CONFIG_MODE] == VR_MODE_FLAT_SCREEN) && (size > 0)) {
|
||||
glEnable(GL_SCISSOR_TEST);
|
||||
glScissor(vrConfig[VR_CONFIG_MOUSE_X], vrConfig[VR_CONFIG_MOUSE_Y], size, size);
|
||||
glViewport(vrConfig[VR_CONFIG_MOUSE_X], vrConfig[VR_CONFIG_MOUSE_Y], size, size);
|
||||
glClearColor(1, 1, 1, 1);
|
||||
glClear(GL_COLOR_BUFFER_BIT);
|
||||
glDisable(GL_SCISSOR_TEST);
|
||||
int vrMode = vrConfig[VR_CONFIG_MODE];
|
||||
bool screenMode = (vrMode == VR_MODE_MONO_SCREEN) || (vrMode == VR_MODE_STEREO_SCREEN);
|
||||
if (screenMode && (size > 0)) {
|
||||
int x = vrConfig[VR_CONFIG_MOUSE_X];
|
||||
int y = vrConfig[VR_CONFIG_MOUSE_Y];
|
||||
ovrRenderer_MouseCursor(&engine->appState.Renderer, x, y, size);
|
||||
}
|
||||
|
||||
ovrFramebuffer* frameBuffer = &engine->appState.Renderer.FrameBuffer[fboIndex];
|
||||
//ovrFramebuffer_Resolve(frameBuffer);
|
||||
ovrFramebuffer_Release(frameBuffer);
|
||||
ovrFramebuffer_SetNone();
|
||||
ovrFramebuffer_Release(&engine->appState.Renderer.FrameBuffer[fboIndex]);
|
||||
}
|
||||
|
||||
void VR_FinishFrame( engine_t* engine ) {
|
||||
@@ -354,7 +417,7 @@ void VR_FinishFrame( engine_t* engine ) {
|
||||
int vrMode = vrConfig[VR_CONFIG_MODE];
|
||||
XrCompositionLayerProjectionView projection_layer_elements[2] = {};
|
||||
if ((vrMode == VR_MODE_MONO_6DOF) || (vrMode == VR_MODE_STEREO_6DOF)) {
|
||||
vrConfig[VR_CONFIG_MENU_YAW] = (int)hmdorientation.y;
|
||||
VR_SetConfigFloat(VR_CONFIG_MENU_YAW, hmdorientation.y);
|
||||
|
||||
for (int eye = 0; eye < ovrMaxNumEyes; eye++) {
|
||||
int imageLayer = engine->appState.Renderer.Multiview ? eye : 0;
|
||||
@@ -390,40 +453,55 @@ void VR_FinishFrame( engine_t* engine ) {
|
||||
projection_layer.views = projection_layer_elements;
|
||||
|
||||
engine->appState.Layers[engine->appState.LayerCount++].Projection = projection_layer;
|
||||
} else if (vrMode == VR_MODE_FLAT_SCREEN) {
|
||||
} else if ((vrMode == VR_MODE_MONO_SCREEN) || (vrMode == VR_MODE_STEREO_SCREEN)) {
|
||||
|
||||
// Build the cylinder layer
|
||||
int width = engine->appState.Renderer.FrameBuffer[0].ColorSwapChain.Width;
|
||||
int height = engine->appState.Renderer.FrameBuffer[0].ColorSwapChain.Height;
|
||||
// Flat screen pose
|
||||
float distance = VR_GetConfigFloat(VR_CONFIG_CANVAS_DISTANCE);
|
||||
float menuPitch = ToRadians(VR_GetConfigFloat(VR_CONFIG_MENU_PITCH));
|
||||
float menuYaw = ToRadians(VR_GetConfigFloat(VR_CONFIG_MENU_YAW));
|
||||
XrVector3f pos = {
|
||||
invViewTransform[0].position.x - sinf(menuYaw) * distance,
|
||||
invViewTransform[0].position.y,
|
||||
invViewTransform[0].position.z - cosf(menuYaw) * distance
|
||||
};
|
||||
XrQuaternionf pitch = XrQuaternionf_CreateFromVectorAngle({1, 0, 0}, -menuPitch);
|
||||
XrQuaternionf yaw = XrQuaternionf_CreateFromVectorAngle({0, 1, 0}, menuYaw);
|
||||
|
||||
// Setup the cylinder layer
|
||||
XrCompositionLayerCylinderKHR cylinder_layer = {};
|
||||
cylinder_layer.type = XR_TYPE_COMPOSITION_LAYER_CYLINDER_KHR;
|
||||
cylinder_layer.layerFlags = XR_COMPOSITION_LAYER_BLEND_TEXTURE_SOURCE_ALPHA_BIT;
|
||||
cylinder_layer.space = engine->appState.CurrentSpace;
|
||||
cylinder_layer.eyeVisibility = XR_EYE_VISIBILITY_BOTH;
|
||||
memset(&cylinder_layer.subImage, 0, sizeof(XrSwapchainSubImage));
|
||||
cylinder_layer.subImage.swapchain = engine->appState.Renderer.FrameBuffer[0].ColorSwapChain.Handle;
|
||||
cylinder_layer.subImage.imageRect.offset.x = 0;
|
||||
cylinder_layer.subImage.imageRect.offset.y = 0;
|
||||
cylinder_layer.subImage.imageRect.extent.width = width;
|
||||
cylinder_layer.subImage.imageRect.extent.height = height;
|
||||
cylinder_layer.subImage.imageRect.extent.width = engine->appState.Renderer.FrameBuffer[0].ColorSwapChain.Width;
|
||||
cylinder_layer.subImage.imageRect.extent.height = engine->appState.Renderer.FrameBuffer[0].ColorSwapChain.Height;
|
||||
cylinder_layer.subImage.swapchain = engine->appState.Renderer.FrameBuffer[0].ColorSwapChain.Handle;
|
||||
cylinder_layer.subImage.imageArrayIndex = 0;
|
||||
float distance = (float)vrConfig[VR_CONFIG_CANVAS_DISTANCE];
|
||||
float menuPitch = ToRadians((float)vrConfig[VR_CONFIG_MENU_PITCH]);
|
||||
float menuYaw = ToRadians((float)vrConfig[VR_CONFIG_MENU_YAW]);
|
||||
XrVector3f pos = {
|
||||
invViewTransform[0].position.x - sin(menuYaw) * distance,
|
||||
invViewTransform[0].position.y,
|
||||
invViewTransform[0].position.z - cos(menuYaw) * distance
|
||||
};
|
||||
XrQuaternionf pitch = XrQuaternionf_CreateFromVectorAngle({1, 0, 0}, -menuPitch);
|
||||
XrQuaternionf yaw = XrQuaternionf_CreateFromVectorAngle({0, 1, 0}, menuYaw);
|
||||
cylinder_layer.pose.orientation = XrQuaternionf_Multiply(pitch, yaw);
|
||||
cylinder_layer.pose.position = pos;
|
||||
cylinder_layer.radius = 12.0f;
|
||||
cylinder_layer.centralAngle = M_PI * 0.5f;
|
||||
cylinder_layer.centralAngle = (float)(M_PI * 0.5);
|
||||
cylinder_layer.aspectRatio = 1;
|
||||
|
||||
engine->appState.Layers[engine->appState.LayerCount++].Cylinder = cylinder_layer;
|
||||
// Build the cylinder layer
|
||||
if (vrMode == VR_MODE_MONO_SCREEN) {
|
||||
cylinder_layer.eyeVisibility = XR_EYE_VISIBILITY_BOTH;
|
||||
engine->appState.Layers[engine->appState.LayerCount++].Cylinder = cylinder_layer;
|
||||
} else if (engine->appState.Renderer.Multiview) {
|
||||
cylinder_layer.eyeVisibility = XR_EYE_VISIBILITY_LEFT;
|
||||
engine->appState.Layers[engine->appState.LayerCount++].Cylinder = cylinder_layer;
|
||||
cylinder_layer.eyeVisibility = XR_EYE_VISIBILITY_RIGHT;
|
||||
cylinder_layer.subImage.imageArrayIndex = 1;
|
||||
engine->appState.Layers[engine->appState.LayerCount++].Cylinder = cylinder_layer;
|
||||
} else {
|
||||
cylinder_layer.eyeVisibility = XR_EYE_VISIBILITY_LEFT;
|
||||
engine->appState.Layers[engine->appState.LayerCount++].Cylinder = cylinder_layer;
|
||||
cylinder_layer.eyeVisibility = XR_EYE_VISIBILITY_RIGHT;
|
||||
cylinder_layer.subImage.swapchain = engine->appState.Renderer.FrameBuffer[1].ColorSwapChain.Handle;
|
||||
engine->appState.Layers[engine->appState.LayerCount++].Cylinder = cylinder_layer;
|
||||
}
|
||||
} else {
|
||||
assert(false);
|
||||
}
|
||||
@@ -458,67 +536,20 @@ void VR_SetConfig( VRConfig config, int value) {
|
||||
vrConfig[config] = value;
|
||||
}
|
||||
|
||||
void VR_BindFramebuffer(engine_t *engine) {
|
||||
if (!initialized) return;
|
||||
int fboIndex = vrConfig[VR_CONFIG_CURRENT_FBO];
|
||||
ovrFramebuffer* frameBuffer = &engine->appState.Renderer.FrameBuffer[fboIndex];
|
||||
unsigned int swapchainIndex = frameBuffer->TextureSwapChainIndex;
|
||||
unsigned int glFramebuffer = frameBuffer->FrameBuffers[swapchainIndex];
|
||||
GL(glBindFramebuffer(GL_DRAW_FRAMEBUFFER, glFramebuffer));
|
||||
float VR_GetConfigFloat(VRConfigFloat config) {
|
||||
return vrConfigFloat[config];
|
||||
}
|
||||
|
||||
void VR_SetConfigFloat(VRConfigFloat config, float value) {
|
||||
vrConfigFloat[config] = value;
|
||||
}
|
||||
|
||||
void* VR_BindFramebuffer(engine_t *engine) {
|
||||
if (!initialized) return nullptr;
|
||||
int fboIndex = VR_GetConfig(VR_CONFIG_CURRENT_FBO);
|
||||
return ovrFramebuffer_SetCurrent(&engine->appState.Renderer.FrameBuffer[fboIndex]);
|
||||
}
|
||||
|
||||
ovrMatrix4f VR_GetMatrix( VRMatrix matrix ) {
|
||||
ovrMatrix4f output;
|
||||
if ((matrix == VR_PROJECTION_MATRIX_LEFT_EYE) || (matrix == VR_PROJECTION_MATRIX_RIGHT_EYE)) {
|
||||
float near = (float)vrConfig[VR_CONFIG_FOV_SCALE] / 200.0f;
|
||||
output = ovrMatrix4f_CreateProjectionFov(fov.angleLeft, fov.angleRight, fov.angleUp, fov.angleDown, near, 0.0f );
|
||||
} else if ((matrix == VR_VIEW_MATRIX_LEFT_EYE) || (matrix == VR_VIEW_MATRIX_RIGHT_EYE)) {
|
||||
XrPosef invView = invViewTransform[0];
|
||||
|
||||
// get axis mirroring configuration
|
||||
float mx = vrConfig[VR_CONFIG_MIRROR_PITCH] ? -1 : 1;
|
||||
float my = vrConfig[VR_CONFIG_MIRROR_YAW] ? -1 : 1;
|
||||
float mz = vrConfig[VR_CONFIG_MIRROR_ROLL] ? -1 : 1;
|
||||
|
||||
// ensure there is maximally one axis to mirror rotation
|
||||
if (mx + my + mz < 0) {
|
||||
mx *= -1.0f;
|
||||
my *= -1.0f;
|
||||
mz *= -1.0f;
|
||||
} else {
|
||||
invView = XrPosef_Inverse(invView);
|
||||
}
|
||||
|
||||
// create updated quaternion
|
||||
if (mx + my + mz < 3 - EPSILON) {
|
||||
XrVector3f rotation = XrQuaternionf_ToEulerAngles(invView.orientation);
|
||||
XrQuaternionf pitch = XrQuaternionf_CreateFromVectorAngle({1, 0, 0}, mx * ToRadians(rotation.x));
|
||||
XrQuaternionf yaw = XrQuaternionf_CreateFromVectorAngle({0, 1, 0}, my * ToRadians(rotation.y));
|
||||
XrQuaternionf roll = XrQuaternionf_CreateFromVectorAngle({0, 0, 1}, mz * ToRadians(rotation.z));
|
||||
invView.orientation = XrQuaternionf_Multiply(roll, XrQuaternionf_Multiply(pitch, yaw));
|
||||
}
|
||||
|
||||
output = ovrMatrix4f_CreateFromQuaternion(&invView.orientation);
|
||||
float scale = (float)VR_GetConfig(VR_CONFIG_6DOF_SCALE) * 0.000001f;
|
||||
if (vrConfig[VR_CONFIG_6DOF_ENABLED]) {
|
||||
output.M[0][3] -= hmdposition.x * (vrConfig[VR_CONFIG_MIRROR_AXIS_X] ? -1.0f : 1.0f) * scale;
|
||||
output.M[1][3] -= hmdposition.y * (vrConfig[VR_CONFIG_MIRROR_AXIS_Y] ? -1.0f : 1.0f) * scale;
|
||||
output.M[2][3] -= hmdposition.z * (vrConfig[VR_CONFIG_MIRROR_AXIS_Z] ? -1.0f : 1.0f) * scale;
|
||||
}
|
||||
if (vrConfig[VR_CONFIG_6DOF_PRECISE] && (matrix == VR_VIEW_MATRIX_RIGHT_EYE)) {
|
||||
float dx = fabs(invViewTransform[1].position.x - invViewTransform[0].position.x);
|
||||
float dy = fabs(invViewTransform[1].position.y - invViewTransform[0].position.y);
|
||||
float dz = fabs(invViewTransform[1].position.z - invViewTransform[0].position.z);
|
||||
float ipd = sqrt(dx * dx + dy * dy + dz * dz);
|
||||
XrVector3f separation = {ipd * scale, 0.0f, 0.0f};
|
||||
separation = XrQuaternionf_Rotate(invView.orientation, separation);
|
||||
separation = XrVector3f_ScalarMultiply(separation, vrConfig[VR_CONFIG_MIRROR_AXIS_Z] ? -1.0f : 1.0f);
|
||||
output.M[0][3] -= separation.x;
|
||||
output.M[1][3] -= separation.y;
|
||||
output.M[2][3] -= separation.z;
|
||||
}
|
||||
} else {
|
||||
assert(false);
|
||||
}
|
||||
return output;
|
||||
return vrMatrix[matrix];
|
||||
}
|
||||
+28
-12
@@ -7,13 +7,12 @@ enum VRConfig {
|
||||
//switching between 2D and 3D
|
||||
VR_CONFIG_MODE, VR_CONFIG_3D_GEOMETRY_COUNT, VR_CONFIG_FORCE_2D,
|
||||
//camera setup
|
||||
VR_CONFIG_FOV_SCALE, VR_CONFIG_CANVAS_DISTANCE,
|
||||
VR_CONFIG_CAMERA_CONTROL,
|
||||
VR_CONFIG_HAS_UNIT_SCALE,
|
||||
//6DoF
|
||||
VR_CONFIG_6DOF_ENABLED, VR_CONFIG_6DOF_SCALE, VR_CONFIG_6DOF_PRECISE,
|
||||
VR_CONFIG_6DOF_ENABLED, VR_CONFIG_MIRROR_UPDATED,
|
||||
VR_CONFIG_MIRROR_AXIS_X, VR_CONFIG_MIRROR_AXIS_Y, VR_CONFIG_MIRROR_AXIS_Z,
|
||||
VR_CONFIG_MIRROR_PITCH, VR_CONFIG_MIRROR_YAW, VR_CONFIG_MIRROR_ROLL,
|
||||
//2D canvas positioning
|
||||
VR_CONFIG_MENU_PITCH, VR_CONFIG_MENU_YAW, VR_CONFIG_RECENTER_YAW,
|
||||
//mouse cursor
|
||||
VR_CONFIG_MOUSE_SIZE, VR_CONFIG_MOUSE_X, VR_CONFIG_MOUSE_Y,
|
||||
//viewport setup
|
||||
@@ -25,17 +24,31 @@ enum VRConfig {
|
||||
VR_CONFIG_MAX
|
||||
};
|
||||
|
||||
enum VRConfigFloat {
|
||||
// 6dof
|
||||
VR_CONFIG_6DOF_SCALE,
|
||||
// camera setup
|
||||
VR_CONFIG_FOV_SCALE, VR_CONFIG_CAMERA_DISTANCE,
|
||||
VR_CONFIG_CAMERA_HEIGHT, VR_CONFIG_CAMERA_SIDE, VR_CONFIG_CANVAS_DISTANCE,
|
||||
// 2D canvas positioning
|
||||
VR_CONFIG_MENU_PITCH, VR_CONFIG_MENU_YAW, VR_CONFIG_RECENTER_YAW,
|
||||
|
||||
VR_CONFIG_FLOAT_MAX
|
||||
};
|
||||
|
||||
enum VRMatrix {
|
||||
VR_PROJECTION_MATRIX_LEFT_EYE = 0,
|
||||
VR_PROJECTION_MATRIX_RIGHT_EYE = 1,
|
||||
VR_VIEW_MATRIX_LEFT_EYE = 2,
|
||||
VR_VIEW_MATRIX_RIGHT_EYE = 3
|
||||
VR_PROJECTION_MATRIX_LEFT_EYE,
|
||||
VR_PROJECTION_MATRIX_RIGHT_EYE,
|
||||
VR_VIEW_MATRIX_LEFT_EYE,
|
||||
VR_VIEW_MATRIX_RIGHT_EYE,
|
||||
VR_MATRIX_COUNT
|
||||
};
|
||||
|
||||
enum VRMode {
|
||||
VR_MODE_FLAT_SCREEN = 0,
|
||||
VR_MODE_MONO_6DOF = 1,
|
||||
VR_MODE_STEREO_6DOF = 2
|
||||
VR_MODE_MONO_SCREEN,
|
||||
VR_MODE_STEREO_SCREEN,
|
||||
VR_MODE_MONO_6DOF,
|
||||
VR_MODE_STEREO_6DOF
|
||||
};
|
||||
|
||||
void VR_GetResolution( engine_t* engine, int *pWidth, int *pHeight );
|
||||
@@ -50,5 +63,8 @@ void VR_FinishFrame( engine_t* engine );
|
||||
int VR_GetConfig( VRConfig config );
|
||||
void VR_SetConfig( VRConfig config, int value);
|
||||
|
||||
void VR_BindFramebuffer(engine_t *engine);
|
||||
float VR_GetConfigFloat( VRConfigFloat config );
|
||||
void VR_SetConfigFloat( VRConfigFloat config, float value );
|
||||
|
||||
void* VR_BindFramebuffer(engine_t *engine);
|
||||
ovrMatrix4f VR_GetMatrix( VRMatrix matrix );
|
||||
@@ -1,93 +0,0 @@
|
||||
#include "VRTweaks.h"
|
||||
#include <iostream>
|
||||
|
||||
bool VR_TweakIsMatrixBigScale(float* matrix) {
|
||||
for (int i = 0; i < 2; i++) {
|
||||
float value = matrix[i * 4 + i];
|
||||
if (fabs(value) < 10.0f) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool VR_TweakIsMatrixIdentity(float* matrix) {
|
||||
for (int i = 0; i < 4; i++) {
|
||||
for (int j = 0; j < 4; j++) {
|
||||
float value = matrix[i * 4 + j];
|
||||
|
||||
// Other number than zero on non-diagonale
|
||||
if ((i != j) && (fabs(value) > EPSILON)) return false;
|
||||
// Other number than one on diagonale
|
||||
if ((i == j) && (fabs(value - 1.0f) > EPSILON)) return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool VR_TweakIsMatrixOneOrtho(float* matrix) {
|
||||
float value = matrix[15];
|
||||
return fabs(value - 1) < EPSILON;
|
||||
}
|
||||
|
||||
bool VR_TweakIsMatrixOneScale(float* matrix) {
|
||||
for (int i = 0; i < 2; i++) {
|
||||
float value = matrix[i * 4 + i];
|
||||
if (fabs(value - 1) > EPSILON) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool VR_TweakIsMatrixOneTransform(float* matrix) {
|
||||
for (int j = 0; j < 4; j++) {
|
||||
float value = matrix[12 + j];
|
||||
if (fabs(fabs(value) - 1.0f) > EPSILON) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
void VR_TweakMirroring(float* projMatrix) {
|
||||
VR_SetConfig(VR_CONFIG_MIRROR_AXIS_X, projMatrix[0] < 0);
|
||||
VR_SetConfig(VR_CONFIG_MIRROR_AXIS_Y, projMatrix[5] < 0);
|
||||
VR_SetConfig(VR_CONFIG_MIRROR_AXIS_Z, projMatrix[10] > 0);
|
||||
if ((projMatrix[0] < 0) && (projMatrix[10] < 0)) { //e.g. Dante's inferno
|
||||
VR_SetConfig(VR_CONFIG_MIRROR_PITCH, true);
|
||||
VR_SetConfig(VR_CONFIG_MIRROR_YAW, true);
|
||||
VR_SetConfig(VR_CONFIG_MIRROR_ROLL, false);
|
||||
} else if (projMatrix[10] < 0) { //e.g. GTA - Liberty city
|
||||
VR_SetConfig(VR_CONFIG_MIRROR_PITCH, false);
|
||||
VR_SetConfig(VR_CONFIG_MIRROR_YAW, false);
|
||||
VR_SetConfig(VR_CONFIG_MIRROR_ROLL, false);
|
||||
} else if (projMatrix[5] < 0) { //e.g. PES 2014
|
||||
VR_SetConfig(VR_CONFIG_MIRROR_PITCH, true);
|
||||
VR_SetConfig(VR_CONFIG_MIRROR_YAW, true);
|
||||
VR_SetConfig(VR_CONFIG_MIRROR_ROLL, false);
|
||||
} else { //e.g. Lego Pirates
|
||||
VR_SetConfig(VR_CONFIG_MIRROR_PITCH, false);
|
||||
VR_SetConfig(VR_CONFIG_MIRROR_YAW, true);
|
||||
VR_SetConfig(VR_CONFIG_MIRROR_ROLL, true);
|
||||
}
|
||||
}
|
||||
|
||||
void VR_TweakProjection(float* src, float* dst, VRMatrix matrix) {
|
||||
ovrMatrix4f hmdProjection = VR_GetMatrix(matrix);
|
||||
for (int i = 0; i < 4; i++) {
|
||||
for (int j = 0; j < 4; j++) {
|
||||
if ((hmdProjection.M[i][j] > 0) != (src[i * 4 + j] > 0)) {
|
||||
hmdProjection.M[i][j] *= -1.0f;
|
||||
}
|
||||
}
|
||||
}
|
||||
memcpy(dst, hmdProjection.M, 16 * sizeof(float));
|
||||
}
|
||||
|
||||
void VR_TweakView(float* view, VRMatrix matrix) {
|
||||
// Get view matrix from the game
|
||||
ovrMatrix4f gameView;
|
||||
memcpy(gameView.M, view, 16 * sizeof(float));
|
||||
|
||||
// Get view matrix from the headset
|
||||
ovrMatrix4f hmdView = VR_GetMatrix(matrix);
|
||||
|
||||
// Combine the matrices
|
||||
ovrMatrix4f renderView = ovrMatrix4f_Multiply(&hmdView, &gameView);
|
||||
memcpy(view, renderView.M, 16 * sizeof(float));
|
||||
}
|
||||
@@ -1,12 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include "VRRenderer.h"
|
||||
|
||||
bool VR_TweakIsMatrixBigScale(float* matrix);
|
||||
bool VR_TweakIsMatrixIdentity(float* matrix);
|
||||
bool VR_TweakIsMatrixOneOrtho(float* matrix);
|
||||
bool VR_TweakIsMatrixOneScale(float* matrix);
|
||||
bool VR_TweakIsMatrixOneTransform(float* matrix);
|
||||
void VR_TweakMirroring(float* projMatrix);
|
||||
void VR_TweakProjection(float* src, float* dst, VRMatrix matrix);
|
||||
void VR_TweakView(float* view, VRMatrix matrix);
|
||||
@@ -278,6 +278,19 @@ inline OpArg MRegSum(X64Reg base, X64Reg offset)
|
||||
return MComplex(base, offset, 1, 0);
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
inline bool Accessible(const T *t1, const T *t2) {
|
||||
ptrdiff_t diff = (const uint8_t *)t1 - (const uint8_t *)t2;
|
||||
return diff > -0x7FFFFFE0 && diff < 0x7FFFFFE0;
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
inline OpArg MAccessibleDisp(X64Reg r, const T *tbase, const T *t) {
|
||||
_assert_(Accessible(tbase, t));
|
||||
ptrdiff_t diff = (const uint8_t *)t - (const uint8_t *)tbase;
|
||||
return MDisp(r, (int)diff);
|
||||
}
|
||||
|
||||
inline OpArg Imm8 (u8 imm) {return OpArg(imm, SCALE_IMM8);}
|
||||
inline OpArg Imm16(u16 imm) {return OpArg(imm, SCALE_IMM16);} //rarely used
|
||||
inline OpArg Imm32(u32 imm) {return OpArg(imm, SCALE_IMM32);}
|
||||
|
||||
+21
-5
@@ -17,6 +17,7 @@
|
||||
|
||||
#include <cstring>
|
||||
|
||||
#include "Common/Log.h"
|
||||
#include "Common/Data/Format/IniFile.h"
|
||||
#include "Common/StringUtils.h"
|
||||
#include "Core/Compatibility.h"
|
||||
@@ -42,21 +43,29 @@ void Compatibility::Load(const std::string &gameID) {
|
||||
}
|
||||
}
|
||||
|
||||
{
|
||||
IniFile compat2;
|
||||
// This one is user-editable. Need to load it after the system one.
|
||||
Path path = GetSysDirectory(DIRECTORY_SYSTEM) / "compat.ini";
|
||||
if (compat2.Load(path.ToString())) {
|
||||
CheckSettings(compat2, gameID);
|
||||
}
|
||||
}
|
||||
|
||||
{
|
||||
IniFile compat;
|
||||
// This loads from assets.
|
||||
if (compat.LoadFromVFS("compatvr.ini")) {
|
||||
CheckSetting(compat, gameID, "Skyplane", &vrCompat_.Skyplane);
|
||||
CheckSetting(compat, gameID, "UnitsPerMeter", &vrCompat_.UnitsPerMeter);
|
||||
CheckVRSettings(compat, gameID);
|
||||
}
|
||||
}
|
||||
|
||||
{
|
||||
IniFile compat2;
|
||||
// This one is user-editable. Need to load it after the system one.
|
||||
Path path = GetSysDirectory(DIRECTORY_SYSTEM) / "compat.ini";
|
||||
Path path = GetSysDirectory(DIRECTORY_SYSTEM) / "compatvr.ini";
|
||||
if (compat2.Load(path.ToString())) {
|
||||
CheckSettings(compat2, gameID);
|
||||
CheckVRSettings(compat2, gameID);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -97,7 +106,6 @@ void Compatibility::CheckSettings(IniFile &iniFile, const std::string &gameID) {
|
||||
CheckSetting(iniFile, gameID, "DateLimited", &flags_.DateLimited);
|
||||
CheckSetting(iniFile, gameID, "ShaderColorBitmask", &flags_.ShaderColorBitmask);
|
||||
CheckSetting(iniFile, gameID, "DisableFirstFrameReadback", &flags_.DisableFirstFrameReadback);
|
||||
CheckSetting(iniFile, gameID, "DisableRangeCulling", &flags_.DisableRangeCulling);
|
||||
CheckSetting(iniFile, gameID, "MpegAvcWarmUp", &flags_.MpegAvcWarmUp);
|
||||
CheckSetting(iniFile, gameID, "BlueToAlpha", &flags_.BlueToAlpha);
|
||||
CheckSetting(iniFile, gameID, "CenteredLines", &flags_.CenteredLines);
|
||||
@@ -110,6 +118,14 @@ void Compatibility::CheckSettings(IniFile &iniFile, const std::string &gameID) {
|
||||
CheckSetting(iniFile, gameID, "ForceLowerResolutionForEffectsOn", &flags_.ForceLowerResolutionForEffectsOn);
|
||||
CheckSetting(iniFile, gameID, "AllowDownloadCLUT", &flags_.AllowDownloadCLUT);
|
||||
CheckSetting(iniFile, gameID, "NearestFilteringOnFramebufferCreate", &flags_.NearestFilteringOnFramebufferCreate);
|
||||
CheckSetting(iniFile, gameID, "SecondaryTextureCache", &flags_.SecondaryTextureCache);
|
||||
}
|
||||
|
||||
void Compatibility::CheckVRSettings(IniFile &iniFile, const std::string &gameID) {
|
||||
CheckSetting(iniFile, gameID, "Skyplane", &vrCompat_.Skyplane);
|
||||
CheckSetting(iniFile, gameID, "UnitsPerMeter", &vrCompat_.UnitsPerMeter);
|
||||
|
||||
NOTICE_LOG(G3D, "UnitsPerMeter for %s: %f", gameID.c_str(), vrCompat_.UnitsPerMeter);
|
||||
}
|
||||
|
||||
void Compatibility::CheckSetting(IniFile &iniFile, const std::string &gameID, const char *option, bool *flag) {
|
||||
|
||||
@@ -77,7 +77,6 @@ struct CompatFlags {
|
||||
bool DateLimited;
|
||||
bool ShaderColorBitmask;
|
||||
bool DisableFirstFrameReadback;
|
||||
bool DisableRangeCulling;
|
||||
bool MpegAvcWarmUp;
|
||||
bool BlueToAlpha;
|
||||
bool CenteredLines;
|
||||
@@ -90,6 +89,7 @@ struct CompatFlags {
|
||||
bool ForceLowerResolutionForEffectsOn;
|
||||
bool AllowDownloadCLUT;
|
||||
bool NearestFilteringOnFramebufferCreate;
|
||||
bool SecondaryTextureCache;
|
||||
};
|
||||
|
||||
struct VRCompat {
|
||||
@@ -115,6 +115,7 @@ public:
|
||||
private:
|
||||
void Clear();
|
||||
void CheckSettings(IniFile &iniFile, const std::string &gameID);
|
||||
void CheckVRSettings(IniFile &iniFile, const std::string &gameID);
|
||||
void CheckSetting(IniFile &iniFile, const std::string &gameID, const char *option, bool *flag);
|
||||
void CheckSetting(IniFile &iniFile, const std::string &gameID, const char *option, float *value);
|
||||
|
||||
|
||||
+21
-17
@@ -697,7 +697,7 @@ const char * const vulkanDefaultBlacklist[] = {
|
||||
};
|
||||
|
||||
static int DefaultGPUBackend() {
|
||||
if (IsVRBuild()) {
|
||||
if (IsVREnabled()) {
|
||||
return (int)GPUBackend::OPENGL;
|
||||
}
|
||||
|
||||
@@ -874,7 +874,8 @@ static ConfigSetting graphicsSettings[] = {
|
||||
#endif
|
||||
ConfigSetting("CameraDevice", &g_Config.sCameraDevice, "", true, false),
|
||||
ConfigSetting("VendorBugChecksEnabled", &g_Config.bVendorBugChecksEnabled, true, false, false),
|
||||
ReportedConfigSetting("RenderingMode", &g_Config.iRenderingMode, 1, true, true),
|
||||
ConfigSetting("UseGeometryShader", &g_Config.bUseGeometryShader, true, true, true),
|
||||
ReportedConfigSetting("SkipBufferEffects", &g_Config.bSkipBufferEffects, false, true, true),
|
||||
ConfigSetting("SoftwareRenderer", &g_Config.bSoftwareRendering, false, true, true),
|
||||
ConfigSetting("SoftwareRendererJit", &g_Config.bSoftwareRenderingJit, true, true, true),
|
||||
ReportedConfigSetting("HardwareTransform", &g_Config.bHardwareTransform, true, true, true),
|
||||
@@ -887,6 +888,8 @@ static ConfigSetting graphicsSettings[] = {
|
||||
ReportedConfigSetting("FrameSkip", &g_Config.iFrameSkip, 0, true, true),
|
||||
ReportedConfigSetting("FrameSkipType", &g_Config.iFrameSkipType, 0, true, true),
|
||||
ReportedConfigSetting("AutoFrameSkip", &g_Config.bAutoFrameSkip, false, true, true),
|
||||
ConfigSetting("StereoRendering", &g_Config.bStereoRendering, false, true, true),
|
||||
ConfigSetting("StereoToMonoShader", &g_Config.sStereoToMonoShader, "RedBlue", true, true),
|
||||
ConfigSetting("FrameRate", &g_Config.iFpsLimit1, 0, true, true),
|
||||
ConfigSetting("FrameRate2", &g_Config.iFpsLimit2, -1, true, true),
|
||||
ConfigSetting("AnalogFrameRate", &g_Config.iAnalogFpsLimit, 240, true, true),
|
||||
@@ -901,7 +904,6 @@ static ConfigSetting graphicsSettings[] = {
|
||||
|
||||
ReportedConfigSetting("VertexDecCache", &g_Config.bVertexCache, false, true, true),
|
||||
ReportedConfigSetting("TextureBackoffCache", &g_Config.bTextureBackoffCache, false, true, true),
|
||||
ReportedConfigSetting("TextureSecondaryCache", &g_Config.bTextureSecondaryCache, false, true, true),
|
||||
ReportedConfigSetting("VertexDecJit", &g_Config.bVertexDecoderJit, &DefaultCodeGen, false),
|
||||
|
||||
#ifndef MOBILE_DEVICE
|
||||
@@ -935,8 +937,7 @@ static ConfigSetting graphicsSettings[] = {
|
||||
ConfigSetting("TextureShader", &g_Config.sTextureShaderName, "Off", true, true),
|
||||
ConfigSetting("ShaderChainRequires60FPS", &g_Config.bShaderChainRequires60FPS, false, true, true),
|
||||
|
||||
ReportedConfigSetting("MemBlockTransferGPU", &g_Config.bBlockTransferGPU, true, true, true),
|
||||
ReportedConfigSetting("FragmentTestCache", &g_Config.bFragmentTestCache, true, true, true),
|
||||
ReportedConfigSetting("SkipGPUReadbacks", &g_Config.bSkipGPUReadbacks, false, true, true),
|
||||
|
||||
ConfigSetting("GfxDebugOutput", &g_Config.bGfxDebugOutput, false, false, false),
|
||||
ConfigSetting("LogFrameDrops", &g_Config.bLogFrameDrops, false, true, false),
|
||||
@@ -1206,8 +1207,14 @@ static ConfigSetting vrSettings[] = {
|
||||
ConfigSetting("VREnable", &g_Config.bEnableVR, true),
|
||||
ConfigSetting("VREnable6DoF", &g_Config.bEnable6DoF, true),
|
||||
ConfigSetting("VREnableStereo", &g_Config.bEnableStereo, false),
|
||||
ConfigSetting("VRCanvasDistance", &g_Config.iCanvasDistance, 6),
|
||||
ConfigSetting("VRFieldOfView", &g_Config.iFieldOfViewPercentage, 100),
|
||||
ConfigSetting("VREnableMotions", &g_Config.bEnableMotions, true),
|
||||
ConfigSetting("VRbForce72Hz", &g_Config.bForce72Hz, true),
|
||||
ConfigSetting("VRCameraDistance", &g_Config.fCameraDistance, 0.0f),
|
||||
ConfigSetting("VRCameraHeight", &g_Config.fCameraHeight, 0.0f),
|
||||
ConfigSetting("VRCameraSide", &g_Config.fCameraSide, 0.0f),
|
||||
ConfigSetting("VRCanvasDistance", &g_Config.fCanvasDistance, 6.0f),
|
||||
ConfigSetting("VRFieldOfView", &g_Config.fFieldOfViewPercentage, 100.0f),
|
||||
ConfigSetting("VRMotionLength", &g_Config.fMotionLength, 0.5f),
|
||||
|
||||
ConfigSetting(false),
|
||||
};
|
||||
@@ -1403,9 +1410,6 @@ void Config::Load(const char *iniFileName, const char *controllerIniFilename) {
|
||||
if (iAnisotropyLevel > 4) {
|
||||
iAnisotropyLevel = 4;
|
||||
}
|
||||
if (iRenderingMode != FB_NON_BUFFERED_MODE && iRenderingMode != FB_BUFFERED_MODE) {
|
||||
g_Config.iRenderingMode = FB_BUFFERED_MODE;
|
||||
}
|
||||
|
||||
// Check for an old dpad setting
|
||||
Section *control = iniFile.GetOrCreateSection("Control");
|
||||
@@ -1424,7 +1428,7 @@ void Config::Load(const char *iniFileName, const char *controllerIniFilename) {
|
||||
// build of PPSSPP, receive an upgrade notice, then start a newer version, and still receive the upgrade notice,
|
||||
// even if said newer version is >= the upgrade found online.
|
||||
if ((dismissedVersion == upgradeVersion) || (versionsValid && (installed >= upgrade))) {
|
||||
upgradeMessage = "";
|
||||
upgradeMessage.clear();
|
||||
}
|
||||
|
||||
// Check for new version on every 10 runs.
|
||||
@@ -1456,8 +1460,8 @@ void Config::Load(const char *iniFileName, const char *controllerIniFilename) {
|
||||
if (sMACAddress.length() != 17)
|
||||
sMACAddress = CreateRandMAC();
|
||||
|
||||
if (g_Config.bAutoFrameSkip && g_Config.iRenderingMode == FB_NON_BUFFERED_MODE) {
|
||||
g_Config.iRenderingMode = FB_BUFFERED_MODE;
|
||||
if (g_Config.bAutoFrameSkip && g_Config.bSkipBufferEffects) {
|
||||
g_Config.bSkipBufferEffects = false;
|
||||
}
|
||||
|
||||
// Override ppsspp.ini JIT value to prevent crashing
|
||||
@@ -1636,16 +1640,16 @@ void Config::DownloadCompletedCallback(http::Download &download) {
|
||||
|
||||
if (installed >= upgrade) {
|
||||
INFO_LOG(LOADER, "Version check: Already up to date, erasing any upgrade message");
|
||||
g_Config.upgradeMessage = "";
|
||||
g_Config.upgradeMessage.clear();
|
||||
g_Config.upgradeVersion = upgrade.ToString();
|
||||
g_Config.dismissedVersion = "";
|
||||
g_Config.dismissedVersion.clear();
|
||||
return;
|
||||
}
|
||||
|
||||
if (installed < upgrade && dismissed != upgrade) {
|
||||
g_Config.upgradeMessage = "New version of PPSSPP available!";
|
||||
g_Config.upgradeVersion = upgrade.ToString();
|
||||
g_Config.dismissedVersion = "";
|
||||
g_Config.dismissedVersion.clear();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1978,5 +1982,5 @@ void Config::GetReportingInfo(UrlEncoder &data) {
|
||||
}
|
||||
|
||||
bool Config::IsPortrait() const {
|
||||
return (iInternalScreenRotation == ROTATION_LOCKED_VERTICAL || iInternalScreenRotation == ROTATION_LOCKED_VERTICAL180) && iRenderingMode != FB_NON_BUFFERED_MODE;
|
||||
return (iInternalScreenRotation == ROTATION_LOCKED_VERTICAL || iInternalScreenRotation == ROTATION_LOCKED_VERTICAL180) && !bSkipBufferEffects;
|
||||
}
|
||||
+20
-7
@@ -162,10 +162,13 @@ public:
|
||||
bool bSoftwareRendering;
|
||||
bool bSoftwareRenderingJit;
|
||||
bool bHardwareTransform; // only used in the GLES backend
|
||||
bool bSoftwareSkinning; // may speed up some games
|
||||
bool bSoftwareSkinning;
|
||||
bool bVendorBugChecksEnabled;
|
||||
bool bUseGeometryShader;
|
||||
|
||||
// Speedhacks (more will be moved here):
|
||||
bool bSkipBufferEffects;
|
||||
|
||||
int iRenderingMode; // 0 = non-buffered rendering 1 = buffered rendering
|
||||
int iTexFiltering; // 1 = auto , 2 = nearest , 3 = linear , 4 = auto max quality
|
||||
int iBufFilter; // 1 = linear, 2 = nearest
|
||||
int iSmallDisplayZoomType; // Used to fit display into screen 0 = stretch, 1 = partial stretch, 2 = auto scaling, 3 = manual scaling.
|
||||
@@ -198,7 +201,6 @@ public:
|
||||
|
||||
bool bVertexCache;
|
||||
bool bTextureBackoffCache;
|
||||
bool bTextureSecondaryCache;
|
||||
bool bVertexDecoderJit;
|
||||
bool bFullScreen;
|
||||
bool bFullScreenMulti;
|
||||
@@ -233,14 +235,19 @@ public:
|
||||
float fCwCheatScrollPosition;
|
||||
float fGameListScrollPosition;
|
||||
int iBloomHack; //0 = off, 1 = safe, 2 = balanced, 3 = aggressive
|
||||
bool bBlockTransferGPU;
|
||||
bool bFragmentTestCache;
|
||||
bool bSkipGPUReadbacks;
|
||||
int iSplineBezierQuality; // 0 = low , 1 = Intermediate , 2 = High
|
||||
bool bHardwareTessellation;
|
||||
bool bShaderCache; // Hidden ini-only setting, useful for debugging shader compile times.
|
||||
|
||||
std::vector<std::string> vPostShaderNames; // Off for chain end (only Off for no shader)
|
||||
std::map<std::string, float> mPostShaderSetting;
|
||||
|
||||
// Note that this is separate from VR stereo, though it'll share some code paths.
|
||||
bool bStereoRendering;
|
||||
// There can only be one, unlike regular post shaders.
|
||||
std::string sStereoToMonoShader;
|
||||
|
||||
bool bShaderChainRequires60FPS;
|
||||
std::string sTextureShaderName;
|
||||
bool bGfxDebugOutput;
|
||||
@@ -457,8 +464,14 @@ public:
|
||||
bool bEnableVR;
|
||||
bool bEnable6DoF;
|
||||
bool bEnableStereo;
|
||||
int iCanvasDistance;
|
||||
int iFieldOfViewPercentage;
|
||||
bool bEnableMotions;
|
||||
bool bForce72Hz;
|
||||
float fCameraDistance;
|
||||
float fCameraHeight;
|
||||
float fCameraSide;
|
||||
float fCanvasDistance;
|
||||
float fFieldOfViewPercentage;
|
||||
float fMotionLength;
|
||||
|
||||
// Debugger
|
||||
int iDisasmWindowX;
|
||||
|
||||
+3
-3
@@ -447,7 +447,7 @@ void Core_MemoryException(u32 address, u32 pc, MemoryExceptionType type) {
|
||||
ExceptionInfo &e = g_exceptionInfo;
|
||||
e = {};
|
||||
e.type = ExceptionType::MEMORY;
|
||||
e.info = "";
|
||||
e.info.clear();
|
||||
e.memory_type = type;
|
||||
e.address = address;
|
||||
e.pc = pc;
|
||||
@@ -483,7 +483,7 @@ void Core_ExecException(u32 address, u32 pc, ExecExceptionType type) {
|
||||
ExceptionInfo &e = g_exceptionInfo;
|
||||
e = {};
|
||||
e.type = ExceptionType::BAD_EXEC_ADDR;
|
||||
e.info = "";
|
||||
e.info.clear();
|
||||
e.exec_type = type;
|
||||
e.address = address;
|
||||
e.pc = pc;
|
||||
@@ -498,7 +498,7 @@ void Core_Break(u32 pc) {
|
||||
ExceptionInfo &e = g_exceptionInfo;
|
||||
e = {};
|
||||
e.type = ExceptionType::BREAK;
|
||||
e.info = "";
|
||||
e.info.clear();
|
||||
e.pc = pc;
|
||||
|
||||
if (!g_Config.bIgnoreBadMemAccess) {
|
||||
|
||||
@@ -648,16 +648,11 @@ void CBreakPoints::Update(u32 addr) {
|
||||
resume = true;
|
||||
}
|
||||
|
||||
{
|
||||
std::lock_guard<std::recursive_mutex> guard(MIPSComp::jitLock);
|
||||
if (MIPSComp::jit) {
|
||||
// In case this is a delay slot, clear the previous instruction too.
|
||||
if (addr != 0)
|
||||
MIPSComp::jit->InvalidateCacheAt(addr - 4, 8);
|
||||
else
|
||||
MIPSComp::jit->ClearCache();
|
||||
}
|
||||
}
|
||||
// In case this is a delay slot, clear the previous instruction too.
|
||||
if (addr != 0)
|
||||
mipsr4k.InvalidateICache(addr - 4, 8);
|
||||
else
|
||||
mipsr4k.ClearJitCache();
|
||||
|
||||
if (resume)
|
||||
Core_EnableStepping(false);
|
||||
|
||||
@@ -316,7 +316,7 @@ void DisassemblyManager::getLine(u32 address, bool insertSymbols, DisassemblyLin
|
||||
dest.params = "Disassembly failure";
|
||||
} else {
|
||||
dest.name = "-";
|
||||
dest.params = "";
|
||||
dest.params.clear();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1003,7 +1003,7 @@ void DisassemblyData::createLines()
|
||||
lines[currentLineStart] = entry;
|
||||
lineAddresses.push_back(currentLineStart);
|
||||
|
||||
currentLine = "";
|
||||
currentLine.clear();
|
||||
currentLineStart = pos-1;
|
||||
inString = false;
|
||||
}
|
||||
@@ -1028,7 +1028,7 @@ void DisassemblyData::createLines()
|
||||
lines[currentLineStart] = entry;
|
||||
lineAddresses.push_back(currentLineStart);
|
||||
|
||||
currentLine = "";
|
||||
currentLine.clear();
|
||||
currentLineStart = pos-1;
|
||||
inString = false;
|
||||
}
|
||||
@@ -1099,7 +1099,7 @@ void DisassemblyData::createLines()
|
||||
lines[currentLineStart] = entry;
|
||||
lineAddresses.push_back(currentLineStart);
|
||||
|
||||
currentLine = "";
|
||||
currentLine.clear();
|
||||
currentLineStart = currentPos;
|
||||
}
|
||||
|
||||
|
||||
@@ -399,12 +399,18 @@ void FlushPendingMemInfo() {
|
||||
pendingNotifyMaxAddr2 = 0;
|
||||
}
|
||||
|
||||
static inline uint32_t NormalizeAddress(uint32_t addr) {
|
||||
if ((addr & 0x3F000000) == 0x04000000)
|
||||
return addr & 0x041FFFFF;
|
||||
return addr & 0x3FFFFFFF;
|
||||
}
|
||||
|
||||
void NotifyMemInfoPC(MemBlockFlags flags, uint32_t start, uint32_t size, uint32_t pc, const char *tagStr, size_t strLength) {
|
||||
if (size == 0) {
|
||||
return;
|
||||
}
|
||||
// Clear the uncached and kernel bits.
|
||||
start &= ~0xC0000000;
|
||||
start = NormalizeAddress(start);
|
||||
|
||||
bool needFlush = false;
|
||||
// When the setting is off, we skip smaller info to keep things fast.
|
||||
@@ -450,7 +456,7 @@ void NotifyMemInfo(MemBlockFlags flags, uint32_t start, uint32_t size, const cha
|
||||
}
|
||||
|
||||
std::vector<MemBlockInfo> FindMemInfo(uint32_t start, uint32_t size) {
|
||||
start &= ~0xC0000000;
|
||||
start = NormalizeAddress(start);
|
||||
|
||||
if (pendingNotifyMinAddr1 < start + size && pendingNotifyMaxAddr1 >= start)
|
||||
FlushPendingMemInfo();
|
||||
@@ -466,7 +472,7 @@ std::vector<MemBlockInfo> FindMemInfo(uint32_t start, uint32_t size) {
|
||||
}
|
||||
|
||||
std::vector<MemBlockInfo> FindMemInfoByFlag(MemBlockFlags flags, uint32_t start, uint32_t size) {
|
||||
start &= ~0xC0000000;
|
||||
start = NormalizeAddress(start);
|
||||
|
||||
if (pendingNotifyMinAddr1 < start + size && pendingNotifyMaxAddr1 >= start)
|
||||
FlushPendingMemInfo();
|
||||
@@ -486,7 +492,7 @@ std::vector<MemBlockInfo> FindMemInfoByFlag(MemBlockFlags flags, uint32_t start,
|
||||
}
|
||||
|
||||
static const char *FindWriteTagByFlag(MemBlockFlags flags, uint32_t start, uint32_t size) {
|
||||
start &= ~0xC0000000;
|
||||
start = NormalizeAddress(start);
|
||||
|
||||
if (pendingNotifyMinAddr1 < start + size && pendingNotifyMaxAddr1 >= start)
|
||||
FlushPendingMemInfo();
|
||||
|
||||
+16
-16
@@ -440,7 +440,7 @@ void SymbolMap::AddModule(const char *name, u32 address, u32 size) {
|
||||
// Just reactivate that one.
|
||||
it->start = address;
|
||||
it->size = size;
|
||||
activeModuleEnds.insert(std::make_pair(it->start + it->size, *it));
|
||||
activeModuleEnds.emplace(it->start + it->size, *it);
|
||||
activeNeedUpdate_ = true;
|
||||
return;
|
||||
}
|
||||
@@ -453,7 +453,7 @@ void SymbolMap::AddModule(const char *name, u32 address, u32 size) {
|
||||
mod.index = (int)modules.size() + 1;
|
||||
|
||||
modules.push_back(mod);
|
||||
activeModuleEnds.insert(std::make_pair(mod.start + mod.size, mod));
|
||||
activeModuleEnds.emplace(mod.start + mod.size, mod);
|
||||
activeNeedUpdate_ = true;
|
||||
}
|
||||
|
||||
@@ -560,7 +560,7 @@ void SymbolMap::AddFunction(const char* name, u32 address, u32 size, int moduleI
|
||||
auto active = activeFunctions.find(address);
|
||||
if (active != activeFunctions.end() && active->second.module == moduleIndex) {
|
||||
activeFunctions.erase(active);
|
||||
activeFunctions.insert(std::make_pair(address, existing->second));
|
||||
activeFunctions.emplace(address, existing->second);
|
||||
}
|
||||
} else {
|
||||
FunctionEntry func;
|
||||
@@ -571,7 +571,7 @@ void SymbolMap::AddFunction(const char* name, u32 address, u32 size, int moduleI
|
||||
functions[symbolKey] = func;
|
||||
|
||||
if (IsModuleActive(moduleIndex)) {
|
||||
activeFunctions.insert(std::make_pair(address, func));
|
||||
activeFunctions.emplace(address, func);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -717,27 +717,27 @@ void SymbolMap::UpdateActiveSymbols() {
|
||||
for (auto it = functions.begin(), end = functions.end(); it != end; ++it) {
|
||||
const auto mod = activeModuleIndexes.find(it->second.module);
|
||||
if (it->second.module == 0) {
|
||||
activeFunctions.insert(std::make_pair(it->second.start, it->second));
|
||||
activeFunctions.emplace(it->second.start, it->second);
|
||||
} else if (mod != activeModuleIndexes.end()) {
|
||||
activeFunctions.insert(std::make_pair(mod->second + it->second.start, it->second));
|
||||
activeFunctions.emplace(mod->second + it->second.start, it->second);
|
||||
}
|
||||
}
|
||||
|
||||
for (auto it = labels.begin(), end = labels.end(); it != end; ++it) {
|
||||
const auto mod = activeModuleIndexes.find(it->second.module);
|
||||
if (it->second.module == 0) {
|
||||
activeLabels.insert(std::make_pair(it->second.addr, it->second));
|
||||
activeLabels.emplace(it->second.addr, it->second);
|
||||
} else if (mod != activeModuleIndexes.end()) {
|
||||
activeLabels.insert(std::make_pair(mod->second + it->second.addr, it->second));
|
||||
activeLabels.emplace(mod->second + it->second.addr, it->second);
|
||||
}
|
||||
}
|
||||
|
||||
for (auto it = data.begin(), end = data.end(); it != end; ++it) {
|
||||
const auto mod = activeModuleIndexes.find(it->second.module);
|
||||
if (it->second.module == 0) {
|
||||
activeData.insert(std::make_pair(it->second.start, it->second));
|
||||
activeData.emplace(it->second.start, it->second);
|
||||
} else if (mod != activeModuleIndexes.end()) {
|
||||
activeData.insert(std::make_pair(mod->second + it->second.start, it->second));
|
||||
activeData.emplace(mod->second + it->second.start, it->second);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -758,7 +758,7 @@ bool SymbolMap::SetFunctionSize(u32 startAddress, u32 newSize) {
|
||||
if (func != functions.end()) {
|
||||
func->second.size = newSize;
|
||||
activeFunctions.erase(funcInfo);
|
||||
activeFunctions.insert(std::make_pair(startAddress, func->second));
|
||||
activeFunctions.emplace(startAddress, func->second);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -830,7 +830,7 @@ void SymbolMap::AddLabel(const char* name, u32 address, int moduleIndex) {
|
||||
auto active = activeLabels.find(address);
|
||||
if (active != activeLabels.end() && active->second.module == moduleIndex) {
|
||||
activeLabels.erase(active);
|
||||
activeLabels.insert(std::make_pair(address, label));
|
||||
activeLabels.emplace(address, label);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
@@ -841,7 +841,7 @@ void SymbolMap::AddLabel(const char* name, u32 address, int moduleIndex) {
|
||||
|
||||
labels[symbolKey] = label;
|
||||
if (IsModuleActive(moduleIndex)) {
|
||||
activeLabels.insert(std::make_pair(address, label));
|
||||
activeLabels.emplace(address, label);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -865,7 +865,7 @@ void SymbolMap::SetLabelName(const char* name, u32 address) {
|
||||
auto active = activeLabels.find(address);
|
||||
if (active != activeLabels.end() && active->second.module == label->second.module) {
|
||||
activeLabels.erase(active);
|
||||
activeLabels.insert(std::make_pair(address, label->second));
|
||||
activeLabels.emplace(address, label->second);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -948,7 +948,7 @@ void SymbolMap::AddData(u32 address, u32 size, DataType type, int moduleIndex) {
|
||||
auto active = activeData.find(address);
|
||||
if (active != activeData.end() && active->second.module == moduleIndex) {
|
||||
activeData.erase(active);
|
||||
activeData.insert(std::make_pair(address, existing->second));
|
||||
activeData.emplace(address, existing->second);
|
||||
}
|
||||
} else {
|
||||
DataEntry entry;
|
||||
@@ -959,7 +959,7 @@ void SymbolMap::AddData(u32 address, u32 size, DataType type, int moduleIndex) {
|
||||
|
||||
data[symbolKey] = entry;
|
||||
if (IsModuleActive(moduleIndex)) {
|
||||
activeData.insert(std::make_pair(address, entry));
|
||||
activeData.emplace(address, entry);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -41,7 +41,7 @@ DebuggerSubscriber *WebSocketGPUBufferInit(DebuggerEventHandlerMap &map) {
|
||||
}
|
||||
|
||||
// Note: Calls req.Respond(). Other data can be added afterward.
|
||||
static bool StreamBufferToDataURI(DebuggerRequest &req, const GPUDebugBuffer &buf, bool includeAlpha, int stackWidth) {
|
||||
static bool StreamBufferToDataURI(DebuggerRequest &req, const GPUDebugBuffer &buf, bool isFramebuffer, bool includeAlpha, int stackWidth) {
|
||||
#ifdef USING_QT_UI
|
||||
req.Fail("Not supported on Qt yet, pull requests accepted");
|
||||
return false;
|
||||
@@ -83,6 +83,9 @@ static bool StreamBufferToDataURI(DebuggerRequest &req, const GPUDebugBuffer &bu
|
||||
auto &json = req.Respond();
|
||||
json.writeInt("width", w);
|
||||
json.writeInt("height", h);
|
||||
if (isFramebuffer) {
|
||||
json.writeBool("isFramebuffer", isFramebuffer);
|
||||
}
|
||||
|
||||
// Start a value...
|
||||
json.writeRaw("uri", "");
|
||||
@@ -191,7 +194,7 @@ static std::string DescribeFormat(GPUDebugBufferFormat fmt) {
|
||||
}
|
||||
|
||||
// Note: Calls req.Respond(). Other data can be added afterward.
|
||||
static bool StreamBufferToBase64(DebuggerRequest &req, const GPUDebugBuffer &buf) {
|
||||
static bool StreamBufferToBase64(DebuggerRequest &req, const GPUDebugBuffer &buf, bool isFramebuffer) {
|
||||
size_t length = buf.GetStride() * buf.GetHeight();
|
||||
|
||||
auto &json = req.Respond();
|
||||
@@ -199,6 +202,9 @@ static bool StreamBufferToBase64(DebuggerRequest &req, const GPUDebugBuffer &buf
|
||||
json.writeInt("height", buf.GetHeight());
|
||||
json.writeBool("flipped", buf.GetFlipped());
|
||||
json.writeString("format", DescribeFormat(buf.GetFormat()));
|
||||
if (isFramebuffer) {
|
||||
json.writeBool("isFramebuffer", isFramebuffer);
|
||||
}
|
||||
|
||||
// Start a value without any actual data yet...
|
||||
json.writeRaw("base64", "");
|
||||
@@ -217,7 +223,7 @@ static bool StreamBufferToBase64(DebuggerRequest &req, const GPUDebugBuffer &buf
|
||||
return true;
|
||||
}
|
||||
|
||||
static void GenericStreamBuffer(DebuggerRequest &req, std::function<bool(const GPUDebugBuffer *&)> func) {
|
||||
static void GenericStreamBuffer(DebuggerRequest &req, std::function<bool(const GPUDebugBuffer *&, bool *isFramebuffer)> func) {
|
||||
if (!currentDebugMIPS->isAlive()) {
|
||||
return req.Fail("CPU not started");
|
||||
}
|
||||
@@ -238,15 +244,16 @@ static void GenericStreamBuffer(DebuggerRequest &req, std::function<bool(const G
|
||||
return req.Fail("Parameter 'type' must be either 'uri' or 'base64'");
|
||||
|
||||
const GPUDebugBuffer *buf = nullptr;
|
||||
if (!func(buf)) {
|
||||
bool isFramebuffer = false;
|
||||
if (!func(buf, &isFramebuffer)) {
|
||||
return req.Fail("Could not download output");
|
||||
}
|
||||
_assert_(buf != nullptr);
|
||||
|
||||
if (type == "base64") {
|
||||
StreamBufferToBase64(req, *buf);
|
||||
StreamBufferToBase64(req, *buf, isFramebuffer);
|
||||
} else if (type == "uri") {
|
||||
StreamBufferToDataURI(req, *buf, includeAlpha, stackWidth);
|
||||
StreamBufferToDataURI(req, *buf, isFramebuffer, includeAlpha, stackWidth);
|
||||
} else {
|
||||
_assert_(false);
|
||||
}
|
||||
@@ -270,7 +277,8 @@ static void GenericStreamBuffer(DebuggerRequest &req, std::function<bool(const G
|
||||
// - format: string indicating format, such as 'R8G8B8A8_UNORM' or 'B8G8R8A8_UNORM'.
|
||||
// - base64: base64 encode of binary data.
|
||||
void WebSocketGPUBufferScreenshot(DebuggerRequest &req) {
|
||||
GenericStreamBuffer(req, [](const GPUDebugBuffer *&buf) {
|
||||
GenericStreamBuffer(req, [](const GPUDebugBuffer *&buf, bool *isFramebuffer) {
|
||||
*isFramebuffer = false;
|
||||
return GPUStepping::GPU_GetOutputFramebuffer(buf);
|
||||
});
|
||||
}
|
||||
@@ -293,7 +301,8 @@ void WebSocketGPUBufferScreenshot(DebuggerRequest &req) {
|
||||
// - format: string indicating format, such as 'R8G8B8A8_UNORM' or 'B8G8R8A8_UNORM'.
|
||||
// - base64: base64 encode of binary data.
|
||||
void WebSocketGPUBufferRenderColor(DebuggerRequest &req) {
|
||||
GenericStreamBuffer(req, [](const GPUDebugBuffer *&buf) {
|
||||
GenericStreamBuffer(req, [](const GPUDebugBuffer *&buf, bool *isFramebuffer) {
|
||||
*isFramebuffer = false;
|
||||
return GPUStepping::GPU_GetCurrentFramebuffer(buf, GPU_DBG_FRAMEBUF_RENDER);
|
||||
});
|
||||
}
|
||||
@@ -316,7 +325,8 @@ void WebSocketGPUBufferRenderColor(DebuggerRequest &req) {
|
||||
// - format: string indicating format, such as 'D16', 'D24_X8' or 'D32F'.
|
||||
// - base64: base64 encode of binary data.
|
||||
void WebSocketGPUBufferRenderDepth(DebuggerRequest &req) {
|
||||
GenericStreamBuffer(req, [](const GPUDebugBuffer *&buf) {
|
||||
GenericStreamBuffer(req, [](const GPUDebugBuffer *&buf, bool *isFramebuffer) {
|
||||
*isFramebuffer = false;
|
||||
return GPUStepping::GPU_GetCurrentDepthbuffer(buf);
|
||||
});
|
||||
}
|
||||
@@ -339,7 +349,8 @@ void WebSocketGPUBufferRenderDepth(DebuggerRequest &req) {
|
||||
// - format: string indicating format, such as 'X24_S8' or 'S8'.
|
||||
// - base64: base64 encode of binary data.
|
||||
void WebSocketGPUBufferRenderStencil(DebuggerRequest &req) {
|
||||
GenericStreamBuffer(req, [](const GPUDebugBuffer *&buf) {
|
||||
GenericStreamBuffer(req, [](const GPUDebugBuffer *&buf, bool *isFramebuffer) {
|
||||
*isFramebuffer = false;
|
||||
return GPUStepping::GPU_GetCurrentStencilbuffer(buf);
|
||||
});
|
||||
}
|
||||
@@ -354,6 +365,7 @@ void WebSocketGPUBufferRenderStencil(DebuggerRequest &req) {
|
||||
// Response (same event name) for 'uri' type:
|
||||
// - width: numeric width of the texture (often wider than visual.)
|
||||
// - height: numeric height of the texture (often wider than visual.)
|
||||
// - isFramebuffer: optional, present and true if this came from a hardware framebuffer.
|
||||
// - uri: data: URI of PNG image for display.
|
||||
//
|
||||
// Response (same event name) for 'base64' type:
|
||||
@@ -361,14 +373,15 @@ void WebSocketGPUBufferRenderStencil(DebuggerRequest &req) {
|
||||
// - height: numeric height of the texture (often wider than visual.)
|
||||
// - flipped: boolean to indicate whether buffer is vertically flipped.
|
||||
// - format: string indicating format, such as 'R8G8B8A8_UNORM' or 'B8G8R8A8_UNORM'.
|
||||
// - isFramebuffer: optional, present and true if this came from a hardware framebuffer.
|
||||
// - base64: base64 encode of binary data.
|
||||
void WebSocketGPUBufferTexture(DebuggerRequest &req) {
|
||||
u32 level = 0;
|
||||
if (!req.ParamU32("level", &level, false, DebuggerParamType::OPTIONAL))
|
||||
return;
|
||||
|
||||
GenericStreamBuffer(req, [level](const GPUDebugBuffer *&buf) {
|
||||
return GPUStepping::GPU_GetCurrentTexture(buf, level);
|
||||
GenericStreamBuffer(req, [level](const GPUDebugBuffer *&buf, bool *isFramebuffer) {
|
||||
return GPUStepping::GPU_GetCurrentTexture(buf, level, isFramebuffer);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -391,7 +404,9 @@ void WebSocketGPUBufferTexture(DebuggerRequest &req) {
|
||||
// - format: string indicating format, such as 'R8G8B8A8_UNORM' or 'B8G8R8A8_UNORM'.
|
||||
// - base64: base64 encode of binary data.
|
||||
void WebSocketGPUBufferClut(DebuggerRequest &req) {
|
||||
GenericStreamBuffer(req, [](const GPUDebugBuffer *&buf) {
|
||||
GenericStreamBuffer(req, [](const GPUDebugBuffer *&buf, bool *isFramebuffer) {
|
||||
// TODO: Or maybe it could be?
|
||||
*isFramebuffer = false;
|
||||
return GPUStepping::GPU_GetCurrentClut(buf);
|
||||
});
|
||||
}
|
||||
@@ -36,6 +36,7 @@ DebuggerSubscriber *WebSocketHLEInit(DebuggerEventHandlerMap &map) {
|
||||
map["hle.func.list"] = &WebSocketHLEFuncList;
|
||||
map["hle.func.add"] = &WebSocketHLEFuncAdd;
|
||||
map["hle.func.remove"] = &WebSocketHLEFuncRemove;
|
||||
map["hle.func.removeRange"] = &WebSocketHLEFuncRemoveRange;
|
||||
map["hle.func.rename"] = &WebSocketHLEFuncRename;
|
||||
map["hle.func.scan"] = &WebSocketHLEFuncScan;
|
||||
map["hle.module.list"] = &WebSocketHLEModuleList;
|
||||
@@ -361,6 +362,72 @@ void WebSocketHLEFuncRemove(DebuggerRequest &req) {
|
||||
json.writeUint("size", funcSize);
|
||||
}
|
||||
|
||||
// This function removes function symbols that intersect or lie inside the range
|
||||
// (Note: this makes no checks whether the range is valid)
|
||||
// Returns the number of removed functions
|
||||
static u32 RemoveFuncSymbolsInRange(u32 addr, u32 size) {
|
||||
u32 func_address = g_symbolMap->GetFunctionStart(addr);
|
||||
if (func_address == SymbolMap::INVALID_ADDRESS) {
|
||||
func_address = g_symbolMap->GetNextSymbolAddress(addr, SymbolType::ST_FUNCTION);
|
||||
}
|
||||
|
||||
u32 counter = 0;
|
||||
while (func_address < addr + size && func_address != SymbolMap::INVALID_ADDRESS) {
|
||||
g_symbolMap->RemoveFunction(func_address, true);
|
||||
++counter;
|
||||
func_address = g_symbolMap->GetNextSymbolAddress(addr, SymbolType::ST_FUNCTION);
|
||||
}
|
||||
|
||||
if (counter) {
|
||||
MIPSAnalyst::ForgetFunctions(addr, addr + size - 1);
|
||||
|
||||
// The following was copied from hle.func.remove:
|
||||
g_symbolMap->SortSymbols();
|
||||
|
||||
MIPSAnalyst::UpdateHashMap();
|
||||
MIPSAnalyst::ApplyHashMap();
|
||||
|
||||
if (g_Config.bFuncReplacements) {
|
||||
MIPSAnalyst::ReplaceFunctions();
|
||||
}
|
||||
|
||||
// Clear cache for branch lines and such.
|
||||
DisassemblyManager manager;
|
||||
manager.clear();
|
||||
}
|
||||
return counter;
|
||||
}
|
||||
|
||||
// Remove function symbols in range (hle.func.removeRange)
|
||||
//
|
||||
// Parameters:
|
||||
// - address: unsigned integer address for the start of the range.
|
||||
// - size: unsigned integer size in bytes for removal
|
||||
//
|
||||
// Response (same event name):
|
||||
// - count: number of removed functions
|
||||
void WebSocketHLEFuncRemoveRange(DebuggerRequest &req) {
|
||||
if (!g_symbolMap)
|
||||
return req.Fail("CPU not active");
|
||||
if (!Core_IsStepping())
|
||||
return req.Fail("CPU currently running (cpu.stepping first)");
|
||||
|
||||
u32 addr;
|
||||
if (!req.ParamU32("address", &addr))
|
||||
return;
|
||||
u32 size;
|
||||
if (!req.ParamU32("size", &size))
|
||||
return;
|
||||
|
||||
if (!Memory::IsValidRange(addr, size))
|
||||
return req.Fail("Address or size outside valid memory");
|
||||
|
||||
u32 count = RemoveFuncSymbolsInRange(addr, size);
|
||||
|
||||
JsonWriter &json = req.Respond();
|
||||
json.writeUint("count", count);
|
||||
}
|
||||
|
||||
// Rename a function symbol (hle.func.rename)
|
||||
//
|
||||
// Parameters:
|
||||
@@ -368,8 +435,8 @@ void WebSocketHLEFuncRemove(DebuggerRequest &req) {
|
||||
// - name: string, new name for the function.
|
||||
//
|
||||
// Response (same event name):
|
||||
// - address: the start address of the removed function.
|
||||
// - size: the size in bytes of the removed function.
|
||||
// - address: the start address of the renamed function.
|
||||
// - size: the size in bytes of the renamed function.
|
||||
// - name: string, new name repeated back.
|
||||
void WebSocketHLEFuncRename(DebuggerRequest &req) {
|
||||
if (!g_symbolMap)
|
||||
@@ -408,8 +475,9 @@ void WebSocketHLEFuncRename(DebuggerRequest &req) {
|
||||
// Auto-detect functions in a memory range (hle.func.scan)
|
||||
//
|
||||
// Parameters:
|
||||
// - address: unsigned integer address within function to rename.
|
||||
// - address: unsigned integer address for the start of the range.
|
||||
// - size: unsigned integer size in bytes for scan.
|
||||
// - remove: optional bool indicating whether functions that intersect or inside lie inside the range must be removed before scanning
|
||||
//
|
||||
// Response (same event name) with no extra data.
|
||||
void WebSocketHLEFuncScan(DebuggerRequest &req) {
|
||||
@@ -425,10 +493,18 @@ void WebSocketHLEFuncScan(DebuggerRequest &req) {
|
||||
if (!req.ParamU32("size", &size))
|
||||
return;
|
||||
|
||||
bool remove = false;
|
||||
if (!req.ParamBool("remove", &remove, DebuggerParamType::OPTIONAL))
|
||||
return;
|
||||
|
||||
if (!Memory::IsValidRange(addr, size))
|
||||
return req.Fail("Address or size outside valid memory");
|
||||
|
||||
bool insertSymbols = MIPSAnalyst::ScanForFunctions(addr, addr + size, true);
|
||||
if (remove) {
|
||||
RemoveFuncSymbolsInRange(addr, size);
|
||||
}
|
||||
|
||||
bool insertSymbols = MIPSAnalyst::ScanForFunctions(addr, addr + size - 1, true);
|
||||
MIPSAnalyst::FinalizeScan(insertSymbols);
|
||||
|
||||
req.Respond();
|
||||
|
||||
@@ -27,6 +27,7 @@ void WebSocketHLEThreadStop(DebuggerRequest &req);
|
||||
void WebSocketHLEFuncList(DebuggerRequest &req);
|
||||
void WebSocketHLEFuncAdd(DebuggerRequest &req);
|
||||
void WebSocketHLEFuncRemove(DebuggerRequest &req);
|
||||
void WebSocketHLEFuncRemoveRange(DebuggerRequest &req);
|
||||
void WebSocketHLEFuncRename(DebuggerRequest &req);
|
||||
void WebSocketHLEFuncScan(DebuggerRequest &req);
|
||||
void WebSocketHLEModuleList(DebuggerRequest &req);
|
||||
|
||||
@@ -227,7 +227,7 @@ static bool AnalogValue(DebuggerRequest &req, float *value, const char *name) {
|
||||
}
|
||||
|
||||
double val = node->value.toNumber();
|
||||
if (val < 1.0 || val > 1.0) {
|
||||
if (val < -1.0 || val > 1.0) {
|
||||
req.Fail(StringFromFormat("Parameter '%s' must be between -1.0 and 1.0", name));
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -216,7 +216,7 @@ bool DebuggerRequest::ParamBool(const char *name, bool *out, DebuggerParamType t
|
||||
*out = true;
|
||||
return true;
|
||||
}
|
||||
if (s == "0" || s == "false" || (s == "" && allowLoose)) {
|
||||
if (s == "0" || s == "false" || (s.empty() && allowLoose)) {
|
||||
*out = false;
|
||||
return true;
|
||||
}
|
||||
@@ -262,7 +262,7 @@ bool DebuggerRequest::ParamString(const char *name, std::string *out, DebuggerPa
|
||||
return true;
|
||||
} else if (tag == JSON_NULL) {
|
||||
if (required) {
|
||||
*out = "";
|
||||
out->clear();
|
||||
}
|
||||
return true;
|
||||
} else if (tag == JSON_NUMBER) {
|
||||
|
||||
@@ -206,12 +206,9 @@ void PSPGamedataInstallDialog::CloseCurrentFile() {
|
||||
void PSPGamedataInstallDialog::WriteSfoFile() {
|
||||
ParamSFOData sfoFile;
|
||||
std::string sfopath = GetGameDataInstallFileName(&request, SFO_FILENAME);
|
||||
PSPFileInfo sfoInfo = pspFileSystem.GetFileInfo(sfopath);
|
||||
if (sfoInfo.exists) {
|
||||
std::vector<u8> sfoData;
|
||||
if (pspFileSystem.ReadEntireFile(sfopath, sfoData) >= 0) {
|
||||
sfoFile.ReadSFO(sfoData);
|
||||
}
|
||||
std::vector<u8> sfoFileData;
|
||||
if (pspFileSystem.ReadEntireFile(sfopath, sfoFileData) >= 0) {
|
||||
sfoFile.ReadSFO(sfoFileData);
|
||||
}
|
||||
|
||||
// Update based on the just-saved data.
|
||||
|
||||
@@ -194,21 +194,21 @@ void PSPNetconfDialog::DisplayMessage(std::string text1, std::string text2a, std
|
||||
|
||||
PPGeScissor(0, (int)(centerY - h2 - 2), 480, (int)(centerY + h2 + 2));
|
||||
PPGeDrawTextWrapped(text1.c_str(), 240.0f, centerY - h2 - scrollPos_, WRAP_WIDTH, 0, messageStyle);
|
||||
if (text2a != "") {
|
||||
if (text2b != "")
|
||||
if (!text2a.empty()) {
|
||||
if (!text2b.empty())
|
||||
PPGeDrawTextWrapped(text2a.c_str(), 240.0f - 5.0f, centerY - h2 - scrollPos_ + totalHeight1 + marginTop, WRAP_WIDTH, 0, messageStyleRight);
|
||||
else
|
||||
PPGeDrawTextWrapped(text2a.c_str(), 240.0f, centerY - h2 - scrollPos_ + totalHeight1 + marginTop, WRAP_WIDTH, 0, messageStyle);
|
||||
}
|
||||
if (text2b != "")
|
||||
if (!text2b.empty())
|
||||
PPGeDrawTextWrapped(text2b.c_str(), 240.0f + 5.0f, centerY - h2 - scrollPos_ + totalHeight1 + marginTop, WRAP_WIDTH, 0, messageStyleLeft);
|
||||
if (text3a != "") {
|
||||
if (text3b != "")
|
||||
if (!text3a.empty()) {
|
||||
if (!text3b.empty())
|
||||
PPGeDrawTextWrapped(text3a.c_str(), 240.0f - 5.0f, centerY - h2 - scrollPos_ + totalHeight1 + totalHeight2 + marginTop, WRAP_WIDTH, 0, messageStyleRight);
|
||||
else
|
||||
PPGeDrawTextWrapped(text3a.c_str(), 240.0f, centerY - h2 - scrollPos_ + totalHeight1 + totalHeight2 + marginTop, WRAP_WIDTH, 0, messageStyle);
|
||||
}
|
||||
if (text3b != "")
|
||||
if (!text3b.empty())
|
||||
PPGeDrawTextWrapped(text3b.c_str(), 240.0f + 5.0f, centerY - h2 - scrollPos_ + totalHeight1 + totalHeight2 + marginTop, WRAP_WIDTH, 0, messageStyleLeft);
|
||||
PPGeScissorReset();
|
||||
|
||||
|
||||
@@ -191,21 +191,21 @@ void PSPNpSigninDialog::DisplayMessage(std::string text1, std::string text2a, st
|
||||
|
||||
PPGeScissor(0, (int)(centerY - h2 - 2), 480, (int)(centerY + h2 + 2));
|
||||
PPGeDrawTextWrapped(text1.c_str(), 240.0f, centerY - h2 - scrollPos_, WRAP_WIDTH, 0, messageStyle);
|
||||
if (text2a != "") {
|
||||
if (text2b != "")
|
||||
if (!text2a.empty()) {
|
||||
if (!text2b.empty())
|
||||
PPGeDrawTextWrapped(text2a.c_str(), 240.0f - 5.0f, centerY - h2 - scrollPos_ + totalHeight1 + marginTop, WRAP_WIDTH, 0, messageStyleRight);
|
||||
else
|
||||
PPGeDrawTextWrapped(text2a.c_str(), 240.0f, centerY - h2 - scrollPos_ + totalHeight1 + marginTop, WRAP_WIDTH, 0, messageStyle);
|
||||
}
|
||||
if (text2b != "")
|
||||
if (!text2b.empty())
|
||||
PPGeDrawTextWrapped(text2b.c_str(), 240.0f + 5.0f, centerY - h2 - scrollPos_ + totalHeight1 + marginTop, WRAP_WIDTH, 0, messageStyleLeft);
|
||||
if (text3a != "") {
|
||||
if (text3b != "")
|
||||
if (!text3a.empty()) {
|
||||
if (!text3b.empty())
|
||||
PPGeDrawTextWrapped(text3a.c_str(), 240.0f - 5.0f, centerY - h2 - scrollPos_ + totalHeight1 + totalHeight2 + marginTop, WRAP_WIDTH, 0, messageStyleRight);
|
||||
else
|
||||
PPGeDrawTextWrapped(text3a.c_str(), 240.0f, centerY - h2 - scrollPos_ + totalHeight1 + totalHeight2 + marginTop, WRAP_WIDTH, 0, messageStyle);
|
||||
}
|
||||
if (text3b != "")
|
||||
if (!text3b.empty())
|
||||
PPGeDrawTextWrapped(text3b.c_str(), 240.0f + 5.0f, centerY - h2 - scrollPos_ + totalHeight1 + totalHeight2 + marginTop, WRAP_WIDTH, 0, messageStyleLeft);
|
||||
PPGeScissorReset();
|
||||
|
||||
|
||||
@@ -56,6 +56,31 @@ const static int SAVEDATA_DIALOG_SIZE_V1 = 1480;
|
||||
const static int SAVEDATA_DIALOG_SIZE_V2 = 1500;
|
||||
const static int SAVEDATA_DIALOG_SIZE_V3 = 1536;
|
||||
|
||||
static bool IsNotVisibleAction(SceUtilitySavedataType type) {
|
||||
switch (type) {
|
||||
case SCE_UTILITY_SAVEDATA_TYPE_AUTOLOAD:
|
||||
case SCE_UTILITY_SAVEDATA_TYPE_AUTOSAVE:
|
||||
case SCE_UTILITY_SAVEDATA_TYPE_SIZES:
|
||||
case SCE_UTILITY_SAVEDATA_TYPE_LIST:
|
||||
case SCE_UTILITY_SAVEDATA_TYPE_FILES:
|
||||
case SCE_UTILITY_SAVEDATA_TYPE_GETSIZE:
|
||||
case SCE_UTILITY_SAVEDATA_TYPE_MAKEDATASECURE:
|
||||
case SCE_UTILITY_SAVEDATA_TYPE_MAKEDATA:
|
||||
case SCE_UTILITY_SAVEDATA_TYPE_WRITEDATASECURE:
|
||||
case SCE_UTILITY_SAVEDATA_TYPE_WRITEDATA:
|
||||
case SCE_UTILITY_SAVEDATA_TYPE_READDATASECURE:
|
||||
case SCE_UTILITY_SAVEDATA_TYPE_READDATA:
|
||||
case SCE_UTILITY_SAVEDATA_TYPE_ERASESECURE:
|
||||
case SCE_UTILITY_SAVEDATA_TYPE_ERASE:
|
||||
case SCE_UTILITY_SAVEDATA_TYPE_DELETEDATA:
|
||||
case SCE_UTILITY_SAVEDATA_TYPE_AUTODELETE:
|
||||
return true;
|
||||
|
||||
default:
|
||||
break;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
PSPSaveDialog::PSPSaveDialog(UtilityDialogType type) : PSPDialog(type) {
|
||||
param.SetPspParam(0);
|
||||
@@ -87,6 +112,8 @@ int PSPSaveDialog::Init(int paramAddr)
|
||||
Memory::Memcpy(&request, requestAddr, size);
|
||||
Memory::Memcpy(&originalRequest, requestAddr, size);
|
||||
|
||||
param.SetIgnoreTextures(IsNotVisibleAction((SceUtilitySavedataType)(u32)request.mode));
|
||||
param.ClearCaches();
|
||||
int retval = param.SetPspParam(&request);
|
||||
|
||||
const u32 mode = (u32)param.GetPspParam()->mode;
|
||||
@@ -197,6 +224,8 @@ int PSPSaveDialog::Init(int paramAddr)
|
||||
case SCE_UTILITY_SAVEDATA_TYPE_WRITEDATA:
|
||||
case SCE_UTILITY_SAVEDATA_TYPE_READDATASECURE:
|
||||
case SCE_UTILITY_SAVEDATA_TYPE_READDATA:
|
||||
case SCE_UTILITY_SAVEDATA_TYPE_ERASESECURE:
|
||||
case SCE_UTILITY_SAVEDATA_TYPE_ERASE:
|
||||
case SCE_UTILITY_SAVEDATA_TYPE_DELETEDATA:
|
||||
display = DS_NONE;
|
||||
break;
|
||||
@@ -239,6 +268,7 @@ int PSPSaveDialog::Init(int paramAddr)
|
||||
ChangeStatusInit(SAVEDATA_INIT_DELAY_US);
|
||||
}
|
||||
|
||||
param.ClearCaches();
|
||||
UpdateButtons();
|
||||
StartFade(true);
|
||||
|
||||
@@ -345,7 +375,7 @@ void PSPSaveDialog::DisplaySaveList(bool canMove) {
|
||||
PPGeImageStyle imageStyle = FadedImageStyle();
|
||||
auto fileInfo = param.GetFileInfo(displayCount);
|
||||
|
||||
if (fileInfo.size == 0 && fileInfo.texture != NULL)
|
||||
if (fileInfo.size == 0 && fileInfo.texture && fileInfo.texture->IsValid())
|
||||
imageStyle.color = CalcFadedColor(0xFF777777);
|
||||
|
||||
// Calc save image position on screen
|
||||
@@ -370,7 +400,7 @@ void PSPSaveDialog::DisplaySaveList(bool canMove) {
|
||||
continue;
|
||||
|
||||
int pad = 0;
|
||||
if (fileInfo.texture != nullptr) {
|
||||
if (fileInfo.texture != nullptr && fileInfo.texture->IsValid()) {
|
||||
fileInfo.texture->SetTexture();
|
||||
int tw = fileInfo.texture->Width();
|
||||
int th = fileInfo.texture->Height();
|
||||
@@ -420,7 +450,7 @@ void PSPSaveDialog::DisplaySaveIcon(bool checkExists)
|
||||
|
||||
int tw = 256;
|
||||
int th = 256;
|
||||
if (curSave.texture != NULL) {
|
||||
if (curSave.texture != nullptr && curSave.texture->IsValid()) {
|
||||
curSave.texture->SetTexture();
|
||||
tw = curSave.texture->Width();
|
||||
th = curSave.texture->Height();
|
||||
@@ -618,6 +648,7 @@ int PSPSaveDialog::Update(int animSpeed)
|
||||
param.SetPspParam(&request);
|
||||
}
|
||||
|
||||
param.ClearCaches();
|
||||
UpdateButtons();
|
||||
UpdateFade(animSpeed);
|
||||
|
||||
@@ -1035,11 +1066,13 @@ int PSPSaveDialog::Update(int animSpeed)
|
||||
|
||||
if (ReadStatus() == SCE_UTILITY_STATUS_FINISHED || pendingStatus == SCE_UTILITY_STATUS_FINISHED)
|
||||
Memory::Memcpy(requestAddr, &request, request.common.size, "SaveDialogParam");
|
||||
param.ClearCaches();
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
void PSPSaveDialog::ExecuteIOAction() {
|
||||
param.ClearCaches();
|
||||
auto &result = param.GetPspParam()->common.result;
|
||||
std::lock_guard<std::mutex> guard(paramLock);
|
||||
switch (display) {
|
||||
@@ -1078,9 +1111,11 @@ void PSPSaveDialog::ExecuteIOAction() {
|
||||
}
|
||||
|
||||
ioThreadStatus = SAVEIO_DONE;
|
||||
param.ClearCaches();
|
||||
}
|
||||
|
||||
void PSPSaveDialog::ExecuteNotVisibleIOAction() {
|
||||
param.ClearCaches();
|
||||
auto &result = param.GetPspParam()->common.result;
|
||||
|
||||
switch ((SceUtilitySavedataType)(u32)param.GetPspParam()->mode) {
|
||||
@@ -1161,6 +1196,8 @@ void PSPSaveDialog::ExecuteNotVisibleIOAction() {
|
||||
default:
|
||||
break;
|
||||
}
|
||||
|
||||
param.ClearCaches();
|
||||
}
|
||||
|
||||
void PSPSaveDialog::JoinIOThread() {
|
||||
@@ -1198,6 +1235,7 @@ int PSPSaveDialog::Shutdown(bool force) {
|
||||
ChangeStatusShutdown(SAVEDATA_SHUTDOWN_DELAY_US);
|
||||
}
|
||||
param.SetPspParam(0);
|
||||
param.ClearCaches();
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
+178
-129
@@ -15,6 +15,8 @@
|
||||
// Official git repository and contact information can be found at
|
||||
// https://github.com/hrydgard/ppsspp and http://www.ppsspp.org/.
|
||||
|
||||
#include <algorithm>
|
||||
#include <memory>
|
||||
#include "Common/Log.h"
|
||||
#include "Common/Data/Text/I18n.h"
|
||||
#include "Common/Data/Format/ZIMLoad.h"
|
||||
@@ -36,14 +38,15 @@
|
||||
#include "Core/HW/MemoryStick.h"
|
||||
#include "Core/Util/PPGeDraw.h"
|
||||
|
||||
#include <algorithm>
|
||||
|
||||
static const std::string ICON0_FILENAME = "ICON0.PNG";
|
||||
static const std::string ICON1_FILENAME = "ICON1.PMF";
|
||||
static const std::string PIC1_FILENAME = "PIC1.PNG";
|
||||
static const std::string SND0_FILENAME = "SND0.AT3";
|
||||
static const std::string SFO_FILENAME = "PARAM.SFO";
|
||||
|
||||
static const int FILE_LIST_COUNT_MAX = 99;
|
||||
static const u32 FILE_LIST_TOTAL_SIZE = sizeof(SaveSFOFileListEntry) * FILE_LIST_COUNT_MAX;
|
||||
|
||||
static const std::string savePath = "ms0:/PSP/SAVEDATA/";
|
||||
|
||||
namespace
|
||||
@@ -95,6 +98,18 @@ namespace
|
||||
return result == dataSize;
|
||||
}
|
||||
|
||||
PSPFileInfo FileFromListing(const std::vector<PSPFileInfo> &listing, const std::string &filename) {
|
||||
for (const PSPFileInfo &sub : listing) {
|
||||
if (sub.name == filename)
|
||||
return sub;
|
||||
}
|
||||
|
||||
PSPFileInfo info;
|
||||
info.name = filename;
|
||||
info.exists = false;
|
||||
return info;
|
||||
}
|
||||
|
||||
bool PSPMatch(std::string text, std::string regexp)
|
||||
{
|
||||
if(text.empty() && regexp.empty())
|
||||
@@ -258,7 +273,7 @@ std::string SavedataParam::GetSaveFilePath(const SceUtilitySavedataParam *param,
|
||||
inline static std::string FixedToString(const char *str, size_t n)
|
||||
{
|
||||
if (!str) {
|
||||
return std::string("");
|
||||
return std::string();
|
||||
} else {
|
||||
return std::string(str, strnlen(str, n));
|
||||
}
|
||||
@@ -331,6 +346,7 @@ bool SavedataParam::Delete(SceUtilitySavedataParam* param, int saveId) {
|
||||
return false;
|
||||
}
|
||||
|
||||
ClearCaches();
|
||||
pspFileSystem.RmDir(dirPath);
|
||||
return true;
|
||||
}
|
||||
@@ -353,11 +369,11 @@ int SavedataParam::DeleteData(SceUtilitySavedataParam* param) {
|
||||
if (!pspFileSystem.GetFileInfo(sfoPath).exists)
|
||||
return SCE_UTILITY_SAVEDATA_ERROR_RW_DATA_BROKEN;
|
||||
|
||||
if (fileName != "" && !pspFileSystem.GetFileInfo(filePath).exists) {
|
||||
if (!fileName.empty() && !pspFileSystem.GetFileInfo(filePath).exists) {
|
||||
return SCE_UTILITY_SAVEDATA_ERROR_RW_FILE_NOT_FOUND;
|
||||
}
|
||||
|
||||
if (fileName == "") {
|
||||
if (fileName.empty()) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
@@ -366,8 +382,42 @@ int SavedataParam::DeleteData(SceUtilitySavedataParam* param) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
ClearCaches();
|
||||
pspFileSystem.RemoveFile(filePath);
|
||||
|
||||
// Update PARAM.SFO to remove the file, if it was in the list.
|
||||
std::shared_ptr<ParamSFOData> sfoFile = LoadCachedSFO(sfoPath);
|
||||
if (sfoFile) {
|
||||
// Note: do not update values such as TITLE in this operation.
|
||||
u32 fileListSize = 0;
|
||||
SaveSFOFileListEntry *fileList = (SaveSFOFileListEntry *)sfoFile->GetValueData("SAVEDATA_FILE_LIST", &fileListSize);
|
||||
size_t fileListCount = fileListSize / sizeof(SaveSFOFileListEntry);
|
||||
bool changed = false;
|
||||
for (size_t i = 0; i < fileListCount; ++i) {
|
||||
if (strncmp(fileList[i].filename, fileName.c_str(), sizeof(fileList[i].filename)) != 0)
|
||||
continue;
|
||||
|
||||
memset(fileList[i].filename, 0, sizeof(fileList[i].filename));
|
||||
memset(fileList[i].hash, 0, sizeof(fileList[i].hash));
|
||||
changed = true;
|
||||
break;
|
||||
}
|
||||
|
||||
if (changed) {
|
||||
std::unique_ptr<u8[]> updatedList(new u8[fileListSize]);
|
||||
memcpy(updatedList.get(), fileList, fileListSize);
|
||||
sfoFile->SetValue("SAVEDATA_FILE_LIST", updatedList.get(), fileListSize, (int)FILE_LIST_TOTAL_SIZE);
|
||||
|
||||
u8 *sfoData;
|
||||
size_t sfoSize;
|
||||
sfoFile->WriteSFO(&sfoData, &sfoSize);
|
||||
|
||||
ClearCaches();
|
||||
WritePSPFile(sfoPath, sfoData, (SceSize)sfoSize);
|
||||
delete[] sfoData;
|
||||
}
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
@@ -443,28 +493,21 @@ int SavedataParam::Save(SceUtilitySavedataParam* param, const std::string &saveD
|
||||
}
|
||||
|
||||
// SAVE PARAM.SFO
|
||||
ParamSFOData sfoFile;
|
||||
std::string sfopath = dirPath + "/" + SFO_FILENAME;
|
||||
{
|
||||
std::vector<u8> sfoData;
|
||||
if (pspFileSystem.ReadEntireFile(sfopath, sfoData) >= 0)
|
||||
sfoFile.ReadSFO(sfoData);
|
||||
}
|
||||
std::shared_ptr<ParamSFOData> sfoFile = LoadCachedSFO(sfopath, true);
|
||||
|
||||
// Update values
|
||||
sfoFile.SetValue("TITLE",param->sfoParam.title,128);
|
||||
sfoFile.SetValue("SAVEDATA_TITLE",param->sfoParam.savedataTitle,128);
|
||||
sfoFile.SetValue("SAVEDATA_DETAIL",param->sfoParam.detail,1024);
|
||||
sfoFile.SetValue("PARENTAL_LEVEL",param->sfoParam.parentalLevel,4);
|
||||
sfoFile.SetValue("CATEGORY","MS",4);
|
||||
sfoFile.SetValue("SAVEDATA_DIRECTORY", GetSaveDir(param, saveDirName), 64);
|
||||
sfoFile->SetValue("TITLE", param->sfoParam.title, 128);
|
||||
sfoFile->SetValue("SAVEDATA_TITLE", param->sfoParam.savedataTitle, 128);
|
||||
sfoFile->SetValue("SAVEDATA_DETAIL", param->sfoParam.detail, 1024);
|
||||
sfoFile->SetValue("PARENTAL_LEVEL", param->sfoParam.parentalLevel, 4);
|
||||
sfoFile->SetValue("CATEGORY", "MS", 4);
|
||||
sfoFile->SetValue("SAVEDATA_DIRECTORY", GetSaveDir(param, saveDirName), 64);
|
||||
|
||||
// Always write and update the file list.
|
||||
// For each file, 13 bytes for filename, 16 bytes for file hash (0 in PPSSPP), 3 byte for padding
|
||||
const int FILE_LIST_COUNT_MAX = 99;
|
||||
const u32 FILE_LIST_TOTAL_SIZE = sizeof(SaveSFOFileListEntry) * FILE_LIST_COUNT_MAX;
|
||||
u32 tmpDataSize = 0;
|
||||
SaveSFOFileListEntry *tmpDataOrig = (SaveSFOFileListEntry *)sfoFile.GetValueData("SAVEDATA_FILE_LIST", &tmpDataSize);
|
||||
SaveSFOFileListEntry *tmpDataOrig = (SaveSFOFileListEntry *)sfoFile->GetValueData("SAVEDATA_FILE_LIST", &tmpDataSize);
|
||||
SaveSFOFileListEntry *updatedList = new SaveSFOFileListEntry[FILE_LIST_COUNT_MAX];
|
||||
if (tmpDataSize != 0)
|
||||
memcpy(updatedList, tmpDataOrig, std::min(tmpDataSize, FILE_LIST_TOTAL_SIZE));
|
||||
@@ -485,28 +528,30 @@ int SavedataParam::Save(SceUtilitySavedataParam* param, const std::string &saveD
|
||||
}
|
||||
}
|
||||
|
||||
sfoFile.SetValue("SAVEDATA_FILE_LIST", (u8 *)updatedList, FILE_LIST_TOTAL_SIZE, (int)FILE_LIST_TOTAL_SIZE);
|
||||
sfoFile->SetValue("SAVEDATA_FILE_LIST", (u8 *)updatedList, FILE_LIST_TOTAL_SIZE, (int)FILE_LIST_TOTAL_SIZE);
|
||||
delete[] updatedList;
|
||||
|
||||
// Init param with 0. This will be used to detect crypted save or not on loading
|
||||
u8 *tmpData = new u8[128];
|
||||
memset(tmpData, 0, 128);
|
||||
sfoFile.SetValue("SAVEDATA_PARAMS", tmpData, 128, 128);
|
||||
sfoFile->SetValue("SAVEDATA_PARAMS", tmpData, 128, 128);
|
||||
delete[] tmpData;
|
||||
|
||||
u8 *sfoData;
|
||||
size_t sfoSize;
|
||||
sfoFile.WriteSFO(&sfoData,&sfoSize);
|
||||
sfoFile->WriteSFO(&sfoData, &sfoSize);
|
||||
|
||||
// Calc SFO hash for PSP.
|
||||
if(cryptedData != 0)
|
||||
{
|
||||
int offset = sfoFile.GetDataOffset(sfoData,"SAVEDATA_PARAMS");
|
||||
if (cryptedData != 0) {
|
||||
int offset = sfoFile->GetDataOffset(sfoData, "SAVEDATA_PARAMS");
|
||||
if(offset >= 0)
|
||||
UpdateHash(sfoData, (int)sfoSize, offset, DetermineCryptMode(param));
|
||||
}
|
||||
|
||||
ClearCaches();
|
||||
WritePSPFile(sfopath, sfoData, (SceSize)sfoSize);
|
||||
delete[] sfoData;
|
||||
sfoData = nullptr;
|
||||
|
||||
if(param->dataBuf.IsValid()) // Can launch save without save data in mode 13
|
||||
{
|
||||
@@ -533,7 +578,7 @@ int SavedataParam::Save(SceUtilitySavedataParam* param, const std::string &saveD
|
||||
// copy back save name in request
|
||||
strncpy(param->saveName, saveDirName.c_str(), 20);
|
||||
|
||||
if (fileName == "") {
|
||||
if (fileName.empty()) {
|
||||
delete[] cryptedData;
|
||||
} else {
|
||||
if (!WritePSPFile(filePath, data_, saveSize)) {
|
||||
@@ -583,13 +628,12 @@ int SavedataParam::Load(SceUtilitySavedataParam *param, const std::string &saveD
|
||||
std::string dirPath = GetSaveFilePath(param, GetSaveDir(param, saveDirName));
|
||||
std::string fileName = GetFileName(param);
|
||||
std::string filePath = dirPath + "/" + fileName;
|
||||
std::string sfoPath = dirPath + "/" + SFO_FILENAME;
|
||||
|
||||
if (!pspFileSystem.GetFileInfo(dirPath).exists) {
|
||||
return isRWMode ? SCE_UTILITY_SAVEDATA_ERROR_RW_NO_DATA : SCE_UTILITY_SAVEDATA_ERROR_LOAD_NO_DATA;
|
||||
}
|
||||
|
||||
if (fileName != "" && !pspFileSystem.GetFileInfo(filePath).exists) {
|
||||
if (!fileName.empty() && !pspFileSystem.GetFileInfo(filePath).exists) {
|
||||
return isRWMode ? SCE_UTILITY_SAVEDATA_ERROR_RW_FILE_NOT_FOUND : SCE_UTILITY_SAVEDATA_ERROR_LOAD_FILE_NOT_FOUND;
|
||||
}
|
||||
|
||||
@@ -637,7 +681,7 @@ int SavedataParam::LoadSaveData(SceUtilitySavedataParam *param, const std::strin
|
||||
std::string filename = GetFileName(param);
|
||||
std::string filePath = dirPath + "/" + filename;
|
||||
// Blank filename always means success, if secureVersion was correct.
|
||||
if (filename == "")
|
||||
if (filename.empty())
|
||||
return 0;
|
||||
|
||||
s64 readSize;
|
||||
@@ -793,38 +837,30 @@ u32 SavedataParam::LoadNotCryptedSave(SceUtilitySavedataParam *param, u8 *data,
|
||||
}
|
||||
|
||||
bool SavedataParam::LoadSFO(SceUtilitySavedataParam *param, const std::string& dirPath) {
|
||||
ParamSFOData sfoFile;
|
||||
std::string sfopath = dirPath + "/" + SFO_FILENAME;
|
||||
std::vector<u8> sfoData;
|
||||
if (pspFileSystem.ReadEntireFile(sfopath, sfoData) >= 0) {
|
||||
sfoFile.ReadSFO(sfoData);
|
||||
|
||||
std::shared_ptr<ParamSFOData> sfoFile = LoadCachedSFO(sfopath);
|
||||
if (sfoFile) {
|
||||
// copy back info in request
|
||||
strncpy(param->sfoParam.title,sfoFile.GetValueString("TITLE").c_str(),128);
|
||||
strncpy(param->sfoParam.savedataTitle,sfoFile.GetValueString("SAVEDATA_TITLE").c_str(),128);
|
||||
strncpy(param->sfoParam.detail,sfoFile.GetValueString("SAVEDATA_DETAIL").c_str(),1024);
|
||||
param->sfoParam.parentalLevel = sfoFile.GetValueInt("PARENTAL_LEVEL");
|
||||
strncpy(param->sfoParam.title, sfoFile->GetValueString("TITLE").c_str(), 128);
|
||||
strncpy(param->sfoParam.savedataTitle, sfoFile->GetValueString("SAVEDATA_TITLE").c_str(), 128);
|
||||
strncpy(param->sfoParam.detail, sfoFile->GetValueString("SAVEDATA_DETAIL").c_str(), 1024);
|
||||
param->sfoParam.parentalLevel = sfoFile->GetValueInt("PARENTAL_LEVEL");
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
std::vector<SaveSFOFileListEntry> SavedataParam::GetSFOEntries(const std::string &dirPath) {
|
||||
std::vector<SaveSFOFileListEntry> result;
|
||||
const std::string sfoPath = dirPath + "/" + SFO_FILENAME;
|
||||
|
||||
ParamSFOData sfoFile;
|
||||
std::vector<u8> sfoData;
|
||||
if (pspFileSystem.ReadEntireFile(sfoPath, sfoData) >= 0) {
|
||||
sfoFile.ReadSFO(sfoData);
|
||||
} else {
|
||||
std::shared_ptr<ParamSFOData> sfoFile = LoadCachedSFO(sfoPath);
|
||||
if (!sfoFile) {
|
||||
return result;
|
||||
}
|
||||
|
||||
const int FILE_LIST_COUNT_MAX = 99;
|
||||
u32 sfoFileListSize = 0;
|
||||
SaveSFOFileListEntry *sfoFileList = (SaveSFOFileListEntry *)sfoFile.GetValueData("SAVEDATA_FILE_LIST", &sfoFileListSize);
|
||||
SaveSFOFileListEntry *sfoFileList = (SaveSFOFileListEntry *)sfoFile->GetValueData("SAVEDATA_FILE_LIST", &sfoFileListSize);
|
||||
const u32 count = std::min((u32)FILE_LIST_COUNT_MAX, sfoFileListSize / (u32)sizeof(SaveSFOFileListEntry));
|
||||
|
||||
for (u32 i = 0; i < count; ++i) {
|
||||
@@ -1095,13 +1131,12 @@ int SavedataParam::GetSizes(SceUtilitySavedataParam *param)
|
||||
const std::string saveName(msData->saveName, strnlen(msData->saveName, sizeof(msData->saveName)));
|
||||
// TODO: How should <> be handled?
|
||||
std::string path = GetSaveFilePath(param, gameName + (saveName == "<>" ? "" : saveName));
|
||||
PSPFileInfo finfo = pspFileSystem.GetFileInfo(path);
|
||||
if (finfo.exists)
|
||||
{
|
||||
bool listingExists = false;
|
||||
auto listing = pspFileSystem.GetDirListing(path, &listingExists);
|
||||
if (listingExists) {
|
||||
param->msData->info.usedClusters = 0;
|
||||
auto listing = pspFileSystem.GetDirListing(path);
|
||||
for (auto it = listing.begin(), end = listing.end(); it != end; ++it) {
|
||||
param->msData->info.usedClusters += (it->size + (u32)MemoryStick_SectorSize() - 1) / (u32)MemoryStick_SectorSize();
|
||||
for (auto &item : listing) {
|
||||
param->msData->info.usedClusters += (item.size + (u32)MemoryStick_SectorSize() - 1) / (u32)MemoryStick_SectorSize();
|
||||
}
|
||||
|
||||
// The usedSpaceKB value is definitely based on clusters, not bytes or even KB.
|
||||
@@ -1252,7 +1287,9 @@ int SavedataParam::GetFilesList(SceUtilitySavedataParam *param, u32 requestAddr)
|
||||
}
|
||||
|
||||
std::string dirPath = savePath + GetGameName(param) + GetSaveName(param);
|
||||
if (!pspFileSystem.GetFileInfo(dirPath).exists) {
|
||||
bool dirPathExists = false;
|
||||
auto files = pspFileSystem.GetDirListing(dirPath, &dirPathExists);
|
||||
if (!dirPathExists) {
|
||||
DEBUG_LOG(SCEUTILITY, "SavedataParam::GetFilesList(): directory %s does not exist", dirPath.c_str());
|
||||
return SCE_UTILITY_SAVEDATA_ERROR_RW_NO_DATA;
|
||||
}
|
||||
@@ -1263,7 +1300,7 @@ int SavedataParam::GetFilesList(SceUtilitySavedataParam *param, u32 requestAddr)
|
||||
fileList->resultNumSystemEntries = 0;
|
||||
|
||||
// We need PARAM.SFO's SAVEDATA_FILE_LIST to determine which entries are secure.
|
||||
PSPFileInfo sfoFileInfo = pspFileSystem.GetFileInfo(dirPath + "/" + SFO_FILENAME);
|
||||
PSPFileInfo sfoFileInfo = FileFromListing(files, SFO_FILENAME);
|
||||
std::set<std::string> secureFilenames;
|
||||
|
||||
if (sfoFileInfo.exists) {
|
||||
@@ -1280,7 +1317,7 @@ int SavedataParam::GetFilesList(SceUtilitySavedataParam *param, u32 requestAddr)
|
||||
requestPtr->bind = 1021;
|
||||
|
||||
// Does not list directories, nor recurse into them, and ignores files not ALL UPPERCASE.
|
||||
auto files = pspFileSystem.GetDirListing(dirPath);
|
||||
bool isCrypted = GetSaveCryptMode(param, GetSaveDirName(param, 0)) != 0;
|
||||
for (auto file = files.begin(), end = files.end(); file != end; ++file) {
|
||||
if (file->type == FILETYPE_DIRECTORY) {
|
||||
continue;
|
||||
@@ -1305,7 +1342,6 @@ int SavedataParam::GetFilesList(SceUtilitySavedataParam *param, u32 requestAddr)
|
||||
entry = &fileList->secureEntries[fileList->resultNumSecureEntries++];
|
||||
}
|
||||
// Secure files are slightly bigger.
|
||||
bool isCrypted = GetSaveCryptMode(param, GetSaveDirName(param, 0)) != 0;
|
||||
if (isCrypted) {
|
||||
sizeOffset = -0x10;
|
||||
}
|
||||
@@ -1349,8 +1385,8 @@ bool SavedataParam::GetSize(SceUtilitySavedataParam *param)
|
||||
}
|
||||
|
||||
const std::string saveDir = savePath + GetGameName(param) + GetSaveName(param);
|
||||
PSPFileInfo info = pspFileSystem.GetFileInfo(saveDir);
|
||||
bool exists = info.exists;
|
||||
bool exists = false;
|
||||
auto listing = pspFileSystem.GetDirListing(saveDir, &exists);
|
||||
|
||||
if (param->sizeInfo.IsValid())
|
||||
{
|
||||
@@ -1360,12 +1396,12 @@ bool SavedataParam::GetSize(SceUtilitySavedataParam *param)
|
||||
s64 writeBytes = 0;
|
||||
for (int i = 0; i < param->sizeInfo->numNormalEntries; ++i) {
|
||||
const auto &entry = param->sizeInfo->normalEntries[i];
|
||||
overwriteBytes += pspFileSystem.GetFileInfo(saveDir + "/" + entry.name).size;
|
||||
overwriteBytes += FileFromListing(listing, entry.name).size;
|
||||
writeBytes += entry.size;
|
||||
}
|
||||
for (int i = 0; i < param->sizeInfo->numSecureEntries; ++i) {
|
||||
const auto &entry = param->sizeInfo->secureEntries[i];
|
||||
overwriteBytes += pspFileSystem.GetFileInfo(saveDir + "/" + entry.name).size;
|
||||
overwriteBytes += FileFromListing(listing, entry.name).size;
|
||||
writeBytes += entry.size + 0x10;
|
||||
}
|
||||
|
||||
@@ -1489,23 +1525,20 @@ int SavedataParam::SetPspParam(SceUtilitySavedataParam *param)
|
||||
for (int i = 0; i < saveDataListCount; i++) {
|
||||
// "<>" means saveName can be anything...
|
||||
if (strncmp(saveNameListData[i], "<>", ARRAY_SIZE(saveNameListData[i])) == 0) {
|
||||
std::string fileDataPath = "";
|
||||
// TODO:Maybe we need a way to reorder the files?
|
||||
auto allSaves = pspFileSystem.GetDirListing(savePath);
|
||||
std::string gameName = GetGameName(param);
|
||||
std::string saveName = "";
|
||||
for(auto it = allSaves.begin(); it != allSaves.end(); ++it) {
|
||||
if(it->name.compare(0, gameName.length(), gameName) == 0) {
|
||||
saveName = it->name.substr(gameName.length());
|
||||
for (auto it = allSaves.begin(); it != allSaves.end(); ++it) {
|
||||
if (it->name.compare(0, gameName.length(), gameName) == 0) {
|
||||
std::string saveName = it->name.substr(gameName.length());
|
||||
|
||||
if(IsInSaveDataList(saveName, realCount)) // Already in SaveDataList, skip...
|
||||
if (IsInSaveDataList(saveName, realCount)) // Already in SaveDataList, skip...
|
||||
continue;
|
||||
|
||||
fileDataPath = savePath + it->name;
|
||||
PSPFileInfo info = pspFileSystem.GetFileInfo(fileDataPath);
|
||||
if (info.exists) {
|
||||
SetFileInfo(realCount, info, saveName);
|
||||
DEBUG_LOG(SCEUTILITY,"%s Exist",fileDataPath.c_str());
|
||||
std::string fileDataPath = savePath + it->name;
|
||||
if (it->exists) {
|
||||
SetFileInfo(realCount, *it, saveName);
|
||||
DEBUG_LOG(SCEUTILITY, "%s Exist", fileDataPath.c_str());
|
||||
++realCount;
|
||||
} else {
|
||||
if (listEmptyFile) {
|
||||
@@ -1576,7 +1609,7 @@ void SavedataParam::SetFileInfo(SaveFileInfo &saveInfo, PSPFileInfo &info, std::
|
||||
saveInfo.idx = 0;
|
||||
saveInfo.modif_time = info.mtime;
|
||||
|
||||
std::string saveDir = savrDir == "" ? GetGameName(pspParam) + saveName : savrDir;
|
||||
std::string saveDir = savrDir.empty() ? GetGameName(pspParam) + saveName : savrDir;
|
||||
saveInfo.saveDir = saveDir;
|
||||
|
||||
// Start with a blank slate.
|
||||
@@ -1592,23 +1625,17 @@ void SavedataParam::SetFileInfo(SaveFileInfo &saveInfo, PSPFileInfo &info, std::
|
||||
|
||||
// Search save image icon0
|
||||
// TODO : If icon0 don't exist, need to use icon1 which is a moving icon. Also play sound
|
||||
std::string fileDataPath2 = savePath + saveDir + "/" + ICON0_FILENAME;
|
||||
PSPFileInfo info2 = pspFileSystem.GetFileInfo(fileDataPath2);
|
||||
if (info2.exists)
|
||||
saveInfo.texture = new PPGeImage(fileDataPath2);
|
||||
if (!ignoreTextures_) {
|
||||
saveInfo.texture = new PPGeImage(savePath + saveDir + "/" + ICON0_FILENAME);
|
||||
}
|
||||
|
||||
// Load info in PARAM.SFO
|
||||
fileDataPath2 = savePath + saveDir + "/" + SFO_FILENAME;
|
||||
info2 = pspFileSystem.GetFileInfo(fileDataPath2);
|
||||
if (info2.exists) {
|
||||
std::vector<u8> sfoData;
|
||||
pspFileSystem.ReadEntireFile(fileDataPath2, sfoData);
|
||||
ParamSFOData sfoFile;
|
||||
if (sfoFile.ReadSFO(sfoData)) {
|
||||
SetStringFromSFO(sfoFile, "TITLE", saveInfo.title, sizeof(saveInfo.title));
|
||||
SetStringFromSFO(sfoFile, "SAVEDATA_TITLE", saveInfo.saveTitle, sizeof(saveInfo.saveTitle));
|
||||
SetStringFromSFO(sfoFile, "SAVEDATA_DETAIL", saveInfo.saveDetail, sizeof(saveInfo.saveDetail));
|
||||
}
|
||||
std::string sfoFilename = savePath + saveDir + "/" + SFO_FILENAME;
|
||||
std::shared_ptr<ParamSFOData> sfoFile = LoadCachedSFO(sfoFilename);
|
||||
if (sfoFile) {
|
||||
SetStringFromSFO(*sfoFile, "TITLE", saveInfo.title, sizeof(saveInfo.title));
|
||||
SetStringFromSFO(*sfoFile, "SAVEDATA_TITLE", saveInfo.saveTitle, sizeof(saveInfo.saveTitle));
|
||||
SetStringFromSFO(*sfoFile, "SAVEDATA_DETAIL", saveInfo.saveDetail, sizeof(saveInfo.saveDetail));
|
||||
} else {
|
||||
saveInfo.broken = true;
|
||||
truncate_cpy(saveInfo.title, saveDir.c_str());
|
||||
@@ -1853,9 +1880,8 @@ bool SavedataParam::wouldHasMultiSaveName(SceUtilitySavedataParam* param) {
|
||||
}
|
||||
}
|
||||
|
||||
void SavedataParam::DoState(PointerWrap &p)
|
||||
{
|
||||
auto s = p.Section("SavedataParam", 1);
|
||||
void SavedataParam::DoState(PointerWrap &p) {
|
||||
auto s = p.Section("SavedataParam", 1, 2);
|
||||
if (!s)
|
||||
return;
|
||||
|
||||
@@ -1863,55 +1889,78 @@ void SavedataParam::DoState(PointerWrap &p)
|
||||
Do(p, selectedSave);
|
||||
Do(p, saveDataListCount);
|
||||
Do(p, saveNameListDataCount);
|
||||
if (p.mode == p.MODE_READ)
|
||||
{
|
||||
if (p.mode == p.MODE_READ) {
|
||||
if (saveDataList != NULL)
|
||||
delete [] saveDataList;
|
||||
if (saveDataListCount != 0)
|
||||
{
|
||||
if (saveDataListCount != 0) {
|
||||
saveDataList = new SaveFileInfo[saveDataListCount];
|
||||
DoArray(p, saveDataList, saveDataListCount);
|
||||
}
|
||||
else
|
||||
} else {
|
||||
saveDataList = NULL;
|
||||
}
|
||||
}
|
||||
else
|
||||
DoArray(p, saveDataList, saveDataListCount);
|
||||
|
||||
if (s >= 2) {
|
||||
Do(p, ignoreTextures_);
|
||||
} else {
|
||||
ignoreTextures_ = false;
|
||||
}
|
||||
}
|
||||
|
||||
int SavedataParam::GetSaveCryptMode(SceUtilitySavedataParam* param, const std::string &saveDirName)
|
||||
{
|
||||
ParamSFOData sfoFile;
|
||||
void SavedataParam::ClearCaches() {
|
||||
std::lock_guard<std::mutex> guard(cacheLock_);
|
||||
sfoCache_.clear();
|
||||
}
|
||||
|
||||
std::shared_ptr<ParamSFOData> SavedataParam::LoadCachedSFO(const std::string &path, bool orCreate) {
|
||||
std::lock_guard<std::mutex> guard(cacheLock_);
|
||||
if (sfoCache_.find(path) == sfoCache_.end()) {
|
||||
std::vector<u8> data;
|
||||
if (pspFileSystem.ReadEntireFile(path, data) < 0) {
|
||||
// Mark as not existing for later.
|
||||
sfoCache_[path].reset();
|
||||
} else {
|
||||
sfoCache_.emplace(path, new ParamSFOData());
|
||||
// If it fails to load, also keep it to indicate failed.
|
||||
if (!sfoCache_.at(path)->ReadSFO(data))
|
||||
sfoCache_.at(path).reset();
|
||||
}
|
||||
}
|
||||
|
||||
if (!sfoCache_.at(path)) {
|
||||
if (!orCreate)
|
||||
return nullptr;
|
||||
sfoCache_.at(path).reset(new ParamSFOData());
|
||||
}
|
||||
return sfoCache_.at(path);
|
||||
}
|
||||
|
||||
int SavedataParam::GetSaveCryptMode(SceUtilitySavedataParam *param, const std::string &saveDirName) {
|
||||
std::string dirPath = GetSaveFilePath(param, GetSaveDir(param, saveDirName));
|
||||
std::string sfopath = dirPath + "/" + SFO_FILENAME;
|
||||
PSPFileInfo sfoInfo = pspFileSystem.GetFileInfo(sfopath);
|
||||
if(sfoInfo.exists) // Read sfo
|
||||
{
|
||||
std::vector<u8> sfoData;
|
||||
if (pspFileSystem.ReadEntireFile(sfopath, sfoData) >= 0)
|
||||
{
|
||||
sfoFile.ReadSFO(sfoData);
|
||||
|
||||
// save created in PPSSPP and not encrypted has '0' in SAVEDATA_PARAMS
|
||||
u32 tmpDataSize = 0;
|
||||
const u8 *tmpDataOrig = sfoFile.GetValueData("SAVEDATA_PARAMS", &tmpDataSize);
|
||||
if (tmpDataSize == 0 || !tmpDataOrig) {
|
||||
return 0;
|
||||
}
|
||||
switch (tmpDataOrig[0]) {
|
||||
case 0:
|
||||
return 0;
|
||||
case 0x01:
|
||||
return 1;
|
||||
case 0x21:
|
||||
return 3;
|
||||
case 0x41:
|
||||
return 5;
|
||||
default:
|
||||
// Well, it's not zero, so yes.
|
||||
ERROR_LOG_REPORT(SCEUTILITY, "Unexpected SAVEDATA_PARAMS hash flag: %02x", tmpDataOrig[0]);
|
||||
return 1;
|
||||
}
|
||||
std::shared_ptr<ParamSFOData> sfoFile = LoadCachedSFO(sfopath);
|
||||
if (sfoFile) {
|
||||
// save created in PPSSPP and not encrypted has '0' in SAVEDATA_PARAMS
|
||||
u32 tmpDataSize = 0;
|
||||
const u8 *tmpDataOrig = sfoFile->GetValueData("SAVEDATA_PARAMS", &tmpDataSize);
|
||||
if (tmpDataSize == 0 || !tmpDataOrig) {
|
||||
return 0;
|
||||
}
|
||||
switch (tmpDataOrig[0]) {
|
||||
case 0:
|
||||
return 0;
|
||||
case 0x01:
|
||||
return 1;
|
||||
case 0x21:
|
||||
return 3;
|
||||
case 0x41:
|
||||
return 5;
|
||||
default:
|
||||
// Well, it's not zero, so yes.
|
||||
ERROR_LOG_REPORT(SCEUTILITY, "Unexpected SAVEDATA_PARAMS hash flag: %02x", tmpDataOrig[0]);
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
|
||||
@@ -17,8 +17,12 @@
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <set>
|
||||
#include <unordered_map>
|
||||
#include "Common/CommonTypes.h"
|
||||
#include "Core/ELF/ParamSFO.h"
|
||||
#include "Core/MemMap.h"
|
||||
#include "Core/HLE/sceRtc.h"
|
||||
#include "Core/Dialog/PSPDialog.h"
|
||||
@@ -324,6 +328,9 @@ public:
|
||||
|
||||
static std::string GetSpaceText(u64 size, bool roundUp);
|
||||
|
||||
void SetIgnoreTextures(bool state) {
|
||||
ignoreTextures_ = state;
|
||||
}
|
||||
int SetPspParam(SceUtilitySavedataParam* param);
|
||||
SceUtilitySavedataParam *GetPspParam();
|
||||
const SceUtilitySavedataParam *GetPspParam() const;
|
||||
@@ -348,6 +355,8 @@ public:
|
||||
|
||||
bool wouldHasMultiSaveName(SceUtilitySavedataParam* param);
|
||||
|
||||
void ClearCaches();
|
||||
|
||||
void DoState(PointerWrap &p);
|
||||
|
||||
private:
|
||||
@@ -373,10 +382,17 @@ private:
|
||||
std::set<std::string> GetSecureFileNames(const std::string &dirPath);
|
||||
bool GetExpectedHash(const std::string &dirPath, const std::string &filename, u8 hash[16]);
|
||||
|
||||
std::shared_ptr<ParamSFOData> LoadCachedSFO(const std::string &path, bool orCreate = false);
|
||||
|
||||
SceUtilitySavedataParam* pspParam = nullptr;
|
||||
int selectedSave = 0;
|
||||
SaveFileInfo *saveDataList = nullptr;
|
||||
SaveFileInfo *noSaveIcon = nullptr;
|
||||
int saveDataListCount = 0;
|
||||
int saveNameListDataCount = 0;
|
||||
bool ignoreTextures_ = false;
|
||||
|
||||
// Cleared before returning to PSP, no need to save state.
|
||||
std::mutex cacheLock_;
|
||||
std::unordered_map<std::string, std::shared_ptr<ParamSFOData>> sfoCache_;
|
||||
};
|
||||
+43
-10
@@ -34,9 +34,10 @@ const char *ElfReader::GetSectionName(int section) const {
|
||||
if (sections[section].sh_type == SHT_NULL)
|
||||
return nullptr;
|
||||
|
||||
int stringsOffset = GetSectionDataOffset(header->e_shstrndx);
|
||||
int nameOffset = sections[section].sh_name;
|
||||
if (nameOffset < 0 || (size_t)nameOffset >= size_) {
|
||||
ERROR_LOG(LOADER, "ELF: Bad name offset %d in section %d (max = %d)", nameOffset, section, (int)size_);
|
||||
if (nameOffset < 0 || (size_t)nameOffset + stringsOffset >= size_) {
|
||||
ERROR_LOG(LOADER, "ELF: Bad name offset %d + %d in section %d (max = %d)", nameOffset, stringsOffset, section, (int)size_);
|
||||
return nullptr;
|
||||
}
|
||||
const char *ptr = (const char *)GetSectionDataPtr(header->e_shstrndx);
|
||||
@@ -235,6 +236,10 @@ void ElfReader::LoadRelocations2(int rel_seg)
|
||||
const Elf32_Phdr *ph = segments + rel_seg;
|
||||
|
||||
buf = (u8*)GetSegmentPtr(rel_seg);
|
||||
if (!buf) {
|
||||
ERROR_LOG(LOADER, "Rel2 segment invalid");
|
||||
return;
|
||||
}
|
||||
end = buf+ph->p_filesz;
|
||||
|
||||
flag_bits = buf[2];
|
||||
@@ -383,6 +388,12 @@ int ElfReader::LoadInto(u32 loadAddress, bool fromTop)
|
||||
{
|
||||
DEBUG_LOG(LOADER,"String section: %i", header->e_shstrndx);
|
||||
|
||||
if (size_ < sizeof(Elf32_Ehdr)) {
|
||||
ERROR_LOG(LOADER, "Truncated ELF header, %d bytes", (int)size_);
|
||||
// Probably not the right error code.
|
||||
return SCE_KERNEL_ERROR_MEMBLOCK_ALLOC_FAILED;
|
||||
}
|
||||
|
||||
if (header->e_ident[0] != ELFMAG0 || header->e_ident[1] != ELFMAG1
|
||||
|| header->e_ident[2] != ELFMAG2 || header->e_ident[3] != ELFMAG3)
|
||||
return SCE_KERNEL_ERROR_UNSUPPORTED_PRX_TYPE;
|
||||
@@ -399,10 +410,13 @@ int ElfReader::LoadInto(u32 loadAddress, bool fromTop)
|
||||
if (header->e_ident[EI_DATA] != ELFDATA2LSB)
|
||||
return SCE_KERNEL_ERROR_MEMBLOCK_ALLOC_FAILED;
|
||||
|
||||
// e_ident[EI_VERSION] is ignored
|
||||
if (size_ < header->e_phoff + sizeof(Elf32_Phdr) * GetNumSegments() || size_ < header->e_shoff + sizeof(Elf32_Shdr) * GetNumSections()) {
|
||||
ERROR_LOG(LOADER, "Truncated ELF, %d bytes with %d sections and %d segments", (int)size_, GetNumSections(), GetNumSegments());
|
||||
// Probably not the right error code.
|
||||
return SCE_KERNEL_ERROR_MEMBLOCK_ALLOC_FAILED;
|
||||
}
|
||||
|
||||
sectionOffsets = new u32[GetNumSections()];
|
||||
sectionAddrs = new u32[GetNumSections()];
|
||||
// e_ident[EI_VERSION] is ignored
|
||||
|
||||
// Should we relocate?
|
||||
bRelocate = (header->e_type != ET_EXEC);
|
||||
@@ -412,11 +426,11 @@ int ElfReader::LoadInto(u32 loadAddress, bool fromTop)
|
||||
for (int i = 0; i < GetNumSections(); i++) {
|
||||
const Elf32_Shdr *s = §ions[i];
|
||||
const char *name = GetSectionName(i);
|
||||
if (name && !strcmp(name, ".rodata.sceModuleInfo")) {
|
||||
if (name && !strcmp(name, ".rodata.sceModuleInfo") && s->sh_offset + sizeof(PspModuleInfo) <= size_) {
|
||||
modInfo = (const PspModuleInfo *)GetPtr(s->sh_offset);
|
||||
}
|
||||
}
|
||||
if (!modInfo && GetNumSegments() >= 1) {
|
||||
if (!modInfo && GetNumSegments() >= 1 && (segments[0].p_paddr & 0x7FFFFFFF) + sizeof(PspModuleInfo) <= size_) {
|
||||
modInfo = (const PspModuleInfo *)GetPtr(segments[0].p_paddr & 0x7FFFFFFF);
|
||||
}
|
||||
|
||||
@@ -493,6 +507,10 @@ int ElfReader::LoadInto(u32 loadAddress, bool fromTop)
|
||||
u32 writeAddr = segmentVAddr[i];
|
||||
|
||||
const u8 *src = GetSegmentPtr(i);
|
||||
if (!src || p->p_offset + p->p_filesz > size_) {
|
||||
ERROR_LOG(LOADER, "Segment %d pointer invalid - truncated?", i);
|
||||
continue;
|
||||
}
|
||||
u8 *dst = Memory::GetPointerWrite(writeAddr);
|
||||
u32 srcSize = p->p_filesz;
|
||||
u32 dstSize = p->p_memsz;
|
||||
@@ -513,6 +531,9 @@ int ElfReader::LoadInto(u32 loadAddress, bool fromTop)
|
||||
|
||||
DEBUG_LOG(LOADER,"%i sections:", header->e_shnum);
|
||||
|
||||
sectionOffsets = new u32[GetNumSections()];
|
||||
sectionAddrs = new u32[GetNumSections()];
|
||||
|
||||
for (int i = 0; i < GetNumSections(); i++)
|
||||
{
|
||||
const Elf32_Shdr *s = §ions[i];
|
||||
@@ -534,7 +555,7 @@ int ElfReader::LoadInto(u32 loadAddress, bool fromTop)
|
||||
}
|
||||
}
|
||||
|
||||
DEBUG_LOG(LOADER,"Relocations:");
|
||||
DEBUG_LOG(LOADER, "Relocations:");
|
||||
|
||||
// Second pass: Do necessary relocations
|
||||
for (int i = 0; i < GetNumSections(); i++)
|
||||
@@ -557,9 +578,11 @@ int ElfReader::LoadInto(u32 loadAddress, bool fromTop)
|
||||
int numRelocs = s->sh_size / sizeof(Elf32_Rel);
|
||||
|
||||
Elf32_Rel *rels = (Elf32_Rel *)GetSectionDataPtr(i);
|
||||
if (GetSectionDataOffset(i) + sizeof(Elf32_Rel) * numRelocs > size_)
|
||||
rels = nullptr;
|
||||
|
||||
DEBUG_LOG(LOADER,"%s: Performing %i relocations on %s : offset = %08x", name, numRelocs, GetSectionName(sectionToModify), sections[i].sh_offset);
|
||||
if (!LoadRelocations(rels, numRelocs)) {
|
||||
if (!rels || !LoadRelocations(rels, numRelocs)) {
|
||||
WARN_LOG(LOADER, "LoadInto: Relocs failed, trying anyway");
|
||||
}
|
||||
}
|
||||
@@ -607,7 +630,9 @@ int ElfReader::LoadInto(u32 loadAddress, bool fromTop)
|
||||
int numRelocs = p->p_filesz / sizeof(Elf32_Rel);
|
||||
|
||||
Elf32_Rel *rels = (Elf32_Rel *)GetSegmentPtr(i);
|
||||
if (!LoadRelocations(rels, numRelocs)) {
|
||||
if (p->p_offset + p->p_filesz > size_)
|
||||
rels = nullptr;
|
||||
if (!rels || !LoadRelocations(rels, numRelocs)) {
|
||||
ERROR_LOG(LOADER, "LoadInto: Relocs failed, trying anyway (2)");
|
||||
}
|
||||
} else if (p->p_type == PT_PSPREL2) {
|
||||
@@ -695,11 +720,17 @@ bool ElfReader::LoadSymbols()
|
||||
int stringSection = sections[sec].sh_link;
|
||||
|
||||
const char *stringBase = (const char*)GetSectionDataPtr(stringSection);
|
||||
u32 stringOffset = GetSectionDataOffset(stringSection);
|
||||
|
||||
//We have a symbol table!
|
||||
Elf32_Sym *symtab = (Elf32_Sym *)(GetSectionDataPtr(sec));
|
||||
u32 symtabOffset = GetSectionDataOffset(sec);
|
||||
|
||||
int numSymbols = sections[sec].sh_size / sizeof(Elf32_Sym);
|
||||
if (!stringBase || !symtab || symtabOffset + sections[sec].sh_size > size_) {
|
||||
ERROR_LOG(LOADER, "Symbols truncated - ignoring");
|
||||
return false;
|
||||
}
|
||||
|
||||
for (int sym = 0; sym<numSymbols; sym++)
|
||||
{
|
||||
@@ -712,6 +743,8 @@ bool ElfReader::LoadSymbols()
|
||||
int sectionIndex = symtab[sym].st_shndx;
|
||||
int value = symtab[sym].st_value;
|
||||
const char *name = stringBase + symtab[sym].st_name;
|
||||
if (stringOffset + symtab[sym].st_name >= size_)
|
||||
continue;
|
||||
|
||||
if (bRelocate)
|
||||
value += sectionAddrs[sectionIndex];
|
||||
|
||||
+14
-6
@@ -77,15 +77,23 @@ public:
|
||||
const u8 *GetPtr(u32 offset) const {
|
||||
return (const u8*)base + offset;
|
||||
}
|
||||
const u8 *GetSectionDataPtr(int section) const {
|
||||
// Note: zero is not a valid output, means unavailable.
|
||||
u32 GetSectionDataOffset(int section) const {
|
||||
if (section < 0 || section >= header->e_shnum)
|
||||
return 0;
|
||||
if (sections[section].sh_type == SHT_NOBITS)
|
||||
return 0;
|
||||
return sections[section].sh_offset;
|
||||
}
|
||||
const u8 *GetSectionDataPtr(int section) const {
|
||||
u32 offset = GetSectionDataOffset(section);
|
||||
if (offset == 0 || offset > size_)
|
||||
return nullptr;
|
||||
if (sections[section].sh_type != SHT_NOBITS)
|
||||
return GetPtr(sections[section].sh_offset);
|
||||
else
|
||||
return nullptr;
|
||||
return GetPtr(offset);
|
||||
}
|
||||
const u8 *GetSegmentPtr(int segment) const {
|
||||
if (segments[segment].p_offset > size_)
|
||||
return nullptr;
|
||||
return GetPtr(segments[segment].p_offset);
|
||||
}
|
||||
u32 GetSectionAddr(SectionID section) const {
|
||||
@@ -154,7 +162,7 @@ private:
|
||||
u32 entryPoint = 0;
|
||||
u32 totalSize = 0;
|
||||
u32 vaddr = 0;
|
||||
u32 segmentVAddr[32];
|
||||
u32 segmentVAddr[32]{};
|
||||
size_t size_ = 0;
|
||||
u32 firstSegAlign = 0;
|
||||
};
|
||||
@@ -283,7 +283,7 @@ std::string ParamSFOData::GenerateFakeID(std::string filename) {
|
||||
// Generates fake gameID for homebrew based on it's folder name.
|
||||
// Should probably not be a part of ParamSFO, but it'll be called in same places.
|
||||
std::string file = PSP_CoreParameter().fileToStart.ToString();
|
||||
if (filename != "")
|
||||
if (!filename.empty())
|
||||
file = filename;
|
||||
|
||||
std::size_t lslash = file.find_last_of("/");
|
||||
|
||||
@@ -30,9 +30,11 @@ void BlobFileSystem::DoState(PointerWrap &p) {
|
||||
// Not used in real emulation.
|
||||
}
|
||||
|
||||
std::vector<PSPFileInfo> BlobFileSystem::GetDirListing(std::string path) {
|
||||
std::vector<PSPFileInfo> BlobFileSystem::GetDirListing(const std::string &path, bool *exists) {
|
||||
std::vector<PSPFileInfo> listing;
|
||||
listing.push_back(GetFileInfo(alias_));
|
||||
if (exists)
|
||||
*exists = true;
|
||||
return listing;
|
||||
}
|
||||
|
||||
|
||||
@@ -34,7 +34,7 @@ public:
|
||||
~BlobFileSystem();
|
||||
|
||||
void DoState(PointerWrap &p) override;
|
||||
std::vector<PSPFileInfo> GetDirListing(std::string path) override;
|
||||
std::vector<PSPFileInfo> GetDirListing(const std::string &path, bool *exists = nullptr) override;
|
||||
int OpenFile(std::string filename, FileAccess access, const char *devicename = nullptr) override;
|
||||
void CloseFile(u32 handle) override;
|
||||
size_t ReadFile(u32 handle, u8 *pointer, s64 size) override;
|
||||
|
||||
@@ -115,6 +115,11 @@ Path DirectoryFileSystem::GetLocalPath(std::string internalPath) const {
|
||||
bool DirectoryFileHandle::Open(const Path &basePath, std::string &fileName, FileAccess access, u32 &error) {
|
||||
error = 0;
|
||||
|
||||
if (access == FILEACCESS_NONE) {
|
||||
error = SCE_KERNEL_ERROR_ERRNO_INVALID_ARGUMENT;
|
||||
return false;
|
||||
}
|
||||
|
||||
#if HOST_IS_CASE_SENSITIVE
|
||||
if (access & (FILEACCESS_APPEND | FILEACCESS_CREATE | FILEACCESS_WRITE)) {
|
||||
DEBUG_LOG(FILESYS, "Checking case for path %s", fileName.c_str());
|
||||
@@ -671,40 +676,34 @@ PSPFileInfo DirectoryFileSystem::GetFileInfo(std::string filename) {
|
||||
PSPFileInfo x;
|
||||
x.name = filename;
|
||||
|
||||
File::FileInfo info;
|
||||
Path fullName = GetLocalPath(filename);
|
||||
if (!File::Exists(fullName)) {
|
||||
if (!File::GetFileInfo(fullName, &info)) {
|
||||
#if HOST_IS_CASE_SENSITIVE
|
||||
if (! FixPathCase(basePath, filename, FPC_FILE_MUST_EXIST))
|
||||
return ReplayApplyDiskFileInfo(x, CoreTiming::GetGlobalTimeUs());
|
||||
fullName = GetLocalPath(filename);
|
||||
|
||||
if (! File::Exists(fullName))
|
||||
if (!File::GetFileInfo(fullName, &info))
|
||||
return ReplayApplyDiskFileInfo(x, CoreTiming::GetGlobalTimeUs());
|
||||
#else
|
||||
return ReplayApplyDiskFileInfo(x, CoreTiming::GetGlobalTimeUs());
|
||||
#endif
|
||||
}
|
||||
|
||||
// TODO: Consolidate to just a File::GetFileInfo call.
|
||||
|
||||
x.type = File::IsDirectory(fullName) ? FILETYPE_DIRECTORY : FILETYPE_NORMAL;
|
||||
x.type = info.isDirectory ? FILETYPE_DIRECTORY : FILETYPE_NORMAL;
|
||||
x.exists = true;
|
||||
|
||||
if (x.type != FILETYPE_DIRECTORY) {
|
||||
File::FileInfo info;
|
||||
if (!File::GetFileInfo(fullName, &info)) {
|
||||
ERROR_LOG(FILESYS, "DirectoryFileSystem::GetFileInfo: GetFileInfo failed: %s", fullName.c_str());
|
||||
} else {
|
||||
x.size = info.size;
|
||||
x.access = info.access;
|
||||
time_t atime = info.atime;
|
||||
time_t ctime = info.ctime;
|
||||
time_t mtime = info.mtime;
|
||||
x.size = info.size;
|
||||
x.access = info.access;
|
||||
time_t atime = info.atime;
|
||||
time_t ctime = info.ctime;
|
||||
time_t mtime = info.mtime;
|
||||
|
||||
localtime_r((time_t*)&atime, &x.atime);
|
||||
localtime_r((time_t*)&ctime, &x.ctime);
|
||||
localtime_r((time_t*)&mtime, &x.mtime);
|
||||
}
|
||||
localtime_r((time_t*)&atime, &x.atime);
|
||||
localtime_r((time_t*)&ctime, &x.ctime);
|
||||
localtime_r((time_t*)&mtime, &x.mtime);
|
||||
}
|
||||
|
||||
return ReplayApplyDiskFileInfo(x, CoreTiming::GetGlobalTimeUs());
|
||||
@@ -795,25 +794,28 @@ bool DirectoryFileSystem::ComputeRecursiveDirSizeIfFast(const std::string &path,
|
||||
}
|
||||
}
|
||||
|
||||
std::vector<PSPFileInfo> DirectoryFileSystem::GetDirListing(std::string path) {
|
||||
std::vector<PSPFileInfo> DirectoryFileSystem::GetDirListing(const std::string &path, bool *exists) {
|
||||
std::vector<PSPFileInfo> myVector;
|
||||
|
||||
std::vector<File::FileInfo> files;
|
||||
Path localPath = GetLocalPath(path);
|
||||
const int flags = File::GETFILES_GETHIDDEN | File::GETFILES_GET_NAVIGATION_ENTRIES;
|
||||
if (!File::GetFilesInDir(localPath, &files, nullptr, flags)) {
|
||||
// TODO: Case sensitivity should be checked on a file system basis, right?
|
||||
bool success = File::GetFilesInDir(localPath, &files, nullptr, flags);
|
||||
#if HOST_IS_CASE_SENSITIVE
|
||||
if (FixPathCase(basePath, path, FPC_FILE_MUST_EXIST)) {
|
||||
if (!success) {
|
||||
// TODO: Case sensitivity should be checked on a file system basis, right?
|
||||
std::string fixedPath = path;
|
||||
if (FixPathCase(basePath, fixedPath, FPC_FILE_MUST_EXIST)) {
|
||||
// May have failed due to case sensitivity, try again
|
||||
localPath = GetLocalPath(path);
|
||||
if (!File::GetFilesInDir(localPath, &files, nullptr, 0)) {
|
||||
return ReplayApplyDiskListing(myVector, CoreTiming::GetGlobalTimeUs());
|
||||
}
|
||||
localPath = GetLocalPath(fixedPath);
|
||||
success = File::GetFilesInDir(localPath, &files, nullptr, flags);
|
||||
}
|
||||
#else
|
||||
return ReplayApplyDiskListing(myVector, CoreTiming::GetGlobalTimeUs());
|
||||
}
|
||||
#endif
|
||||
if (!success) {
|
||||
if (exists)
|
||||
*exists = false;
|
||||
return ReplayApplyDiskListing(myVector, CoreTiming::GetGlobalTimeUs());
|
||||
}
|
||||
|
||||
bool hideISOFiles = PSP_CoreParameter().compat.flags().HideISOFiles;
|
||||
@@ -841,6 +843,7 @@ std::vector<PSPFileInfo> DirectoryFileSystem::GetDirListing(std::string path) {
|
||||
entry.type = FILETYPE_NORMAL;
|
||||
}
|
||||
entry.access = file.access;
|
||||
entry.exists = file.exists;
|
||||
|
||||
localtime_r((time_t*)&file.atime, &entry.atime);
|
||||
localtime_r((time_t*)&file.ctime, &entry.ctime);
|
||||
@@ -849,6 +852,8 @@ std::vector<PSPFileInfo> DirectoryFileSystem::GetDirListing(std::string path) {
|
||||
myVector.push_back(entry);
|
||||
}
|
||||
|
||||
if (exists)
|
||||
*exists = true;
|
||||
return ReplayApplyDiskListing(myVector, CoreTiming::GetGlobalTimeUs());
|
||||
}
|
||||
|
||||
@@ -1079,9 +1084,11 @@ size_t VFSFileSystem::SeekFile(u32 handle, s32 position, FileMove type) {
|
||||
}
|
||||
}
|
||||
|
||||
std::vector<PSPFileInfo> VFSFileSystem::GetDirListing(std::string path) {
|
||||
std::vector<PSPFileInfo> VFSFileSystem::GetDirListing(const std::string &path, bool *exists) {
|
||||
std::vector<PSPFileInfo> myVector;
|
||||
// TODO
|
||||
if (exists)
|
||||
*exists = false;
|
||||
return myVector;
|
||||
}
|
||||
|
||||
|
||||
@@ -65,7 +65,7 @@ public:
|
||||
void CloseAll();
|
||||
|
||||
void DoState(PointerWrap &p) override;
|
||||
std::vector<PSPFileInfo> GetDirListing(std::string path) override;
|
||||
std::vector<PSPFileInfo> GetDirListing(const std::string &path, bool *exists = nullptr) override;
|
||||
int OpenFile(std::string filename, FileAccess access, const char *devicename = nullptr) override;
|
||||
void CloseFile(u32 handle) override;
|
||||
size_t ReadFile(u32 handle, u8 *pointer, s64 size) override;
|
||||
@@ -111,7 +111,7 @@ public:
|
||||
~VFSFileSystem();
|
||||
|
||||
void DoState(PointerWrap &p) override;
|
||||
std::vector<PSPFileInfo> GetDirListing(std::string path) override;
|
||||
std::vector<PSPFileInfo> GetDirListing(const std::string &path, bool *exists = nullptr) override;
|
||||
int OpenFile(std::string filename, FileAccess access, const char *devicename = nullptr) override;
|
||||
void CloseFile(u32 handle) override;
|
||||
size_t ReadFile(u32 handle, u8 *pointer, s64 size) override;
|
||||
|
||||
Loaded 100 of 407 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user