Compare commits

..

26 Commits

Author SHA1 Message Date
CamilleLaVey 5f0f6e6306 Experimenting with scissors offsets 2026-09-01 21:53:15 -04:00
CamilleLaVey d43238b9af Another change 2026-09-02 02:57:14 +02:00
CamilleLaVey 2addf1556e Another check 2026-09-02 02:57:14 +02:00
CamilleLaVey 883cdead8b Some sanity on the vertex stream 2026-09-02 02:57:14 +02:00
CamilleLaVey 104bfa3a8f Another take for indexing guards 2026-09-02 02:57:14 +02:00
CamilleLaVey 023c4758e9 Unify vertex entries from the indexed and non-indexed resolves into a single path 2026-09-02 02:57:14 +02:00
CamilleLaVey b9239c4944 Add instance draw counts to vertex buffers 2026-09-02 02:57:14 +02:00
CamilleLaVey f229172d3b Some cleanups on the vertex buffer path 2026-09-02 02:57:14 +02:00
CamilleLaVey eb18c5b8bd Removing redundant stagging per downloaded and swizzled image 2026-09-02 02:57:14 +02:00
CamilleLaVey 0c7d068112 Blit corrections within the image initialization 2026-09-02 02:57:14 +02:00
CamilleLaVey f29a23738a A quick change on the e3D pass 2026-09-02 02:57:14 +02:00
CamilleLaVey 7e5e326842 Another meow 2026-09-02 02:57:14 +02:00
CamilleLaVey f93e4031ba tie gpu modified regions to rescalable textures 2026-09-02 02:57:14 +02:00
CamilleLaVey 7e55b4b563 Dale a tu cuerpo alegría macarena 2026-09-02 02:57:14 +02:00
CamilleLaVey ee5049f0d3 Mercy please 2026-09-02 02:57:14 +02:00
CamilleLaVey 15de6e0e08 AAAAAAH 2026-09-02 02:57:14 +02:00
CamilleLaVey 75519010d2 Refining fix 2026-09-02 02:57:14 +02:00
CamilleLaVey 3e61e6da87 AQUI LLEGO TU LOBITO, MI LOBA. 2026-09-02 02:57:14 +02:00
CamilleLaVey 8242e54e42 This is so fucking tiring 2026-09-02 02:57:14 +02:00
CamilleLaVey 47b310266e Another try to fix QCOM driver, dear god. 2026-09-02 02:57:14 +02:00
CamilleLaVey 3cfac4abcd Just a small touch on the 3d swizzle params 2026-09-02 02:57:14 +02:00
CamilleLaVey 92c52342b8 Another try on the 3D pass 2026-09-02 02:57:14 +02:00
CamilleLaVey db2bdde9b3 Revert "Just another change"
This reverts commit 2ea449f71a.
2026-09-02 02:57:14 +02:00
CamilleLaVey ce0b15dcf7 Just another change 2026-09-02 02:57:14 +02:00
CamilleLaVey db922e50e3 Another check on feedback loop 2026-09-02 02:57:14 +02:00
CamilleLaVey ca52cf679a Another try on unswizzling 2026-09-02 02:57:14 +02:00
50 changed files with 1864 additions and 529 deletions
+1 -1
View File
@@ -238,7 +238,7 @@ option(YUZU_USE_BUNDLED_SIRIT "Download bundled sirit" ${BUNDLED_SIRIT_DEFAULT})
# FreeBSD 15+ has libusb, versions below should disable it # FreeBSD 15+ has libusb, versions below should disable it
cmake_dependent_option(ENABLE_LIBUSB "Enable the use of LibUSB" ON "WIN32 OR LINUX OR FREEBSD OR APPLE" OFF) cmake_dependent_option(ENABLE_LIBUSB "Enable the use of LibUSB" ON "WIN32 OR LINUX OR FREEBSD OR APPLE" OFF)
cmake_dependent_option(ENABLE_OPENGL "Enable OpenGL" ON "NOT (WIN32 AND ARCHITECTURE_arm64) AND NOT APPLE AND NOT ANDROID" OFF) cmake_dependent_option(ENABLE_OPENGL "Enable OpenGL" ON "NOT (WIN32 AND ARCHITECTURE_arm64) AND NOT APPLE" OFF)
mark_as_advanced(FORCE ENABLE_OPENGL) mark_as_advanced(FORCE ENABLE_OPENGL)
option(ENABLE_WEB_SERVICE "Enable web services (telemetry, etc.)" ON) option(ENABLE_WEB_SERVICE "Enable web services (telemetry, etc.)" ON)
+1 -1
View File
@@ -76,7 +76,7 @@ The following options are desktop only.
- `ENABLE_LIBUSB` (ON) Enable the use of the libusb input backend (HIGHLY RECOMMENDED) - `ENABLE_LIBUSB` (ON) Enable the use of the libusb input backend (HIGHLY RECOMMENDED)
- `ENABLE_OPENGL` (ON) Enable the OpenGL graphics backend - `ENABLE_OPENGL` (ON) Enable the OpenGL graphics backend
- Unavailable on Windows/ARM64 and on Android - Unavailable on Windows/ARM64
- You probably shouldn't turn this off. - You probably shouldn't turn this off.
### Qt ### Qt
-1
View File
@@ -11,7 +11,6 @@
#include <limits> #include <limits>
#include <span> #include <span>
#include <array> #include <array>
#include <algorithm>
#include <time.h> #include <time.h>
namespace Tz { namespace Tz {
+1
View File
@@ -89,6 +89,7 @@ add_library(
param_package.h param_package.h
parent_of_member.h parent_of_member.h
point.h point.h
quaternion.h
range_map.h range_map.h
range_mutex.h range_mutex.h
range_sets.h range_sets.h
-1
View File
@@ -5,7 +5,6 @@
// SPDX-License-Identifier: GPL-2.0-or-later // SPDX-License-Identifier: GPL-2.0-or-later
#include <string> #include <string>
#include <cstdlib>
#include <string_view> #include <string_view>
#ifdef _WIN32 #ifdef _WIN32
#include <llvm/Demangle/Demangle.h> #include <llvm/Demangle/Demangle.h>
+79
View File
@@ -0,0 +1,79 @@
// SPDX-FileCopyrightText: 2016 Citra Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
#pragma once
#include "common/vector_math.h"
namespace Common {
template <typename T>
class Quaternion {
public:
Vec3<T> xyz;
T w{};
[[nodiscard]] Quaternion<decltype(-T{})> Inverse() const {
return {-xyz, w};
}
[[nodiscard]] Quaternion<decltype(T{} + T{})> operator+(const Quaternion& other) const {
return {xyz + other.xyz, w + other.w};
}
[[nodiscard]] Quaternion<decltype(T{} - T{})> operator-(const Quaternion& other) const {
return {xyz - other.xyz, w - other.w};
}
[[nodiscard]] Quaternion<decltype(T{} * T{} - T{} * T{})> operator*(
const Quaternion& other) const {
return {xyz * other.w + other.xyz * w + Cross(xyz, other.xyz),
w * other.w - Dot(xyz, other.xyz)};
}
[[nodiscard]] Quaternion<T> Normalized() const {
T length = std::sqrt(xyz.Length2() + w * w);
return {xyz / length, w / length};
}
[[nodiscard]] std::array<decltype(-T{}), 16> ToMatrix() const {
const T x2 = xyz[0] * xyz[0];
const T y2 = xyz[1] * xyz[1];
const T z2 = xyz[2] * xyz[2];
const T xy = xyz[0] * xyz[1];
const T wz = w * xyz[2];
const T xz = xyz[0] * xyz[2];
const T wy = w * xyz[1];
const T yz = xyz[1] * xyz[2];
const T wx = w * xyz[0];
return {1.0f - 2.0f * (y2 + z2),
2.0f * (xy + wz),
2.0f * (xz - wy),
0.0f,
2.0f * (xy - wz),
1.0f - 2.0f * (x2 + z2),
2.0f * (yz + wx),
0.0f,
2.0f * (xz + wy),
2.0f * (yz - wx),
1.0f - 2.0f * (x2 + y2),
0.0f,
0.0f,
0.0f,
0.0f,
1.0f};
}
};
template <typename T>
[[nodiscard]] auto QuaternionRotate(const Quaternion<T>& q, const Vec3<T>& v) {
return v + 2 * Cross(q.xyz, Cross(q.xyz, v) + v * q.w);
}
[[nodiscard]] inline Quaternion<float> MakeQuaternion(const Vec3<float>& axis, float angle) {
return {axis * std::sin(angle / 2), std::cos(angle / 2)};
}
} // namespace Common
+721 -97
View File
@@ -1,4 +1,4 @@
// SPDX-FileCopyrightText: Copyright 2026 Eden Emulator Project // SPDX-FileCopyrightText: Copyright 2025 Eden Emulator Project
// SPDX-License-Identifier: GPL-3.0-or-later // SPDX-License-Identifier: GPL-3.0-or-later
// SPDX-FileCopyrightText: 2014 Tony Wasserka // SPDX-FileCopyrightText: 2014 Tony Wasserka
@@ -7,128 +7,752 @@
#pragma once #pragma once
#ifdef __ARM_NEON
#include <arm_neon.h>
#endif
#include <cmath> #include <cmath>
#include <type_traits> #include <type_traits>
namespace Common { namespace Common {
template <typename T, size_t N> template <typename T>
class Vec { class Vec2;
template <typename T>
class Vec3;
template <typename T>
class Vec4;
template <typename T>
class Vec2 {
public: public:
std::array<T, N> elems{}; T x{};
T y{};
constexpr Vec() = default; constexpr Vec2() = default;
constexpr Vec(T e0) noexcept : elems{e0} {} constexpr Vec2(const T& x_, const T& y_) : x(x_), y(y_) {}
constexpr Vec(T e0, T e1) noexcept : elems{e0, e1} {}
constexpr Vec(T e0, T e1, T e2) noexcept : elems{e0, e1, e2} {}
constexpr Vec(T e0, T e1, T e2, T e4) noexcept : elems{e0, e1, e2, e4} {}
//explicit constexpr Vec(const std::initializer_list<T> elems_) noexcept : elems{elems_} {}
[[nodiscard]] constexpr Vec<decltype(T{} + T{}), N> operator+(const Vec o) const noexcept { template <typename T2>
Vec<decltype(T{} + T{}), N> r{}; [[nodiscard]] constexpr Vec2<T2> Cast() const {
for (size_t i = 0; i < N; ++i) return Vec2<T2>(static_cast<T2>(x), static_cast<T2>(y));
r.elems[i] = elems[i] + o.elems[i];
return r;
} }
constexpr Vec<T, N> operator+=(const Vec<T, N> o) noexcept { return *this = *this + o; }
[[nodiscard]] constexpr Vec<decltype(T{} - T{}), N> operator-(const Vec o) const noexcept { [[nodiscard]] static constexpr Vec2 AssignToAll(const T& f) {
Vec<decltype(T{} - T{}), N> r{}; return Vec2{f, f};
for (size_t i = 0; i < N; ++i) }
r.elems[i] = elems[i] - o.elems[i];
return r; [[nodiscard]] constexpr Vec2<decltype(T{} + T{})> operator+(const Vec2& other) const {
return {x + other.x, y + other.y};
}
constexpr Vec2& operator+=(const Vec2& other) {
x += other.x;
y += other.y;
return *this;
}
[[nodiscard]] constexpr Vec2<decltype(T{} - T{})> operator-(const Vec2& other) const {
return {x - other.x, y - other.y};
}
constexpr Vec2& operator-=(const Vec2& other) {
x -= other.x;
y -= other.y;
return *this;
} }
constexpr Vec<T, N> operator-=(const Vec<T, N> o) noexcept { return *this = *this - o; }
template <typename U = T> template <typename U = T>
[[nodiscard]] constexpr Vec<std::enable_if_t<std::is_signed_v<U>, U>, N> operator-() const noexcept { [[nodiscard]] constexpr Vec2<std::enable_if_t<std::is_signed_v<U>, U>> operator-() const {
Vec<U, N> r{}; return {-x, -y};
for (size_t i = 0; i < N; ++i) }
r.elems[i] = -elems[i]; [[nodiscard]] constexpr Vec2<decltype(T{} * T{})> operator*(const Vec2& other) const {
return r; return {x * other.x, y * other.y};
} }
[[nodiscard]] constexpr Vec<decltype(T{} * T{}), N> operator*(const Vec o) const noexcept {
Vec<decltype(T{} * T{}), N> r{};
for (size_t i = 0; i < N; ++i)
r.elems[i] = elems[i] * o.elems[i];
return r;
}
template <typename V> template <typename V>
[[nodiscard]] constexpr Vec<decltype(T{} * V{}), N> operator*(const V f) const noexcept { [[nodiscard]] constexpr Vec2<decltype(T{} * V{})> operator*(const V& f) const {
using TV = decltype(T{} * V{}); using TV = decltype(T{} * V{});
using C = std::common_type_t<T, V>; using C = std::common_type_t<T, V>;
Vec<TV, N> r{};
for (size_t i = 0; i < N; ++i) return {
r.elems[i] = TV(C(elems[i]) * C(f)); static_cast<TV>(static_cast<C>(x) * static_cast<C>(f)),
return r; static_cast<TV>(static_cast<C>(y) * static_cast<C>(f)),
};
} }
template <typename V>
constexpr Vec<T, N> operator*=(const V f) noexcept { return *this = *this * f; }
template <typename V> template <typename V>
[[nodiscard]] constexpr Vec<decltype(T{} / V{}), N> operator/(const V f) const noexcept { constexpr Vec2& operator*=(const V& f) {
*this = *this * f;
return *this;
}
template <typename V>
[[nodiscard]] constexpr Vec2<decltype(T{} / V{})> operator/(const V& f) const {
using TV = decltype(T{} / V{}); using TV = decltype(T{} / V{});
using C = std::common_type_t<T, V>; using C = std::common_type_t<T, V>;
Vec<TV, N> r{};
for (size_t i = 0; i < N; ++i) return {
r.elems[i] = TV(C(elems[i]) / C(f)); static_cast<TV>(static_cast<C>(x) / static_cast<C>(f)),
return r; static_cast<TV>(static_cast<C>(y) / static_cast<C>(f)),
};
}
template <typename V>
constexpr Vec2& operator/=(const V& f) {
*this = *this / f;
return *this;
}
[[nodiscard]] constexpr T Length2() const {
return x * x + y * y;
}
// Only implemented for T=float
[[nodiscard]] float Length() const;
[[nodiscard]] float Normalize(); // returns the previous length, which is often useful
[[nodiscard]] constexpr T& operator[](std::size_t i) {
return *((&x) + i);
}
[[nodiscard]] constexpr const T& operator[](std::size_t i) const {
return *((&x) + i);
}
constexpr void SetZero() {
x = 0;
y = 0;
}
// Common aliases: UV (texel coordinates), ST (texture coordinates)
[[nodiscard]] constexpr T& u() {
return x;
}
[[nodiscard]] constexpr T& v() {
return y;
}
[[nodiscard]] constexpr T& s() {
return x;
}
[[nodiscard]] constexpr T& t() {
return y;
}
[[nodiscard]] constexpr const T& u() const {
return x;
}
[[nodiscard]] constexpr const T& v() const {
return y;
}
[[nodiscard]] constexpr const T& s() const {
return x;
}
[[nodiscard]] constexpr const T& t() const {
return y;
}
// swizzlers - create a subvector of specific components
[[nodiscard]] constexpr Vec2 yx() const {
return Vec2(y, x);
}
[[nodiscard]] constexpr Vec2 vu() const {
return Vec2(y, x);
}
[[nodiscard]] constexpr Vec2 ts() const {
return Vec2(y, x);
}
};
template <typename T, typename V>
[[nodiscard]] constexpr Vec2<T> operator*(const V& f, const Vec2<T>& vec) {
using C = std::common_type_t<T, V>;
return Vec2<T>(static_cast<T>(static_cast<C>(f) * static_cast<C>(vec.x)),
static_cast<T>(static_cast<C>(f) * static_cast<C>(vec.y)));
}
using Vec2f = Vec2<float>;
template <>
inline float Vec2<float>::Length() const {
return std::sqrt(x * x + y * y);
}
template <>
inline float Vec2<float>::Normalize() {
float length = Length();
*this /= length;
return length;
}
template <typename T>
class Vec3 {
public:
T x{};
T y{};
T z{};
constexpr Vec3() = default;
constexpr Vec3(const T& x_, const T& y_, const T& z_) : x(x_), y(y_), z(z_) {}
template <typename T2>
[[nodiscard]] constexpr Vec3<T2> Cast() const {
return Vec3<T2>(static_cast<T2>(x), static_cast<T2>(y), static_cast<T2>(z));
}
[[nodiscard]] static constexpr Vec3 AssignToAll(const T& f) {
return Vec3(f, f, f);
}
[[nodiscard]] constexpr Vec3<decltype(T{} + T{})> operator+(const Vec3& other) const {
return {x + other.x, y + other.y, z + other.z};
}
constexpr Vec3& operator+=(const Vec3& other) {
x += other.x;
y += other.y;
z += other.z;
return *this;
}
[[nodiscard]] constexpr Vec3<decltype(T{} - T{})> operator-(const Vec3& other) const {
return {x - other.x, y - other.y, z - other.z};
}
constexpr Vec3& operator-=(const Vec3& other) {
x -= other.x;
y -= other.y;
z -= other.z;
return *this;
}
template <typename U = T>
[[nodiscard]] constexpr Vec3<std::enable_if_t<std::is_signed_v<U>, U>> operator-() const {
return {-x, -y, -z};
}
[[nodiscard]] constexpr Vec3<decltype(T{} * T{})> operator*(const Vec3& other) const {
return {x * other.x, y * other.y, z * other.z};
}
template <typename V>
[[nodiscard]] constexpr Vec3<decltype(T{} * V{})> operator*(const V& f) const {
using TV = decltype(T{} * V{});
using C = std::common_type_t<T, V>;
return {
static_cast<TV>(static_cast<C>(x) * static_cast<C>(f)),
static_cast<TV>(static_cast<C>(y) * static_cast<C>(f)),
static_cast<TV>(static_cast<C>(z) * static_cast<C>(f)),
};
}
template <typename V>
constexpr Vec3& operator*=(const V& f) {
*this = *this * f;
return *this;
} }
template <typename V> template <typename V>
constexpr Vec<T, N> operator/=(const V f) noexcept { return *this = *this / f; } [[nodiscard]] constexpr Vec3<decltype(T{} / V{})> operator/(const V& f) const {
using TV = decltype(T{} / V{});
[[nodiscard]] constexpr T Length2() const noexcept {
T r{};
for (size_t i = 0; i < N; ++i)
r += elems[i] * elems[i];
return r;
}
// Only implemented for T=float
[[nodiscard]] T Length() const { return T(std::sqrt(float(Length2()))); }
[[nodiscard]] Vec<T, N> Normalized() const { return *this / Length(); }
[[nodiscard]] constexpr T& operator[](std::size_t i) noexcept { return elems[i]; }
[[nodiscard]] constexpr const T& operator[](std::size_t i) const noexcept { return elems[i]; }
[[nodiscard]] std::array<decltype(-T{}), 16> ToMatrix() const {
const T x2 = elems[0] * elems[0];
const T y2 = elems[1] * elems[1];
const T z2 = elems[2] * elems[2];
const T xy = elems[0] * elems[1];
const T wz = elems[3] * elems[2];
const T xz = elems[0] * elems[2];
const T wy = elems[3] * elems[1];
const T yz = elems[1] * elems[2];
const T wx = elems[3] * elems[0];
return {
1.0f - 2.0f * (y2 + z2),
2.0f * (xy + wz),
2.0f * (xz - wy),
0.0f,
2.0f * (xy - wz),
1.0f - 2.0f * (x2 + z2),
2.0f * (yz + wx),
0.0f,
2.0f * (xz + wy),
2.0f * (yz - wx),
1.0f - 2.0f * (x2 + y2),
0.0f,
0.0f,
0.0f,
0.0f,
1.0f
};
}
};
template <typename T, size_t N, typename V>
[[nodiscard]] constexpr Vec<T, N> operator*(const V f, const Vec<T, N> v) noexcept {
using C = std::common_type_t<T, V>; using C = std::common_type_t<T, V>;
Vec<T, N> r{};
for (size_t i = 0; i < N; ++i) return {
r.elems[i] = T(C(f) * C(v.elems[i])); static_cast<TV>(static_cast<C>(x) / static_cast<C>(f)),
return r; static_cast<TV>(static_cast<C>(y) / static_cast<C>(f)),
static_cast<TV>(static_cast<C>(z) / static_cast<C>(f)),
};
}
template <typename V>
constexpr Vec3& operator/=(const V& f) {
*this = *this / f;
return *this;
}
void RotateFromOrigin(float roll, float pitch, float yaw) {
float temp = y;
y = std::cos(roll) * y - std::sin(roll) * z;
z = std::sin(roll) * temp + std::cos(roll) * z;
temp = x;
x = std::cos(pitch) * x + std::sin(pitch) * z;
z = -std::sin(pitch) * temp + std::cos(pitch) * z;
temp = x;
x = std::cos(yaw) * x - std::sin(yaw) * y;
y = std::sin(yaw) * temp + std::cos(yaw) * y;
}
[[nodiscard]] constexpr T Length2() const {
return x * x + y * y + z * z;
}
// Only implemented for T=float
[[nodiscard]] float Length() const;
[[nodiscard]] Vec3 Normalized() const;
[[nodiscard]] float Normalize(); // returns the previous length, which is often useful
[[nodiscard]] constexpr T& operator[](std::size_t i) {
return *((&x) + i);
}
[[nodiscard]] constexpr const T& operator[](std::size_t i) const {
return *((&x) + i);
}
constexpr void SetZero() {
x = 0;
y = 0;
z = 0;
}
// Common aliases: UVW (texel coordinates), RGB (colors), STQ (texture coordinates)
[[nodiscard]] constexpr T& u() {
return x;
}
[[nodiscard]] constexpr T& v() {
return y;
}
[[nodiscard]] constexpr T& w() {
return z;
}
[[nodiscard]] constexpr T& r() {
return x;
}
[[nodiscard]] constexpr T& g() {
return y;
}
[[nodiscard]] constexpr T& b() {
return z;
}
[[nodiscard]] constexpr T& s() {
return x;
}
[[nodiscard]] constexpr T& t() {
return y;
}
[[nodiscard]] constexpr T& q() {
return z;
}
[[nodiscard]] constexpr const T& u() const {
return x;
}
[[nodiscard]] constexpr const T& v() const {
return y;
}
[[nodiscard]] constexpr const T& w() const {
return z;
}
[[nodiscard]] constexpr const T& r() const {
return x;
}
[[nodiscard]] constexpr const T& g() const {
return y;
}
[[nodiscard]] constexpr const T& b() const {
return z;
}
[[nodiscard]] constexpr const T& s() const {
return x;
}
[[nodiscard]] constexpr const T& t() const {
return y;
}
[[nodiscard]] constexpr const T& q() const {
return z;
}
// swizzlers - create a subvector of specific components
// e.g. Vec2 uv() { return Vec2(x,y); }
// _DEFINE_SWIZZLER2 defines a single such function, DEFINE_SWIZZLER2 defines all of them for all
// component names (x<->r) and permutations (xy<->yx)
#define _DEFINE_SWIZZLER2(a, b, name) \
[[nodiscard]] constexpr Vec2<T> name() const { return Vec2<T>(a, b); }
#define DEFINE_SWIZZLER2(a, b, a2, b2, a3, b3, a4, b4) \
_DEFINE_SWIZZLER2(a, b, a##b); \
_DEFINE_SWIZZLER2(a, b, a2##b2); \
_DEFINE_SWIZZLER2(a, b, a3##b3); \
_DEFINE_SWIZZLER2(a, b, a4##b4); \
_DEFINE_SWIZZLER2(b, a, b##a); \
_DEFINE_SWIZZLER2(b, a, b2##a2); \
_DEFINE_SWIZZLER2(b, a, b3##a3); \
_DEFINE_SWIZZLER2(b, a, b4##a4)
DEFINE_SWIZZLER2(x, y, r, g, u, v, s, t);
DEFINE_SWIZZLER2(x, z, r, b, u, w, s, q);
DEFINE_SWIZZLER2(y, z, g, b, v, w, t, q);
#undef DEFINE_SWIZZLER2
#undef _DEFINE_SWIZZLER2
};
template <typename T, typename V>
[[nodiscard]] constexpr Vec3<T> operator*(const V& f, const Vec3<T>& vec) {
using C = std::common_type_t<T, V>;
return Vec3<T>(static_cast<T>(static_cast<C>(f) * static_cast<C>(vec.x)),
static_cast<T>(static_cast<C>(f) * static_cast<C>(vec.y)),
static_cast<T>(static_cast<C>(f) * static_cast<C>(vec.z)));
}
template <>
inline float Vec3<float>::Length() const {
return std::sqrt(x * x + y * y + z * z);
}
template <>
inline Vec3<float> Vec3<float>::Normalized() const {
return *this / Length();
}
template <>
inline float Vec3<float>::Normalize() {
float length = Length();
*this /= length;
return length;
}
using Vec3f = Vec3<float>;
template <typename T>
class Vec4 {
public:
T x{};
T y{};
T z{};
T w{};
constexpr Vec4() = default;
constexpr Vec4(const T& x_, const T& y_, const T& z_, const T& w_)
: x(x_), y(y_), z(z_), w(w_) {}
template <typename T2>
[[nodiscard]] constexpr Vec4<T2> Cast() const {
return Vec4<T2>(static_cast<T2>(x), static_cast<T2>(y), static_cast<T2>(z),
static_cast<T2>(w));
}
[[nodiscard]] static constexpr Vec4 AssignToAll(const T& f) {
return Vec4(f, f, f, f);
}
[[nodiscard]] constexpr Vec4<decltype(T{} + T{})> operator+(const Vec4& other) const {
return {x + other.x, y + other.y, z + other.z, w + other.w};
}
constexpr Vec4& operator+=(const Vec4& other) {
x += other.x;
y += other.y;
z += other.z;
w += other.w;
return *this;
}
[[nodiscard]] constexpr Vec4<decltype(T{} - T{})> operator-(const Vec4& other) const {
return {x - other.x, y - other.y, z - other.z, w - other.w};
}
constexpr Vec4& operator-=(const Vec4& other) {
x -= other.x;
y -= other.y;
z -= other.z;
w -= other.w;
return *this;
}
template <typename U = T>
[[nodiscard]] constexpr Vec4<std::enable_if_t<std::is_signed_v<U>, U>> operator-() const {
return {-x, -y, -z, -w};
}
[[nodiscard]] constexpr Vec4<decltype(T{} * T{})> operator*(const Vec4& other) const {
return {x * other.x, y * other.y, z * other.z, w * other.w};
}
template <typename V>
[[nodiscard]] constexpr Vec4<decltype(T{} * V{})> operator*(const V& f) const {
using TV = decltype(T{} * V{});
using C = std::common_type_t<T, V>;
return {
static_cast<TV>(static_cast<C>(x) * static_cast<C>(f)),
static_cast<TV>(static_cast<C>(y) * static_cast<C>(f)),
static_cast<TV>(static_cast<C>(z) * static_cast<C>(f)),
static_cast<TV>(static_cast<C>(w) * static_cast<C>(f)),
};
}
template <typename V>
constexpr Vec4& operator*=(const V& f) {
*this = *this * f;
return *this;
}
template <typename V>
[[nodiscard]] constexpr Vec4<decltype(T{} / V{})> operator/(const V& f) const {
using TV = decltype(T{} / V{});
using C = std::common_type_t<T, V>;
return {
static_cast<TV>(static_cast<C>(x) / static_cast<C>(f)),
static_cast<TV>(static_cast<C>(y) / static_cast<C>(f)),
static_cast<TV>(static_cast<C>(z) / static_cast<C>(f)),
static_cast<TV>(static_cast<C>(w) / static_cast<C>(f)),
};
}
template <typename V>
constexpr Vec4& operator/=(const V& f) {
*this = *this / f;
return *this;
}
[[nodiscard]] constexpr T Length2() const {
return x * x + y * y + z * z + w * w;
}
[[nodiscard]] constexpr T& operator[](std::size_t i) {
return *((&x) + i);
}
[[nodiscard]] constexpr const T& operator[](std::size_t i) const {
return *((&x) + i);
}
constexpr void SetZero() {
x = 0;
y = 0;
z = 0;
w = 0;
}
// Common alias: RGBA (colors)
[[nodiscard]] constexpr T& r() {
return x;
}
[[nodiscard]] constexpr T& g() {
return y;
}
[[nodiscard]] constexpr T& b() {
return z;
}
[[nodiscard]] constexpr T& a() {
return w;
}
[[nodiscard]] constexpr const T& r() const {
return x;
}
[[nodiscard]] constexpr const T& g() const {
return y;
}
[[nodiscard]] constexpr const T& b() const {
return z;
}
[[nodiscard]] constexpr const T& a() const {
return w;
}
// Swizzlers - Create a subvector of specific components
// e.g. Vec2 uv() { return Vec2(x,y); }
// _DEFINE_SWIZZLER2 defines a single such function
// DEFINE_SWIZZLER2_COMP1 defines one-component functions for all component names (x<->r)
// DEFINE_SWIZZLER2_COMP2 defines two component functions for all component names (x<->r) and
// permutations (xy<->yx)
#define _DEFINE_SWIZZLER2(a, b, name) \
[[nodiscard]] constexpr Vec2<T> name() const { return Vec2<T>(a, b); }
#define DEFINE_SWIZZLER2_COMP1(a, a2) \
_DEFINE_SWIZZLER2(a, a, a##a); \
_DEFINE_SWIZZLER2(a, a, a2##a2)
#define DEFINE_SWIZZLER2_COMP2(a, b, a2, b2) \
_DEFINE_SWIZZLER2(a, b, a##b); \
_DEFINE_SWIZZLER2(a, b, a2##b2); \
_DEFINE_SWIZZLER2(b, a, b##a); \
_DEFINE_SWIZZLER2(b, a, b2##a2)
DEFINE_SWIZZLER2_COMP2(x, y, r, g);
DEFINE_SWIZZLER2_COMP2(x, z, r, b);
DEFINE_SWIZZLER2_COMP2(x, w, r, a);
DEFINE_SWIZZLER2_COMP2(y, z, g, b);
DEFINE_SWIZZLER2_COMP2(y, w, g, a);
DEFINE_SWIZZLER2_COMP2(z, w, b, a);
DEFINE_SWIZZLER2_COMP1(x, r);
DEFINE_SWIZZLER2_COMP1(y, g);
DEFINE_SWIZZLER2_COMP1(z, b);
DEFINE_SWIZZLER2_COMP1(w, a);
#undef DEFINE_SWIZZLER2_COMP1
#undef DEFINE_SWIZZLER2_COMP2
#undef _DEFINE_SWIZZLER2
#define _DEFINE_SWIZZLER3(a, b, c, name) \
[[nodiscard]] constexpr Vec3<T> name() const { return Vec3<T>(a, b, c); }
#define DEFINE_SWIZZLER3_COMP1(a, a2) \
_DEFINE_SWIZZLER3(a, a, a, a##a##a); \
_DEFINE_SWIZZLER3(a, a, a, a2##a2##a2)
#define DEFINE_SWIZZLER3_COMP3(a, b, c, a2, b2, c2) \
_DEFINE_SWIZZLER3(a, b, c, a##b##c); \
_DEFINE_SWIZZLER3(a, c, b, a##c##b); \
_DEFINE_SWIZZLER3(b, a, c, b##a##c); \
_DEFINE_SWIZZLER3(b, c, a, b##c##a); \
_DEFINE_SWIZZLER3(c, a, b, c##a##b); \
_DEFINE_SWIZZLER3(c, b, a, c##b##a); \
_DEFINE_SWIZZLER3(a, b, c, a2##b2##c2); \
_DEFINE_SWIZZLER3(a, c, b, a2##c2##b2); \
_DEFINE_SWIZZLER3(b, a, c, b2##a2##c2); \
_DEFINE_SWIZZLER3(b, c, a, b2##c2##a2); \
_DEFINE_SWIZZLER3(c, a, b, c2##a2##b2); \
_DEFINE_SWIZZLER3(c, b, a, c2##b2##a2)
DEFINE_SWIZZLER3_COMP3(x, y, z, r, g, b);
DEFINE_SWIZZLER3_COMP3(x, y, w, r, g, a);
DEFINE_SWIZZLER3_COMP3(x, z, w, r, b, a);
DEFINE_SWIZZLER3_COMP3(y, z, w, g, b, a);
DEFINE_SWIZZLER3_COMP1(x, r);
DEFINE_SWIZZLER3_COMP1(y, g);
DEFINE_SWIZZLER3_COMP1(z, b);
DEFINE_SWIZZLER3_COMP1(w, a);
#undef DEFINE_SWIZZLER3_COMP1
#undef DEFINE_SWIZZLER3_COMP3
#undef _DEFINE_SWIZZLER3
};
template <typename T, typename V>
[[nodiscard]] constexpr Vec4<decltype(V{} * T{})> operator*(const V& f, const Vec4<T>& vec) {
using TV = decltype(V{} * T{});
using C = std::common_type_t<T, V>;
return {
static_cast<TV>(static_cast<C>(f) * static_cast<C>(vec.x)),
static_cast<TV>(static_cast<C>(f) * static_cast<C>(vec.y)),
static_cast<TV>(static_cast<C>(f) * static_cast<C>(vec.z)),
static_cast<TV>(static_cast<C>(f) * static_cast<C>(vec.w)),
};
}
using Vec4f = Vec4<float>;
template <typename T>
constexpr decltype(T{} * T{} + T{} * T{}) Dot(const Vec2<T>& a, const Vec2<T>& b) {
return a.x * b.x + a.y * b.y;
}
template <typename T>
[[nodiscard]] constexpr decltype(T{} * T{} + T{} * T{}) Dot(const Vec3<T>& a, const Vec3<T>& b) {
return a.x * b.x + a.y * b.y + a.z * b.z;
}
template <typename T>
[[nodiscard]] constexpr decltype(T{} * T{} + T{} * T{}) Dot(const Vec4<T>& a, const Vec4<T>& b) {
return a.x * b.x + a.y * b.y + a.z * b.z + a.w * b.w;
}
template <>
[[nodiscard]] inline float Dot(const Vec4<float>& a, const Vec4<float>& b) {
#ifdef __ARM_NEON
float32x4_t va = vld1q_f32(&a.x);
float32x4_t vb = vld1q_f32(&b.x);
float32x4_t result = vmulq_f32(va, vb);
#if defined(__aarch64__) // Use vaddvq_f32 in ARMv8 architectures
return vaddvq_f32(result);
#else // Use manual addition for older architectures
float32x2_t sum2 = vadd_f32(vget_high_f32(result), vget_low_f32(result));
return vget_lane_f32(vpadd_f32(sum2, sum2), 0);
#endif
#else
return a.x * b.x + a.y * b.y + a.z * b.z + a.w * b.w;
#endif
}
template <typename T>
[[nodiscard]] constexpr Vec3<decltype(T{} * T{} - T{} * T{})> Cross(const Vec3<T>& a,
const Vec3<T>& b) {
return {a.y * b.z - a.z * b.y, a.z * b.x - a.x * b.z, a.x * b.y - a.y * b.x};
}
// linear interpolation via float: 0.0=begin, 1.0=end
template <typename X>
[[nodiscard]] constexpr decltype(X{} * float{} + X{} * float{}) Lerp(const X& begin, const X& end,
const float t) {
return begin * (1.f - t) + end * t;
}
// linear interpolation via int: 0=begin, base=end
template <typename X, int base>
[[nodiscard]] constexpr decltype((X{} * int{} + X{} * int{}) / base) LerpInt(const X& begin,
const X& end,
const int t) {
return (begin * (base - t) + end * t) / base;
}
// bilinear interpolation. s is for interpolating x00-x01 and x10-x11, and t is for the second
// interpolation.
template <typename X>
[[nodiscard]] constexpr auto BilinearInterp(const X& x00, const X& x01, const X& x10, const X& x11,
const float s, const float t) {
auto y0 = Lerp(x00, x01, s);
auto y1 = Lerp(x10, x11, s);
return Lerp(y0, y1, t);
}
// Utility vector factories
template <typename T>
[[nodiscard]] constexpr Vec2<T> MakeVec(const T& x, const T& y) {
return Vec2<T>{x, y};
}
template <typename T>
[[nodiscard]] constexpr Vec3<T> MakeVec(const T& x, const T& y, const T& z) {
return Vec3<T>{x, y, z};
}
template <typename T>
[[nodiscard]] constexpr Vec4<T> MakeVec(const T& x, const T& y, const Vec2<T>& zw) {
return MakeVec(x, y, zw[0], zw[1]);
}
template <typename T>
[[nodiscard]] constexpr Vec3<T> MakeVec(const Vec2<T>& xy, const T& z) {
return MakeVec(xy[0], xy[1], z);
}
template <typename T>
[[nodiscard]] constexpr Vec3<T> MakeVec(const T& x, const Vec2<T>& yz) {
return MakeVec(x, yz[0], yz[1]);
}
template <typename T>
[[nodiscard]] constexpr Vec4<T> MakeVec(const T& x, const T& y, const T& z, const T& w) {
return Vec4<T>{x, y, z, w};
}
template <typename T>
[[nodiscard]] constexpr Vec4<T> MakeVec(const Vec2<T>& xy, const T& z, const T& w) {
return MakeVec(xy[0], xy[1], z, w);
}
template <typename T>
[[nodiscard]] constexpr Vec4<T> MakeVec(const T& x, const Vec2<T>& yz, const T& w) {
return MakeVec(x, yz[0], yz[1], w);
}
// NOTE: This has priority over "Vec2<Vec2<T>> MakeVec(const Vec2<T>& x, const Vec2<T>& y)".
// Even if someone wanted to use an odd object like Vec2<Vec2<T>>, the compiler would error
// out soon enough due to misuse of the returned structure.
template <typename T>
[[nodiscard]] constexpr Vec4<T> MakeVec(const Vec2<T>& xy, const Vec2<T>& zw) {
return MakeVec(xy[0], xy[1], zw[0], zw[1]);
}
template <typename T>
[[nodiscard]] constexpr Vec4<T> MakeVec(const Vec3<T>& xyz, const T& w) {
return MakeVec(xyz[0], xyz[1], xyz[2], w);
}
template <typename T>
[[nodiscard]] constexpr Vec4<T> MakeVec(const T& x, const Vec3<T>& yzw) {
return MakeVec(x, yzw[0], yzw[1], yzw[2]);
} }
} // namespace Common } // namespace Common
+1 -1
View File
@@ -358,7 +358,7 @@ private:
ConnectionState(boost::asio::ip::tcp::socket&& client_socket_, async_pipe signal_pipe_, Kernel::KernelCore& kernel) ConnectionState(boost::asio::ip::tcp::socket&& client_socket_, async_pipe signal_pipe_, Kernel::KernelCore& kernel)
: client_socket{std::move(client_socket_)} : client_socket{std::move(client_socket_)}
, signal_pipe{std::move(signal_pipe_)} , signal_pipe{signal_pipe_}
, active_thread{kernel, nullptr} , active_thread{kernel, nullptr}
{} {}
-3
View File
@@ -1021,9 +1021,6 @@ Result KProcess::Run(KernelCore& kernel, s32 priority, size_t stack_size) {
// Suspend for debug, if we should. // Suspend for debug, if we should.
if (kernel.System().DebuggerEnabled()) { if (kernel.System().DebuggerEnabled()) {
LOG_INFO(Debug_GDBStub,
"GDB stub enabled; suspending guest process until a debugger continues execution on port {}",
Settings::values.gdbstub_port.GetValue());
main_thread->RequestSuspend(kernel, SuspendType::Debug); main_thread->RequestSuspend(kernel, SuspendType::Debug);
} }
@@ -1,6 +1,3 @@
// SPDX-FileCopyrightText: Copyright 2026 Eden Emulator Project
// SPDX-License-Identifier: GPL-3.0-or-later
// SPDX-FileCopyrightText: Copyright 2018 yuzu Emulator Project // SPDX-FileCopyrightText: Copyright 2018 yuzu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later // SPDX-License-Identifier: GPL-2.0-or-later
@@ -33,15 +30,15 @@ struct DeviceSettings {
INSERT_PADDING_BYTES(0x20); // Reserved INSERT_PADDING_BYTES(0x20); // Reserved
// nn::settings::system::ConsoleSixAxisSensorAccelerationBias // nn::settings::system::ConsoleSixAxisSensorAccelerationBias
Common::Vec<f32, 3> console_six_axis_sensor_acceleration_bias; Common::Vec3<f32> console_six_axis_sensor_acceleration_bias;
// nn::settings::system::ConsoleSixAxisSensorAngularVelocityBias // nn::settings::system::ConsoleSixAxisSensorAngularVelocityBias
Common::Vec<f32, 3> console_six_axis_sensor_angular_velocity_bias; Common::Vec3<f32> console_six_axis_sensor_angular_velocity_bias;
// nn::settings::system::ConsoleSixAxisSensorAccelerationGain // nn::settings::system::ConsoleSixAxisSensorAccelerationGain
std::array<u8, 0x24> console_six_axis_sensor_acceleration_gain; std::array<u8, 0x24> console_six_axis_sensor_acceleration_gain;
// nn::settings::system::ConsoleSixAxisSensorAngularVelocityGain // nn::settings::system::ConsoleSixAxisSensorAngularVelocityGain
std::array<u8, 0x24> console_six_axis_sensor_angular_velocity_gain; std::array<u8, 0x24> console_six_axis_sensor_angular_velocity_gain;
// nn::settings::system::ConsoleSixAxisSensorAngularVelocityTimeBias // nn::settings::system::ConsoleSixAxisSensorAngularVelocityTimeBias
Common::Vec<f32, 3> console_six_axis_sensor_angular_velocity_time_bias; Common::Vec3<f32> console_six_axis_sensor_angular_velocity_time_bias;
// nn::settings::system::ConsoleSixAxisSensorAngularAcceleration // nn::settings::system::ConsoleSixAxisSensorAngularAcceleration
std::array<u8, 0x24> console_six_axis_sensor_angular_acceleration; std::array<u8, 0x24> console_six_axis_sensor_angular_acceleration;
}; };
@@ -1,4 +1,4 @@
// SPDX-FileCopyrightText: Copyright 2026 Eden Emulator Project // SPDX-FileCopyrightText: Copyright 2025 Eden Emulator Project
// SPDX-License-Identifier: GPL-3.0-or-later // SPDX-License-Identifier: GPL-3.0-or-later
// SPDX-FileCopyrightText: Copyright 2018 yuzu Emulator Project // SPDX-FileCopyrightText: Copyright 2018 yuzu Emulator Project
@@ -153,15 +153,15 @@ struct SystemSettings {
INSERT_PADDING_BYTES(0x7FF8); // Reserved INSERT_PADDING_BYTES(0x7FF8); // Reserved
// nn::settings::system::ConsoleSixAxisSensorAccelerationBias // nn::settings::system::ConsoleSixAxisSensorAccelerationBias
Common::Vec<f32, 3> console_six_axis_sensor_acceleration_bias; Common::Vec3<f32> console_six_axis_sensor_acceleration_bias;
// nn::settings::system::ConsoleSixAxisSensorAngularVelocityBias // nn::settings::system::ConsoleSixAxisSensorAngularVelocityBias
Common::Vec<f32, 3> console_six_axis_sensor_angular_velocity_bias; Common::Vec3<f32> console_six_axis_sensor_angular_velocity_bias;
// nn::settings::system::ConsoleSixAxisSensorAccelerationGain // nn::settings::system::ConsoleSixAxisSensorAccelerationGain
std::array<u8, 0x24> console_six_axis_sensor_acceleration_gain; std::array<u8, 0x24> console_six_axis_sensor_acceleration_gain;
// nn::settings::system::ConsoleSixAxisSensorAngularVelocityGain // nn::settings::system::ConsoleSixAxisSensorAngularVelocityGain
std::array<u8, 0x24> console_six_axis_sensor_angular_velocity_gain; std::array<u8, 0x24> console_six_axis_sensor_angular_velocity_gain;
// nn::settings::system::ConsoleSixAxisSensorAngularVelocityTimeBias // nn::settings::system::ConsoleSixAxisSensorAngularVelocityTimeBias
Common::Vec<f32, 3> console_six_axis_sensor_angular_velocity_time_bias; Common::Vec3<f32> console_six_axis_sensor_angular_velocity_time_bias;
// nn::settings::system::ConsoleSixAxisSensorAngularAcceleration // nn::settings::system::ConsoleSixAxisSensorAngularAcceleration
std::array<u8, 0x24> console_six_axis_sensor_angular_velocity_acceleration; std::array<u8, 0x24> console_six_axis_sensor_angular_velocity_acceleration;
INSERT_PADDING_BYTES(0x70); // Reserved INSERT_PADDING_BYTES(0x70); // Reserved
+2 -2
View File
@@ -170,12 +170,12 @@ void EmulatedConsole::SetMotion(const Common::Input::CallbackStatus& callback) {
auto& emulated = console.motion_values.emulated; auto& emulated = console.motion_values.emulated;
raw_status = TransformToMotion(callback); raw_status = TransformToMotion(callback);
emulated.SetAcceleration(Common::Vec<f32, 3>{ emulated.SetAcceleration(Common::Vec3f{
raw_status.accel.x.value, raw_status.accel.x.value,
raw_status.accel.y.value, raw_status.accel.y.value,
raw_status.accel.z.value, raw_status.accel.z.value,
}); });
emulated.SetGyroscope(Common::Vec<f32, 3>{ emulated.SetGyroscope(Common::Vec3f{
raw_status.gyro.x.value, raw_status.gyro.x.value,
raw_status.gyro.y.value, raw_status.gyro.y.value,
raw_status.gyro.z.value, raw_status.gyro.z.value,
+7 -6
View File
@@ -18,6 +18,7 @@
#include "common/input.h" #include "common/input.h"
#include "common/param_package.h" #include "common/param_package.h"
#include "common/point.h" #include "common/point.h"
#include "common/quaternion.h"
#include "common/vector_math.h" #include "common/vector_math.h"
#include "hid_core/frontend/motion_input.h" #include "hid_core/frontend/motion_input.h"
#include "hid_core/hid_types.h" #include "hid_core/hid_types.h"
@@ -42,12 +43,12 @@ using TouchValues = std::array<Common::Input::TouchStatus, MaxTouchDevices>;
// Contains all motion related data that is used on the services // Contains all motion related data that is used on the services
struct ConsoleMotion { struct ConsoleMotion {
Common::Vec<f32, 3> accel{}; Common::Vec3f accel{};
Common::Vec<f32, 3> gyro{}; Common::Vec3f gyro{};
Common::Vec<f32, 3> rotation{}; Common::Vec3f rotation{};
std::array<Common::Vec<f32, 3>, 3> orientation{}; std::array<Common::Vec3f, 3> orientation{};
Common::Vec<f32, 4> quaternion{}; Common::Quaternion<f32> quaternion{};
Common::Vec<f32, 3> gyro_bias{}; Common::Vec3f gyro_bias{};
f32 verticalization_error{}; f32 verticalization_error{};
bool is_at_rest{}; bool is_at_rest{};
}; };
@@ -1051,12 +1051,12 @@ void EmulatedController::SetMotion(const Common::Input::CallbackStatus& callback
auto& emulated = controller.motion_values[index].emulated; auto& emulated = controller.motion_values[index].emulated;
raw_status = TransformToMotion(callback); raw_status = TransformToMotion(callback);
emulated.SetAcceleration(Common::Vec<f32, 3>{ emulated.SetAcceleration(Common::Vec3f{
raw_status.accel.x.value, raw_status.accel.x.value,
raw_status.accel.y.value, raw_status.accel.y.value,
raw_status.accel.z.value, raw_status.accel.z.value,
}); });
emulated.SetGyroscope(Common::Vec<f32, 3>{ emulated.SetGyroscope(Common::Vec3f{
raw_status.gyro.x.value, raw_status.gyro.x.value,
raw_status.gyro.y.value, raw_status.gyro.y.value,
raw_status.gyro.z.value, raw_status.gyro.z.value,
+5 -5
View File
@@ -107,11 +107,11 @@ struct RingSensorForce {
using NfcState = Common::Input::NfcStatus; using NfcState = Common::Input::NfcStatus;
struct ControllerMotion { struct ControllerMotion {
Common::Vec<f32, 3> accel{}; Common::Vec3f accel{};
Common::Vec<f32, 3> gyro{}; Common::Vec3f gyro{};
Common::Vec<f32, 3> rotation{}; Common::Vec3f rotation{};
Common::Vec<f32, 3> euler{}; Common::Vec3f euler{};
std::array<Common::Vec<f32, 3>, 3> orientation{}; std::array<Common::Vec3f, 3> orientation{};
bool is_at_rest{}; bool is_at_rest{};
}; };
+90 -90
View File
@@ -26,19 +26,20 @@ void MotionInput::SetPID(f32 new_kp, f32 new_ki, f32 new_kd) {
kd = new_kd; kd = new_kd;
} }
void MotionInput::SetAcceleration(const Common::Vec<f32, 3>& acceleration) { void MotionInput::SetAcceleration(const Common::Vec3f& acceleration) {
accel = acceleration; accel = acceleration;
accel[0] = std::clamp(accel[0], -AccelMaxValue, AccelMaxValue);
accel[1] = std::clamp(accel[1], -AccelMaxValue, AccelMaxValue); accel.x = std::clamp(accel.x, -AccelMaxValue, AccelMaxValue);
accel[2] = std::clamp(accel[2], -AccelMaxValue, AccelMaxValue); accel.y = std::clamp(accel.y, -AccelMaxValue, AccelMaxValue);
accel.z = std::clamp(accel.z, -AccelMaxValue, AccelMaxValue);
} }
void MotionInput::SetGyroscope(const Common::Vec<f32, 3>& gyroscope) { void MotionInput::SetGyroscope(const Common::Vec3f& gyroscope) {
gyro = gyroscope - gyro_bias; gyro = gyroscope - gyro_bias;
gyro[0] = std::clamp(gyro[0], -GyroMaxValue, GyroMaxValue); gyro.x = std::clamp(gyro.x, -GyroMaxValue, GyroMaxValue);
gyro[1] = std::clamp(gyro[1], -GyroMaxValue, GyroMaxValue); gyro.y = std::clamp(gyro.y, -GyroMaxValue, GyroMaxValue);
gyro[2] = std::clamp(gyro[2], -GyroMaxValue, GyroMaxValue); gyro.z = std::clamp(gyro.z, -GyroMaxValue, GyroMaxValue);
// Auto adjust gyro_bias to minimize drift // Auto adjust gyro_bias to minimize drift
if (!IsMoving(IsAtRestRelaxed)) { if (!IsMoving(IsAtRestRelaxed)) {
@@ -58,25 +59,25 @@ void MotionInput::SetGyroscope(const Common::Vec<f32, 3>& gyroscope) {
} }
} }
void MotionInput::SetQuaternion(const Common::Vec<f32, 4>& quaternion) { void MotionInput::SetQuaternion(const Common::Quaternion<f32>& quaternion) {
quat = quaternion; quat = quaternion;
} }
void MotionInput::SetEulerAngles(const Common::Vec<f32, 3>& euler_angles) { void MotionInput::SetEulerAngles(const Common::Vec3f& euler_angles) {
const float cr = std::cos(euler_angles[0] * 0.5f); const float cr = std::cos(euler_angles.x * 0.5f);
const float sr = std::sin(euler_angles[0] * 0.5f); const float sr = std::sin(euler_angles.x * 0.5f);
const float cp = std::cos(euler_angles[1] * 0.5f); const float cp = std::cos(euler_angles.y * 0.5f);
const float sp = std::sin(euler_angles[1] * 0.5f); const float sp = std::sin(euler_angles.y * 0.5f);
const float cy = std::cos(euler_angles[2] * 0.5f); const float cy = std::cos(euler_angles.z * 0.5f);
const float sy = std::sin(euler_angles[2] * 0.5f); const float sy = std::sin(euler_angles.z * 0.5f);
quat[3] = cr * cp * cy + sr * sp * sy; quat.w = cr * cp * cy + sr * sp * sy;
quat[0] = sr * cp * cy - cr * sp * sy; quat.xyz.x = sr * cp * cy - cr * sp * sy;
quat[1] = cr * sp * cy + sr * cp * sy; quat.xyz.y = cr * sp * cy + sr * cp * sy;
quat[2] = cr * cp * sy - sr * sp * cy; quat.xyz.z = cr * cp * sy - sr * sp * cy;
} }
void MotionInput::SetGyroBias(const Common::Vec<f32, 3>& bias) { void MotionInput::SetGyroBias(const Common::Vec3f& bias) {
gyro_bias = bias; gyro_bias = bias;
} }
@@ -97,7 +98,7 @@ void MotionInput::ResetRotations() {
} }
void MotionInput::ResetQuaternion() { void MotionInput::ResetQuaternion() {
quat = Common::Vec<f32, 4>{0.0f, 0.0f, -1.0f, 0.0f}; quat = {{0.0f, 0.0f, -1.0f}, 0.0f};
} }
bool MotionInput::IsMoving(f32 sensitivity) const { bool MotionInput::IsMoving(f32 sensitivity) const {
@@ -136,10 +137,10 @@ void MotionInput::UpdateOrientation(u64 elapsed_time) {
ResetOrientation(); ResetOrientation();
} }
// Short name local variable for readability // Short name local variable for readability
f32 q1 = quat[3]; f32 q1 = quat.w;
f32 q2 = quat[0]; f32 q2 = quat.xyz[0];
f32 q3 = quat[1]; f32 q3 = quat.xyz[1];
f32 q4 = quat[2]; f32 q4 = quat.xyz[2];
const auto sample_period = static_cast<f32>(elapsed_time) / 1000000.0f; const auto sample_period = static_cast<f32>(elapsed_time) / 1000000.0f;
// Ignore invalid elapsed time // Ignore invalid elapsed time
@@ -149,23 +150,23 @@ void MotionInput::UpdateOrientation(u64 elapsed_time) {
const auto normal_accel = accel.Normalized(); const auto normal_accel = accel.Normalized();
auto rad_gyro = gyro * std::numbers::pi_v<float> * 2.f; auto rad_gyro = gyro * std::numbers::pi_v<float> * 2.f;
const f32 swap = rad_gyro[0]; const f32 swap = rad_gyro.x;
rad_gyro[0] = rad_gyro[1]; rad_gyro.x = rad_gyro.y;
rad_gyro[1] = -swap; rad_gyro.y = -swap;
rad_gyro[2] = -rad_gyro[2]; rad_gyro.z = -rad_gyro.z;
// Clear gyro values if there is no gyro present // Clear gyro values if there is no gyro present
if (only_accelerometer) { if (only_accelerometer) {
rad_gyro[0] = 0; rad_gyro.x = 0;
rad_gyro[1] = 0; rad_gyro.y = 0;
rad_gyro[2] = 0; rad_gyro.z = 0;
} }
// Ignore drift correction if acceleration is not reliable // Ignore drift correction if acceleration is not reliable
if (accel.Length() >= 0.75f && accel.Length() <= 1.25f) { if (accel.Length() >= 0.75f && accel.Length() <= 1.25f) {
const f32 ax = -normal_accel[0]; const f32 ax = -normal_accel.x;
const f32 ay = normal_accel[1]; const f32 ay = normal_accel.y;
const f32 az = -normal_accel[2]; const f32 az = -normal_accel.z;
// Estimated direction of gravity // Estimated direction of gravity
const f32 vx = 2.0f * (q2 * q4 - q1 * q3); const f32 vx = 2.0f * (q2 * q4 - q1 * q3);
@@ -173,7 +174,7 @@ void MotionInput::UpdateOrientation(u64 elapsed_time) {
const f32 vz = q1 * q1 - q2 * q2 - q3 * q3 + q4 * q4; const f32 vz = q1 * q1 - q2 * q2 - q3 * q3 + q4 * q4;
// Error is cross product between estimated direction and measured direction of gravity // Error is cross product between estimated direction and measured direction of gravity
const Common::Vec<f32, 3> new_real_error{ const Common::Vec3f new_real_error = {
az * vx - ax * vz, az * vx - ax * vz,
ay * vz - az * vy, ay * vz - az * vy,
ax * vy - ay * vx, ax * vy - ay * vx,
@@ -201,16 +202,16 @@ void MotionInput::UpdateOrientation(u64 elapsed_time) {
rad_gyro += 10.0f * kd * derivative_error; rad_gyro += 10.0f * kd * derivative_error;
// Emulate gyro values for games that need them // Emulate gyro values for games that need them
gyro[0] = -rad_gyro[1]; gyro.x = -rad_gyro.y;
gyro[1] = rad_gyro[0]; gyro.y = rad_gyro.x;
gyro[2] = -rad_gyro[2]; gyro.z = -rad_gyro.z;
UpdateRotation(elapsed_time); UpdateRotation(elapsed_time);
} }
} }
const f32 gx = rad_gyro[1]; const f32 gx = rad_gyro.y;
const f32 gy = rad_gyro[0]; const f32 gy = rad_gyro.x;
const f32 gz = rad_gyro[2]; const f32 gz = rad_gyro.z;
// Integrate rate of change of quaternion // Integrate rate of change of quaternion
const f32 pa = q2; const f32 pa = q2;
@@ -221,58 +222,57 @@ void MotionInput::UpdateOrientation(u64 elapsed_time) {
q3 = pb + (q1 * gy - pa * gz + pc * gx) * (0.5f * sample_period); q3 = pb + (q1 * gy - pa * gz + pc * gx) * (0.5f * sample_period);
q4 = pc + (q1 * gz + pa * gy - pb * gx) * (0.5f * sample_period); q4 = pc + (q1 * gz + pa * gy - pb * gx) * (0.5f * sample_period);
quat[3] = q1; quat.w = q1;
quat[0] = q2; quat.xyz[0] = q2;
quat[1] = q3; quat.xyz[1] = q3;
quat[2] = q4; quat.xyz[2] = q4;
quat = quat.Normalized(); quat = quat.Normalized();
} }
std::array<Common::Vec<f32, 3>, 3> MotionInput::GetOrientation() const { std::array<Common::Vec3f, 3> MotionInput::GetOrientation() const {
const Common::Vec<f32, 4> quad{ const Common::Quaternion<float> quad{
-quat[1], .xyz = {-quat.xyz[1], -quat.xyz[0], -quat.w},
-quat[0], .w = -quat.xyz[2],
-quat[3],
-quat[2],
}; };
const std::array<f32, 16> matrix4x4 = quad.ToMatrix(); const std::array<float, 16> matrix4x4 = quad.ToMatrix();
return {Common::Vec<f32, 3>(matrix4x4[0], matrix4x4[1], -matrix4x4[2]),
Common::Vec<f32, 3>(matrix4x4[4], matrix4x4[5], -matrix4x4[6]), return {Common::Vec3f(matrix4x4[0], matrix4x4[1], -matrix4x4[2]),
Common::Vec<f32, 3>(-matrix4x4[8], -matrix4x4[9], matrix4x4[10])}; Common::Vec3f(matrix4x4[4], matrix4x4[5], -matrix4x4[6]),
Common::Vec3f(-matrix4x4[8], -matrix4x4[9], matrix4x4[10])};
} }
Common::Vec<f32, 3> MotionInput::GetAcceleration() const { Common::Vec3f MotionInput::GetAcceleration() const {
return accel; return accel;
} }
Common::Vec<f32, 3> MotionInput::GetGyroscope() const { Common::Vec3f MotionInput::GetGyroscope() const {
return gyro; return gyro;
} }
Common::Vec<f32, 3> MotionInput::GetGyroBias() const { Common::Vec3f MotionInput::GetGyroBias() const {
return gyro_bias; return gyro_bias;
} }
Common::Vec<f32, 4> MotionInput::GetQuaternion() const { Common::Quaternion<f32> MotionInput::GetQuaternion() const {
return quat; return quat;
} }
Common::Vec<f32, 3> MotionInput::GetRotations() const { Common::Vec3f MotionInput::GetRotations() const {
return rotations; return rotations;
} }
Common::Vec<f32, 3> MotionInput::GetEulerAngles() const { Common::Vec3f MotionInput::GetEulerAngles() const {
// roll (x-axis rotation) // roll (x-axis rotation)
const float sinr_cosp = 2 * (quat[3] * quat[0] + quat[1] * quat[2]); const float sinr_cosp = 2 * (quat.w * quat.xyz.x + quat.xyz.y * quat.xyz.z);
const float cosr_cosp = 1 - 2 * (quat[0] * quat[0] + quat[1] * quat[1]); const float cosr_cosp = 1 - 2 * (quat.xyz.x * quat.xyz.x + quat.xyz.y * quat.xyz.y);
// pitch (y-axis rotation) // pitch (y-axis rotation)
const float sinp = std::sqrt(1 + 2 * (quat[3] * quat[1] - quat[0] * quat[2])); const float sinp = std::sqrt(1 + 2 * (quat.w * quat.xyz.y - quat.xyz.x * quat.xyz.z));
const float cosp = std::sqrt(1 - 2 * (quat[3] * quat[1] - quat[0] * quat[2])); const float cosp = std::sqrt(1 - 2 * (quat.w * quat.xyz.y - quat.xyz.x * quat.xyz.z));
// yaw (z-axis rotation) // yaw (z-axis rotation)
const float siny_cosp = 2 * (quat[3] * quat[2] + quat[0] * quat[1]); const float siny_cosp = 2 * (quat.w * quat.xyz.z + quat.xyz.x * quat.xyz.y);
const float cosy_cosp = 1 - 2 * (quat[1] * quat[1] + quat[2] * quat[2]); const float cosy_cosp = 1 - 2 * (quat.xyz.y * quat.xyz.y + quat.xyz.z * quat.xyz.z);
return { return {
std::atan2(sinr_cosp, cosr_cosp), std::atan2(sinr_cosp, cosr_cosp),
@@ -285,13 +285,13 @@ void MotionInput::ResetOrientation() {
if (!reset_enabled || only_accelerometer) { if (!reset_enabled || only_accelerometer) {
return; return;
} }
if (!IsMoving(IsAtRestRelaxed) && accel[2] <= -0.9f) { if (!IsMoving(IsAtRestRelaxed) && accel.z <= -0.9f) {
++reset_counter; ++reset_counter;
if (reset_counter > 900) { if (reset_counter > 900) {
quat[3] = 0; quat.w = 0;
quat[0] = 0; quat.xyz[0] = 0;
quat[1] = 0; quat.xyz[1] = 0;
quat[2] = -1; quat.xyz[2] = -1;
SetOrientationFromAccelerometer(); SetOrientationFromAccelerometer();
integral_error = {}; integral_error = {};
reset_counter = 0; reset_counter = 0;
@@ -309,15 +309,15 @@ void MotionInput::SetOrientationFromAccelerometer() {
while (!IsCalibrated(0.01f) && ++iterations < 100) { while (!IsCalibrated(0.01f) && ++iterations < 100) {
// Short name local variable for readability // Short name local variable for readability
f32 q1 = quat[3]; f32 q1 = quat.w;
f32 q2 = quat[0]; f32 q2 = quat.xyz[0];
f32 q3 = quat[1]; f32 q3 = quat.xyz[1];
f32 q4 = quat[2]; f32 q4 = quat.xyz[2];
Common::Vec<f32, 3> rad_gyro; Common::Vec3f rad_gyro;
const f32 ax = -normal_accel[0]; const f32 ax = -normal_accel.x;
const f32 ay = normal_accel[1]; const f32 ay = normal_accel.y;
const f32 az = -normal_accel[2]; const f32 az = -normal_accel.z;
// Estimated direction of gravity // Estimated direction of gravity
const f32 vx = 2.0f * (q2 * q4 - q1 * q3); const f32 vx = 2.0f * (q2 * q4 - q1 * q3);
@@ -325,7 +325,7 @@ void MotionInput::SetOrientationFromAccelerometer() {
const f32 vz = q1 * q1 - q2 * q2 - q3 * q3 + q4 * q4; const f32 vz = q1 * q1 - q2 * q2 - q3 * q3 + q4 * q4;
// Error is cross product between estimated direction and measured direction of gravity // Error is cross product between estimated direction and measured direction of gravity
const Common::Vec<f32, 3> new_real_error = { const Common::Vec3f new_real_error = {
az * vx - ax * vz, az * vx - ax * vz,
ay * vz - az * vy, ay * vz - az * vy,
ax * vy - ay * vx, ax * vy - ay * vx,
@@ -338,9 +338,9 @@ void MotionInput::SetOrientationFromAccelerometer() {
rad_gyro += 5.0f * ki * integral_error; rad_gyro += 5.0f * ki * integral_error;
rad_gyro += 10.0f * kd * derivative_error; rad_gyro += 10.0f * kd * derivative_error;
const f32 gx = rad_gyro[1]; const f32 gx = rad_gyro.y;
const f32 gy = rad_gyro[0]; const f32 gy = rad_gyro.x;
const f32 gz = rad_gyro[2]; const f32 gz = rad_gyro.z;
// Integrate rate of change of quaternion // Integrate rate of change of quaternion
const f32 pa = q2; const f32 pa = q2;
@@ -351,10 +351,10 @@ void MotionInput::SetOrientationFromAccelerometer() {
q3 = pb + (q1 * gy - pa * gz + pc * gx) * (0.5f * sample_period); q3 = pb + (q1 * gy - pa * gz + pc * gx) * (0.5f * sample_period);
q4 = pc + (q1 * gz + pa * gy - pb * gx) * (0.5f * sample_period); q4 = pc + (q1 * gz + pa * gy - pb * gx) * (0.5f * sample_period);
quat[3] = q1; quat.w = q1;
quat[0] = q2; quat.xyz[0] = q2;
quat[1] = q3; quat.xyz[1] = q3;
quat[2] = q4; quat.xyz[2] = q4;
quat = quat.Normalized(); quat = quat.Normalized();
} }
} }
+21 -23
View File
@@ -1,12 +1,10 @@
// SPDX-FileCopyrightText: Copyright 2026 Eden Emulator Project
// SPDX-License-Identifier: GPL-3.0-or-later
// SPDX-FileCopyrightText: Copyright 2020 yuzu Emulator Project // SPDX-FileCopyrightText: Copyright 2020 yuzu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later // SPDX-License-Identifier: GPL-2.0-or-later
#pragma once #pragma once
#include "common/common_types.h" #include "common/common_types.h"
#include "common/quaternion.h"
#include "common/vector_math.h" #include "common/vector_math.h"
namespace Core::HID { namespace Core::HID {
@@ -36,11 +34,11 @@ public:
MotionInput& operator=(MotionInput&&) = default; MotionInput& operator=(MotionInput&&) = default;
void SetPID(f32 new_kp, f32 new_ki, f32 new_kd); void SetPID(f32 new_kp, f32 new_ki, f32 new_kd);
void SetAcceleration(const Common::Vec<f32, 3>& acceleration); void SetAcceleration(const Common::Vec3f& acceleration);
void SetGyroscope(const Common::Vec<f32, 3>& gyroscope); void SetGyroscope(const Common::Vec3f& gyroscope);
void SetQuaternion(const Common::Vec<f32, 4>& quaternion); void SetQuaternion(const Common::Quaternion<f32>& quaternion);
void SetEulerAngles(const Common::Vec<f32, 3>& euler_angles); void SetEulerAngles(const Common::Vec3f& euler_angles);
void SetGyroBias(const Common::Vec<f32, 3>& bias); void SetGyroBias(const Common::Vec3f& bias);
void SetGyroThreshold(f32 threshold); void SetGyroThreshold(f32 threshold);
/// Applies a modifier on top of the normal gyro threshold /// Applies a modifier on top of the normal gyro threshold
@@ -55,13 +53,13 @@ public:
void Calibrate(); void Calibrate();
[[nodiscard]] std::array<Common::Vec<f32, 3>, 3> GetOrientation() const; [[nodiscard]] std::array<Common::Vec3f, 3> GetOrientation() const;
[[nodiscard]] Common::Vec<f32, 3> GetAcceleration() const; [[nodiscard]] Common::Vec3f GetAcceleration() const;
[[nodiscard]] Common::Vec<f32, 3> GetGyroscope() const; [[nodiscard]] Common::Vec3f GetGyroscope() const;
[[nodiscard]] Common::Vec<f32, 3> GetGyroBias() const; [[nodiscard]] Common::Vec3f GetGyroBias() const;
[[nodiscard]] Common::Vec<f32, 3> GetRotations() const; [[nodiscard]] Common::Vec3f GetRotations() const;
[[nodiscard]] Common::Vec<f32, 4> GetQuaternion() const; [[nodiscard]] Common::Quaternion<f32> GetQuaternion() const;
[[nodiscard]] Common::Vec<f32, 3> GetEulerAngles() const; [[nodiscard]] Common::Vec3f GetEulerAngles() const;
[[nodiscard]] bool IsMoving(f32 sensitivity) const; [[nodiscard]] bool IsMoving(f32 sensitivity) const;
[[nodiscard]] bool IsCalibrated(f32 sensitivity) const; [[nodiscard]] bool IsCalibrated(f32 sensitivity) const;
@@ -77,24 +75,24 @@ private:
f32 kd; f32 kd;
// PID errors // PID errors
Common::Vec<f32, 3> real_error; Common::Vec3f real_error;
Common::Vec<f32, 3> integral_error; Common::Vec3f integral_error;
Common::Vec<f32, 3> derivative_error; Common::Vec3f derivative_error;
// Quaternion containing the device orientation // Quaternion containing the device orientation
Common::Vec<f32, 4> quat; Common::Quaternion<f32> quat;
// Number of full rotations in each axis // Number of full rotations in each axis
Common::Vec<f32, 3> rotations; Common::Vec3f rotations;
// Acceleration vector measurement in G force // Acceleration vector measurement in G force
Common::Vec<f32, 3> accel; Common::Vec3f accel;
// Gyroscope vector measurement in radians/s. // Gyroscope vector measurement in radians/s.
Common::Vec<f32, 3> gyro; Common::Vec3f gyro;
// Vector to be subtracted from gyro measurements // Vector to be subtracted from gyro measurements
Common::Vec<f32, 3> gyro_bias; Common::Vec3f gyro_bias;
// Minimum gyro amplitude to detect if the device is moving // Minimum gyro amplitude to detect if the device is moving
f32 gyro_threshold = 0.0f; f32 gyro_threshold = 0.0f;
+4 -7
View File
@@ -1,6 +1,3 @@
// SPDX-FileCopyrightText: Copyright 2026 Eden Emulator Project
// SPDX-License-Identifier: GPL-3.0-or-later
// SPDX-FileCopyrightText: Copyright 2021 yuzu Emulator Project // SPDX-FileCopyrightText: Copyright 2021 yuzu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later // SPDX-License-Identifier: GPL-2.0-or-later
@@ -605,10 +602,10 @@ static_assert(sizeof(SixAxisSensorAttribute) == 4, "SixAxisSensorAttribute is an
struct SixAxisSensorState { struct SixAxisSensorState {
s64 delta_time{}; s64 delta_time{};
s64 sampling_number{}; s64 sampling_number{};
Common::Vec<f32, 3> accel{}; Common::Vec3f accel{};
Common::Vec<f32, 3> gyro{}; Common::Vec3f gyro{};
Common::Vec<f32, 3> rotation{}; Common::Vec3f rotation{};
std::array<Common::Vec<f32, 3>, 3> orientation{}; std::array<Common::Vec3f, 3> orientation{};
SixAxisSensorAttribute attribute{}; SixAxisSensorAttribute attribute{};
INSERT_PADDING_BYTES(4); // Reserved INSERT_PADDING_BYTES(4); // Reserved
}; };
@@ -1,4 +1,4 @@
// SPDX-FileCopyrightText: Copyright 2026 Eden Emulator Project // SPDX-FileCopyrightText: Copyright 2025 Eden Emulator Project
// SPDX-License-Identifier: GPL-3.0-or-later // SPDX-License-Identifier: GPL-3.0-or-later
// SPDX-FileCopyrightText: Copyright 2023 yuzu Emulator Project // SPDX-FileCopyrightText: Copyright 2023 yuzu Emulator Project
@@ -196,7 +196,7 @@ struct ConsoleSixAxisSensorSharedMemoryFormat {
bool is_seven_six_axis_sensor_at_rest{}; bool is_seven_six_axis_sensor_at_rest{};
INSERT_PADDING_BYTES(3); // padding INSERT_PADDING_BYTES(3); // padding
f32 verticalization_error{}; f32 verticalization_error{};
Common::Vec<f32, 3> gyro_bias{}; Common::Vec3f gyro_bias{};
INSERT_PADDING_BYTES(4); // padding INSERT_PADDING_BYTES(4); // padding
}; };
static_assert(sizeof(ConsoleSixAxisSensorSharedMemoryFormat) == 0x20, static_assert(sizeof(ConsoleSixAxisSensorSharedMemoryFormat) == 0x20,
@@ -46,11 +46,14 @@ void SevenSixAxis::OnUpdate(const Core::Timing::CoreTiming& core_timing) {
next_seven_sixaxis_state.accel = motion_status.accel; next_seven_sixaxis_state.accel = motion_status.accel;
next_seven_sixaxis_state.gyro = motion_status.gyro; next_seven_sixaxis_state.gyro = motion_status.gyro;
next_seven_sixaxis_state.quaternion = { next_seven_sixaxis_state.quaternion = {
motion_status.quaternion[1], {
motion_status.quaternion[0], motion_status.quaternion.xyz.y,
-motion_status.quaternion[3], motion_status.quaternion.xyz.x,
-motion_status.quaternion[2], -motion_status.quaternion.w,
},
-motion_status.quaternion.xyz.z,
}; };
seven_sixaxis_lifo.WriteNextEntry(next_seven_sixaxis_state); seven_sixaxis_lifo.WriteNextEntry(next_seven_sixaxis_state);
transfer_memory_owner->GetMemory().WriteBlock(transfer_memory, &seven_sixaxis_lifo, transfer_memory_owner->GetMemory().WriteBlock(transfer_memory, &seven_sixaxis_lifo,
sizeof(seven_sixaxis_lifo)); sizeof(seven_sixaxis_lifo));
@@ -7,7 +7,7 @@
#pragma once #pragma once
#include "common/common_types.h" #include "common/common_types.h"
#include "common/vector_math.h" #include "common/quaternion.h"
#include "common/typed_address.h" #include "common/typed_address.h"
#include "hid_core/resources/controller_base.h" #include "hid_core/resources/controller_base.h"
#include "hid_core/resources/ring_lifo.h" #include "hid_core/resources/ring_lifo.h"
@@ -51,9 +51,9 @@ private:
u64 timestamp{}; u64 timestamp{};
u64 sampling_number{}; u64 sampling_number{};
u64 unknown{}; u64 unknown{};
Common::Vec<f32, 3> accel{}; Common::Vec3f accel{};
Common::Vec<f32, 3> gyro{}; Common::Vec3f gyro{};
Common::Vec<f32, 4> quaternion{}; Common::Quaternion<f32> quaternion{};
}; };
static_assert(sizeof(SevenSixAxisState) == 0x48, "SevenSixAxisState is an invalid size"); static_assert(sizeof(SevenSixAxisState) == 0x48, "SevenSixAxisState is an invalid size");
+3 -6
View File
@@ -1,6 +1,3 @@
// SPDX-FileCopyrightText: Copyright 2026 Eden Emulator Project
// SPDX-License-Identifier: GPL-3.0-or-later
// SPDX-FileCopyrightText: Copyright 2023 yuzu Emulator Project // SPDX-FileCopyrightText: Copyright 2023 yuzu Emulator Project
// SPDX-License-Identifier: GPL-3.0-or-later // SPDX-License-Identifier: GPL-3.0-or-later
@@ -96,9 +93,9 @@ void SixAxis::OnUpdate(const Core::Timing::CoreTiming& core_timing) {
.accel = {0, 0, -1.0f}, .accel = {0, 0, -1.0f},
.orientation = .orientation =
{ {
Common::Vec<f32, 3>{1.0f, 0, 0}, Common::Vec3f{1.0f, 0, 0},
Common::Vec<f32, 3>{0, 1.0f, 0}, Common::Vec3f{0, 1.0f, 0},
Common::Vec<f32, 3>{0, 0, 1.0f}, Common::Vec3f{0, 0, 1.0f},
}, },
.attribute = {1}, .attribute = {1},
}; };
+43 -36
View File
@@ -88,8 +88,8 @@ void Mouse::UpdateStickInput() {
last_mouse_change *= maximum_stick_range; last_mouse_change *= maximum_stick_range;
} }
SetAxis(identifier, mouse_axis_x, last_mouse_change[0]); SetAxis(identifier, mouse_axis_x, last_mouse_change.x);
SetAxis(identifier, mouse_axis_y, -last_mouse_change[1]); SetAxis(identifier, mouse_axis_y, -last_mouse_change.y);
// Decay input over time // Decay input over time
const float clamped_length = (std::min)(1.0f, length); const float clamped_length = (std::min)(1.0f, length);
@@ -104,20 +104,20 @@ void Mouse::UpdateMotionInput() {
const float sensitivity = const float sensitivity =
IsMousePanningEnabled() ? default_motion_panning_sensitivity : default_motion_sensitivity; IsMousePanningEnabled() ? default_motion_panning_sensitivity : default_motion_sensitivity;
const float rotation_velocity = std::sqrt(last_motion_change[0] * last_motion_change[0] + const float rotation_velocity = std::sqrt(last_motion_change.x * last_motion_change.x +
last_motion_change[1] * last_motion_change[1]); last_motion_change.y * last_motion_change.y);
// Clamp rotation speed // Clamp rotation speed
if (rotation_velocity > maximum_rotation_speed / sensitivity) { if (rotation_velocity > maximum_rotation_speed / sensitivity) {
const float multiplier = maximum_rotation_speed / rotation_velocity / sensitivity; const float multiplier = maximum_rotation_speed / rotation_velocity / sensitivity;
last_motion_change[0] = last_motion_change[0] * multiplier; last_motion_change.x = last_motion_change.x * multiplier;
last_motion_change[1] = last_motion_change[1] * multiplier; last_motion_change.y = last_motion_change.y * multiplier;
} }
const BasicMotion motion_data{ const BasicMotion motion_data{
.gyro_x = last_motion_change[0] * sensitivity, .gyro_x = last_motion_change.x * sensitivity,
.gyro_y = last_motion_change[1] * sensitivity, .gyro_y = last_motion_change.y * sensitivity,
.gyro_z = last_motion_change[2] * sensitivity, .gyro_z = last_motion_change.z * sensitivity,
.accel_x = 0, .accel_x = 0,
.accel_y = 0, .accel_y = 0,
.accel_z = 0, .accel_z = 0,
@@ -125,46 +125,53 @@ void Mouse::UpdateMotionInput() {
}; };
if (IsMousePanningEnabled()) { if (IsMousePanningEnabled()) {
last_motion_change[0] = 0; last_motion_change.x = 0;
last_motion_change[1] = 0; last_motion_change.y = 0;
} }
last_motion_change[2] = 0; last_motion_change.z = 0;
SetMotion(motion_identifier, 0, motion_data); SetMotion(motion_identifier, 0, motion_data);
} }
void Mouse::Move(int x, int y, int center_x, int center_y) { void Mouse::Move(int x, int y, int center_x, int center_y) {
if (IsMousePanningEnabled()) { if (IsMousePanningEnabled()) {
auto const mouse_change_int = Common::Vec<int, 2>(x, y) - Common::Vec<int, 2>(center_x, center_y); const auto mouse_change =
auto const mouse_change = Common::Vec<float, 2>(float(mouse_change_int[0]), float(mouse_change_int[1])); (Common::MakeVec(x, y) - Common::MakeVec(center_x, center_y)).Cast<float>();
auto const x_sensitivity = Settings::values.mouse_panning_x_sensitivity.GetValue() * default_panning_sensitivity; const float x_sensitivity =
auto const y_sensitivity = Settings::values.mouse_panning_y_sensitivity.GetValue() * default_panning_sensitivity; Settings::values.mouse_panning_x_sensitivity.GetValue() * default_panning_sensitivity;
auto const deadzone_cw = Settings::values.mouse_panning_deadzone_counterweight.GetValue() * default_deadzone_counterweight; const float y_sensitivity =
last_motion_change += {-mouse_change[1] * x_sensitivity, -mouse_change[0] * y_sensitivity, 0}; Settings::values.mouse_panning_y_sensitivity.GetValue() * default_panning_sensitivity;
last_mouse_change[0] += mouse_change[0] * x_sensitivity; const float deadzone_counterweight =
last_mouse_change[1] += mouse_change[1] * y_sensitivity; Settings::values.mouse_panning_deadzone_counterweight.GetValue() *
// Bind the mouse change to [0 <= deadzone_cw <= 1.0] default_deadzone_counterweight;
last_motion_change += {-mouse_change.y * x_sensitivity, -mouse_change.x * y_sensitivity, 0};
last_mouse_change.x += mouse_change.x * x_sensitivity;
last_mouse_change.y += mouse_change.y * y_sensitivity;
// Bind the mouse change to [0 <= deadzone_counterweight <= 1.0]
const float length = last_mouse_change.Length(); const float length = last_mouse_change.Length();
if (length < deadzone_cw && length != 0.0f) { if (length < deadzone_counterweight && length != 0.0f) {
last_mouse_change /= length; last_mouse_change /= length;
last_mouse_change *= deadzone_cw; last_mouse_change *= deadzone_counterweight;
} }
return; return;
} }
if (button_pressed) { if (button_pressed) {
const auto mouse_move = Common::Vec<int, 2>(x, y) - mouse_origin; const auto mouse_move = Common::MakeVec<int>(x, y) - mouse_origin;
const float x_sensitivity = const float x_sensitivity =
Settings::values.mouse_panning_x_sensitivity.GetValue() * default_stick_sensitivity; Settings::values.mouse_panning_x_sensitivity.GetValue() * default_stick_sensitivity;
const float y_sensitivity = const float y_sensitivity =
Settings::values.mouse_panning_y_sensitivity.GetValue() * default_stick_sensitivity; Settings::values.mouse_panning_y_sensitivity.GetValue() * default_stick_sensitivity;
SetAxis(identifier, mouse_axis_x, float(mouse_move[0]) * x_sensitivity); SetAxis(identifier, mouse_axis_x, static_cast<float>(mouse_move.x) * x_sensitivity);
SetAxis(identifier, mouse_axis_y, float(-mouse_move[1]) * y_sensitivity); SetAxis(identifier, mouse_axis_y, static_cast<float>(-mouse_move.y) * y_sensitivity);
last_motion_change = { last_motion_change = {
float(-mouse_move[1]) * x_sensitivity, static_cast<float>(-mouse_move.y) * x_sensitivity,
float(-mouse_move[0]) * y_sensitivity, static_cast<float>(-mouse_move.x) * y_sensitivity,
last_motion_change[2], last_motion_change.z,
}; };
} }
} }
@@ -213,18 +220,18 @@ void Mouse::ReleaseButton(MouseButton button) {
SetAxis(identifier, mouse_axis_y, 0); SetAxis(identifier, mouse_axis_y, 0);
} }
last_motion_change[0] = 0; last_motion_change.x = 0;
last_motion_change[1] = 0; last_motion_change.y = 0;
button_pressed = false; button_pressed = false;
} }
void Mouse::MouseWheelChange(int x, int y) { void Mouse::MouseWheelChange(int x, int y) {
wheel_position[0] += x; wheel_position.x += x;
wheel_position[1] += y; wheel_position.y += y;
last_motion_change[2] += static_cast<f32>(y); last_motion_change.z += static_cast<f32>(y);
SetAxis(identifier, wheel_axis_x, static_cast<f32>(wheel_position[0])); SetAxis(identifier, wheel_axis_x, static_cast<f32>(wheel_position.x));
SetAxis(identifier, wheel_axis_y, static_cast<f32>(wheel_position[1])); SetAxis(identifier, wheel_axis_y, static_cast<f32>(wheel_position.y));
} }
void Mouse::ReleaseAllButtons() { void Mouse::ReleaseAllButtons() {
+5 -5
View File
@@ -107,11 +107,11 @@ private:
Common::Input::ButtonNames GetUIButtonName(const Common::ParamPackage& params) const; Common::Input::ButtonNames GetUIButtonName(const Common::ParamPackage& params) const;
Common::Vec<int, 2> mouse_origin; Common::Vec2<int> mouse_origin;
Common::Vec<int, 2> last_mouse_position; Common::Vec2<int> last_mouse_position;
Common::Vec<float, 2> last_mouse_change; Common::Vec2<float> last_mouse_change;
Common::Vec<float, 3> last_motion_change; Common::Vec3<float> last_motion_change;
Common::Vec<int, 2> wheel_position; Common::Vec2<int> wheel_position;
bool button_pressed = false; bool button_pressed = false;
}; };
-20
View File
@@ -20,8 +20,6 @@ namespace VideoCommon {
enum class BufferFlagBits { enum class BufferFlagBits {
Picked = 1 << 0, Picked = 1 << 0,
CachedWrites = 1 << 1,
PreemtiveDownload = 1 << 2,
}; };
DECLARE_ENUM_FLAG_OPERATORS(BufferFlagBits) DECLARE_ENUM_FLAG_OPERATORS(BufferFlagBits)
@@ -58,15 +56,6 @@ public:
flags |= BufferFlagBits::Picked; flags |= BufferFlagBits::Picked;
} }
void MarkPreemtiveDownload() noexcept {
flags |= BufferFlagBits::PreemtiveDownload;
}
/// Unmark buffer as picked
void Unpick() noexcept {
flags &= ~BufferFlagBits::Picked;
}
/// Increases the likeliness of this being a stream buffer /// Increases the likeliness of this being a stream buffer
void IncreaseStreamScore(int score) noexcept { void IncreaseStreamScore(int score) noexcept {
stream_score += score; stream_score += score;
@@ -87,15 +76,6 @@ public:
return True(flags & BufferFlagBits::Picked); return True(flags & BufferFlagBits::Picked);
} }
/// Returns true when the buffer has pending cached writes
[[nodiscard]] bool HasCachedWrites() const noexcept {
return True(flags & BufferFlagBits::CachedWrites);
}
bool IsPreemtiveDownload() const noexcept {
return True(flags & BufferFlagBits::PreemtiveDownload);
}
/// Returns the base CPU address of the buffer /// Returns the base CPU address of the buffer
[[nodiscard]] VAddr CpuAddr() const noexcept { [[nodiscard]] VAddr CpuAddr() const noexcept {
return cpu_addr; return cpu_addr;
+161 -46
View File
@@ -7,6 +7,7 @@
#pragma once #pragma once
#include <algorithm> #include <algorithm>
#include <limits>
#include <memory> #include <memory>
#include <numeric> #include <numeric>
@@ -121,25 +122,6 @@ void BufferCache<P>::WriteMemory(DAddr device_addr, u64 size) {
memory_tracker.MarkRegionAsCpuModified(device_addr, size); memory_tracker.MarkRegionAsCpuModified(device_addr, size);
} }
template <class P>
void BufferCache<P>::CachedWriteMemory(DAddr device_addr, u64 size) {
const bool is_dirty = IsRegionRegistered(device_addr, size);
if (!is_dirty) {
return;
}
DAddr aligned_start = Common::AlignDown(device_addr, DEVICE_PAGESIZE);
DAddr aligned_end = Common::AlignUp(device_addr + size, DEVICE_PAGESIZE);
if (!IsRegionGpuModified(aligned_start, aligned_end - aligned_start)) {
WriteMemory(device_addr, size);
return;
}
tmp_buffer.resize_destructive(size);
device_memory.ReadBlockUnsafe(device_addr, tmp_buffer.data(), size);
InlineMemoryImplementation(device_addr, size, tmp_buffer);
}
template <class P> template <class P>
bool BufferCache<P>::OnCPUWrite(DAddr device_addr, u64 size) { bool BufferCache<P>::OnCPUWrite(DAddr device_addr, u64 size) {
const bool is_dirty = IsRegionRegistered(device_addr, size); const bool is_dirty = IsRegionRegistered(device_addr, size);
@@ -422,7 +404,7 @@ void BufferCache<P>::UnbindGraphicsStorageBuffers(size_t stage) {
} }
template <class P> template <class P>
bool BufferCache<P>::BindGraphicsStorageBuffer(size_t stage, size_t ssbo_index, u32 cbuf_index, void BufferCache<P>::BindGraphicsStorageBuffer(size_t stage, size_t ssbo_index, u32 cbuf_index,
u32 cbuf_offset, bool is_written) { u32 cbuf_offset, bool is_written) {
const bool already_enabled = const bool already_enabled =
((channel_state->enabled_storage_buffers[stage] >> ssbo_index) & 1U) != 0; ((channel_state->enabled_storage_buffers[stage] >> ssbo_index) & 1U) != 0;
@@ -433,7 +415,7 @@ bool BufferCache<P>::BindGraphicsStorageBuffer(size_t stage, size_t ssbo_index,
LOG_WARNING(HW_GPU, LOG_WARNING(HW_GPU,
"Skipping graphics storage buffer {} due to driver limit {}", "Skipping graphics storage buffer {} due to driver limit {}",
ssbo_index, max_bindings); ssbo_index, max_bindings);
return false; return;
} }
} }
} }
@@ -449,7 +431,6 @@ bool BufferCache<P>::BindGraphicsStorageBuffer(size_t stage, size_t ssbo_index,
const GPUVAddr ssbo_addr = cbufs.const_buffers[cbuf_index].address + cbuf_offset; const GPUVAddr ssbo_addr = cbufs.const_buffers[cbuf_index].address + cbuf_offset;
channel_state->storage_buffers[stage][ssbo_index] = channel_state->storage_buffers[stage][ssbo_index] =
StorageBufferBinding(ssbo_addr, cbuf_index, is_written); StorageBufferBinding(ssbo_addr, cbuf_index, is_written);
return (channel_state->storage_buffers[stage][ssbo_index].buffer_id != NULL_BUFFER_ID);
} }
template <class P> template <class P>
@@ -762,16 +743,6 @@ void BufferCache<P>::BindHostIndexBuffer() {
} }
} }
template <class P>
void BufferCache<P>::BindHostVertexBuffer(u32 index, Buffer& buffer, u32 offset, u32 size,
u32 stride) {
if constexpr (IS_OPENGL) {
runtime.BindVertexBuffer(index, buffer, offset, size, stride);
} else {
runtime.BindVertexBuffer(index, buffer.Handle(), offset, size, stride);
}
}
template <class P> template <class P>
Binding& BufferCache<P>::VertexBufferSlot(u32 index) { Binding& BufferCache<P>::VertexBufferSlot(u32 index) {
ASSERT(index < NUM_VERTEX_BUFFERS); ASSERT(index < NUM_VERTEX_BUFFERS);
@@ -1197,7 +1168,7 @@ void BufferCache<P>::DoUpdateGraphicsBuffers(bool is_indexed) {
if (is_indexed) { if (is_indexed) {
UpdateIndexBuffer(); UpdateIndexBuffer();
} }
UpdateVertexBuffers(); UpdateVertexBuffers(is_indexed);
UpdateTransformFeedbackBuffers(); UpdateTransformFeedbackBuffers();
for (size_t stage = 0; stage < NUM_STAGES; ++stage) { for (size_t stage = 0; stage < NUM_STAGES; ++stage) {
UpdateUniformBuffers(stage); UpdateUniformBuffers(stage);
@@ -1251,9 +1222,14 @@ void BufferCache<P>::UpdateIndexBuffer() {
const GPUVAddr gpu_addr_begin = index_buffer_ref.StartAddress(); const GPUVAddr gpu_addr_begin = index_buffer_ref.StartAddress();
const GPUVAddr gpu_addr_end = index_buffer_ref.EndAddress(); const GPUVAddr gpu_addr_end = index_buffer_ref.EndAddress();
const std::optional<DAddr> device_addr = gpu_memory->GpuToCpuAddress(gpu_addr_begin); const std::optional<DAddr> device_addr = gpu_memory->GpuToCpuAddress(gpu_addr_begin);
const u32 address_size = static_cast<u32>(gpu_addr_end - gpu_addr_begin); u64 address_size = 0;
const u32 draw_size = (index_buffer_ref.count + index_buffer_ref.first) * u32(index_buffer_ref.FormatSizeInBytes()); if (gpu_addr_end > gpu_addr_begin) {
const u32 size = (std::min)(address_size, draw_size); address_size = (std::min)(gpu_addr_end - gpu_addr_begin,
u64{(std::numeric_limits<u32>::max)()});
}
const u64 draw_size = (u64{index_buffer_ref.count} + u64{index_buffer_ref.first}) *
u64{index_buffer_ref.FormatSizeInBytes()};
const u32 size = static_cast<u32>((std::min)(address_size, draw_size));
if (size == 0 || !device_addr) { if (size == 0 || !device_addr) {
channel_state->index_buffer = NULL_BINDING; channel_state->index_buffer = NULL_BINDING;
return; return;
@@ -1266,20 +1242,142 @@ void BufferCache<P>::UpdateIndexBuffer() {
} }
template <class P> template <class P>
void BufferCache<P>::UpdateVertexBuffers() { u64 BufferCache<P>::DrawMaxIndex() {
if (max_index_scanned) {
return cached_max_index;
}
max_index_scanned = true;
cached_max_index = 0;
const auto& index_buffer_ref = maxwell3d->draw_manager.draw_state.index_buffer;
const u32 count = index_buffer_ref.count;
if (count == 0) {
return 0;
}
index_scan_buffer.resize_destructive(count);
gpu_memory->ReadBlockUnsafe(index_buffer_ref.IndexStart(), index_scan_buffer.data(),
size_t{count} * sizeof(u32));
u32 restart_index = (std::numeric_limits<u32>::max)();
if (maxwell3d->regs.primitive_restart.enabled != 0) {
restart_index = maxwell3d->regs.primitive_restart.index;
}
u32 max_index = 0;
for (u32 i = 0; i < count; ++i) {
const u32 value = index_scan_buffer[i];
if (value == restart_index) {
continue;
}
max_index = (std::max)(max_index, value);
}
cached_max_index = max_index;
return cached_max_index;
}
template <class P>
u64 BufferCache<P>::StreamAttributeExtent(u32 index) {
using VertexAttribute = typename Maxwell::VertexAttribute;
if (stream_extents_valid) {
return stream_extents[index];
}
stream_extents_valid = true;
stream_extents.fill(0);
for (size_t i = 0; i < Maxwell::NumVertexAttributes; ++i) {
const auto& attribute = maxwell3d->regs.vertex_attrib_format[i];
if (attribute.constant != 0 || attribute.size == VertexAttribute::Size::Invalid) {
continue;
}
const u32 buffer = attribute.buffer.Value();
if (buffer >= NUM_VERTEX_BUFFERS) {
continue;
}
const u64 end = static_cast<u64>(attribute.offset.Value()) +
static_cast<u64>(attribute.SizeInBytes());
stream_extents[buffer] = (std::max)(stream_extents[buffer], end);
}
return stream_extents[index];
}
template <class P>
u64 BufferCache<P>::DrawVertexBound(u32 index, bool is_indexed) {
const auto& array = maxwell3d->regs.vertex_streams[index];
if (array.enable == 0) {
return 0;
}
const u64 extent = StreamAttributeExtent(index);
if (extent == 0) {
return 0;
}
const u64 stride = static_cast<u64>(array.stride);
if (stride == 0) {
return extent;
}
const auto& draw_state = maxwell3d->draw_manager.draw_state;
u64 elements = 0;
if (maxwell3d->regs.vertex_stream_instances.IsInstancingEnabled(index)) {
if (draw_instance_count == 0) {
return 0;
}
const u64 base_instance = static_cast<u64>(draw_state.base_instance);
elements = base_instance + 1;
if (array.frequency != 0) {
elements = (base_instance + static_cast<u64>(draw_instance_count) - 1) /
static_cast<u64>(array.frequency) +
1;
}
} else if (!is_indexed) {
elements = static_cast<u64>(draw_state.vertex_buffer.first) +
static_cast<u64>(draw_state.vertex_buffer.count);
} else {
const auto format = draw_state.index_buffer.format;
u64 max_index = 0xFF;
if (format == Maxwell::IndexFormat::UnsignedShort) {
max_index = 0xFFFF;
} else if (format != Maxwell::IndexFormat::UnsignedByte) {
const auto& limit = maxwell3d->regs.vertex_stream_limits[index];
const GPUVAddr gpu_addr_begin = array.Address();
const GPUVAddr gpu_addr_end = limit.Address() + 1;
if (gpu_addr_end <= gpu_addr_begin) {
return 0;
}
const bool walks = gpu_addr_end - gpu_addr_begin >= IMPLAUSIBLE_VERTEX_SIZE ||
!gpu_memory->IsWithinGPUAddressRange(gpu_addr_end);
if (!walks) {
return 0;
}
max_index = DrawMaxIndex();
}
elements = static_cast<u64>(draw_state.base_index) + max_index + 1;
}
if (elements == 0) {
return extent;
}
return (elements - 1) * stride + extent;
}
template <class P>
void BufferCache<P>::UpdateVertexBuffers(bool is_indexed) {
auto& flags = maxwell3d->dirty.flags; auto& flags = maxwell3d->dirty.flags;
max_index_scanned = false;
stream_extents_valid = false;
for (u32 index = 0; index < NUM_VERTEX_BUFFERS; ++index) {
const u64 bound = DrawVertexBound(index, is_indexed);
if (bound <= last_draw_bounds[index]) {
continue;
}
flags[Dirty::VertexBuffer0 + index] = true;
flags[Dirty::VertexBuffers] = true;
}
if (!maxwell3d->dirty.flags[Dirty::VertexBuffers]) { if (!maxwell3d->dirty.flags[Dirty::VertexBuffers]) {
return; return;
} }
flags[Dirty::VertexBuffers] = false; flags[Dirty::VertexBuffers] = false;
for (u32 index = 0; index < NUM_VERTEX_BUFFERS; ++index) { for (u32 index = 0; index < NUM_VERTEX_BUFFERS; ++index) {
UpdateVertexBuffer(index); UpdateVertexBuffer(index, is_indexed);
} }
} }
template <class P> template <class P>
void BufferCache<P>::UpdateVertexBuffer(u32 index) { void BufferCache<P>::UpdateVertexBuffer(u32 index, bool is_indexed) {
if (!maxwell3d->dirty.flags[Dirty::VertexBuffer0 + index]) { if (!maxwell3d->dirty.flags[Dirty::VertexBuffer0 + index]) {
return; return;
} }
@@ -1288,15 +1386,31 @@ void BufferCache<P>::UpdateVertexBuffer(u32 index) {
const GPUVAddr gpu_addr_begin = array.Address(); const GPUVAddr gpu_addr_begin = array.Address();
const GPUVAddr gpu_addr_end = limit.Address() + 1; const GPUVAddr gpu_addr_end = limit.Address() + 1;
const std::optional<DAddr> device_addr = gpu_memory->GpuToCpuAddress(gpu_addr_begin); const std::optional<DAddr> device_addr = gpu_memory->GpuToCpuAddress(gpu_addr_begin);
const u32 address_size = static_cast<u32>(gpu_addr_end - gpu_addr_begin); if (array.enable == 0 || !device_addr || gpu_addr_end <= gpu_addr_begin) {
u32 size = address_size; // TODO: Analyze stride and number of vertices
if (array.enable == 0 || size == 0 || !device_addr) {
channel_state->vertex_buffers[index] = NULL_BINDING; channel_state->vertex_buffers[index] = NULL_BINDING;
UpdateVertexBufferSlot(index, NULL_BINDING); UpdateVertexBufferSlot(index, NULL_BINDING);
return; return;
} }
if (!gpu_memory->IsWithinGPUAddressRange(gpu_addr_end) || size >= 64_MiB) { // TODO: Analyze stride and number of vertices
size = static_cast<u32>(gpu_memory->MaxContinuousRange(gpu_addr_begin, size)); constexpr u64 implausible_size = IMPLAUSIBLE_VERTEX_SIZE;
u64 address_size = gpu_addr_end - gpu_addr_begin;
if (address_size > u64{(std::numeric_limits<u32>::max)()}) {
address_size = implausible_size;
}
const u64 draw_bound = DrawVertexBound(index, is_indexed);
last_draw_bounds[index] = (std::numeric_limits<u64>::max)();
if (draw_bound != 0) {
last_draw_bounds[index] = draw_bound;
address_size = (std::min)(address_size, draw_bound);
}
if (!gpu_memory->IsWithinGPUAddressRange(gpu_addr_end) || address_size >= implausible_size) {
address_size = gpu_memory->MaxContinuousRange(gpu_addr_begin, address_size);
}
const u32 size = static_cast<u32>(address_size);
if (size == 0) {
channel_state->vertex_buffers[index] = NULL_BINDING;
UpdateVertexBufferSlot(index, NULL_BINDING);
return;
} }
const BufferId buffer_id = FindBuffer(*device_addr, size); const BufferId buffer_id = FindBuffer(*device_addr, size);
const Binding binding{ const Binding binding{
@@ -1578,9 +1692,10 @@ template <class P>
BufferId BufferCache<P>::CreateBuffer(DAddr device_addr, u32 wanted_size) { BufferId BufferCache<P>::CreateBuffer(DAddr device_addr, u32 wanted_size) {
DAddr device_addr_end = Common::AlignUp(device_addr + wanted_size, CACHING_PAGESIZE); DAddr device_addr_end = Common::AlignUp(device_addr + wanted_size, CACHING_PAGESIZE);
device_addr = Common::AlignDown(device_addr, CACHING_PAGESIZE); device_addr = Common::AlignDown(device_addr, CACHING_PAGESIZE);
wanted_size = static_cast<u32>(device_addr_end - device_addr); constexpr u64 max_buffer_size = u64{(std::numeric_limits<u32>::max)()};
wanted_size = static_cast<u32>((std::min)(device_addr_end - device_addr, max_buffer_size));
const OverlapResult overlap = ResolveOverlaps(device_addr, wanted_size); const OverlapResult overlap = ResolveOverlaps(device_addr, wanted_size);
const u32 size = static_cast<u32>(overlap.end - overlap.begin); const u32 size = static_cast<u32>((std::min)(overlap.end - overlap.begin, max_buffer_size));
const BufferId new_buffer_id = slot_buffers.insert(runtime, overlap.begin, size); const BufferId new_buffer_id = slot_buffers.insert(runtime, overlap.begin, size);
auto& new_buffer = slot_buffers[new_buffer_id]; auto& new_buffer = slot_buffers[new_buffer_id];
const size_t size_bytes = new_buffer.SizeBytes(); const size_t size_bytes = new_buffer.SizeBytes();
@@ -51,6 +51,7 @@ constexpr u32 NUM_VERTEX_BUFFERS = 16;
#else #else
constexpr u32 NUM_VERTEX_BUFFERS = 32; constexpr u32 NUM_VERTEX_BUFFERS = 32;
#endif #endif
constexpr u64 IMPLAUSIBLE_VERTEX_SIZE = 64_MiB;
constexpr u32 NUM_TRANSFORM_FEEDBACK_BUFFERS = 4; constexpr u32 NUM_TRANSFORM_FEEDBACK_BUFFERS = 4;
constexpr u32 NUM_GRAPHICS_UNIFORM_BUFFERS = 18; constexpr u32 NUM_GRAPHICS_UNIFORM_BUFFERS = 18;
constexpr u32 NUM_COMPUTE_UNIFORM_BUFFERS = 8; constexpr u32 NUM_COMPUTE_UNIFORM_BUFFERS = 8;
@@ -217,8 +218,6 @@ public:
void WriteMemory(DAddr device_addr, u64 size); void WriteMemory(DAddr device_addr, u64 size);
void CachedWriteMemory(DAddr device_addr, u64 size);
bool OnCPUWrite(DAddr device_addr, u64 size); bool OnCPUWrite(DAddr device_addr, u64 size);
void DownloadMemory(DAddr device_addr, u64 size); void DownloadMemory(DAddr device_addr, u64 size);
@@ -248,7 +247,7 @@ public:
void UnbindGraphicsStorageBuffers(size_t stage); void UnbindGraphicsStorageBuffers(size_t stage);
bool BindGraphicsStorageBuffer(size_t stage, size_t ssbo_index, u32 cbuf_index, u32 cbuf_offset, void BindGraphicsStorageBuffer(size_t stage, size_t ssbo_index, u32 cbuf_index, u32 cbuf_offset,
bool is_written); bool is_written);
void UnbindGraphicsTextureBuffers(size_t stage); void UnbindGraphicsTextureBuffers(size_t stage);
@@ -309,6 +308,10 @@ public:
current_draw_indirect = current_draw_indirect_; current_draw_indirect = current_draw_indirect_;
} }
void SetDrawInstanceCount(u32 draw_instance_count_) {
draw_instance_count = draw_instance_count_;
}
[[nodiscard]] std::pair<Buffer*, u32> GetDrawIndirectCount(); [[nodiscard]] std::pair<Buffer*, u32> GetDrawIndirectCount();
[[nodiscard]] std::pair<Buffer*, u32> GetDrawIndirectBuffer(); [[nodiscard]] std::pair<Buffer*, u32> GetDrawIndirectBuffer();
@@ -376,8 +379,6 @@ private:
void BindHostTransformFeedbackBuffers(); void BindHostTransformFeedbackBuffers();
void BindHostVertexBuffer(u32 index, Buffer& buffer, u32 offset, u32 size, u32 stride);
void BindHostComputeUniformBuffers(); void BindHostComputeUniformBuffers();
void BindHostComputeStorageBuffers(); void BindHostComputeStorageBuffers();
@@ -390,9 +391,15 @@ private:
void UpdateIndexBuffer(); void UpdateIndexBuffer();
void UpdateVertexBuffers(); void UpdateVertexBuffers(bool is_indexed);
void UpdateVertexBuffer(u32 index); void UpdateVertexBuffer(u32 index, bool is_indexed);
[[nodiscard]] u64 DrawVertexBound(u32 index, bool is_indexed);
[[nodiscard]] u64 DrawMaxIndex();
[[nodiscard]] u64 StreamAttributeExtent(u32 index);
void UpdateDrawIndirect(); void UpdateDrawIndirect();
@@ -484,6 +491,14 @@ private:
const Tegra::Engines::Maxwell3D::DrawManager::IndirectParams* current_draw_indirect{}; const Tegra::Engines::Maxwell3D::DrawManager::IndirectParams* current_draw_indirect{};
u32 draw_instance_count = 0;
std::array<u64, NUM_VERTEX_BUFFERS> last_draw_bounds{};
Common::ScratchBuffer<u32> index_scan_buffer;
u64 cached_max_index = 0;
bool max_index_scanned = false;
std::array<u64, NUM_VERTEX_BUFFERS> stream_extents{};
bool stream_extents_valid = false;
u32 last_index_count = 0; u32 last_index_count = 0;
u32 enabled_vertex_buffers_mask = 0; u32 enabled_vertex_buffers_mask = 0;
@@ -206,6 +206,40 @@ foreach(VARIANT IN ITEMS ${SHADER_TYPE_VARIANTS})
set(SHADER_HEADERS ${SHADER_HEADERS} ${VARIANT_HEADER_FILE}) set(SHADER_HEADERS ${SHADER_HEADERS} ${VARIANT_HEADER_FILE})
endforeach() endforeach()
set(SHADER_DEFINE_VARIANTS
"block_linear_unswizzle_2d.comp|nonarrow|HAS_EXTENDED_TYPES=0"
"pitch_unswizzle.comp|nonarrow|HAS_EXTENDED_TYPES=0"
"block_linear_unswizzle_3d.comp|nonarrow|HAS_EXTENDED_TYPES=0"
)
foreach(VARIANT IN ITEMS ${SHADER_DEFINE_VARIANTS})
string(REPLACE "|" ";" VARIANT_PARTS ${VARIANT})
list(GET VARIANT_PARTS 0 VARIANT_FILENAME)
list(GET VARIANT_PARTS 1 VARIANT_SUFFIX)
list(GET VARIANT_PARTS 2 VARIANT_DEFINE)
set(VARIANT_SOURCE ${CMAKE_CURRENT_SOURCE_DIR}/${VARIANT_FILENAME})
get_filename_component(VARIANT_STEM ${VARIANT_FILENAME} NAME_WE)
get_filename_component(VARIANT_EXT ${VARIANT_FILENAME} EXT)
string(REPLACE "." "" VARIANT_EXT ${VARIANT_EXT})
set(VARIANT_NAME ${VARIANT_STEM}_${VARIANT_SUFFIX}_${VARIANT_EXT})
string(TOUPPER ${VARIANT_NAME}_SPV VARIANT_VARIABLE_NAME)
set(VARIANT_HEADER_FILE ${SHADER_DIR}/${VARIANT_NAME}_spv.h)
add_custom_command(
OUTPUT
${VARIANT_HEADER_FILE}
COMMAND
${GLSLANGVALIDATOR} -V ${QUIET_FLAG} -I"${FIDELITYFX_INCLUDE_DIR}" ${GLSL_FLAGS}
-D${VARIANT_DEFINE}
--variable-name ${VARIANT_VARIABLE_NAME} -o ${VARIANT_HEADER_FILE} ${VARIANT_SOURCE}
--target-env ${SPIR_V_VERSION}
MAIN_DEPENDENCY
${VARIANT_SOURCE}
)
set(SHADER_HEADERS ${SHADER_HEADERS} ${VARIANT_HEADER_FILE})
endforeach()
foreach(FILEPATH IN ITEMS ${FIDELITYFX_FILES}) foreach(FILEPATH IN ITEMS ${FIDELITYFX_FILES})
get_filename_component(FILENAME ${FILEPATH} NAME) get_filename_component(FILENAME ${FILEPATH} NAME)
string(REPLACE "." "_" HEADER_NAME ${FILENAME}) string(REPLACE "." "_" HEADER_NAME ${FILENAME})
@@ -5,9 +5,13 @@
#ifdef VULKAN #ifdef VULKAN
#ifndef HAS_EXTENDED_TYPES
#define HAS_EXTENDED_TYPES 1
#endif
#if HAS_EXTENDED_TYPES
#extension GL_EXT_shader_16bit_storage : require #extension GL_EXT_shader_16bit_storage : require
#extension GL_EXT_shader_8bit_storage : require #extension GL_EXT_shader_8bit_storage : require
#define HAS_EXTENDED_TYPES 1 #endif
#define BEGIN_PUSH_CONSTANTS layout(push_constant) uniform PushConstants { #define BEGIN_PUSH_CONSTANTS layout(push_constant) uniform PushConstants {
#define END_PUSH_CONSTANTS }; #define END_PUSH_CONSTANTS };
#define UNIFORM(n) #define UNIFORM(n)
@@ -5,9 +5,13 @@
#ifdef VULKAN #ifdef VULKAN
#ifndef HAS_EXTENDED_TYPES
#define HAS_EXTENDED_TYPES 1
#endif
#if HAS_EXTENDED_TYPES
#extension GL_EXT_shader_16bit_storage : require #extension GL_EXT_shader_16bit_storage : require
#extension GL_EXT_shader_8bit_storage : require #extension GL_EXT_shader_8bit_storage : require
#define HAS_EXTENDED_TYPES 1 #endif
#define BEGIN_PUSH_CONSTANTS layout(push_constant) uniform PushConstants { #define BEGIN_PUSH_CONSTANTS layout(push_constant) uniform PushConstants {
#define END_PUSH_CONSTANTS }; #define END_PUSH_CONSTANTS };
#define UNIFORM(n) #define UNIFORM(n)
@@ -5,9 +5,13 @@
#ifdef VULKAN #ifdef VULKAN
#ifndef HAS_EXTENDED_TYPES
#define HAS_EXTENDED_TYPES 1
#endif
#if HAS_EXTENDED_TYPES
#extension GL_EXT_shader_16bit_storage : require #extension GL_EXT_shader_16bit_storage : require
#extension GL_EXT_shader_8bit_storage : require #extension GL_EXT_shader_8bit_storage : require
#define HAS_EXTENDED_TYPES 1 #endif
#define BEGIN_PUSH_CONSTANTS layout(push_constant) uniform PushConstants { #define BEGIN_PUSH_CONSTANTS layout(push_constant) uniform PushConstants {
#define END_PUSH_CONSTANTS }; #define END_PUSH_CONSTANTS };
#define UNIFORM(n) #define UNIFORM(n)
@@ -226,22 +226,6 @@ void BufferCacheRuntime::BindIndexBuffer(Buffer& buffer, u32 offset, u32 size) {
} }
} }
void BufferCacheRuntime::BindVertexBuffer(u32 index, Buffer& buffer, u32 offset, u32 size,
u32 stride) {
if (index >= max_attributes) {
return;
}
if (has_unified_vertex_buffers) {
buffer.MakeResident(GL_READ_ONLY);
glBindVertexBuffer(index, 0, 0, static_cast<GLsizei>(stride));
glBufferAddressRangeNV(GL_VERTEX_ATTRIB_ARRAY_ADDRESS_NV, index,
buffer.HostGpuAddr() + offset, static_cast<GLsizeiptr>(size));
} else {
glBindVertexBuffer(index, buffer.Handle(), static_cast<GLintptr>(offset),
static_cast<GLsizei>(stride));
}
}
void BufferCacheRuntime::BindVertexBuffers(VideoCommon::HostBindings<Buffer>& bindings) { void BufferCacheRuntime::BindVertexBuffers(VideoCommon::HostBindings<Buffer>& bindings) {
// TODO: Should HostBindings provide the correct runtime types to avoid these transforms? // TODO: Should HostBindings provide the correct runtime types to avoid these transforms?
std::array<GLuint, 32> buffer_handles; std::array<GLuint, 32> buffer_handles;
@@ -99,8 +99,6 @@ public:
void BindIndexBuffer(Buffer& buffer, u32 offset, u32 size); void BindIndexBuffer(Buffer& buffer, u32 offset, u32 size);
void BindVertexBuffer(u32 index, Buffer& buffer, u32 offset, u32 size, u32 stride);
void BindVertexBuffers(VideoCommon::HostBindings<Buffer>& bindings); void BindVertexBuffers(VideoCommon::HostBindings<Buffer>& bindings);
void BindUniformBuffer(size_t stage, u32 binding_index, Buffer& buffer, u32 offset, u32 size); void BindUniformBuffer(size_t stage, u32 binding_index, Buffer& buffer, u32 offset, u32 size);
@@ -259,6 +259,7 @@ void RasterizerOpenGL::PrepareDraw(bool is_indexed, Func&& draw_func) {
} }
void RasterizerOpenGL::Draw(bool is_indexed, u32 instance_count) { void RasterizerOpenGL::Draw(bool is_indexed, u32 instance_count) {
buffer_cache.SetDrawInstanceCount(instance_count);
PrepareDraw(is_indexed, [this, is_indexed, instance_count](GLenum primitive_mode) { PrepareDraw(is_indexed, [this, is_indexed, instance_count](GLenum primitive_mode) {
const auto& draw_state = maxwell3d->draw_manager.draw_state; const auto& draw_state = maxwell3d->draw_manager.draw_state;
const GLuint base_instance = GLuint(draw_state.base_instance); const GLuint base_instance = GLuint(draw_state.base_instance);
@@ -304,6 +305,7 @@ void RasterizerOpenGL::Draw(bool is_indexed, u32 instance_count) {
void RasterizerOpenGL::DrawIndirect() { void RasterizerOpenGL::DrawIndirect() {
const auto& params = maxwell3d->draw_manager.indirect_state; const auto& params = maxwell3d->draw_manager.indirect_state;
buffer_cache.SetDrawIndirect(&params); buffer_cache.SetDrawIndirect(&params);
buffer_cache.SetDrawInstanceCount(0);
PrepareDraw(params.is_indexed, [this, &params](GLenum primitive_mode) { PrepareDraw(params.is_indexed, [this, &params](GLenum primitive_mode) {
if (params.is_byte_count) { if (params.is_byte_count) {
const GPUVAddr tfb_object_base_addr = params.indirect_start_address - 4U; const GPUVAddr tfb_object_base_addr = params.indirect_start_address - 4U;
@@ -585,29 +585,6 @@ void BufferCacheRuntime::BindQuadIndexBuffer(PrimitiveTopology topology, u32 fir
} }
} }
void BufferCacheRuntime::BindVertexBuffer(u32 index, VkBuffer buffer, u32 offset, u32 size, u32 stride) {
if (index >= device.GetMaxVertexInputBindings()) {
return;
}
if (device.IsExtExtendedDynamicStateSupported()) {
scheduler.Record([index, buffer, offset, size, stride](vk::CommandBuffer cmdbuf) {
const VkDeviceSize vk_offset = buffer != VK_NULL_HANDLE ? offset : 0;
const VkDeviceSize vk_size = buffer != VK_NULL_HANDLE ? size : VK_WHOLE_SIZE;
const VkDeviceSize vk_stride = stride;
cmdbuf.BindVertexBuffers2EXT(index, 1, &buffer, &vk_offset, &vk_size, &vk_stride);
});
} else {
if (!device.HasNullDescriptor() && buffer == VK_NULL_HANDLE) {
ReserveNullBuffer();
buffer = *null_buffer;
offset = 0;
}
scheduler.Record([index, buffer, offset](vk::CommandBuffer cmdbuf) {
cmdbuf.BindVertexBuffer(index, buffer, offset);
});
}
}
void BufferCacheRuntime::BindVertexBuffers(VideoCommon::HostBindings<Buffer>& bindings) { void BufferCacheRuntime::BindVertexBuffers(VideoCommon::HostBindings<Buffer>& bindings) {
boost::container::static_vector<VkBuffer, VideoCommon::NUM_VERTEX_BUFFERS> buffer_handles(bindings.buffers.size()); boost::container::static_vector<VkBuffer, VideoCommon::NUM_VERTEX_BUFFERS> buffer_handles(bindings.buffers.size());
for (u32 i = 0; i < bindings.buffers.size(); ++i) { for (u32 i = 0; i < bindings.buffers.size(); ++i) {
@@ -138,8 +138,6 @@ public:
void BindQuadIndexBuffer(PrimitiveTopology topology, u32 first, u32 count); void BindQuadIndexBuffer(PrimitiveTopology topology, u32 first, u32 count);
void BindVertexBuffer(u32 index, VkBuffer buffer, u32 offset, u32 size, u32 stride);
void BindVertexBuffers(VideoCommon::HostBindings<Buffer>& bindings); void BindVertexBuffers(VideoCommon::HostBindings<Buffer>& bindings);
void BindTransformFeedbackBuffer(u32 index, VkBuffer buffer, u32 offset, u32 size); void BindTransformFeedbackBuffer(u32 index, VkBuffer buffer, u32 offset, u32 size);
@@ -22,7 +22,13 @@
#include "video_core/host_shaders/resolve_conditional_render_comp_spv.h" #include "video_core/host_shaders/resolve_conditional_render_comp_spv.h"
#include "video_core/host_shaders/vulkan_quad_indexed_comp_spv.h" #include "video_core/host_shaders/vulkan_quad_indexed_comp_spv.h"
#include "video_core/host_shaders/vulkan_uint8_comp_spv.h" #include "video_core/host_shaders/vulkan_uint8_comp_spv.h"
#include "video_core/host_shaders/block_linear_unswizzle_2d_comp_spv.h"
#include "video_core/host_shaders/block_linear_unswizzle_2d_nonarrow_comp_spv.h"
#include "video_core/host_shaders/block_linear_unswizzle_3d_bcn_comp_spv.h" #include "video_core/host_shaders/block_linear_unswizzle_3d_bcn_comp_spv.h"
#include "video_core/host_shaders/block_linear_unswizzle_3d_comp_spv.h"
#include "video_core/host_shaders/block_linear_unswizzle_3d_nonarrow_comp_spv.h"
#include "video_core/host_shaders/pitch_unswizzle_comp_spv.h"
#include "video_core/host_shaders/pitch_unswizzle_nonarrow_comp_spv.h"
#include "video_core/renderer_vulkan/vk_compute_pass.h" #include "video_core/renderer_vulkan/vk_compute_pass.h"
#include "video_core/surface.h" #include "video_core/surface.h"
#include "video_core/renderer_vulkan/vk_descriptor_pool.h" #include "video_core/renderer_vulkan/vk_descriptor_pool.h"
@@ -872,4 +878,291 @@ void BlockLinearUnswizzle3DPass::UnswizzleChunk(
}); });
} }
namespace {
constexpr u32 UNSWIZZLE_BINDING_INPUT_BUFFER = 0;
constexpr u32 UNSWIZZLE_BINDING_OUTPUT_IMAGE = 1;
constexpr size_t UNSWIZZLE_NUM_BINDINGS = 2;
constexpr std::array<VkDescriptorSetLayoutBinding, UNSWIZZLE_NUM_BINDINGS>
UNSWIZZLE_DESCRIPTOR_SET_BINDINGS{{
{
.binding = UNSWIZZLE_BINDING_INPUT_BUFFER,
.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER,
.descriptorCount = 1,
.stageFlags = VK_SHADER_STAGE_COMPUTE_BIT,
.pImmutableSamplers = nullptr,
},
{
.binding = UNSWIZZLE_BINDING_OUTPUT_IMAGE,
.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_IMAGE,
.descriptorCount = 1,
.stageFlags = VK_SHADER_STAGE_COMPUTE_BIT,
.pImmutableSamplers = nullptr,
},
}};
constexpr std::array<VkDescriptorUpdateTemplateEntry, UNSWIZZLE_NUM_BINDINGS>
UNSWIZZLE_DESCRIPTOR_UPDATE_TEMPLATE{{
{
.dstBinding = UNSWIZZLE_BINDING_INPUT_BUFFER,
.dstArrayElement = 0,
.descriptorCount = 1,
.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER,
.offset = UNSWIZZLE_BINDING_INPUT_BUFFER * sizeof(DescriptorUpdateEntry),
.stride = sizeof(DescriptorUpdateEntry),
},
{
.dstBinding = UNSWIZZLE_BINDING_OUTPUT_IMAGE,
.dstArrayElement = 0,
.descriptorCount = 1,
.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_IMAGE,
.offset = UNSWIZZLE_BINDING_OUTPUT_IMAGE * sizeof(DescriptorUpdateEntry),
.stride = sizeof(DescriptorUpdateEntry),
},
}};
constexpr DescriptorBankInfo UNSWIZZLE_BANK_INFO{
.uniform_buffers = 0,
.storage_buffers = 1,
.texture_buffers = 0,
.image_buffers = 0,
.textures = 0,
.images = 1,
.score = 2,
};
[[nodiscard]] std::span<const u32> UnswizzleSpv(const Device& device,
std::span<const u32> extended,
std::span<const u32> narrow) {
if (device.IsStorageBuffer8BitAccessSupported() &&
device.IsStorageBuffer16BitAccessSupported()) {
return extended;
}
return narrow;
}
struct PitchUnswizzlePushConstants {
alignas(8) std::array<u32, 2> origin;
alignas(8) std::array<s32, 2> destination;
u32 bytes_per_block;
u32 pitch;
};
void RecordUnswizzleEntryBarrier(Scheduler& scheduler, VkPipeline vk_pipeline, VkImage vk_image,
VkImageAspectFlags aspect_mask, bool is_initialized) {
scheduler.Record([vk_pipeline, vk_image, aspect_mask,
is_initialized](vk::CommandBuffer cmdbuf) {
VkAccessFlags src_access = VK_ACCESS_NONE;
VkImageLayout old_layout = VK_IMAGE_LAYOUT_UNDEFINED;
if (is_initialized) {
src_access = VK_ACCESS_SHADER_WRITE_BIT | VK_ACCESS_TRANSFER_WRITE_BIT |
VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;
old_layout = VK_IMAGE_LAYOUT_GENERAL;
}
const VkImageMemoryBarrier image_barrier{
.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER,
.pNext = nullptr,
.srcAccessMask = src_access,
.dstAccessMask = VK_ACCESS_SHADER_WRITE_BIT,
.oldLayout = old_layout,
.newLayout = VK_IMAGE_LAYOUT_GENERAL,
.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
.image = vk_image,
.subresourceRange{
.aspectMask = aspect_mask,
.baseMipLevel = 0,
.levelCount = VK_REMAINING_MIP_LEVELS,
.baseArrayLayer = 0,
.layerCount = VK_REMAINING_ARRAY_LAYERS,
},
};
VkPipelineStageFlags src_stage = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT;
if (is_initialized) {
src_stage = vk::PIPELINE_STAGE_GRAPHICS_COMPUTE_TRANSFER;
}
cmdbuf.PipelineBarrier(src_stage, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, image_barrier);
cmdbuf.BindPipeline(VK_PIPELINE_BIND_POINT_COMPUTE, vk_pipeline);
});
}
void RecordUnswizzleExitBarrier(Scheduler& scheduler, VkImage vk_image,
VkImageAspectFlags aspect_mask) {
scheduler.Record([vk_image, aspect_mask](vk::CommandBuffer cmdbuf) {
const VkImageMemoryBarrier image_barrier{
.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER,
.pNext = nullptr,
.srcAccessMask = VK_ACCESS_SHADER_WRITE_BIT,
.dstAccessMask = VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_TRANSFER_READ_BIT |
VK_ACCESS_COLOR_ATTACHMENT_READ_BIT,
.oldLayout = VK_IMAGE_LAYOUT_GENERAL,
.newLayout = VK_IMAGE_LAYOUT_GENERAL,
.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
.image = vk_image,
.subresourceRange{
.aspectMask = aspect_mask,
.baseMipLevel = 0,
.levelCount = VK_REMAINING_MIP_LEVELS,
.baseArrayLayer = 0,
.layerCount = VK_REMAINING_ARRAY_LAYERS,
},
};
cmdbuf.PipelineBarrier(VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT,
vk::PIPELINE_STAGE_GRAPHICS_COMPUTE_TRANSFER, 0, image_barrier);
});
}
} // Anonymous namespace
BlockLinearUnswizzle2DPass::BlockLinearUnswizzle2DPass(
const Device& device_, Scheduler& scheduler_, DescriptorPool& descriptor_pool_,
ComputePassDescriptorQueue& compute_pass_descriptor_queue_)
: ComputePass(device_, scheduler_, descriptor_pool_, UNSWIZZLE_DESCRIPTOR_SET_BINDINGS,
UNSWIZZLE_DESCRIPTOR_UPDATE_TEMPLATE, UNSWIZZLE_BANK_INFO,
COMPUTE_PUSH_CONSTANT_RANGE<sizeof(
VideoCommon::Accelerated::BlockLinearSwizzle2DParams)>,
UnswizzleSpv(device_, BLOCK_LINEAR_UNSWIZZLE_2D_COMP_SPV,
BLOCK_LINEAR_UNSWIZZLE_2D_NONARROW_COMP_SPV)),
scheduler{scheduler_}, compute_pass_descriptor_queue{compute_pass_descriptor_queue_} {}
BlockLinearUnswizzle2DPass::~BlockLinearUnswizzle2DPass() = default;
void BlockLinearUnswizzle2DPass::Unswizzle(
Image& image, const StagingBufferRef& map,
std::span<const VideoCommon::SwizzleParameters> swizzles) {
using namespace VideoCommon::Accelerated;
scheduler.RequestOutsideRenderPassOperationContext();
const VkPipeline vk_pipeline = *pipeline;
const VkImageAspectFlags aspect_mask = image.AspectMask();
const VkImage vk_image = image.Handle();
const bool is_initialized = image.ExchangeInitialization();
RecordUnswizzleEntryBarrier(scheduler, vk_pipeline, vk_image, aspect_mask, is_initialized);
const u32 num_layers = static_cast<u32>(image.info.resources.layers);
for (const VideoCommon::SwizzleParameters& swizzle : swizzles) {
const size_t input_offset = swizzle.buffer_offset + map.offset;
const u32 num_dispatches_x = Common::DivCeil(swizzle.num_tiles.width, 32U);
const u32 num_dispatches_y = Common::DivCeil(swizzle.num_tiles.height, 32U);
compute_pass_descriptor_queue.Acquire(scheduler, 2);
compute_pass_descriptor_queue.AddBuffer(map.buffer, input_offset,
image.guest_size_bytes - swizzle.buffer_offset);
compute_pass_descriptor_queue.AddImage(image.StorageImageView(swizzle.level));
const void* const descriptor_data{compute_pass_descriptor_queue.UpdateData()};
const auto params = MakeBlockLinearSwizzle2DParams(swizzle, image.info);
scheduler.Record([this, num_dispatches_x, num_dispatches_y, num_layers, params,
descriptor_data](vk::CommandBuffer cmdbuf) {
const VkDescriptorSet set = descriptor_allocator.Commit();
device.GetLogical().UpdateDescriptorSet(set, *descriptor_template, descriptor_data);
cmdbuf.BindDescriptorSets(VK_PIPELINE_BIND_POINT_COMPUTE, *layout, 0, set, {});
cmdbuf.PushConstants(*layout, VK_SHADER_STAGE_COMPUTE_BIT, params);
cmdbuf.Dispatch(num_dispatches_x, num_dispatches_y, num_layers);
});
}
RecordUnswizzleExitBarrier(scheduler, vk_image, aspect_mask);
}
BlockLinearUnswizzleImage3DPass::BlockLinearUnswizzleImage3DPass(
const Device& device_, Scheduler& scheduler_, DescriptorPool& descriptor_pool_,
ComputePassDescriptorQueue& compute_pass_descriptor_queue_)
: ComputePass(device_, scheduler_, descriptor_pool_, UNSWIZZLE_DESCRIPTOR_SET_BINDINGS,
UNSWIZZLE_DESCRIPTOR_UPDATE_TEMPLATE, UNSWIZZLE_BANK_INFO,
COMPUTE_PUSH_CONSTANT_RANGE<sizeof(BlockLinearSwizzle3DParams)>,
UnswizzleSpv(device_, BLOCK_LINEAR_UNSWIZZLE_3D_COMP_SPV,
BLOCK_LINEAR_UNSWIZZLE_3D_NONARROW_COMP_SPV)),
scheduler{scheduler_}, compute_pass_descriptor_queue{compute_pass_descriptor_queue_} {}
BlockLinearUnswizzleImage3DPass::~BlockLinearUnswizzleImage3DPass() = default;
void BlockLinearUnswizzleImage3DPass::Unswizzle(
Image& image, const StagingBufferRef& map,
std::span<const VideoCommon::SwizzleParameters> swizzles) {
using namespace VideoCommon::Accelerated;
scheduler.RequestOutsideRenderPassOperationContext();
const VkPipeline vk_pipeline = *pipeline;
const VkImageAspectFlags aspect_mask = image.AspectMask();
const VkImage vk_image = image.Handle();
const bool is_initialized = image.ExchangeInitialization();
RecordUnswizzleEntryBarrier(scheduler, vk_pipeline, vk_image, aspect_mask, is_initialized);
for (const VideoCommon::SwizzleParameters& swizzle : swizzles) {
const size_t input_offset = swizzle.buffer_offset + map.offset;
const u32 num_dispatches_x = Common::DivCeil(swizzle.num_tiles.width, 16U);
const u32 num_dispatches_y = Common::DivCeil(swizzle.num_tiles.height, 8U);
const u32 num_dispatches_z = Common::DivCeil(swizzle.num_tiles.depth, 8U);
compute_pass_descriptor_queue.Acquire(scheduler, 2);
compute_pass_descriptor_queue.AddBuffer(map.buffer, input_offset,
image.guest_size_bytes - swizzle.buffer_offset);
compute_pass_descriptor_queue.AddImage(image.StorageImageView(swizzle.level));
const void* const descriptor_data{compute_pass_descriptor_queue.UpdateData()};
const auto params = MakeBlockLinearSwizzle3DParams(swizzle, image.info);
scheduler.Record([this, num_dispatches_x, num_dispatches_y, num_dispatches_z, params,
descriptor_data](vk::CommandBuffer cmdbuf) {
const VkDescriptorSet set = descriptor_allocator.Commit();
device.GetLogical().UpdateDescriptorSet(set, *descriptor_template, descriptor_data);
cmdbuf.BindDescriptorSets(VK_PIPELINE_BIND_POINT_COMPUTE, *layout, 0, set, {});
cmdbuf.PushConstants(*layout, VK_SHADER_STAGE_COMPUTE_BIT, params);
cmdbuf.Dispatch(num_dispatches_x, num_dispatches_y, num_dispatches_z);
});
}
RecordUnswizzleExitBarrier(scheduler, vk_image, aspect_mask);
}
PitchUnswizzlePass::PitchUnswizzlePass(
const Device& device_, Scheduler& scheduler_, DescriptorPool& descriptor_pool_,
ComputePassDescriptorQueue& compute_pass_descriptor_queue_)
: ComputePass(device_, scheduler_, descriptor_pool_, UNSWIZZLE_DESCRIPTOR_SET_BINDINGS,
UNSWIZZLE_DESCRIPTOR_UPDATE_TEMPLATE, UNSWIZZLE_BANK_INFO,
COMPUTE_PUSH_CONSTANT_RANGE<sizeof(PitchUnswizzlePushConstants)>,
UnswizzleSpv(device_, PITCH_UNSWIZZLE_COMP_SPV,
PITCH_UNSWIZZLE_NONARROW_COMP_SPV)),
scheduler{scheduler_}, compute_pass_descriptor_queue{compute_pass_descriptor_queue_} {}
PitchUnswizzlePass::~PitchUnswizzlePass() = default;
void PitchUnswizzlePass::Unswizzle(Image& image, const StagingBufferRef& map,
std::span<const VideoCommon::SwizzleParameters> swizzles) {
scheduler.RequestOutsideRenderPassOperationContext();
const VkPipeline vk_pipeline = *pipeline;
const VkImageAspectFlags aspect_mask = image.AspectMask();
const VkImage vk_image = image.Handle();
const bool is_initialized = image.ExchangeInitialization();
RecordUnswizzleEntryBarrier(scheduler, vk_pipeline, vk_image, aspect_mask, is_initialized);
const u32 bytes_per_block = VideoCore::Surface::BytesPerBlock(image.info.format);
const u32 pitch = image.info.pitch;
for (const VideoCommon::SwizzleParameters& swizzle : swizzles) {
const size_t input_offset = swizzle.buffer_offset + map.offset;
const u32 num_dispatches_x = Common::DivCeil(swizzle.num_tiles.width, 32U);
const u32 num_dispatches_y = Common::DivCeil(swizzle.num_tiles.height, 32U);
compute_pass_descriptor_queue.Acquire(scheduler, 2);
compute_pass_descriptor_queue.AddBuffer(map.buffer, input_offset,
image.guest_size_bytes - swizzle.buffer_offset);
compute_pass_descriptor_queue.AddImage(image.StorageImageView(swizzle.level));
const void* const descriptor_data{compute_pass_descriptor_queue.UpdateData()};
const PitchUnswizzlePushConstants params{
.origin{0, 0},
.destination{0, 0},
.bytes_per_block = bytes_per_block,
.pitch = pitch,
};
scheduler.Record([this, num_dispatches_x, num_dispatches_y, params,
descriptor_data](vk::CommandBuffer cmdbuf) {
const VkDescriptorSet set = descriptor_allocator.Commit();
device.GetLogical().UpdateDescriptorSet(set, *descriptor_template, descriptor_data);
cmdbuf.BindDescriptorSets(VK_PIPELINE_BIND_POINT_COMPUTE, *layout, 0, set, {});
cmdbuf.PushConstants(*layout, VK_SHADER_STAGE_COMPUTE_BIT, params);
cmdbuf.Dispatch(num_dispatches_x, num_dispatches_y, 1);
});
}
RecordUnswizzleExitBarrier(scheduler, vk_image, aspect_mask);
}
} // namespace Vulkan } // namespace Vulkan
@@ -164,4 +164,49 @@ private:
ComputePassDescriptorQueue& compute_pass_descriptor_queue; ComputePassDescriptorQueue& compute_pass_descriptor_queue;
}; };
class BlockLinearUnswizzle2DPass final : public ComputePass {
public:
explicit BlockLinearUnswizzle2DPass(
const Device& device_, Scheduler& scheduler_, DescriptorPool& descriptor_pool_,
ComputePassDescriptorQueue& compute_pass_descriptor_queue_);
~BlockLinearUnswizzle2DPass();
void Unswizzle(Image& image, const StagingBufferRef& map,
std::span<const VideoCommon::SwizzleParameters> swizzles);
private:
Scheduler& scheduler;
ComputePassDescriptorQueue& compute_pass_descriptor_queue;
};
class BlockLinearUnswizzleImage3DPass final : public ComputePass {
public:
explicit BlockLinearUnswizzleImage3DPass(
const Device& device_, Scheduler& scheduler_, DescriptorPool& descriptor_pool_,
ComputePassDescriptorQueue& compute_pass_descriptor_queue_);
~BlockLinearUnswizzleImage3DPass();
void Unswizzle(Image& image, const StagingBufferRef& map,
std::span<const VideoCommon::SwizzleParameters> swizzles);
private:
Scheduler& scheduler;
ComputePassDescriptorQueue& compute_pass_descriptor_queue;
};
class PitchUnswizzlePass final : public ComputePass {
public:
explicit PitchUnswizzlePass(const Device& device_, Scheduler& scheduler_,
DescriptorPool& descriptor_pool_,
ComputePassDescriptorQueue& compute_pass_descriptor_queue_);
~PitchUnswizzlePass();
void Unswizzle(Image& image, const StagingBufferRef& map,
std::span<const VideoCommon::SwizzleParameters> swizzles);
private:
Scheduler& scheduler;
ComputePassDescriptorQueue& compute_pass_descriptor_queue;
};
} // namespace Vulkan } // namespace Vulkan
@@ -694,9 +694,11 @@ void GraphicsPipeline::MakePipeline(VkRenderPass render_pass) {
const size_t num_vertex_arrays = (std::min)( const size_t num_vertex_arrays = (std::min)(
Maxwell::NumVertexArrays, static_cast<size_t>(device.GetMaxVertexInputBindings())); Maxwell::NumVertexArrays, static_cast<size_t>(device.GetMaxVertexInputBindings()));
for (size_t index = 0; index < num_vertex_arrays; ++index) { for (size_t index = 0; index < num_vertex_arrays; ++index) {
const bool instanced = key.state.binding_divisors[index] != 0; const bool instanced = ((key.state.enabled_divisors >> index) & 1) != 0;
const auto rate = auto rate = VK_VERTEX_INPUT_RATE_VERTEX;
instanced ? VK_VERTEX_INPUT_RATE_INSTANCE : VK_VERTEX_INPUT_RATE_VERTEX; if (instanced) {
rate = VK_VERTEX_INPUT_RATE_INSTANCE;
}
vertex_bindings.push_back({ vertex_bindings.push_back({
.binding = static_cast<u32>(index), .binding = static_cast<u32>(index),
.stride = key.state.vertex_strides[index], .stride = key.state.vertex_strides[index],
@@ -705,7 +707,7 @@ void GraphicsPipeline::MakePipeline(VkRenderPass render_pass) {
if (instanced) { if (instanced) {
vertex_binding_divisors.push_back({ vertex_binding_divisors.push_back({
.binding = static_cast<u32>(index), .binding = static_cast<u32>(index),
.divisor = key.state.binding_divisors[index], .divisor = device.GetVertexAttribDivisor(key.state.binding_divisors[index]),
}); });
} }
} }
@@ -137,10 +137,12 @@ VkRect2D GetScissorState(const Maxwell& regs, size_t index, u32 up_scale = 1, u3
max_y = (std::max)(max_y, 0); max_y = (std::max)(max_y, 0);
if (src.enable) { if (src.enable) {
scissor.offset.x = scale_up(src.min_x); const s32 min_x = static_cast<s32>(src.min_x.Value());
const s32 max_x = static_cast<s32>(src.max_x.Value());
scissor.offset.x = scale_up(min_x);
scissor.offset.y = scale_up(min_y); scissor.offset.y = scale_up(min_y);
scissor.extent.width = scale_up(src.max_x - src.min_x); scissor.extent.width = scale_up((std::max)(max_x - min_x, 0));
scissor.extent.height = scale_up(max_y - min_y); scissor.extent.height = scale_up((std::max)(max_y - min_y, 0));
} else { } else {
scissor.offset.x = 0; scissor.offset.x = 0;
scissor.offset.y = 0; scissor.offset.y = 0;
@@ -260,6 +262,7 @@ void RasterizerVulkan::PrepareDraw(bool is_indexed, Func&& draw_func) {
} }
void RasterizerVulkan::Draw(bool is_indexed, u32 instance_count) { void RasterizerVulkan::Draw(bool is_indexed, u32 instance_count) {
buffer_cache.SetDrawInstanceCount(instance_count);
PrepareDraw(is_indexed, [this, is_indexed, instance_count] { PrepareDraw(is_indexed, [this, is_indexed, instance_count] {
const auto& draw_state = maxwell3d->draw_manager.draw_state; const auto& draw_state = maxwell3d->draw_manager.draw_state;
const u32 num_instances{instance_count}; const u32 num_instances{instance_count};
@@ -295,6 +298,7 @@ void RasterizerVulkan::Draw(bool is_indexed, u32 instance_count) {
void RasterizerVulkan::DrawIndirect() { void RasterizerVulkan::DrawIndirect() {
const auto& params = maxwell3d->draw_manager.indirect_state; const auto& params = maxwell3d->draw_manager.indirect_state;
buffer_cache.SetDrawIndirect(&params); buffer_cache.SetDrawIndirect(&params);
buffer_cache.SetDrawInstanceCount(0);
PrepareDraw(params.is_indexed, [this, &params] { PrepareDraw(params.is_indexed, [this, &params] {
const auto indirect_buffer = buffer_cache.GetDrawIndirectBuffer(); const auto indirect_buffer = buffer_cache.GetDrawIndirectBuffer();
const auto& buffer = indirect_buffer.first; const auto& buffer = indirect_buffer.first;
@@ -1917,13 +1921,19 @@ void RasterizerVulkan::UpdateVertexInput(Tegra::Engines::Maxwell3D::Regs& regs)
for (u32 binding = 0; binding < max_bindings; ++binding) { for (u32 binding = 0; binding < max_bindings; ++binding) {
const auto& input_binding{regs.vertex_streams[binding]}; const auto& input_binding{regs.vertex_streams[binding]};
const bool is_instanced{regs.vertex_stream_instances.IsInstancingEnabled(binding)}; const bool is_instanced{regs.vertex_stream_instances.IsInstancingEnabled(binding)};
auto input_rate = VK_VERTEX_INPUT_RATE_VERTEX;
u32 divisor = 1;
if (is_instanced) {
input_rate = VK_VERTEX_INPUT_RATE_INSTANCE;
divisor = device.GetVertexAttribDivisor(input_binding.frequency);
}
bindings.push_back({ bindings.push_back({
.sType = VK_STRUCTURE_TYPE_VERTEX_INPUT_BINDING_DESCRIPTION_2_EXT, .sType = VK_STRUCTURE_TYPE_VERTEX_INPUT_BINDING_DESCRIPTION_2_EXT,
.pNext = nullptr, .pNext = nullptr,
.binding = binding, .binding = binding,
.stride = input_binding.stride, .stride = input_binding.stride,
.inputRate = is_instanced ? VK_VERTEX_INPUT_RATE_INSTANCE : VK_VERTEX_INPUT_RATE_VERTEX, .inputRate = input_rate,
.divisor = is_instanced ? input_binding.frequency : 1, .divisor = divisor,
}); });
} }
@@ -449,7 +449,9 @@ void Scheduler::EndRenderPass()
| VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_READ_BIT
| VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT
| VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT
| VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT, | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT
| VK_ACCESS_TRANSFER_READ_BIT
| VK_ACCESS_TRANSFER_WRITE_BIT,
.oldLayout = VK_IMAGE_LAYOUT_GENERAL, .oldLayout = VK_IMAGE_LAYOUT_GENERAL,
.newLayout = VK_IMAGE_LAYOUT_GENERAL, .newLayout = VK_IMAGE_LAYOUT_GENERAL,
.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, .srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
@@ -460,7 +462,7 @@ void Scheduler::EndRenderPass()
} }
cmdbuf.EndRenderPass(); cmdbuf.EndRenderPass();
cmdbuf.PipelineBarrier(VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT | VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT | cmdbuf.PipelineBarrier(VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT | VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT |
VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, vk::PIPELINE_STAGE_GRAPHICS_COMPUTE, VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, vk::PIPELINE_STAGE_GRAPHICS_COMPUTE_TRANSFER,
0, nullptr, nullptr, vk::Span(barriers.data(), num_images)); 0, nullptr, nullptr, vk::Span(barriers.data(), num_images));
if (has_transform_feedback) { if (has_transform_feedback) {
static constexpr VkMemoryBarrier XFB_OUTPUT_BARRIER{ static constexpr VkMemoryBarrier XFB_OUTPUT_BARRIER{
@@ -160,6 +160,55 @@ constexpr VkBorderColor ConvertBorderColor(const std::array<float, 4>& color) {
info.size.depth == 1; info.size.depth == 1;
} }
[[nodiscard]] PixelFormat UnswizzleViewFormat(u32 bytes_per_block) {
switch (bytes_per_block) {
case 1:
return PixelFormat::R8_UINT;
case 2:
return PixelFormat::R16_UINT;
case 4:
return PixelFormat::R32_UINT;
case 8:
return PixelFormat::R32G32_UINT;
case 16:
return PixelFormat::R32G32B32A32_UINT;
default:
return PixelFormat::Invalid;
}
}
constexpr u32 UNSWIZZLE_WORKGROUP_INVOCATIONS = 32 * 32;
[[nodiscard]] bool SupportsAcceleratedUnswizzleDevice(const Device& device) {
return device.IsKhrImageFormatListSupported() &&
device.GetMaxComputeWorkGroupInvocations() >= UNSWIZZLE_WORKGROUP_INVOCATIONS;
}
[[nodiscard]] bool SupportsAcceleratedUnswizzle(const Device& device, const ImageInfo& info) {
if (!SupportsAcceleratedUnswizzleDevice(device)) {
return false;
}
if (info.num_samples > 1) {
return false;
}
if (info.type != ImageType::e2D && info.type != ImageType::e3D &&
info.type != ImageType::Linear) {
return false;
}
const PixelFormat view_format =
UnswizzleViewFormat(VideoCore::Surface::BytesPerBlock(info.format));
if (view_format == PixelFormat::Invalid) {
return false;
}
if (!VideoCore::Surface::IsViewCompatible(info.format, view_format, false, true)) {
return false;
}
const auto host_format =
MaxwellToVK::SurfaceFormat(device, FormatType::Optimal, false, view_format);
return device.IsFormatSupported(host_format.format, VK_FORMAT_FEATURE_STORAGE_IMAGE_BIT,
FormatType::Optimal);
}
[[nodiscard]] VkImageCreateInfo MakeImageCreateInfo(const Device& device, const ImageInfo& info, [[nodiscard]] VkImageCreateInfo MakeImageCreateInfo(const Device& device, const ImageInfo& info,
std::optional<VkFormat> format_override = {}) { std::optional<VkFormat> format_override = {}) {
auto format_info = auto format_info =
@@ -248,8 +297,18 @@ constexpr VkBorderColor ConvertBorderColor(const std::array<float, 4>& color) {
return allocator.CreateImage(image_ci); return allocator.CreateImage(image_ci);
} }
[[nodiscard]] VkImageViewType StorageViewType(ImageType type) {
if (type == ImageType::e3D) {
return VK_IMAGE_VIEW_TYPE_3D;
}
if (type == ImageType::Linear) {
return VK_IMAGE_VIEW_TYPE_2D;
}
return VK_IMAGE_VIEW_TYPE_2D_ARRAY;
}
[[nodiscard]] vk::ImageView MakeStorageView(const vk::Device& device, u32 level, VkImage image, [[nodiscard]] vk::ImageView MakeStorageView(const vk::Device& device, u32 level, VkImage image,
VkFormat format) { VkFormat format, VkImageViewType view_type) {
static constexpr VkImageViewUsageCreateInfo storage_image_view_usage_create_info{ static constexpr VkImageViewUsageCreateInfo storage_image_view_usage_create_info{
.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_USAGE_CREATE_INFO, .sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_USAGE_CREATE_INFO,
.pNext = nullptr, .pNext = nullptr,
@@ -260,7 +319,7 @@ constexpr VkBorderColor ConvertBorderColor(const std::array<float, 4>& color) {
.pNext = &storage_image_view_usage_create_info, .pNext = &storage_image_view_usage_create_info,
.flags = 0, .flags = 0,
.image = image, .image = image,
.viewType = VK_IMAGE_VIEW_TYPE_2D_ARRAY, .viewType = view_type,
.format = format, .format = format,
.components{ .components{
.r = VK_COMPONENT_SWIZZLE_IDENTITY, .r = VK_COMPONENT_SWIZZLE_IDENTITY,
@@ -658,18 +717,11 @@ void CopyBufferToImage(vk::CommandBuffer cmdbuf, VkBuffer src_buffer, VkImage im
.subresourceRange = subresource_range, .subresourceRange = subresource_range,
}; };
cmdbuf.PipelineBarrier(VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT | cmdbuf.PipelineBarrier(vk::PIPELINE_STAGE_GRAPHICS_COMPUTE, VK_PIPELINE_STAGE_TRANSFER_BIT, 0,
VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT |
VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0,
read_barrier); read_barrier);
cmdbuf.CopyBufferToImage(src_buffer, image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, copies); cmdbuf.CopyBufferToImage(src_buffer, image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, copies);
// TODO: Move this to another API cmdbuf.PipelineBarrier(VK_PIPELINE_STAGE_TRANSFER_BIT, vk::PIPELINE_STAGE_GRAPHICS_COMPUTE, 0,
cmdbuf.PipelineBarrier( nullptr, nullptr, write_barrier);
VK_PIPELINE_STAGE_TRANSFER_BIT,
VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT |
VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT |
VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT,
0, nullptr, nullptr, write_barrier);
} }
[[nodiscard]] VkImageBlit MakeImageBlit(const Region2D& dst_region, const Region2D& src_region, [[nodiscard]] VkImageBlit MakeImageBlit(const Region2D& dst_region, const Region2D& src_region,
@@ -968,6 +1020,14 @@ TextureCacheRuntime::TextureCacheRuntime(const Device& device_, Scheduler& sched
bl3d_unswizzle_pass.emplace(device, scheduler, descriptor_pool, bl3d_unswizzle_pass.emplace(device, scheduler, descriptor_pool,
staging_buffer_pool, compute_pass_descriptor_queue); staging_buffer_pool, compute_pass_descriptor_queue);
} }
if (SupportsAcceleratedUnswizzleDevice(device)) {
bl_unswizzle_2d_pass.emplace(device, scheduler, descriptor_pool,
compute_pass_descriptor_queue);
bl_unswizzle_image_3d_pass.emplace(device, scheduler, descriptor_pool,
compute_pass_descriptor_queue);
pitch_unswizzle_pass.emplace(device, scheduler, descriptor_pool,
compute_pass_descriptor_queue);
}
} }
void TextureCacheRuntime::Finish() { void TextureCacheRuntime::Finish() {
@@ -1902,16 +1962,12 @@ Image::Image(TextureCacheRuntime& runtime_, const ImageInfo& info_, GPUVAddr gpu
if (runtime->device.HasDebuggingToolAttached()) { if (runtime->device.HasDebuggingToolAttached()) {
original_image.SetObjectNameEXT(VideoCommon::Name(*this).c_str()); original_image.SetObjectNameEXT(VideoCommon::Name(*this).c_str());
} }
if (False(flags & VideoCommon::ImageFlagBits::Converted) &&
SupportsAcceleratedUnswizzle(runtime->device, info)) {
flags |= VideoCommon::ImageFlagBits::AcceleratedUpload;
}
current_image = &Image::original_image; current_image = &Image::original_image;
storage_image_views.resize(info.resources.levels); storage_image_views.resize(info.resources.levels);
if (WillUseAcceleratedAstcDecode(runtime->device, info)) {
const auto& device = runtime->device.GetLogical();
const VkFormat storage_format = VK_FORMAT_A8B8G8R8_UNORM_PACK32;
for (s32 level = 0; level < info.resources.levels; ++level) {
storage_image_views[level] =
MakeStorageView(device, level, *original_image, storage_format);
}
}
} }
Image::Image(const VideoCommon::NullImageParams& params) : VideoCommon::ImageBase{params} {} Image::Image(const VideoCommon::NullImageParams& params) : VideoCommon::ImageBase{params} {}
@@ -2035,7 +2091,7 @@ void Image::UploadMemory(VkBuffer buffer, VkDeviceSize offset,
temp_vk_image, info.format, info.num_samples, temp_vk_image, info.format, info.num_samples,
{image_copies.data(), image_copies.size()}, false); {image_copies.data(), image_copies.size()}, false);
} }
initialized = true; InitializationFor(current_image) = true;
runtime->ReleaseMsaaScratchImage(temp_vk_image); runtime->ReleaseMsaaScratchImage(temp_vk_image);
if (is_rescaled) { if (is_rescaled) {
@@ -2056,7 +2112,7 @@ void Image::UploadMemory(VkBuffer buffer, VkDeviceSize offset,
const VkBuffer src_buffer = buffer; const VkBuffer src_buffer = buffer;
const VkImage vk_image = *original_image; const VkImage vk_image = *original_image;
const VkImageAspectFlags vk_aspect_mask = aspect_mask; const VkImageAspectFlags vk_aspect_mask = aspect_mask;
const bool was_initialized = std::exchange(initialized, true); const bool was_initialized = std::exchange(InitializationFor(&Image::original_image), true);
scheduler->Record([src_buffer, vk_image, vk_aspect_mask, was_initialized, scheduler->Record([src_buffer, vk_image, vk_aspect_mask, was_initialized,
vk_copies](vk::CommandBuffer cmdbuf) { vk_copies](vk::CommandBuffer cmdbuf) {
@@ -2321,16 +2377,46 @@ void Image::DownloadMemory(const StagingBufferRef& map, std::span<const BufferIm
DownloadMemory(buffers, offsets, copies); DownloadMemory(buffers, offsets, copies);
} }
std::vector<vk::ImageView>& Image::StorageViewsFor(vk::Image Image::*image) {
if (image == &Image::scaled_image) {
if (scaled_storage_image_views.empty()) {
scaled_storage_image_views.resize(info.resources.levels);
}
return scaled_storage_image_views;
}
return storage_image_views;
}
bool& Image::InitializationFor(vk::Image Image::*image) noexcept {
if (image == &Image::scaled_image) {
return scaled_initialized;
}
return original_initialized;
}
VkImageView Image::StorageImageView(s32 level) noexcept { VkImageView Image::StorageImageView(s32 level) noexcept {
auto& view = storage_image_views[level]; const bool astc_decode = WillUseAcceleratedAstcDecode(runtime->device, info);
const bool unswizzle_upload =
!astc_decode && True(flags & ImageFlagBits::AcceleratedUpload);
vk::Image Image::*target = current_image;
if (astc_decode || unswizzle_upload) {
target = &Image::original_image;
}
auto& view = StorageViewsFor(target)[level];
if (!view) { if (!view) {
auto format_info = auto format_info =
MaxwellToVK::SurfaceFormat(runtime->device, FormatType::Optimal, true, info.format); MaxwellToVK::SurfaceFormat(runtime->device, FormatType::Optimal, true, info.format);
if (WillUseAcceleratedAstcDecode(runtime->device, info)) { if (astc_decode) {
format_info.format = VK_FORMAT_A8B8G8R8_UNORM_PACK32; format_info.format = VK_FORMAT_A8B8G8R8_UNORM_PACK32;
} }
view = MakeStorageView(runtime->device.GetLogical(), level, *(this->*current_image), if (unswizzle_upload) {
format_info.format); const PixelFormat view_format =
UnswizzleViewFormat(VideoCore::Surface::BytesPerBlock(info.format));
format_info = MaxwellToVK::SurfaceFormat(runtime->device, FormatType::Optimal, false,
view_format);
}
view = MakeStorageView(runtime->device.GetLogical(), level, *(this->*target),
format_info.format, StorageViewType(info.type));
} }
return *view; return *view;
} }
@@ -2370,6 +2456,7 @@ bool Image::ScaleUp(bool ignore) {
} }
if (NeedsScaleHelper()) { if (NeedsScaleHelper()) {
if (!BlitScaleHelper(true)) { if (!BlitScaleHelper(true)) {
flags &= ~ImageFlagBits::Rescaled;
current_image = &Image::original_image; current_image = &Image::original_image;
return false; return false;
} }
@@ -2559,6 +2646,10 @@ ImageView::ImageView(TextureCacheRuntime& runtime, const VideoCommon::ImageViewI
if (device->IsExtAstcDecodeModeSupported() && IsLdrAstcFormat(format_info.format)) { if (device->IsExtAstcDecodeModeSupported() && IsLdrAstcFormat(format_info.format)) {
view_next = &astc_decode_mode; view_next = &astc_decode_mode;
} }
auto subresource_range = MakeSubresourceRange(aspect_mask, info.range);
if (True(flags & VideoCommon::ImageViewFlagBits::Slice)) {
subresource_range.levelCount = 1;
}
const VkImageViewCreateInfo create_info{ const VkImageViewCreateInfo create_info{
.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO, .sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO,
.pNext = view_next, .pNext = view_next,
@@ -2567,7 +2658,7 @@ ImageView::ImageView(TextureCacheRuntime& runtime, const VideoCommon::ImageViewI
.viewType = VkImageViewType{}, .viewType = VkImageViewType{},
.format = format_info.format, .format = format_info.format,
.components = swizzle_mapping, .components = swizzle_mapping,
.subresourceRange = MakeSubresourceRange(aspect_mask, info.range), .subresourceRange = subresource_range,
}; };
const auto create = [&](TextureType tex_type, std::optional<u32> num_layers) { const auto create = [&](TextureType tex_type, std::optional<u32> num_layers) {
VkImageViewCreateInfo ci{create_info}; VkImageViewCreateInfo ci{create_info};
@@ -3141,6 +3232,19 @@ void TextureCacheRuntime::AccelerateImageUpload(
return astc_decoder_pass->Assemble(image, map, swizzles); return astc_decoder_pass->Assemble(image, map, swizzles);
} }
if (bl_unswizzle_2d_pass && image.info.type == ImageType::e2D) {
return bl_unswizzle_2d_pass->Unswizzle(image, map, swizzles);
}
if (bl_unswizzle_image_3d_pass && image.info.type == ImageType::e3D &&
!IsPixelFormatBCn(image.info.format)) {
return bl_unswizzle_image_3d_pass->Unswizzle(image, map, swizzles);
}
if (pitch_unswizzle_pass && image.info.type == ImageType::Linear) {
return pitch_unswizzle_pass->Unswizzle(image, map, swizzles);
}
if (!Settings::values.gpu_unswizzle_enabled.GetValue() || !bl3d_unswizzle_pass) { if (!Settings::values.gpu_unswizzle_enabled.GetValue() || !bl3d_unswizzle_pass) {
if (IsPixelFormatBCn(image.info.format) && image.info.type == ImageType::e3D) { if (IsPixelFormatBCn(image.info.format) && image.info.type == ImageType::e3D) {
ASSERT(false && "GPU unswizzle is disabled for BCn 3D texture"); ASSERT(false && "GPU unswizzle is disabled for BCn 3D texture");
@@ -159,6 +159,9 @@ public:
std::optional<ASTCDecoderPass> astc_decoder_pass; std::optional<ASTCDecoderPass> astc_decoder_pass;
std::optional<BlockLinearUnswizzle3DPass> bl3d_unswizzle_pass; std::optional<BlockLinearUnswizzle3DPass> bl3d_unswizzle_pass;
std::optional<BlockLinearUnswizzle2DPass> bl_unswizzle_2d_pass;
std::optional<BlockLinearUnswizzleImage3DPass> bl_unswizzle_image_3d_pass;
std::optional<PitchUnswizzlePass> pitch_unswizzle_pass;
const Settings::ResolutionScalingInfo& resolution; const Settings::ResolutionScalingInfo& resolution;
std::array<std::vector<VkFormat>, VideoCore::Surface::MaxPixelFormat> view_formats; std::array<std::vector<VkFormat>, VideoCore::Surface::MaxPixelFormat> view_formats;
@@ -350,7 +353,7 @@ public:
/// Returns true when the image is already initialized and mark it as initialized /// Returns true when the image is already initialized and mark it as initialized
[[nodiscard]] bool ExchangeInitialization() noexcept { [[nodiscard]] bool ExchangeInitialization() noexcept {
return std::exchange(initialized, true); return std::exchange(InitializationFor(current_image), true);
} }
VkImageView StorageImageView(s32 level) noexcept; VkImageView StorageImageView(s32 level) noexcept;
@@ -370,6 +373,10 @@ private:
bool NeedsScaleHelper() const; bool NeedsScaleHelper() const;
std::vector<vk::ImageView>& StorageViewsFor(vk::Image Image::*image);
bool& InitializationFor(vk::Image Image::*image) noexcept;
Scheduler* scheduler{}; Scheduler* scheduler{};
TextureCacheRuntime* runtime{}; TextureCacheRuntime* runtime{};
@@ -387,8 +394,10 @@ private:
vk::Image Image::*current_image{}; vk::Image Image::*current_image{};
std::vector<vk::ImageView> storage_image_views; std::vector<vk::ImageView> storage_image_views;
std::vector<vk::ImageView> scaled_storage_image_views;
VkImageAspectFlags aspect_mask = 0; VkImageAspectFlags aspect_mask = 0;
bool initialized = false; bool original_initialized = false;
bool scaled_initialized = false;
std::optional<Framebuffer> scale_framebuffer; std::optional<Framebuffer> scale_framebuffer;
std::optional<Framebuffer> normal_framebuffer; std::optional<Framebuffer> normal_framebuffer;
@@ -1,3 +1,6 @@
// SPDX-FileCopyrightText: Copyright 2026 Eden Emulator Project
// SPDX-License-Identifier: GPL-3.0-or-later
// SPDX-FileCopyrightText: Copyright 2020 yuzu Emulator Project // SPDX-FileCopyrightText: Copyright 2020 yuzu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later // SPDX-License-Identifier: GPL-2.0-or-later
@@ -23,8 +26,8 @@ struct BlockLinearSwizzle2DParams {
}; };
struct BlockLinearSwizzle3DParams { struct BlockLinearSwizzle3DParams {
std::array<u32, 3> origin; alignas(16) std::array<u32, 3> origin;
std::array<s32, 3> destination; alignas(16) std::array<s32, 3> destination;
u32 bytes_per_block_log2; u32 bytes_per_block_log2;
u32 slice_size; u32 slice_size;
u32 block_size; u32 block_size;
+53 -27
View File
@@ -20,6 +20,7 @@
#include "video_core/engines/kepler_compute.h" #include "video_core/engines/kepler_compute.h"
#include "video_core/guest_memory.h" #include "video_core/guest_memory.h"
#include "video_core/host1x/gpu_device_memory_manager.h" #include "video_core/host1x/gpu_device_memory_manager.h"
#include "video_core/texture_cache/accelerated_swizzle.h"
#include "video_core/texture_cache/image_view_base.h" #include "video_core/texture_cache/image_view_base.h"
#include "video_core/texture_cache/samples_helper.h" #include "video_core/texture_cache/samples_helper.h"
#include "video_core/texture_cache/texture_cache_base.h" #include "video_core/texture_cache/texture_cache_base.h"
@@ -279,11 +280,11 @@ void TextureCache<P>::CheckFeedbackLoop(std::span<const ImageViewInOut> views) {
const ImageId view_image_id = slot_image_views[view.id].image_id; const ImageId view_image_id = slot_image_views[view.id].image_id;
{ {
bool is_continue = false; bool is_feedback = false;
for (size_t i = 0; i < 8; ++i) for (size_t i = 0; i < 8; ++i)
is_continue |= (rt_active_mask & (1u << i)) && view_image_id == rt_image_id[i]; is_feedback |= (rt_active_mask & (1u << i)) && view_image_id == rt_image_id[i];
if (is_continue) if (is_feedback)
continue; return true;
} }
if (depth_active && view_image_id == rt_depth_image_id) { if (depth_active && view_image_id == rt_depth_image_id) {
return true; return true;
@@ -626,14 +627,25 @@ void TextureCache<P>::DownloadMemory(DAddr cpu_addr, size_t size) {
std::ranges::sort(images, [this](ImageId lhs, ImageId rhs) { std::ranges::sort(images, [this](ImageId lhs, ImageId rhs) {
return slot_images[lhs].modification_tick < slot_images[rhs].modification_tick; return slot_images[lhs].modification_tick < slot_images[rhs].modification_tick;
}); });
size_t total_size_bytes = 0;
for (const ImageId image_id : images) {
total_size_bytes += slot_images[image_id].unswizzled_size_bytes;
}
auto download_map = runtime.DownloadStagingBuffer(total_size_bytes);
for (const ImageId image_id : images) { for (const ImageId image_id : images) {
Image& image = slot_images[image_id]; Image& image = slot_images[image_id];
auto map = runtime.DownloadStagingBuffer(image.unswizzled_size_bytes);
const auto copies = FixSmallVectorADL(FullDownloadCopies(image.info)); const auto copies = FixSmallVectorADL(FullDownloadCopies(image.info));
image.DownloadMemory(map, copies); image.DownloadMemory(download_map, copies);
download_map.offset += image.unswizzled_size_bytes;
}
runtime.Finish(); runtime.Finish();
SwizzleImage(*gpu_memory, image.gpu_addr, image.info, copies, map.mapped_span, std::span<u8> download_span = download_map.mapped_span;
for (const ImageId image_id : images) {
const ImageBase& image = slot_images[image_id];
const auto copies = FixSmallVectorADL(FullDownloadCopies(image.info));
SwizzleImage(*gpu_memory, image.gpu_addr, image.info, copies, download_span,
swizzle_data_buffer); swizzle_data_buffer);
download_span = download_span.subspan(image.unswizzled_size_bytes);
} }
} }
@@ -1122,6 +1134,12 @@ void TextureCache<P>::RefreshContents(Image& image, ImageId image_id) {
TrackImage(image, image_id); TrackImage(image, image_id);
if (image.info.rescaleable &&
IsRegionGpuModified(image.cpu_addr, image.guest_size_bytes)) {
runtime.TransitionImageLayout(image);
return;
}
if (image.info.num_samples > 1 && !runtime.CanUploadMSAA()) { if (image.info.num_samples > 1 && !runtime.CanUploadMSAA()) {
LOG_WARNING(HW_GPU, "MSAA image uploads are not implemented"); LOG_WARNING(HW_GPU, "MSAA image uploads are not implemented");
runtime.TransitionImageLayout(image); runtime.TransitionImageLayout(image);
@@ -1157,8 +1175,7 @@ void TextureCache<P>::UploadImageContents(Image& image, StagingBuffer& staging)
const GPUVAddr gpu_addr = image.gpu_addr; const GPUVAddr gpu_addr = image.gpu_addr;
if (True(image.flags & ImageFlagBits::AcceleratedUpload)) { if (True(image.flags & ImageFlagBits::AcceleratedUpload)) {
gpu_memory->ReadBlock(gpu_addr, mapped_span.data(), mapped_span.size_bytes(), gpu_memory->ReadBlockUnsafe(gpu_addr, mapped_span.data(), image.guest_size_bytes);
VideoCommon::CacheType::NoTextureCache);
const auto uploads = FullUploadSwizzles(image.info); const auto uploads = FullUploadSwizzles(image.info);
runtime.AccelerateImageUpload(image, staging, FixSmallVectorADL(uploads), 0, 0); runtime.AccelerateImageUpload(image, staging, FixSmallVectorADL(uploads), 0, 0);
return; return;
@@ -1265,6 +1282,9 @@ ImageId TextureCache<P>::FindImage(const ImageInfo& info, GPUVAddr gpu_addr,
template <class P> template <class P>
bool TextureCache<P>::ImageCanRescale(ImageBase& image) { bool TextureCache<P>::ImageCanRescale(ImageBase& image) {
if (!Settings::values.resolution_info.active) {
return false;
}
if (!image.info.rescaleable) { if (!image.info.rescaleable) {
return false; return false;
} }
@@ -1352,12 +1372,12 @@ void TextureCache<P>::QueueAsyncDecode(Image& image, ImageId image_id) {
decode->image_id = image_id; decode->image_id = image_id;
async_decodes.push_back(std::move(decode)); async_decodes.push_back(std::move(decode));
std::vector<u8> local_unswizzle_data_buffer(image.unswizzled_size_bytes, 0); Common::ScratchBuffer<u8> local_unswizzle_data_buffer(image.unswizzled_size_bytes);
Tegra::Memory::GpuGuestMemory<u8, Tegra::Memory::GuestMemoryFlags::UnsafeRead> swizzle_data(*gpu_memory, image.gpu_addr, image.guest_size_bytes, &swizzle_data_buffer); Tegra::Memory::GpuGuestMemory<u8, Tegra::Memory::GuestMemoryFlags::UnsafeRead> swizzle_data(*gpu_memory, image.gpu_addr, image.guest_size_bytes, &swizzle_data_buffer);
auto copies = UnswizzleImage(*gpu_memory, image.gpu_addr, image.info, swizzle_data, local_unswizzle_data_buffer); auto copies = UnswizzleImage(*gpu_memory, image.gpu_addr, image.info, swizzle_data, local_unswizzle_data_buffer);
const size_t out_size = MapSizeBytes(image); const size_t out_size = MapSizeBytes(image);
auto func = [out_size, copies, info = image.info, auto func = [out_size, copies = std::move(copies), info = image.info,
input = std::move(local_unswizzle_data_buffer), input = std::move(local_unswizzle_data_buffer),
async_decode = decode_ptr]() mutable { async_decode = decode_ptr]() mutable {
async_decode->decoded_data.resize_destructive(out_size); async_decode->decoded_data.resize_destructive(out_size);
@@ -1426,18 +1446,16 @@ void TextureCache<P>::TickAsyncUnswizzle() {
Image& image = slot_images[task.image_id]; Image& image = slot_images[task.image_id];
if (!task.initialized) { if (!task.initialized) {
task.total_size = MapSizeBytes(image); task.total_size = image.guest_size_bytes;
task.staging_buffer = runtime.UploadStagingBuffer(task.total_size, true); task.staging_buffer = runtime.UploadStagingBuffer(task.total_size, true);
const auto& info = image.info; const auto layout = FullUploadSwizzles(task.info);
const u32 bytes_per_block = BytesPerBlock(info.format); const auto params =
const u32 width_blocks = Common::DivCeil(info.size.width, 4u); VideoCommon::Accelerated::MakeBlockLinearSwizzle3DParams(layout.front(), task.info);
const u32 height_blocks = Common::DivCeil(info.size.height, 4u); task.bytes_per_slice = params.slice_size;
task.chunked = task.info.block.depth == 0;
const u32 stride = width_blocks * bytes_per_block;
const u32 aligned_height = height_blocks;
task.bytes_per_slice = static_cast<size_t>(stride) * aligned_height;
task.last_submitted_offset = 0; task.last_submitted_offset = 0;
task.slices_submitted = 0;
task.initialized = true; task.initialized = true;
} }
@@ -1452,31 +1470,39 @@ void TextureCache<P>::TickAsyncUnswizzle() {
if (copy_amount == 0) copy_amount = task.bytes_per_slice; if (copy_amount == 0) copy_amount = task.bytes_per_slice;
} }
gpu_memory->ReadBlock(image.gpu_addr + task.current_offset, gpu_memory->ReadBlockUnsafe(image.gpu_addr + task.current_offset,
task.staging_buffer.mapped_span.data() + task.current_offset, task.staging_buffer.mapped_span.data() + task.current_offset,
copy_amount); copy_amount);
task.current_offset += copy_amount; task.current_offset += copy_amount;
} }
const bool is_final_batch = task.current_offset >= task.total_size; const bool is_final_batch = task.current_offset >= task.total_size;
if (task.chunked) {
const size_t bytes_ready = task.current_offset - task.last_submitted_offset; const size_t bytes_ready = task.current_offset - task.last_submitted_offset;
const u32 complete_slices = static_cast<u32>(bytes_ready / task.bytes_per_slice); const u32 complete_slices = static_cast<u32>(bytes_ready / task.bytes_per_slice);
if (complete_slices >= swizzle_slices_per_batch || (is_final_batch && complete_slices > 0)) { if (complete_slices >= swizzle_slices_per_batch || (is_final_batch && complete_slices > 0)) {
const u32 z_start = static_cast<u32>(task.last_submitted_offset / task.bytes_per_slice); const u32 z_start = task.slices_submitted;
const u32 slices_to_process = (std::min)(complete_slices, swizzle_slices_per_batch); const u32 slices_to_process = (std::min)(complete_slices, swizzle_slices_per_batch);
const u32 z_count = (std::min)(slices_to_process, image.info.size.depth - z_start); const u32 z_count = (std::min)(slices_to_process, image.info.size.depth - z_start);
if (z_count > 0) { if (z_count > 0) {
const auto uploads = FullUploadSwizzles(task.info); const auto uploads = FullUploadSwizzles(task.info);
runtime.AccelerateImageUpload(image, task.staging_buffer, FixSmallVectorADL(uploads), z_start, z_count); runtime.AccelerateImageUpload(image, task.staging_buffer,
task.last_submitted_offset += (static_cast<size_t>(z_count) * task.bytes_per_slice); FixSmallVectorADL(uploads), z_start, z_count);
task.last_submitted_offset += static_cast<size_t>(z_count) * task.bytes_per_slice;
task.slices_submitted += z_count;
} }
} }
} else if (is_final_batch && task.slices_submitted == 0) {
const auto uploads = FullUploadSwizzles(task.info);
runtime.AccelerateImageUpload(image, task.staging_buffer, FixSmallVectorADL(uploads), 0,
image.info.size.depth);
task.slices_submitted = image.info.size.depth;
}
// Check if complete const bool all_slices_submitted = task.slices_submitted >= image.info.size.depth;
const u32 slices_submitted = static_cast<u32>(task.last_submitted_offset / task.bytes_per_slice);
const bool all_slices_submitted = slices_submitted >= image.info.size.depth;
if (is_final_batch && all_slices_submitted) { if (is_final_batch && all_slices_submitted) {
runtime.FreeDeferredStagingBuffer(task.staging_buffer); runtime.FreeDeferredStagingBuffer(task.staging_buffer);
@@ -139,6 +139,8 @@ class TextureCache : public VideoCommon::ChannelSetupCaches<TextureCacheChannelI
AsyncBuffer staging_buffer; AsyncBuffer staging_buffer;
size_t last_submitted_offset = 0; size_t last_submitted_offset = 0;
size_t bytes_per_slice; size_t bytes_per_slice;
u32 slices_submitted = 0;
bool chunked = false;
bool initialized = false; bool initialized = false;
}; };
@@ -1219,6 +1219,11 @@ bool Device::GetSuitability(bool requires_swapchain) {
VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_TRANSFORM_FEEDBACK_PROPERTIES_EXT; VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_TRANSFORM_FEEDBACK_PROPERTIES_EXT;
SetNext(next, properties.transform_feedback); SetNext(next, properties.transform_feedback);
} }
if (extensions.vertex_attribute_divisor) {
properties.vertex_attribute_divisor.sType =
VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VERTEX_ATTRIBUTE_DIVISOR_PROPERTIES_EXT;
SetNext(next, properties.vertex_attribute_divisor);
}
if (extensions.maintenance5) { if (extensions.maintenance5) {
properties.maintenance5.sType = properties.maintenance5.sType =
VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MAINTENANCE_5_PROPERTIES_KHR; VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MAINTENANCE_5_PROPERTIES_KHR;
+29 -1
View File
@@ -70,6 +70,7 @@ VK_DEFINE_HANDLE(VmaAllocator)
FEATURE(EXT, ProvokingVertex, PROVOKING_VERTEX, provoking_vertex) \ FEATURE(EXT, ProvokingVertex, PROVOKING_VERTEX, provoking_vertex) \
FEATURE(EXT, Robustness2, ROBUSTNESS_2, robustness2) \ FEATURE(EXT, Robustness2, ROBUSTNESS_2, robustness2) \
FEATURE(EXT, TransformFeedback, TRANSFORM_FEEDBACK, transform_feedback) \ FEATURE(EXT, TransformFeedback, TRANSFORM_FEEDBACK, transform_feedback) \
FEATURE(EXT, VertexAttributeDivisor, VERTEX_ATTRIBUTE_DIVISOR, vertex_attribute_divisor) \
FEATURE(EXT, VertexInputDynamicState, VERTEX_INPUT_DYNAMIC_STATE, vertex_input_dynamic_state) \ FEATURE(EXT, VertexInputDynamicState, VERTEX_INPUT_DYNAMIC_STATE, vertex_input_dynamic_state) \
FEATURE(KHR, Maintenance5, MAINTENANCE_5, maintenance5) \ FEATURE(KHR, Maintenance5, MAINTENANCE_5, maintenance5) \
FEATURE(KHR, Maintenance6, MAINTENANCE_6, maintenance6) \ FEATURE(KHR, Maintenance6, MAINTENANCE_6, maintenance6) \
@@ -92,7 +93,6 @@ VK_DEFINE_HANDLE(VmaAllocator)
EXTENSION(EXT, SHADER_STENCIL_EXPORT, shader_stencil_export) \ EXTENSION(EXT, SHADER_STENCIL_EXPORT, shader_stencil_export) \
EXTENSION(EXT, SHADER_VIEWPORT_INDEX_LAYER, shader_viewport_index_layer) \ EXTENSION(EXT, SHADER_VIEWPORT_INDEX_LAYER, shader_viewport_index_layer) \
EXTENSION(EXT, TOOLING_INFO, tooling_info) \ EXTENSION(EXT, TOOLING_INFO, tooling_info) \
EXTENSION(EXT, VERTEX_ATTRIBUTE_DIVISOR, vertex_attribute_divisor) \
EXTENSION(KHR, CREATE_RENDERPASS_2, create_renderpass2) \ EXTENSION(KHR, CREATE_RENDERPASS_2, create_renderpass2) \
EXTENSION(KHR, DEPTH_STENCIL_RESOLVE, depth_stencil_resolve) \ EXTENSION(KHR, DEPTH_STENCIL_RESOLVE, depth_stencil_resolve) \
EXTENSION(KHR, DRAW_INDIRECT_COUNT, draw_indirect_count) \ EXTENSION(KHR, DRAW_INDIRECT_COUNT, draw_indirect_count) \
@@ -359,6 +359,7 @@ public:
#define FN_MAX_LIMIT_LIST \ #define FN_MAX_LIMIT_LIST \
FN_MAX_LIMIT_ELEM(ComputeSharedMemorySize) \ FN_MAX_LIMIT_ELEM(ComputeSharedMemorySize) \
FN_MAX_LIMIT_ELEM(ComputeWorkGroupInvocations) \
FN_MAX_LIMIT_ELEM(PerStageDescriptorSampledImages) \ FN_MAX_LIMIT_ELEM(PerStageDescriptorSampledImages) \
FN_MAX_LIMIT_ELEM(PerStageResources) \ FN_MAX_LIMIT_ELEM(PerStageResources) \
FN_MAX_LIMIT_ELEM(DescriptorSetSamplers) \ FN_MAX_LIMIT_ELEM(DescriptorSetSamplers) \
@@ -689,6 +690,32 @@ FN_MAX_LIMIT_LIST
return features.host_query_reset.hostQueryReset != VK_FALSE; return features.host_query_reset.hostQueryReset != VK_FALSE;
} }
u32 GetMaxVertexAttribDivisor() const {
const u32 reported = properties.vertex_attribute_divisor.maxVertexAttribDivisor;
if (reported == 0) {
return 1;
}
return reported;
}
bool IsVertexAttributeInstanceRateZeroDivisorSupported() const {
return features.vertex_attribute_divisor.vertexAttributeInstanceRateZeroDivisor == VK_TRUE;
}
u32 GetVertexAttribDivisor(u32 frequency) const {
const u32 max_divisor = GetMaxVertexAttribDivisor();
if (frequency == 0) {
if (IsVertexAttributeInstanceRateZeroDivisorSupported()) {
return 0;
}
return max_divisor;
}
if (frequency > max_divisor) {
return max_divisor;
}
return frequency;
}
/// Returns true if the device supports VK_EXT_transform_feedback. /// Returns true if the device supports VK_EXT_transform_feedback.
bool IsExtTransformFeedbackSupported() const { bool IsExtTransformFeedbackSupported() const {
return extensions.transform_feedback; return extensions.transform_feedback;
@@ -1189,6 +1216,7 @@ private:
VkPhysicalDeviceDescriptorBufferPropertiesEXT descriptor_buffer{}; VkPhysicalDeviceDescriptorBufferPropertiesEXT descriptor_buffer{};
VkPhysicalDeviceSubgroupSizeControlProperties subgroup_size_control{}; VkPhysicalDeviceSubgroupSizeControlProperties subgroup_size_control{};
VkPhysicalDeviceTransformFeedbackPropertiesEXT transform_feedback{}; VkPhysicalDeviceTransformFeedbackPropertiesEXT transform_feedback{};
VkPhysicalDeviceVertexAttributeDivisorPropertiesEXT vertex_attribute_divisor{};
VkPhysicalDeviceMaintenance5PropertiesKHR maintenance5{}; VkPhysicalDeviceMaintenance5PropertiesKHR maintenance5{};
VkPhysicalDeviceDepthStencilResolveProperties depth_stencil_resolve{}; VkPhysicalDeviceDepthStencilResolveProperties depth_stencil_resolve{};
VkPhysicalDeviceCustomBorderColorPropertiesEXT custom_border_color{}; VkPhysicalDeviceCustomBorderColorPropertiesEXT custom_border_color{};
@@ -2936,10 +2936,10 @@ void PlayerControlPreview::DrawArrow(QPainter& p, const QPointF center, const Di
} }
// Draw motion functions // Draw motion functions
void PlayerControlPreview::Draw3dCube(QPainter& p, QPointF center, const Common::Vec<f32, 3>& euler, void PlayerControlPreview::Draw3dCube(QPainter& p, QPointF center, const Common::Vec3f& euler,
float size) { float size) {
std::array<Common::Vec<f32, 3>, 8> cube{ std::array<Common::Vec3f, 8> cube{
Common::Vec<f32, 3>{-0.7f, -1, -0.5f}, Common::Vec3f{-0.7f, -1, -0.5f},
{-0.7f, 1, -0.5f}, {-0.7f, 1, -0.5f},
{0.7f, 1, -0.5f}, {0.7f, 1, -0.5f},
{0.7f, -1, -0.5f}, {0.7f, -1, -0.5f},
@@ -2949,38 +2949,30 @@ void PlayerControlPreview::Draw3dCube(QPainter& p, QPointF center, const Common:
{0.7f, -1, 0.5f}, {0.7f, -1, 0.5f},
}; };
for (Common::Vec<f32, 3>& point : cube) { for (Common::Vec3f& point : cube) {
float temp = point[1]; point.RotateFromOrigin(euler.x, euler.y, euler.z);
point[1] = std::cos(euler[0]) * point[1] - std::sin(euler[0]) * point[2];
point[2] = std::sin(euler[0]) * temp + std::cos(euler[0]) * point[2];
temp = point[0];
point[0] = std::cos(euler[1]) * point[0] + std::sin(euler[1]) * point[2];
point[2] = -std::sin(euler[1]) * temp + std::cos(euler[1]) * point[2];
temp = point[0];
point[0] = std::cos(euler[2]) * point[0] - std::sin(euler[2]) * point[1];
point[1] = std::sin(euler[2]) * temp + std::cos(euler[2]) * point[1];
point *= size; point *= size;
} }
const std::array<QPointF, 4> front_face{ const std::array<QPointF, 4> front_face{
center + QPointF{cube[0][0], cube[0][1]}, center + QPointF{cube[0].x, cube[0].y},
center + QPointF{cube[1][0], cube[1][1]}, center + QPointF{cube[1].x, cube[1].y},
center + QPointF{cube[2][0], cube[2][1]}, center + QPointF{cube[2].x, cube[2].y},
center + QPointF{cube[3][0], cube[3][1]}, center + QPointF{cube[3].x, cube[3].y},
}; };
const std::array<QPointF, 4> back_face{ const std::array<QPointF, 4> back_face{
center + QPointF{cube[4][0], cube[4][1]}, center + QPointF{cube[4].x, cube[4].y},
center + QPointF{cube[5][0], cube[5][1]}, center + QPointF{cube[5].x, cube[5].y},
center + QPointF{cube[6][0], cube[6][1]}, center + QPointF{cube[6].x, cube[6].y},
center + QPointF{cube[7][0], cube[7][1]}, center + QPointF{cube[7].x, cube[7].y},
}; };
DrawPolygon(p, front_face); DrawPolygon(p, front_face);
DrawPolygon(p, back_face); DrawPolygon(p, back_face);
p.drawLine(center + QPointF{cube[0][0], cube[0][1]}, center + QPointF{cube[4][0], cube[4][1]}); p.drawLine(center + QPointF{cube[0].x, cube[0].y}, center + QPointF{cube[4].x, cube[4].y});
p.drawLine(center + QPointF{cube[1][0], cube[1][1]}, center + QPointF{cube[5][0], cube[5][1]}); p.drawLine(center + QPointF{cube[1].x, cube[1].y}, center + QPointF{cube[5].x, cube[5].y});
p.drawLine(center + QPointF{cube[2][0], cube[2][1]}, center + QPointF{cube[6][0], cube[6][1]}); p.drawLine(center + QPointF{cube[2].x, cube[2].y}, center + QPointF{cube[6].x, cube[6].y});
p.drawLine(center + QPointF{cube[3][0], cube[3][1]}, center + QPointF{cube[7][0], cube[7][1]}); p.drawLine(center + QPointF{cube[3].x, cube[3].y}, center + QPointF{cube[7].x, cube[7].y});
} }
template <size_t N> template <size_t N>
@@ -1,4 +1,4 @@
// SPDX-FileCopyrightText: Copyright 2026 Eden Emulator Project // SPDX-FileCopyrightText: Copyright 2025 Eden Emulator Project
// SPDX-License-Identifier: GPL-3.0-or-later // SPDX-License-Identifier: GPL-3.0-or-later
// SPDX-FileCopyrightText: Copyright 2020 yuzu Emulator Project // SPDX-FileCopyrightText: Copyright 2020 yuzu Emulator Project
@@ -198,7 +198,7 @@ private:
void DrawArrow(QPainter& p, QPointF center, Direction direction, float size); void DrawArrow(QPainter& p, QPointF center, Direction direction, float size);
// Draw motion functions // Draw motion functions
void Draw3dCube(QPainter& p, QPointF center, const Common::Vec<f32, 3>& euler, float size); void Draw3dCube(QPainter& p, QPointF center, const Common::Vec3f& euler, float size);
// Draw primitive types // Draw primitive types
template <size_t N> template <size_t N>