summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--externals/CMakeLists.txt3
-rw-r--r--externals/bc_decoder/bc_decoder.cpp1522
-rw-r--r--externals/bc_decoder/bc_decoder.h43
-rw-r--r--src/android/app/build.gradle.kts4
-rw-r--r--src/android/app/src/main/AndroidManifest.xml5
-rw-r--r--src/common/input.h2
-rw-r--r--src/input_common/drivers/joycon.cpp35
-rw-r--r--src/input_common/drivers/joycon.h3
-rw-r--r--src/input_common/helpers/joycon_driver.cpp129
-rw-r--r--src/input_common/helpers/joycon_driver.h48
-rw-r--r--src/input_common/helpers/joycon_protocol/calibration.cpp53
-rw-r--r--src/input_common/helpers/joycon_protocol/calibration.h15
-rw-r--r--src/input_common/helpers/joycon_protocol/common_protocol.cpp104
-rw-r--r--src/input_common/helpers/joycon_protocol/common_protocol.h44
-rw-r--r--src/input_common/helpers/joycon_protocol/generic_functions.cpp52
-rw-r--r--src/input_common/helpers/joycon_protocol/generic_functions.h41
-rw-r--r--src/input_common/helpers/joycon_protocol/irs.cpp70
-rw-r--r--src/input_common/helpers/joycon_protocol/irs.h22
-rw-r--r--src/input_common/helpers/joycon_protocol/joycon_types.h17
-rw-r--r--src/input_common/helpers/joycon_protocol/nfc.cpp231
-rw-r--r--src/input_common/helpers/joycon_protocol/nfc.h66
-rw-r--r--src/input_common/helpers/joycon_protocol/ringcon.cpp45
-rw-r--r--src/input_common/helpers/joycon_protocol/ringcon.h14
-rw-r--r--src/input_common/helpers/joycon_protocol/rumble.cpp5
-rw-r--r--src/input_common/helpers/joycon_protocol/rumble.h8
-rw-r--r--src/video_core/CMakeLists.txt6
-rw-r--r--src/video_core/renderer_vulkan/blit_image.cpp3
-rw-r--r--src/video_core/renderer_vulkan/maxwell_to_vk.cpp20
-rw-r--r--src/video_core/renderer_vulkan/renderer_vulkan.cpp18
-rw-r--r--src/video_core/renderer_vulkan/renderer_vulkan.h5
-rw-r--r--src/video_core/renderer_vulkan/vk_buffer_cache.cpp3
-rw-r--r--src/video_core/renderer_vulkan/vk_graphics_pipeline.cpp5
-rw-r--r--src/video_core/renderer_vulkan/vk_pipeline_cache.cpp7
-rw-r--r--src/video_core/renderer_vulkan/vk_rasterizer.cpp23
-rw-r--r--src/video_core/renderer_vulkan/vk_staging_buffer_pool.cpp16
-rw-r--r--src/video_core/renderer_vulkan/vk_texture_cache.cpp4
-rw-r--r--src/video_core/surface.cpp22
-rw-r--r--src/video_core/surface.h2
-rw-r--r--src/video_core/texture_cache/decode_bc.cpp129
-rw-r--r--src/video_core/texture_cache/decode_bc.h (renamed from src/video_core/texture_cache/decode_bc4.h)6
-rw-r--r--src/video_core/texture_cache/decode_bc4.cpp96
-rw-r--r--src/video_core/texture_cache/util.cpp24
-rw-r--r--src/video_core/textures/bcn.cpp1
-rw-r--r--src/video_core/textures/bcn.h9
-rw-r--r--src/video_core/vulkan_common/vulkan_debug_callback.cpp40
-rw-r--r--src/video_core/vulkan_common/vulkan_debug_callback.h4
-rw-r--r--src/video_core/vulkan_common/vulkan_device.cpp14
-rw-r--r--src/video_core/vulkan_common/vulkan_device.h35
-rw-r--r--src/video_core/vulkan_common/vulkan_instance.cpp58
-rw-r--r--src/video_core/vulkan_common/vulkan_wrapper.cpp14
-rw-r--r--src/video_core/vulkan_common/vulkan_wrapper.h9
-rw-r--r--src/yuzu/configuration/configure_ringcon.cpp3
52 files changed, 2500 insertions, 657 deletions
diff --git a/externals/CMakeLists.txt b/externals/CMakeLists.txt
index 0184289eb..4ff588851 100644
--- a/externals/CMakeLists.txt
+++ b/externals/CMakeLists.txt
@@ -157,6 +157,9 @@ endif()
add_library(stb stb/stb_dxt.cpp)
target_include_directories(stb PUBLIC ./stb)
+add_library(bc_decoder bc_decoder/bc_decoder.cpp)
+target_include_directories(bc_decoder PUBLIC ./bc_decoder)
+
if (ANDROID)
if (ARCHITECTURE_arm64)
add_subdirectory(libadrenotools)
diff --git a/externals/bc_decoder/bc_decoder.cpp b/externals/bc_decoder/bc_decoder.cpp
new file mode 100644
index 000000000..536c44f34
--- /dev/null
+++ b/externals/bc_decoder/bc_decoder.cpp
@@ -0,0 +1,1522 @@
+// SPDX-License-Identifier: MPL-2.0
+// Copyright © 2022 Skyline Team and Contributors (https://github.com/skyline-emu/)
+// Copyright 2019 The SwiftShader Authors. All Rights Reserved.
+
+// This BCn Decoder is directly derivative of Swiftshader's BCn Decoder found at: https://github.com/google/swiftshader/blob/d070309f7d154d6764cbd514b1a5c8bfcef61d06/src/Device/BC_Decoder.cpp
+// This file does not follow the Skyline code conventions but has certain Skyline specific code
+// There are a lot of implicit and narrowing conversions in this file due to this (Warnings are disabled as a result)
+
+#include <array>
+#include <assert.h>
+#include <stddef.h>
+#include <stdint.h>
+
+namespace {
+ constexpr int BlockWidth = 4;
+ constexpr int BlockHeight = 4;
+
+ struct BC_color {
+ void decode(uint8_t *dst, size_t x, size_t y, size_t dstW, size_t dstH, size_t dstPitch, size_t dstBpp, bool hasAlphaChannel, bool hasSeparateAlpha) const {
+ Color c[4];
+ c[0].extract565(c0);
+ c[1].extract565(c1);
+ if (hasSeparateAlpha || (c0 > c1)) {
+ c[2] = ((c[0] * 2) + c[1]) / 3;
+ c[3] = ((c[1] * 2) + c[0]) / 3;
+ } else {
+ c[2] = (c[0] + c[1]) >> 1;
+ if (hasAlphaChannel) {
+ c[3].clearAlpha();
+ }
+ }
+
+ for (int j = 0; j < BlockHeight && (y + j) < dstH; j++) {
+ size_t dstOffset = j * dstPitch;
+ size_t idxOffset = j * BlockHeight;
+ for (size_t i = 0; i < BlockWidth && (x + i) < dstW; i++, idxOffset++, dstOffset += dstBpp) {
+ *reinterpret_cast<unsigned int *>(dst + dstOffset) = c[getIdx(idxOffset)].pack8888();
+ }
+ }
+ }
+
+ private:
+ struct Color {
+ Color() {
+ c[0] = c[1] = c[2] = 0;
+ c[3] = 0xFF000000;
+ }
+
+ void extract565(const unsigned int c565) {
+ c[0] = ((c565 & 0x0000001F) << 3) | ((c565 & 0x0000001C) >> 2);
+ c[1] = ((c565 & 0x000007E0) >> 3) | ((c565 & 0x00000600) >> 9);
+ c[2] = ((c565 & 0x0000F800) >> 8) | ((c565 & 0x0000E000) >> 13);
+ }
+
+ unsigned int pack8888() const {
+ return ((c[0] & 0xFF) << 16) | ((c[1] & 0xFF) << 8) | (c[2] & 0xFF) | c[3];
+ }
+
+ void clearAlpha() {
+ c[3] = 0;
+ }
+
+ Color operator*(int factor) const {
+ Color res;
+ for (int i = 0; i < 4; ++i) {
+ res.c[i] = c[i] * factor;
+ }
+ return res;
+ }
+
+ Color operator/(int factor) const {
+ Color res;
+ for (int i = 0; i < 4; ++i) {
+ res.c[i] = c[i] / factor;
+ }
+ return res;
+ }
+
+ Color operator>>(int shift) const {
+ Color res;
+ for (int i = 0; i < 4; ++i) {
+ res.c[i] = c[i] >> shift;
+ }
+ return res;
+ }
+
+ Color operator+(Color const &obj) const {
+ Color res;
+ for (int i = 0; i < 4; ++i) {
+ res.c[i] = c[i] + obj.c[i];
+ }
+ return res;
+ }
+
+ private:
+ int c[4];
+ };
+
+ size_t getIdx(int i) const {
+ size_t offset = i << 1; // 2 bytes per index
+ return (idx & (0x3 << offset)) >> offset;
+ }
+
+ unsigned short c0;
+ unsigned short c1;
+ unsigned int idx;
+ };
+ static_assert(sizeof(BC_color) == 8, "BC_color must be 8 bytes");
+
+ struct BC_channel {
+ void decode(uint8_t *dst, size_t x, size_t y, size_t dstW, size_t dstH, size_t dstPitch, size_t dstBpp, size_t channel, bool isSigned) const {
+ int c[8] = {0};
+
+ if (isSigned) {
+ c[0] = static_cast<signed char>(data & 0xFF);
+ c[1] = static_cast<signed char>((data & 0xFF00) >> 8);
+ } else {
+ c[0] = static_cast<uint8_t>(data & 0xFF);
+ c[1] = static_cast<uint8_t>((data & 0xFF00) >> 8);
+ }
+
+ if (c[0] > c[1]) {
+ for (int i = 2; i < 8; ++i) {
+ c[i] = ((8 - i) * c[0] + (i - 1) * c[1]) / 7;
+ }
+ } else {
+ for (int i = 2; i < 6; ++i) {
+ c[i] = ((6 - i) * c[0] + (i - 1) * c[1]) / 5;
+ }
+ c[6] = isSigned ? -128 : 0;
+ c[7] = isSigned ? 127 : 255;
+ }
+
+ for (size_t j = 0; j < BlockHeight && (y + j) < dstH; j++) {
+ for (size_t i = 0; i < BlockWidth && (x + i) < dstW; i++) {
+ dst[channel + (i * dstBpp) + (j * dstPitch)] = static_cast<uint8_t>(c[getIdx((j * BlockHeight) + i)]);
+ }
+ }
+ }
+
+ private:
+ uint8_t getIdx(int i) const {
+ int offset = i * 3 + 16;
+ return static_cast<uint8_t>((data & (0x7ull << offset)) >> offset);
+ }
+
+ uint64_t data;
+ };
+ static_assert(sizeof(BC_channel) == 8, "BC_channel must be 8 bytes");
+
+ struct BC_alpha {
+ void decode(uint8_t *dst, size_t x, size_t y, size_t dstW, size_t dstH, size_t dstPitch, size_t dstBpp) const {
+ dst += 3; // Write only to alpha (channel 3)
+ for (size_t j = 0; j < BlockHeight && (y + j) < dstH; j++, dst += dstPitch) {
+ uint8_t *dstRow = dst;
+ for (size_t i = 0; i < BlockWidth && (x + i) < dstW; i++, dstRow += dstBpp) {
+ *dstRow = getAlpha(j * BlockHeight + i);
+ }
+ }
+ }
+
+ private:
+ uint8_t getAlpha(int i) const {
+ int offset = i << 2;
+ int alpha = (data & (0xFull << offset)) >> offset;
+ return static_cast<uint8_t>(alpha | (alpha << 4));
+ }
+
+ uint64_t data;
+ };
+ static_assert(sizeof(BC_alpha) == 8, "BC_alpha must be 8 bytes");
+
+ namespace BC6H {
+ static constexpr int MaxPartitions = 64;
+
+ // @fmt:off
+
+ static constexpr uint8_t PartitionTable2[MaxPartitions][16] = {
+ { 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1 },
+ { 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1 },
+ { 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1 },
+ { 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 1 },
+ { 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 1 },
+ { 0, 0, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1 },
+ { 0, 0, 0, 1, 0, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1 },
+ { 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 1, 1, 1 },
+ { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1 },
+ { 0, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 },
+ { 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1 },
+ { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 1 },
+ { 0, 0, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 },
+ { 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1 },
+ { 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 },
+ { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1 },
+ { 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 0, 1, 1, 1, 1 },
+ { 0, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0 },
+ { 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 0 },
+ { 0, 1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0 },
+ { 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0 },
+ { 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0 },
+ { 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0 },
+ { 0, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1 },
+ { 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0 },
+ { 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0 },
+ { 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0 },
+ { 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0 },
+ { 0, 0, 0, 1, 0, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0 },
+ { 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0 },
+ { 0, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 0 },
+ { 0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0 },
+ { 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1 },
+ { 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1 },
+ { 0, 1, 0, 1, 1, 0, 1, 0, 0, 1, 0, 1, 1, 0, 1, 0 },
+ { 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0 },
+ { 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0 },
+ { 0, 1, 0, 1, 0, 1, 0, 1, 1, 0, 1, 0, 1, 0, 1, 0 },
+ { 0, 1, 1, 0, 1, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 1 },
+ { 0, 1, 0, 1, 1, 0, 1, 0, 1, 0, 1, 0, 0, 1, 0, 1 },
+ { 0, 1, 1, 1, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 1, 0 },
+ { 0, 0, 0, 1, 0, 0, 1, 1, 1, 1, 0, 0, 1, 0, 0, 0 },
+ { 0, 0, 1, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 1, 0, 0 },
+ { 0, 0, 1, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 0, 0 },
+ { 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0 },
+ { 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1 },
+ { 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1 },
+ { 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0 },
+ { 0, 1, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0 },
+ { 0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0 },
+ { 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 1, 0 },
+ { 0, 0, 0, 0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0 },
+ { 0, 1, 1, 0, 1, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 1 },
+ { 0, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 0, 1, 0, 0, 1 },
+ { 0, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 1, 0, 0 },
+ { 0, 0, 1, 1, 1, 0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 0 },
+ { 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 0, 0, 1 },
+ { 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 1 },
+ { 0, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 1 },
+ { 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 1 },
+ { 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1 },
+ { 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0 },
+ { 0, 0, 1, 0, 0, 0, 1, 0, 1, 1, 1, 0, 1, 1, 1, 0 },
+ { 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 0, 1, 1, 1 },
+ };
+
+ static constexpr uint8_t AnchorTable2[MaxPartitions] = {
+ 0xf, 0xf, 0xf, 0xf, 0xf, 0xf, 0xf, 0xf,
+ 0xf, 0xf, 0xf, 0xf, 0xf, 0xf, 0xf, 0xf,
+ 0xf, 0x2, 0x8, 0x2, 0x2, 0x8, 0x8, 0xf,
+ 0x2, 0x8, 0x2, 0x2, 0x8, 0x8, 0x2, 0x2,
+ 0xf, 0xf, 0x6, 0x8, 0x2, 0x8, 0xf, 0xf,
+ 0x2, 0x8, 0x2, 0x2, 0x2, 0xf, 0xf, 0x6,
+ 0x6, 0x2, 0x6, 0x8, 0xf, 0xf, 0x2, 0x2,
+ 0xf, 0xf, 0xf, 0xf, 0xf, 0x2, 0x2, 0xf,
+ };
+
+ // @fmt:on
+
+ // 1.0f in half-precision floating point format
+ static constexpr uint16_t halfFloat1 = 0x3C00;
+ union Color {
+ struct RGBA {
+ uint16_t r = 0;
+ uint16_t g = 0;
+ uint16_t b = 0;
+ uint16_t a = halfFloat1;
+
+ RGBA(uint16_t r, uint16_t g, uint16_t b)
+ : r(r), g(g), b(b) {
+ }
+
+ RGBA &operator=(const RGBA &other) {
+ this->r = other.r;
+ this->g = other.g;
+ this->b = other.b;
+ this->a = halfFloat1;
+
+ return *this;
+ }
+ };
+
+ Color(uint16_t r, uint16_t g, uint16_t b)
+ : rgba(r, g, b) {
+ }
+
+ Color(int r, int g, int b)
+ : rgba((uint16_t) r, (uint16_t) g, (uint16_t) b) {
+ }
+
+ Color() {}
+
+ Color(const Color &other) {
+ this->rgba = other.rgba;
+ }
+
+ Color &operator=(const Color &other) {
+ this->rgba = other.rgba;
+
+ return *this;
+ }
+
+ RGBA rgba;
+ uint16_t channel[4];
+ };
+ static_assert(sizeof(Color) == 8, "BC6h::Color must be 8 bytes long");
+
+ inline int32_t extendSign(int32_t val, size_t size) {
+ // Suppose we have a 2-bit integer being stored in 4 bit variable:
+ // x = 0b00AB
+ //
+ // In order to sign extend x, we need to turn the 0s into A's:
+ // x_extend = 0bAAAB
+ //
+ // We can do that by flipping A in x then subtracting 0b0010 from x.
+ // Suppose A is 1:
+ // x = 0b001B
+ // x_flip = 0b000B
+ // x_minus = 0b111B
+ // Since A is flipped to 0, subtracting the mask sets it and all the bits above it to 1.
+ // And if A is 0:
+ // x = 0b000B
+ // x_flip = 0b001B
+ // x_minus = 0b000B
+ // We unset the bit we flipped, and touch no other bit
+ uint16_t mask = 1u << (size - 1);
+ return (val ^ mask) - mask;
+ }
+
+ static int constexpr RGBfChannels = 3;
+ struct RGBf {
+ uint16_t channel[RGBfChannels];
+ size_t size[RGBfChannels];
+ bool isSigned;
+
+ RGBf() {
+ static_assert(RGBfChannels == 3, "RGBf must have exactly 3 channels");
+ static_assert(sizeof(channel) / sizeof(channel[0]) == RGBfChannels, "RGBf must have exactly 3 channels");
+ static_assert(sizeof(channel) / sizeof(channel[0]) == sizeof(size) / sizeof(size[0]), "RGBf requires equally sized arrays for channels and channel sizes");
+
+ for (int i = 0; i < RGBfChannels; i++) {
+ channel[i] = 0;
+ size[i] = 0;
+ }
+
+ isSigned = false;
+ }
+
+ void extendSign() {
+ for (int i = 0; i < RGBfChannels; i++) {
+ channel[i] = BC6H::extendSign(channel[i], size[i]);
+ }
+ }
+
+ // Assuming this is the delta, take the base-endpoint and transform this into
+ // a proper endpoint.
+ //
+ // The final computed endpoint is truncated to the base-endpoint's size;
+ void resolveDelta(RGBf base) {
+ for (int i = 0; i < RGBfChannels; i++) {
+ size[i] = base.size[i];
+ channel[i] = (base.channel[i] + channel[i]) & ((1 << base.size[i]) - 1);
+ }
+
+ // Per the spec:
+ // "For signed formats, the results of the delta calculation must be sign
+ // extended as well."
+ if (isSigned) {
+ extendSign();
+ }
+ }
+
+ void unquantize() {
+ if (isSigned) {
+ unquantizeSigned();
+ } else {
+ unquantizeUnsigned();
+ }
+ }
+
+ void unquantizeUnsigned() {
+ for (int i = 0; i < RGBfChannels; i++) {
+ if (size[i] >= 15 || channel[i] == 0) {
+ continue;
+ } else if (channel[i] == ((1u << size[i]) - 1)) {
+ channel[i] = 0xFFFFu;
+ } else {
+ // Need 32 bits to avoid overflow
+ uint32_t tmp = channel[i];
+ channel[i] = (uint16_t) (((tmp << 16) + 0x8000) >> size[i]);
+ }
+ size[i] = 16;
+ }
+ }
+
+ void unquantizeSigned() {
+ for (int i = 0; i < RGBfChannels; i++) {
+ if (size[i] >= 16 || channel[i] == 0) {
+ continue;
+ }
+
+ int16_t value = (int16_t)channel[i];
+ int32_t result = value;
+ bool signBit = value < 0;
+ if (signBit) {
+ value = -value;
+ }
+
+ if (value >= ((1 << (size[i] - 1)) - 1)) {
+ result = 0x7FFF;
+ } else {
+ // Need 32 bits to avoid overflow
+ int32_t tmp = value;
+ result = (((tmp << 15) + 0x4000) >> (size[i] - 1));
+ }
+
+ if (signBit) {
+ result = -result;
+ }
+
+ channel[i] = (uint16_t) result;
+ size[i] = 16;
+ }
+ }
+ };
+
+ struct Data {
+ uint64_t low64;
+ uint64_t high64;
+
+ Data() = default;
+
+ Data(uint64_t low64, uint64_t high64)
+ : low64(low64), high64(high64) {
+ }
+
+ // Consumes the lowest N bits from from low64 and high64 where N is:
+ // abs(MSB - LSB)
+ // MSB and LSB come from the block description of the BC6h spec and specify
+ // the location of the bits in the returned bitstring.
+ //
+ // If MSB < LSB, then the bits are reversed. Otherwise, the bitstring is read and
+ // shifted without further modification.
+ //
+ uint32_t consumeBits(uint32_t MSB, uint32_t LSB) {
+ bool reversed = MSB < LSB;
+ if (reversed) {
+ std::swap(MSB, LSB);
+ }
+ assert(MSB - LSB + 1 < sizeof(uint32_t) * 8);
+
+ uint32_t numBits = MSB - LSB + 1;
+ uint32_t mask = (1 << numBits) - 1;
+ // Read the low N bits
+ uint32_t bits = (low64 & mask);
+
+ low64 >>= numBits;
+ // Put the low N bits of high64 into the high 64-N bits of low64
+ low64 |= (high64 & mask) << (sizeof(high64) * 8 - numBits);
+ high64 >>= numBits;
+
+ if (reversed) {
+ uint32_t tmp = 0;
+ for (uint32_t numSwaps = 0; numSwaps < numBits; numSwaps++) {
+ tmp <<= 1;
+ tmp |= (bits & 1);
+ bits >>= 1;
+ }
+
+ bits = tmp;
+ }
+
+ return bits << LSB;
+ }
+ };
+
+ struct IndexInfo {
+ uint64_t value;
+ int numBits;
+ };
+
+// Interpolates between two endpoints, then does a final unquantization step
+ Color interpolate(RGBf e0, RGBf e1, const IndexInfo &index, bool isSigned) {
+ static constexpr uint32_t weights3[] = {0, 9, 18, 27, 37, 46, 55, 64};
+ static constexpr uint32_t weights4[] = {0, 4, 9, 13, 17, 21, 26, 30,
+ 34, 38, 43, 47, 51, 55, 60, 64};
+ static constexpr uint32_t const *weightsN[] = {
+ nullptr, nullptr, nullptr, weights3, weights4
+ };
+ auto weights = weightsN[index.numBits];
+ assert(weights != nullptr);
+ Color color;
+ uint32_t e0Weight = 64 - weights[index.value];
+ uint32_t e1Weight = weights[index.value];
+
+ for (int i = 0; i < RGBfChannels; i++) {
+ int32_t e0Channel = e0.channel[i];
+ int32_t e1Channel = e1.channel[i];
+
+ if (isSigned) {
+ e0Channel = extendSign(e0Channel, 16);
+ e1Channel = extendSign(e1Channel, 16);
+ }
+
+ int32_t e0Value = e0Channel * e0Weight;
+ int32_t e1Value = e1Channel * e1Weight;
+
+ uint32_t tmp = ((e0Value + e1Value + 32) >> 6);
+
+ // Need to unquantize value to limit it to the legal range of half-precision
+ // floats. We do this by scaling by 31/32 or 31/64 depending on if the value
+ // is signed or unsigned.
+ if (isSigned) {
+ tmp = ((tmp & 0x80000000) != 0) ? (((~tmp + 1) * 31) >> 5) | 0x8000 : (tmp * 31) >> 5;
+ // Don't return -0.0f, just normalize it to 0.0f.
+ if (tmp == 0x8000)
+ tmp = 0;
+ } else {
+ tmp = (tmp * 31) >> 6;
+ }
+
+ color.channel[i] = (uint16_t) tmp;
+ }
+
+ return color;
+ }
+
+ enum DataType {
+ // Endpoints
+ EP0 = 0,
+ EP1 = 1,
+ EP2 = 2,
+ EP3 = 3,
+ Mode,
+ Partition,
+ End,
+ };
+
+ enum Channel {
+ R = 0,
+ G = 1,
+ B = 2,
+ None,
+ };
+
+ struct DeltaBits {
+ size_t channel[3];
+
+ constexpr DeltaBits()
+ : channel{0, 0, 0} {
+ }
+
+ constexpr DeltaBits(size_t r, size_t g, size_t b)
+ : channel{r, g, b} {
+ }
+ };
+
+ struct ModeDesc {
+ int number;
+ bool hasDelta;
+ int partitionCount;
+ int endpointBits;
+ DeltaBits deltaBits;
+
+ constexpr ModeDesc()
+ : number(-1), hasDelta(false), partitionCount(0), endpointBits(0) {
+ }
+
+ constexpr ModeDesc(int number, bool hasDelta, int partitionCount, int endpointBits, DeltaBits deltaBits)
+ : number(number), hasDelta(hasDelta), partitionCount(partitionCount), endpointBits(endpointBits), deltaBits(deltaBits) {
+ }
+ };
+
+ struct BlockDesc {
+ DataType type;
+ Channel channel;
+ int MSB;
+ int LSB;
+ ModeDesc modeDesc;
+
+ constexpr BlockDesc()
+ : type(End), channel(None), MSB(0), LSB(0), modeDesc() {
+ }
+
+ constexpr BlockDesc(const DataType type, Channel channel, int MSB, int LSB, ModeDesc modeDesc)
+ : type(type), channel(channel), MSB(MSB), LSB(LSB), modeDesc(modeDesc) {
+ }
+
+ constexpr BlockDesc(DataType type, Channel channel, int MSB, int LSB)
+ : type(type), channel(channel), MSB(MSB), LSB(LSB), modeDesc() {
+ }
+ };
+
+// Turns a legal mode into an index into the BlockDesc table.
+// Illegal or reserved modes return -1.
+ static int modeToIndex(uint8_t mode) {
+ if (mode <= 3) {
+ return mode;
+ } else if ((mode & 0x2) != 0) {
+ if (mode <= 18) {
+// Turns 6 into 4, 7 into 5, 10 into 6, etc.
+ return (mode / 2) + 1 + (mode & 0x1);
+ } else if (mode == 22 || mode == 26 || mode == 30) {
+// Turns 22 into 11, 26 into 12, etc.
+ return mode / 4 + 6;
+ }
+ }
+
+ return -1;
+ }
+
+// Returns a description of the bitfields for each mode from the LSB
+// to the MSB before the index data starts.
+//
+// The numbers come from the BC6h block description. Each BlockDesc in the
+// {Type, Channel, MSB, LSB}
+// * Type describes which endpoint this is, or if this is a mode, a partition
+// number, or the end of the block description.
+// * Channel describes one of the 3 color channels within an endpoint
+// * MSB and LSB specificy:
+// * The size of the bitfield being read
+// * The position of the bitfield within the variable it is being read to
+// * If the bitfield is stored in reverse bit order
+// If MSB < LSB then the bitfield is stored in reverse order. The size of
+// the bitfield is abs(MSB-LSB+1). And the position of the bitfield within
+// the variable is min(LSB, MSB).
+//
+// Invalid or reserved modes return an empty list.
+ static constexpr int NumBlocks = 14;
+// The largest number of descriptions within a block.
+ static constexpr int MaxBlockDescIndex = 26;
+ static constexpr BlockDesc blockDescs[NumBlocks][MaxBlockDescIndex] = {
+// @fmt:off
+// Mode 0, Index 0
+{
+{ Mode, None, 1, 0, { 0, true, 2, 10, { 5, 5, 5 } } },
+{ EP2, G, 4, 4 }, { EP2, B, 4, 4 }, { EP3, B, 4, 4 },
+{ EP0, R, 9, 0 }, { EP0, G, 9, 0 }, { EP0, B, 9, 0 },
+{ EP1, R, 4, 0 }, { EP3, G, 4, 4 }, { EP2, G, 3, 0 },
+{ EP1, G, 4, 0 }, { EP3, B, 0, 0 }, { EP3, G, 3, 0 },
+{ EP1, B, 4, 0 }, { EP3, B, 1, 1 }, { EP2, B, 3, 0 },
+{ EP2, R, 4, 0 }, { EP3, B, 2, 2 }, { EP3, R, 4, 0 },
+{ EP3, B, 3, 3 },
+{ Partition, None, 4, 0 },
+{ End, None, 0, 0},
+},
+// Mode 1, Index 1
+{
+{ Mode, None, 1, 0, { 1, true, 2, 7, { 6, 6, 6 } } },
+{ EP2, G, 5, 5 }, { EP3, G, 5, 4 }, { EP0, R, 6, 0 },
+{ EP3, B, 1, 0 }, { EP2, B, 4, 4 }, { EP0, G, 6, 0 },
+{ EP2, B, 5, 5 }, { EP3, B, 2, 2 }, { EP2, G, 4, 4 },
+{ EP0, B, 6, 0 }, { EP3, B, 3, 3 }, { EP3, B, 5, 5 },
+{ EP3, B, 4, 4 }, { EP1, R, 5, 0 }, { EP2, G, 3, 0 },
+{ EP1, G, 5, 0 }, { EP3, G, 3, 0 }, { EP1, B, 5, 0 },
+{ EP2, B, 3, 0 }, { EP2, R, 5, 0 }, { EP3, R, 5, 0 },
+{ Partition, None, 4, 0 },
+{ End, None, 0, 0},
+},
+// Mode 2, Index 2
+{
+{ Mode, None, 4, 0, { 2, true, 2, 11, { 5, 4, 4 } } },
+{ EP0, R, 9, 0 }, { EP0, G, 9, 0 }, { EP0, B, 9, 0 },
+{ EP1, R, 4, 0 }, { EP0, R, 10, 10 }, { EP2, G, 3, 0 },
+{ EP1, G, 3, 0 }, { EP0, G, 10, 10 }, { EP3, B, 0, 0 },
+{ EP3, G, 3, 0 }, { EP1, B, 3, 0 }, { EP0, B, 10, 10 },
+{ EP3, B, 1, 1 }, { EP2, B, 3, 0 }, { EP2, R, 4, 0 },
+{ EP3, B, 2, 2 }, { EP3, R, 4, 0 }, { EP3, B, 3, 3 },
+{ Partition, None, 4, 0 },
+{ End, None, 0, 0},
+},
+// Mode 3, Index 3
+{
+{ Mode, None, 4, 0, { 3, false, 1, 10, { 0, 0, 0 } } },
+{ EP0, R, 9, 0 }, { EP0, G, 9, 0 }, { EP0, B, 9, 0 },
+{ EP1, R, 9, 0 }, { EP1, G, 9, 0 }, { EP1, B, 9, 0 },
+{ End, None, 0, 0},
+},
+// Mode 6, Index 4
+{
+{ Mode, None, 4, 0, { 6, true, 2, 11, { 4, 5, 4 } } }, // 1 1
+{ EP0, R, 9, 0 }, { EP0, G, 9, 0 }, { EP0, B, 9, 0 },
+{ EP1, R, 3, 0 }, { EP0, R, 10, 10 }, { EP3, G, 4, 4 },
+{ EP2, G, 3, 0 }, { EP1, G, 4, 0 }, { EP0, G, 10, 10 },
+{ EP3, G, 3, 0 }, { EP1, B, 3, 0 }, { EP0, B, 10, 10 },
+{ EP3, B, 1, 1 }, { EP2, B, 3, 0 }, { EP2, R, 3, 0 },
+{ EP3, B, 0, 0 }, { EP3, B, 2, 2 }, { EP3, R, 3, 0 }, // 18 19
+{ EP2, G, 4, 4 }, { EP3, B, 3, 3 }, // 2 21
+{ Partition, None, 4, 0 },
+{ End, None, 0, 0},
+},
+// Mode 7, Index 5
+{
+{ Mode, None, 4, 0, { 7, true, 1, 11, { 9, 9, 9 } } },
+{ EP0, R, 9, 0 }, { EP0, G, 9, 0 }, { EP0, B, 9, 0 },
+{ EP1, R, 8, 0 }, { EP0, R, 10, 10 }, { EP1, G, 8, 0 },
+{ EP0, G, 10, 10 }, { EP1, B, 8, 0 }, { EP0, B, 10, 10 },
+{ End, None, 0, 0},
+},
+// Mode 10, Index 6
+{
+{ Mode, None, 4, 0, { 10, true, 2, 11, { 4, 4, 5 } } },
+{ EP0, R, 9, 0 }, { EP0, G, 9, 0 }, { EP0, B, 9, 0 },
+{ EP1, R, 3, 0 }, { EP0, R, 10, 10 }, { EP2, B, 4, 4 },
+{ EP2, G, 3, 0 }, { EP1, G, 3, 0 }, { EP0, G, 10, 10 },
+{ EP3, B, 0, 0 }, { EP3, G, 3, 0 }, { EP1, B, 4, 0 },
+{ EP0, B, 10, 10 }, { EP2, B, 3, 0 }, { EP2, R, 3, 0 },
+{ EP3, B, 1, 1 }, { EP3, B, 2, 2 }, { EP3, R, 3, 0 },
+{ EP3, B, 4, 4 }, { EP3, B, 3, 3 },
+{ Partition, None, 4, 0 },
+{ End, None, 0, 0},
+},
+// Mode 11, Index 7
+{
+{ Mode, None, 4, 0, { 11, true, 1, 12, { 8, 8, 8 } } },
+{ EP0, R, 9, 0 }, { EP0, G, 9, 0 }, { EP0, B, 9, 0 },
+{ EP1, R, 7, 0 }, { EP0, R, 10, 11 }, { EP1, G, 7, 0 },
+{ EP0, G, 10, 11 }, { EP1, B, 7, 0 }, { EP0, B, 10, 11 },
+{ End, None, 0, 0},
+},
+// Mode 14, Index 8
+{
+{ Mode, None, 4, 0, { 14, true, 2, 9, { 5, 5, 5 } } },
+{ EP0, R, 8, 0 }, { EP2, B, 4, 4 }, { EP0, G, 8, 0 },
+{ EP2, G, 4, 4 }, { EP0, B, 8, 0 }, { EP3, B, 4, 4 },
+{ EP1, R, 4, 0 }, { EP3, G, 4, 4 }, { EP2, G, 3, 0 },
+{ EP1, G, 4, 0 }, { EP3, B, 0, 0 }, { EP3, G, 3, 0 },
+{ EP1, B, 4, 0 }, { EP3, B, 1, 1 }, { EP2, B, 3, 0 },
+{ EP2, R, 4, 0 }, { EP3, B, 2, 2 }, { EP3, R, 4, 0 },
+{ EP3, B, 3, 3 },
+{ Partition, None, 4, 0 },
+{ End, None, 0, 0},
+},
+// Mode 15, Index 9
+{
+{ Mode, None, 4, 0, { 15, true, 1, 16, { 4, 4, 4 } } },
+{ EP0, R, 9, 0 }, { EP0, G, 9, 0 }, { EP0, B, 9, 0 },
+{ EP1, R, 3, 0 }, { EP0, R, 10, 15 }, { EP1, G, 3, 0 },
+{ EP0, G, 10, 15 }, { EP1, B, 3, 0 }, { EP0, B, 10, 15 },
+{ End, None, 0, 0},
+},
+// Mode 18, Index 10
+{
+{ Mode, None, 4, 0, { 18, true, 2, 8, { 6, 5, 5 } } },
+{ EP0, R, 7, 0 }, { EP3, G, 4, 4 }, { EP2, B, 4, 4 },
+{ EP0, G, 7, 0 }, { EP3, B, 2, 2 }, { EP2, G, 4, 4 },
+{ EP0, B, 7, 0 }, { EP3, B, 3, 3 }, { EP3, B, 4, 4 },
+{ EP1, R, 5, 0 }, { EP2, G, 3, 0 }, { EP1, G, 4, 0 },
+{ EP3, B, 0, 0 }, { EP3, G, 3, 0 }, { EP1, B, 4, 0 },
+{ EP3, B, 1, 1 }, { EP2, B, 3, 0 }, { EP2, R, 5, 0 },
+{ EP3, R, 5, 0 },
+{ Partition, None, 4, 0 },
+{ End, None, 0, 0},
+},
+// Mode 22, Index 11
+{
+{ Mode, None, 4, 0, { 22, true, 2, 8, { 5, 6, 5 } } },
+{ EP0, R, 7, 0 }, { EP3, B, 0, 0 }, { EP2, B, 4, 4 },
+{ EP0, G, 7, 0 }, { EP2, G, 5, 5 }, { EP2, G, 4, 4 },
+{ EP0, B, 7, 0 }, { EP3, G, 5, 5 }, { EP3, B, 4, 4 },
+{ EP1, R, 4, 0 }, { EP3, G, 4, 4 }, { EP2, G, 3, 0 },
+{ EP1, G, 5, 0 }, { EP3, G, 3, 0 }, { EP1, B, 4, 0 },
+{ EP3, B, 1, 1 }, { EP2, B, 3, 0 }, { EP2, R, 4, 0 },
+{ EP3, B, 2, 2 }, { EP3, R, 4, 0 }, { EP3, B, 3, 3 },
+{ Partition, None, 4, 0 },
+{ End, None, 0, 0},
+},
+// Mode 26, Index 12
+{
+{ Mode, None, 4, 0, { 26, true, 2, 8, { 5, 5, 6 } } },
+{ EP0, R, 7, 0 }, { EP3, B, 1, 1 }, { EP2, B, 4, 4 },
+{ EP0, G, 7, 0 }, { EP2, B, 5, 5 }, { EP2, G, 4, 4 },
+{ EP0, B, 7, 0 }, { EP3, B, 5, 5 }, { EP3, B, 4, 4 },
+{ EP1, R, 4, 0 }, { EP3, G, 4, 4 }, { EP2, G, 3, 0 },
+{ EP1, G, 4, 0 }, { EP3, B, 0, 0 }, { EP3, G, 3, 0 },
+{ EP1, B, 5, 0 }, { EP2, B, 3, 0 }, { EP2, R, 4, 0 },
+{ EP3, B, 2, 2 }, { EP3, R, 4, 0 }, { EP3, B, 3, 3 },
+{ Partition, None, 4, 0 },
+{ End, None, 0, 0},
+},
+// Mode 30, Index 13
+{
+{ Mode, None, 4, 0, { 30, false, 2, 6, { 0, 0, 0 } } },
+{ EP0, R, 5, 0 }, { EP3, G, 4, 4 }, { EP3, B, 0, 0 },
+{ EP3, B, 1, 1 }, { EP2, B, 4, 4 }, { EP0, G, 5, 0 },
+{ EP2, G, 5, 5 }, { EP2, B, 5, 5 }, { EP3, B, 2, 2 },
+{ EP2, G, 4, 4 }, { EP0, B, 5, 0 }, { EP3, G, 5, 5 },
+{ EP3, B, 3, 3 }, { EP3, B, 5, 5 }, { EP3, B, 4, 4 },
+{ EP1, R, 5, 0 }, { EP2, G, 3, 0 }, { EP1, G, 5, 0 },
+{ EP3, G, 3, 0 }, { EP1, B, 5, 0 }, { EP2, B, 3, 0 },
+{ EP2, R, 5, 0 }, { EP3, R, 5, 0 },
+{ Partition, None, 4, 0 },
+{ End, None, 0, 0},
+}
+// @fmt:on
+ };
+
+ struct Block {
+ uint64_t low64;
+ uint64_t high64;
+
+ void decode(uint8_t *dst, size_t dstX, size_t dstY, size_t dstWidth, size_t dstHeight, size_t dstPitch, size_t dstBpp, bool isSigned) const {
+ uint8_t mode = 0;
+ Data data(low64, high64);
+ assert(dstBpp == sizeof(Color));
+
+ if ((data.low64 & 0x2) == 0) {
+ mode = data.consumeBits(1, 0);
+ } else {
+ mode = data.consumeBits(4, 0);
+ }
+
+ int blockIndex = modeToIndex(mode);
+ // Handle illegal or reserved mode
+ if (blockIndex == -1) {
+ for (int y = 0; y < 4 && y + dstY < dstHeight; y++) {
+ for (int x = 0; x < 4 && x + dstX < dstWidth; x++) {
+ auto out = reinterpret_cast<Color *>(dst + sizeof(Color) * x + dstPitch * y);
+ out->rgba = {0, 0, 0};
+ }
+ }
+ return;
+ }
+ const BlockDesc *blockDesc = blockDescs[blockIndex];
+
+ RGBf e[4];
+ e[0].isSigned = e[1].isSigned = e[2].isSigned = e[3].isSigned = isSigned;
+
+ int partition = 0;
+ ModeDesc modeDesc;
+ for (int index = 0; blockDesc[index].type != End; index++) {
+ const BlockDesc desc = blockDesc[index];
+
+ switch (desc.type) {
+ case Mode:
+ modeDesc = desc.modeDesc;
+ assert(modeDesc.number == mode);
+
+ e[0].size[0] = e[0].size[1] = e[0].size[2] = modeDesc.endpointBits;
+ for (int i = 0; i < RGBfChannels; i++) {
+ if (modeDesc.hasDelta) {
+ e[1].size[i] = e[2].size[i] = e[3].size[i] = modeDesc.deltaBits.channel[i];
+ } else {
+ e[1].size[i] = e[2].size[i] = e[3].size[i] = modeDesc.endpointBits;
+ }
+ }
+ break;
+ case Partition:
+ partition |= data.consumeBits(desc.MSB, desc.LSB);
+ break;
+ case EP0:
+ case EP1:
+ case EP2:
+ case EP3:
+ e[desc.type].channel[desc.channel] |= data.consumeBits(desc.MSB, desc.LSB);
+ break;
+ default:
+ assert(false);
+ return;
+ }
+ }
+
+ // Sign extension
+ if (isSigned) {
+ for (int ep = 0; ep < modeDesc.partitionCount * 2; ep++) {
+ e[ep].extendSign();
+ }
+ } else if (modeDesc.hasDelta) {
+ // Don't sign-extend the base endpoint in an unsigned format.
+ for (int ep = 1; ep < modeDesc.partitionCount * 2; ep++) {
+ e[ep].extendSign();
+ }
+ }
+
+ // Turn the deltas into endpoints
+ if (modeDesc.hasDelta) {
+ for (int ep = 1; ep < modeDesc.partitionCount * 2; ep++) {
+ e[ep].resolveDelta(e[0]);
+ }
+ }
+
+ for (int ep = 0; ep < modeDesc.partitionCount * 2; ep++) {
+ e[ep].unquantize();
+ }
+
+ // Get the indices, calculate final colors, and output
+ for (int y = 0; y < 4; y++) {
+ for (int x = 0; x < 4; x++) {
+ int pixelNum = x + y * 4;
+ IndexInfo idx;
+ bool isAnchor = false;
+ int firstEndpoint = 0;
+ // Bc6H can have either 1 or 2 petitions depending on the mode.
+ // The number of petitions affects the number of indices with implicit
+ // leading 0 bits and the number of bits per index.
+ if (modeDesc.partitionCount == 1) {
+ idx.numBits = 4;
+ // There's an implicit leading 0 bit for the first idx
+ isAnchor = (pixelNum == 0);
+ } else {
+ idx.numBits = 3;
+ // There are 2 indices with implicit leading 0-bits.
+ isAnchor = ((pixelNum == 0) || (pixelNum == AnchorTable2[partition]));
+ firstEndpoint = PartitionTable2[partition][pixelNum] * 2;
+ }
+
+ idx.value = data.consumeBits(idx.numBits - isAnchor - 1, 0);
+
+ // Don't exit the loop early, we need to consume these index bits regardless if
+ // we actually output them or not.
+ if ((y + dstY >= dstHeight) || (x + dstX >= dstWidth)) {
+ continue;
+ }
+
+ Color color = interpolate(e[firstEndpoint], e[firstEndpoint + 1], idx, isSigned);
+ auto out = reinterpret_cast<Color *>(dst + dstBpp * x + dstPitch * y);
+ *out = color;
+ }
+ }
+ }
+ };
+
+ } // namespace BC6H
+
+ namespace BC7 {
+// https://www.khronos.org/registry/OpenGL/extensions/ARB/ARB_texture_compression_bptc.txt
+// https://docs.microsoft.com/en-us/windows/win32/direct3d11/bc7-format
+
+ struct Bitfield {
+ int offset;
+ int count;
+
+ constexpr Bitfield Then(const int bits) { return {offset + count, bits}; }
+
+ constexpr bool operator==(const Bitfield &rhs) {
+ return offset == rhs.offset && count == rhs.count;
+ }
+ };
+
+ struct Mode {
+ const int IDX; // Mode index
+ const int NS; // Number of subsets in each partition
+ const int PB; // Partition bits
+ const int RB; // Rotation bits
+ const int ISB; // Index selection bits
+ const int CB; // Color bits
+ const int AB; // Alpha bits
+ const int EPB; // Endpoint P-bits
+ const int SPB; // Shared P-bits
+ const int IB; // Primary index bits per element
+ const int IBC; // Primary index bits total
+ const int IB2; // Secondary index bits per element
+
+ constexpr int NumColors() const { return NS * 2; }
+
+ constexpr Bitfield Partition() const { return {IDX + 1, PB}; }
+
+ constexpr Bitfield Rotation() const { return Partition().Then(RB); }
+
+ constexpr Bitfield IndexSelection() const { return Rotation().Then(ISB); }
+
+ constexpr Bitfield Red(int idx) const {
+ return IndexSelection().Then(CB * idx).Then(CB);
+ }
+
+ constexpr Bitfield Green(int idx) const {
+ return Red(NumColors() - 1).Then(CB * idx).Then(CB);
+ }
+
+ constexpr Bitfield Blue(int idx) const {
+ return Green(NumColors() - 1).Then(CB * idx).Then(CB);
+ }
+
+ constexpr Bitfield Alpha(int idx) const {
+ return Blue(NumColors() - 1).Then(AB * idx).Then(AB);
+ }
+
+ constexpr Bitfield EndpointPBit(int idx) const {
+ return Alpha(NumColors() - 1).Then(EPB * idx).Then(EPB);
+ }
+
+ constexpr Bitfield SharedPBit0() const {
+ return EndpointPBit(NumColors() - 1).Then(SPB);
+ }
+
+ constexpr Bitfield SharedPBit1() const {
+ return SharedPBit0().Then(SPB);
+ }
+
+ constexpr Bitfield PrimaryIndex(int offset, int count) const {
+ return SharedPBit1().Then(offset).Then(count);
+ }
+
+ constexpr Bitfield SecondaryIndex(int offset, int count) const {
+ return SharedPBit1().Then(IBC + offset).Then(count);
+ }
+ };
+
+ static constexpr Mode Modes[] = {
+ // IDX NS PB RB ISB CB AB EPB SPB IB IBC, IB2
+ /**/ {0x0, 0x3, 0x4, 0x0, 0x0, 0x4, 0x0, 0x1, 0x0, 0x3, 0x2d, 0x0},
+/**/ {0x1, 0x2, 0x6, 0x0, 0x0, 0x6, 0x0, 0x0, 0x1, 0x3, 0x2e, 0x0},
+/**/ {0x2, 0x3, 0x6, 0x0, 0x0, 0x5, 0x0, 0x0, 0x0, 0x2, 0x1d, 0x0},
+/**/ {0x3, 0x2, 0x6, 0x0, 0x0, 0x7, 0x0, 0x1, 0x0, 0x2, 0x1e, 0x0},
+/**/ {0x4, 0x1, 0x0, 0x2, 0x1, 0x5, 0x6, 0x0, 0x0, 0x2, 0x1f, 0x3},
+/**/ {0x5, 0x1, 0x0, 0x2, 0x0, 0x7, 0x8, 0x0, 0x0, 0x2, 0x1f, 0x2},
+/**/ {0x6, 0x1, 0x0, 0x0, 0x0, 0x7, 0x7, 0x1, 0x0, 0x4, 0x3f, 0x0},
+/**/ {0x7, 0x2, 0x6, 0x0, 0x0, 0x5, 0x5, 0x1, 0x0, 0x2, 0x1e, 0x0},
+/**/ {-1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x00, 0x0},
+ };
+
+ static constexpr int MaxPartitions = 64;
+ static constexpr int MaxSubsets = 3;
+
+ static constexpr uint8_t PartitionTable2[MaxPartitions][16] = {
+ {0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1},
+ {0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1},
+ {0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1},
+ {0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 1},
+ {0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 1},
+ {0, 0, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1},
+ {0, 0, 0, 1, 0, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1},
+ {0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 1, 1, 1},
+ {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1},
+ {0, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
+ {0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1},
+ {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 1},
+ {0, 0, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
+ {0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1},
+ {0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
+ {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1},
+ {0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 0, 1, 1, 1, 1},
+ {0, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0},
+ {0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 0},
+ {0, 1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0},
+ {0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0},
+ {0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0},
+ {0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0},
+ {0, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1},
+ {0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0},
+ {0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0},
+ {0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0},
+ {0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0},
+ {0, 0, 0, 1, 0, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0},
+ {0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0},
+ {0, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 0},
+ {0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0},
+ {0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1},
+ {0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1},
+ {0, 1, 0, 1, 1, 0, 1, 0, 0, 1, 0, 1, 1, 0, 1, 0},
+ {0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0},
+ {0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0},
+ {0, 1, 0, 1, 0, 1, 0, 1, 1, 0, 1, 0, 1, 0, 1, 0},
+ {0, 1, 1, 0, 1, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 1},
+ {0, 1, 0, 1, 1, 0, 1, 0, 1, 0, 1, 0, 0, 1, 0, 1},
+ {0, 1, 1, 1, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 1, 0},
+ {0, 0, 0, 1, 0, 0, 1, 1, 1, 1, 0, 0, 1, 0, 0, 0},
+ {0, 0, 1, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 1, 0, 0},
+ {0, 0, 1, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 0, 0},
+ {0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0},
+ {0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1},
+ {0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1},
+ {0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0},
+ {0, 1, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0},
+ {0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0},
+ {0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 1, 0},
+ {0, 0, 0, 0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0},
+ {0, 1, 1, 0, 1, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 1},
+ {0, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 0, 1, 0, 0, 1},
+ {0, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 1, 0, 0},
+ {0, 0, 1, 1, 1, 0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 0},
+ {0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 0, 0, 1},
+ {0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 1},
+ {0, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 1},
+ {0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 1},
+ {0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1},
+ {0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0},
+ {0, 0, 1, 0, 0, 0, 1, 0, 1, 1, 1, 0, 1, 1, 1, 0},
+ {0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 0, 1, 1, 1},
+ };
+
+ static constexpr uint8_t PartitionTable3[MaxPartitions][16] = {
+ {0, 0, 1, 1, 0, 0, 1, 1, 0, 2, 2, 1, 2, 2, 2, 2},
+ {0, 0, 0, 1, 0, 0, 1, 1, 2, 2, 1, 1, 2, 2, 2, 1},
+ {0, 0, 0, 0, 2, 0, 0, 1, 2, 2, 1, 1, 2, 2, 1, 1},
+ {0, 2, 2, 2, 0, 0, 2, 2, 0, 0, 1, 1, 0, 1, 1, 1},
+ {0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 2, 2, 1, 1, 2, 2},
+ {0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 2, 2, 0, 0, 2, 2},
+ {0, 0, 2, 2, 0, 0, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1},
+ {0, 0, 1, 1, 0, 0, 1, 1, 2, 2, 1, 1, 2, 2, 1, 1},
+ {0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2},
+ {0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2},
+ {0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2},
+ {0, 0, 1, 2, 0, 0, 1, 2, 0, 0, 1, 2, 0, 0, 1, 2},
+ {0, 1, 1, 2, 0, 1, 1, 2, 0, 1, 1, 2, 0, 1, 1, 2},
+ {0, 1, 2, 2, 0, 1, 2, 2, 0, 1, 2, 2, 0, 1, 2, 2},
+ {0, 0, 1, 1, 0, 1, 1, 2, 1, 1, 2, 2, 1, 2, 2, 2},
+ {0, 0, 1, 1, 2, 0, 0, 1, 2, 2, 0, 0, 2, 2, 2, 0},
+ {0, 0, 0, 1, 0, 0, 1, 1, 0, 1, 1, 2, 1, 1, 2, 2},
+ {0, 1, 1, 1, 0, 0, 1, 1, 2, 0, 0, 1, 2, 2, 0, 0},
+ {0, 0, 0, 0, 1, 1, 2, 2, 1, 1, 2, 2, 1, 1, 2, 2},
+ {0, 0, 2, 2, 0, 0, 2, 2, 0, 0, 2, 2, 1, 1, 1, 1},
+ {0, 1, 1, 1, 0, 1, 1, 1, 0, 2, 2, 2, 0, 2, 2, 2},
+ {0, 0, 0, 1, 0, 0, 0, 1, 2, 2, 2, 1, 2, 2, 2, 1},
+ {0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 2, 2, 0, 1, 2, 2},
+ {0, 0, 0, 0, 1, 1, 0, 0, 2, 2, 1, 0, 2, 2, 1, 0},
+ {0, 1, 2, 2, 0, 1, 2, 2, 0, 0, 1, 1, 0, 0, 0, 0},
+ {0, 0, 1, 2, 0, 0, 1, 2, 1, 1, 2, 2, 2, 2, 2, 2},
+ {0, 1, 1, 0, 1, 2, 2, 1, 1, 2, 2, 1, 0, 1, 1, 0},
+ {0, 0, 0, 0, 0, 1, 1, 0, 1, 2, 2, 1, 1, 2, 2, 1},
+ {0, 0, 2, 2, 1, 1, 0, 2, 1, 1, 0, 2, 0, 0, 2, 2},
+ {0, 1, 1, 0, 0, 1, 1, 0, 2, 0, 0, 2, 2, 2, 2, 2},
+ {0, 0, 1, 1, 0, 1, 2, 2, 0, 1, 2, 2, 0, 0, 1, 1},
+ {0, 0, 0, 0, 2, 0, 0, 0, 2, 2, 1, 1, 2, 2, 2, 1},
+ {0, 0, 0, 0, 0, 0, 0, 2, 1, 1, 2, 2, 1, 2, 2, 2},
+ {0, 2, 2, 2, 0, 0, 2, 2, 0, 0, 1, 2, 0, 0, 1, 1},
+ {0, 0, 1, 1, 0, 0, 1, 2, 0, 0, 2, 2, 0, 2, 2, 2},
+ {0, 1, 2, 0, 0, 1, 2, 0, 0, 1, 2, 0, 0, 1, 2, 0},
+ {0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 0, 0, 0, 0},
+ {0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0},
+ {0, 1, 2, 0, 2, 0, 1, 2, 1, 2, 0, 1, 0, 1, 2, 0},
+ {0, 0, 1, 1, 2, 2, 0, 0, 1, 1, 2, 2, 0, 0, 1, 1},
+ {0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 0, 0, 0, 0, 1, 1},
+ {0, 1, 0, 1, 0, 1, 0, 1, 2, 2, 2, 2, 2, 2, 2, 2},
+ {0, 0, 0, 0, 0, 0, 0, 0, 2, 1, 2, 1, 2, 1, 2, 1},
+ {0, 0, 2, 2, 1, 1, 2, 2, 0, 0, 2, 2, 1, 1, 2, 2},
+ {0, 0, 2, 2, 0, 0, 1, 1, 0, 0, 2, 2, 0, 0, 1, 1},
+ {0, 2, 2, 0, 1, 2, 2, 1, 0, 2, 2, 0, 1, 2, 2, 1},
+ {0, 1, 0, 1, 2, 2, 2, 2, 2, 2, 2, 2, 0, 1, 0, 1},
+ {0, 0, 0, 0, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1},
+ {0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 2, 2, 2, 2},
+ {0, 2, 2, 2, 0, 1, 1, 1, 0, 2, 2, 2, 0, 1, 1, 1},
+ {0, 0, 0, 2, 1, 1, 1, 2, 0, 0, 0, 2, 1, 1, 1, 2},
+ {0, 0, 0, 0, 2, 1, 1, 2, 2, 1, 1, 2, 2, 1, 1, 2},
+ {0, 2, 2, 2, 0, 1, 1, 1, 0, 1, 1, 1, 0, 2, 2, 2},
+ {0, 0, 0, 2, 1, 1, 1, 2, 1, 1, 1, 2, 0, 0, 0, 2},
+ {0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 2, 2, 2, 2},
+ {0, 0, 0, 0, 0, 0, 0, 0, 2, 1, 1, 2, 2, 1, 1, 2},
+ {0, 1, 1, 0, 0, 1, 1, 0, 2, 2, 2, 2, 2, 2, 2, 2},
+ {0, 0, 2, 2, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 2, 2},
+ {0, 0, 2, 2, 1, 1, 2, 2, 1, 1, 2, 2, 0, 0, 2, 2},
+ {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 1, 1, 2},
+ {0, 0, 0, 2, 0, 0, 0, 1, 0, 0, 0, 2, 0, 0, 0, 1},
+ {0, 2, 2, 2, 1, 2, 2, 2, 0, 2, 2, 2, 1, 2, 2, 2},
+ {0, 1, 0, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2},
+ {0, 1, 1, 1, 2, 0, 1, 1, 2, 2, 0, 1, 2, 2, 2, 0},
+ };
+
+ static constexpr uint8_t AnchorTable2[MaxPartitions] = {
+// @fmt:off
+0xf, 0xf, 0xf, 0xf, 0xf, 0xf, 0xf, 0xf,
+0xf, 0xf, 0xf, 0xf, 0xf, 0xf, 0xf, 0xf,
+0xf, 0x2, 0x8, 0x2, 0x2, 0x8, 0x8, 0xf,
+0x2, 0x8, 0x2, 0x2, 0x8, 0x8, 0x2, 0x2,
+0xf, 0xf, 0x6, 0x8, 0x2, 0x8, 0xf, 0xf,
+0x2, 0x8, 0x2, 0x2, 0x2, 0xf, 0xf, 0x6,
+0x6, 0x2, 0x6, 0x8, 0xf, 0xf, 0x2, 0x2,
+0xf, 0xf, 0xf, 0xf, 0xf, 0x2, 0x2, 0xf,
+// @fmt:on
+ };
+
+ static constexpr uint8_t AnchorTable3a[MaxPartitions] = {
+// @fmt:off
+0x3, 0x3, 0xf, 0xf, 0x8, 0x3, 0xf, 0xf,
+0x8, 0x8, 0x6, 0x6, 0x6, 0x5, 0x3, 0x3,
+0x3, 0x3, 0x8, 0xf, 0x3, 0x3, 0x6, 0xa,
+0x5, 0x8, 0x8, 0x6, 0x8, 0x5, 0xf, 0xf,
+0x8, 0xf, 0x3, 0x5, 0x6, 0xa, 0x8, 0xf,
+0xf, 0x3, 0xf, 0x5, 0xf, 0xf, 0xf, 0xf,
+0x3, 0xf, 0x5, 0x5, 0x5, 0x8, 0x5, 0xa,
+0x5, 0xa, 0x8, 0xd, 0xf, 0xc, 0x3, 0x3,
+// @fmt:on
+ };
+
+ static constexpr uint8_t AnchorTable3b[MaxPartitions] = {
+// @fmt:off
+0xf, 0x8, 0x8, 0x3, 0xf, 0xf, 0x3, 0x8,
+0xf, 0xf, 0xf, 0xf, 0xf, 0xf, 0xf, 0x8,
+0xf, 0x8, 0xf, 0x3, 0xf, 0x8, 0xf, 0x8,
+0x3, 0xf, 0x6, 0xa, 0xf, 0xf, 0xa, 0x8,
+0xf, 0x3, 0xf, 0xa, 0xa, 0x8, 0x9, 0xa,
+0x6, 0xf, 0x8, 0xf, 0x3, 0x6, 0x6, 0x8,
+0xf, 0x3, 0xf, 0xf, 0xf, 0xf, 0xf, 0xf,
+0xf, 0xf, 0xf, 0xf, 0x3, 0xf, 0xf, 0x8,
+// @fmt:on
+ };
+
+ struct Color {
+ struct RGB {
+ RGB() = default;
+
+ RGB(uint8_t r, uint8_t g, uint8_t b)
+ : b(b), g(g), r(r) {}
+
+ RGB(int r, int g, int b)
+ : b(static_cast<uint8_t>(b)), g(static_cast<uint8_t>(g)), r(static_cast<uint8_t>(r)) {}
+
+ RGB operator<<(int shift) const { return {r << shift, g << shift, b << shift}; }
+
+ RGB operator>>(int shift) const { return {r >> shift, g >> shift, b >> shift}; }
+
+ RGB operator|(int bits) const { return {r | bits, g | bits, b | bits}; }
+
+ RGB operator|(const RGB &rhs) const { return {r | rhs.r, g | rhs.g, b | rhs.b}; }
+
+ RGB operator+(const RGB &rhs) const { return {r + rhs.r, g + rhs.g, b + rhs.b}; }
+
+ uint8_t b;
+ uint8_t g;
+ uint8_t r;
+ };
+
+ RGB rgb;
+ uint8_t a;
+ };
+
+ static_assert(sizeof(Color) == 4, "Color size must be 4 bytes");
+
+ struct Block {
+ constexpr uint64_t Get(const Bitfield &bf) const {
+ uint64_t mask = (1ULL << bf.count) - 1;
+ if (bf.offset + bf.count <= 64) {
+ return (low >> bf.offset) & mask;
+ }
+ if (bf.offset >= 64) {
+ return (high >> (bf.offset - 64)) & mask;
+ }
+ return ((low >> bf.offset) | (high << (64 - bf.offset))) & mask;
+ }
+
+ const Mode &mode() const {
+ if ((low & 0b00000001) != 0) {
+ return Modes[0];
+ }
+ if ((low & 0b00000010) != 0) {
+ return Modes[1];
+ }
+ if ((low & 0b00000100) != 0) {
+ return Modes[2];
+ }
+ if ((low & 0b00001000) != 0) {
+ return Modes[3];
+ }
+ if ((low & 0b00010000) != 0) {
+ return Modes[4];
+ }
+ if ((low & 0b00100000) != 0) {
+ return Modes[5];
+ }
+ if ((low & 0b01000000) != 0) {
+ return Modes[6];
+ }
+ if ((low & 0b10000000) != 0) {
+ return Modes[7];
+ }
+ return Modes[8]; // Invalid mode
+ }
+
+ struct IndexInfo {
+ uint64_t value;
+ int numBits;
+ };
+
+ uint8_t interpolate(uint8_t e0, uint8_t e1, const IndexInfo &index) const {
+ static constexpr uint16_t weights2[] = {0, 21, 43, 64};
+ static constexpr uint16_t weights3[] = {0, 9, 18, 27, 37, 46, 55, 64};
+ static constexpr uint16_t weights4[] = {0, 4, 9, 13, 17, 21, 26, 30,
+ 34, 38, 43, 47, 51, 55, 60, 64};
+ static constexpr uint16_t const *weightsN[] = {
+ nullptr, nullptr, weights2, weights3, weights4
+ };
+ auto weights = weightsN[index.numBits];
+ assert(weights != nullptr);
+ return (uint8_t) (((64 - weights[index.value]) * uint16_t(e0) + weights[index.value] * uint16_t(e1) + 32) >> 6);
+ }
+
+ void decode(uint8_t *dst, size_t dstX, size_t dstY, size_t dstWidth, size_t dstHeight, size_t dstPitch) const {
+ auto const &mode = this->mode();
+
+ if (mode.IDX < 0) // Invalid mode:
+ {
+ for (size_t y = 0; y < 4 && y + dstY < dstHeight; y++) {
+ for (size_t x = 0; x < 4 && x + dstX < dstWidth; x++) {
+ auto out = reinterpret_cast<Color *>(dst + sizeof(Color) * x + dstPitch * y);
+ out->rgb = {0, 0, 0};
+ out->a = 0;
+ }
+ }
+ return;
+ }
+
+ using Endpoint = std::array<Color, 2>;
+ std::array<Endpoint, MaxSubsets> subsets;
+
+ for (size_t i = 0; i < mode.NS; i++) {
+ auto &subset = subsets[i];
+ subset[0].rgb.r = Get(mode.Red(i * 2 + 0));
+ subset[0].rgb.g = Get(mode.Green(i * 2 + 0));
+ subset[0].rgb.b = Get(mode.Blue(i * 2 + 0));
+ subset[0].a = (mode.AB > 0) ? Get(mode.Alpha(i * 2 + 0)) : 255;
+
+ subset[1].rgb.r = Get(mode.Red(i * 2 + 1));
+ subset[1].rgb.g = Get(mode.Green(i * 2 + 1));
+ subset[1].rgb.b = Get(mode.Blue(i * 2 + 1));
+ subset[1].a = (mode.AB > 0) ? Get(mode.Alpha(i * 2 + 1)) : 255;
+ }
+
+ if (mode.SPB > 0) {
+ auto pbit0 = Get(mode.SharedPBit0());
+ auto pbit1 = Get(mode.SharedPBit1());
+ subsets[0][0].rgb = (subsets[0][0].rgb << 1) | pbit0;
+ subsets[0][1].rgb = (subsets[0][1].rgb << 1) | pbit0;
+ subsets[1][0].rgb = (subsets[1][0].rgb << 1) | pbit1;
+ subsets[1][1].rgb = (subsets[1][1].rgb << 1) | pbit1;
+ }
+
+ if (mode.EPB > 0) {
+ for (size_t i = 0; i < mode.NS; i++) {
+ auto &subset = subsets[i];
+ auto pbit0 = Get(mode.EndpointPBit(i * 2 + 0));
+ auto pbit1 = Get(mode.EndpointPBit(i * 2 + 1));
+ subset[0].rgb = (subset[0].rgb << 1) | pbit0;
+ subset[1].rgb = (subset[1].rgb << 1) | pbit1;
+ if (mode.AB > 0) {
+ subset[0].a = (subset[0].a << 1) | pbit0;
+ subset[1].a = (subset[1].a << 1) | pbit1;
+ }
+ }
+ }
+
+ auto const colorBits = mode.CB + mode.SPB + mode.EPB;
+ auto const alphaBits = mode.AB + mode.SPB + mode.EPB;
+
+ for (size_t i = 0; i < mode.NS; i++) {
+ auto &subset = subsets[i];
+ subset[0].rgb = subset[0].rgb << (8 - colorBits);
+ subset[1].rgb = subset[1].rgb << (8 - colorBits);
+ subset[0].rgb = subset[0].rgb | (subset[0].rgb >> colorBits);
+ subset[1].rgb = subset[1].rgb | (subset[1].rgb >> colorBits);
+
+ if (mode.AB > 0) {
+ subset[0].a = subset[0].a << (8 - alphaBits);
+ subset[1].a = subset[1].a << (8 - alphaBits);
+ subset[0].a = subset[0].a | (subset[0].a >> alphaBits);
+ subset[1].a = subset[1].a | (subset[1].a >> alphaBits);
+ }
+ }
+
+ int colorIndexBitOffset = 0;
+ int alphaIndexBitOffset = 0;
+ for (int y = 0; y < 4; y++) {
+ for (int x = 0; x < 4; x++) {
+ auto texelIdx = y * 4 + x;
+ auto partitionIdx = Get(mode.Partition());
+ assert(partitionIdx < MaxPartitions);
+ auto subsetIdx = subsetIndex(mode, partitionIdx, texelIdx);
+ assert(subsetIdx < MaxSubsets);
+ auto const &subset = subsets[subsetIdx];
+
+ auto anchorIdx = anchorIndex(mode, partitionIdx, subsetIdx);
+ auto isAnchor = anchorIdx == texelIdx;
+ auto colorIdx = colorIndex(mode, isAnchor, colorIndexBitOffset);
+ auto alphaIdx = alphaIndex(mode, isAnchor, alphaIndexBitOffset);
+
+ if (y + dstY >= dstHeight || x + dstX >= dstWidth) {
+ // Don't be tempted to skip early at the loops:
+ // The calls to colorIndex() and alphaIndex() adjust bit
+ // offsets that need to be carefully tracked.
+ continue;
+ }
+
+ Color output;
+ // Note: We flip r and b channels past this point as the texture storage is BGR while the output is RGB
+ output.rgb.r = interpolate(subset[0].rgb.b, subset[1].rgb.b, colorIdx);
+ output.rgb.g = interpolate(subset[0].rgb.g, subset[1].rgb.g, colorIdx);
+ output.rgb.b = interpolate(subset[0].rgb.r, subset[1].rgb.r, colorIdx);
+ output.a = interpolate(subset[0].a, subset[1].a, alphaIdx);
+
+ switch (Get(mode.Rotation())) {
+ default:
+ break;
+ case 1:
+ std::swap(output.a, output.rgb.b);
+ break;
+ case 2:
+ std::swap(output.a, output.rgb.g);
+ break;
+ case 3:
+ std::swap(output.a, output.rgb.r);
+ break;
+ }
+
+ auto out = reinterpret_cast<Color *>(dst + sizeof(Color) * x + dstPitch * y);
+ *out = output;
+ }
+ }
+ }
+
+ int subsetIndex(const Mode &mode, int partitionIdx, int texelIndex) const {
+ switch (mode.NS) {
+ default:
+ return 0;
+ case 2:
+ return PartitionTable2[partitionIdx][texelIndex];
+ case 3:
+ return PartitionTable3[partitionIdx][texelIndex];
+ }
+ }
+
+ int anchorIndex(const Mode &mode, int partitionIdx, int subsetIdx) const {
+ // ARB_texture_compression_bptc states:
+ // "In partition zero, the anchor index is always index zero.
+ // In other partitions, the anchor index is specified by tables
+ // Table.A2 and Table.A3.""
+ // Note: This is really confusing - I believe they meant subset instead
+ // of partition here.
+ switch (subsetIdx) {
+ default:
+ return 0;
+ case 1:
+ return mode.NS == 2 ? AnchorTable2[partitionIdx] : AnchorTable3a[partitionIdx];
+ case 2:
+ return AnchorTable3b[partitionIdx];
+ }
+ }
+
+ IndexInfo colorIndex(const Mode &mode, bool isAnchor,
+ int &indexBitOffset) const {
+ // ARB_texture_compression_bptc states:
+ // "The index value for interpolating color comes from the secondary
+ // index for the texel if the format has an index selection bit and its
+ // value is one and from the primary index otherwise.""
+ auto idx = Get(mode.IndexSelection());
+ assert(idx <= 1);
+ bool secondary = idx == 1;
+ auto numBits = secondary ? mode.IB2 : mode.IB;
+ auto numReadBits = numBits - (isAnchor ? 1 : 0);
+ auto index =
+ Get(secondary ? mode.SecondaryIndex(indexBitOffset, numReadBits)
+ : mode.PrimaryIndex(indexBitOffset, numReadBits));
+ indexBitOffset += numReadBits;
+ return {index, numBits};
+ }
+
+ IndexInfo alphaIndex(const Mode &mode, bool isAnchor,
+ int &indexBitOffset) const {
+ // ARB_texture_compression_bptc states:
+ // "The alpha index comes from the secondary index if the block has a
+ // secondary index and the block either doesn't have an index selection
+ // bit or that bit is zero and the primary index otherwise."
+ auto idx = Get(mode.IndexSelection());
+ assert(idx <= 1);
+ bool secondary = (mode.IB2 != 0) && (idx == 0);
+ auto numBits = secondary ? mode.IB2 : mode.IB;
+ auto numReadBits = numBits - (isAnchor ? 1 : 0);
+ auto index =
+ Get(secondary ? mode.SecondaryIndex(indexBitOffset, numReadBits)
+ : mode.PrimaryIndex(indexBitOffset, numReadBits));
+ indexBitOffset += numReadBits;
+ return {index, numBits};
+ }
+
+ // Assumes little-endian
+ uint64_t low;
+ uint64_t high;
+ };
+
+ } // namespace BC7
+} // anonymous namespace
+
+namespace bcn {
+ constexpr size_t R8Bpp{1}; //!< The amount of bytes per pixel in R8
+ constexpr size_t R8g8Bpp{2}; //!< The amount of bytes per pixel in R8G8
+ constexpr size_t R8g8b8a8Bpp{4}; //!< The amount of bytes per pixel in R8G8B8A8
+ constexpr size_t R16g16b16a16Bpp{8}; //!< The amount of bytes per pixel in R16G16B16
+
+ void DecodeBc1(const uint8_t *src, uint8_t *dst, size_t x, size_t y, size_t width, size_t height) {
+ const auto *color{reinterpret_cast<const BC_color *>(src)};
+ size_t pitch{R8g8b8a8Bpp * width};
+ color->decode(dst, x, y, width, height, pitch, R8g8b8a8Bpp, true, false);
+ }
+
+ void DecodeBc2(const uint8_t *src, uint8_t *dst, size_t x, size_t y, size_t width, size_t height) {
+ const auto *alpha{reinterpret_cast<const BC_alpha *>(src)};
+ const auto *color{reinterpret_cast<const BC_color *>(src + 8)};
+ size_t pitch{R8g8b8a8Bpp * width};
+ color->decode(dst, x, y, width, height, pitch, R8g8b8a8Bpp, false, true);
+ alpha->decode(dst, x, y, width, height, pitch, R8g8b8a8Bpp);
+ }
+
+ void DecodeBc3(const uint8_t *src, uint8_t *dst, size_t x, size_t y, size_t width, size_t height) {
+ const auto *alpha{reinterpret_cast<const BC_channel *>(src)};
+ const auto *color{reinterpret_cast<const BC_color *>(src + 8)};
+ size_t pitch{R8g8b8a8Bpp * width};
+ color->decode(dst, x, y, width, height, pitch, R8g8b8a8Bpp, false, true);
+ alpha->decode(dst, x, y, width, height, pitch, R8g8b8a8Bpp, 3, false);
+ }
+
+ void DecodeBc4(const uint8_t *src, uint8_t *dst, size_t x, size_t y, size_t width, size_t height, bool isSigned) {
+ const auto *red{reinterpret_cast<const BC_channel *>(src)};
+ size_t pitch{R8Bpp * width};
+ red->decode(dst, x, y, width, height, pitch, R8Bpp, 0, isSigned);
+ }
+
+ void DecodeBc5(const uint8_t *src, uint8_t *dst, size_t x, size_t y, size_t width, size_t height, bool isSigned) {
+ const auto *red{reinterpret_cast<const BC_channel *>(src)};
+ const auto *green{reinterpret_cast<const BC_channel *>(src + 8)};
+ size_t pitch{R8g8Bpp * width};
+ red->decode(dst, x, y, width, height, pitch, R8g8Bpp, 0, isSigned);
+ green->decode(dst, x, y, width, height, pitch, R8g8Bpp, 1, isSigned);
+ }
+
+ void DecodeBc6(const uint8_t *src, uint8_t *dst, size_t x, size_t y, size_t width, size_t height, bool isSigned) {
+ const auto *block{reinterpret_cast<const BC6H::Block *>(src)};
+ size_t pitch{R16g16b16a16Bpp * width};
+ block->decode(dst, x, y, width, height, pitch, R16g16b16a16Bpp, isSigned);
+ }
+
+ void DecodeBc7(const uint8_t *src, uint8_t *dst, size_t x, size_t y, size_t width, size_t height) {
+ const auto *block{reinterpret_cast<const BC7::Block *>(src)};
+ size_t pitch{R8g8b8a8Bpp * width};
+ block->decode(dst, x, y, width, height, pitch);
+ }
+}
diff --git a/externals/bc_decoder/bc_decoder.h b/externals/bc_decoder/bc_decoder.h
new file mode 100644
index 000000000..4f0ead7d3
--- /dev/null
+++ b/externals/bc_decoder/bc_decoder.h
@@ -0,0 +1,43 @@
+// SPDX-License-Identifier: MPL-2.0
+// Copyright © 2022 Skyline Team and Contributors (https://github.com/skyline-emu/)
+
+#pragma once
+
+#include <cstdint>
+
+namespace bcn {
+ /**
+ * @brief Decodes a BC1 encoded image to R8G8B8A8
+ */
+ void DecodeBc1(const uint8_t *src, uint8_t *dst, size_t x, size_t y, size_t width, size_t height);
+
+ /**
+ * @brief Decodes a BC2 encoded image to R8G8B8A8
+ */
+ void DecodeBc2(const uint8_t *src, uint8_t *dst, size_t x, size_t y, size_t width, size_t height);
+
+ /**
+ * @brief Decodes a BC3 encoded image to R8G8B8A8
+ */
+ void DecodeBc3(const uint8_t *src, uint8_t *dst, size_t x, size_t y, size_t width, size_t height);
+
+ /**
+ * @brief Decodes a BC4 encoded image to R8
+ */
+ void DecodeBc4(const uint8_t *src, uint8_t *dst, size_t x, size_t y, size_t width, size_t height, bool isSigned);
+
+ /**
+ * @brief Decodes a BC5 encoded image to R8G8
+ */
+ void DecodeBc5(const uint8_t *src, uint8_t *dst, size_t x, size_t y, size_t width, size_t height, bool isSigned);
+
+ /**
+ * @brief Decodes a BC6 encoded image to R16G16B16A16
+ */
+ void DecodeBc6(const uint8_t *src, uint8_t *dst, size_t x, size_t y, size_t width, size_t height, bool isSigned);
+
+ /**
+ * @brief Decodes a BC7 encoded image to R8G8B8A8
+ */
+ void DecodeBc7(const uint8_t *src, uint8_t *dst, size_t x, size_t y, size_t width, size_t height);
+}
diff --git a/src/android/app/build.gradle.kts b/src/android/app/build.gradle.kts
index bab4f4d0f..9a47e2bd8 100644
--- a/src/android/app/build.gradle.kts
+++ b/src/android/app/build.gradle.kts
@@ -26,7 +26,7 @@ val autoVersion = (((System.currentTimeMillis() / 1000) - 1451606400) / 10).toIn
android {
namespace = "org.yuzu.yuzu_emu"
- compileSdkVersion = "android-33"
+ compileSdkVersion = "android-34"
ndkVersion = "25.2.9519653"
buildFeatures {
@@ -51,7 +51,7 @@ android {
// TODO If this is ever modified, change application_id in strings.xml
applicationId = "org.yuzu.yuzu_emu"
minSdk = 30
- targetSdk = 33
+ targetSdk = 34
versionName = getGitVersion()
// If you want to use autoVersion for the versionCode, create a property in local.properties
diff --git a/src/android/app/src/main/AndroidManifest.xml b/src/android/app/src/main/AndroidManifest.xml
index e31ad69e2..51d949d65 100644
--- a/src/android/app/src/main/AndroidManifest.xml
+++ b/src/android/app/src/main/AndroidManifest.xml
@@ -13,6 +13,7 @@ SPDX-License-Identifier: GPL-3.0-or-later
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
+ <uses-permission android:name="android.permission.FOREGROUND_SERVICE_SPECIAL_USE" />
<uses-permission android:name="android.permission.NFC" />
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
@@ -69,7 +70,9 @@ SPDX-License-Identifier: GPL-3.0-or-later
android:resource="@xml/nfc_tech_filter" />
</activity>
- <service android:name="org.yuzu.yuzu_emu.utils.ForegroundService"/>
+ <service android:name="org.yuzu.yuzu_emu.utils.ForegroundService" android:foregroundServiceType="specialUse">
+ <property android:name="android.app.PROPERTY_SPECIAL_USE_FGS_SUBTYPE" android:value="Keep emulation running in background"/>
+ </service>
<provider
android:name=".features.DocumentProvider"
diff --git a/src/common/input.h b/src/common/input.h
index ea30770ae..2c4ccea22 100644
--- a/src/common/input.h
+++ b/src/common/input.h
@@ -75,8 +75,10 @@ enum class DriverResult {
ErrorWritingData,
NoDeviceDetected,
InvalidHandle,
+ InvalidParameters,
NotSupported,
Disabled,
+ Delayed,
Unknown,
};
diff --git a/src/input_common/drivers/joycon.cpp b/src/input_common/drivers/joycon.cpp
index 52494e0d9..0aca5a3a3 100644
--- a/src/input_common/drivers/joycon.cpp
+++ b/src/input_common/drivers/joycon.cpp
@@ -102,12 +102,12 @@ bool Joycons::IsDeviceNew(SDL_hid_device_info* device_info) const {
Joycon::SerialNumber serial_number{};
const auto result = Joycon::JoyconDriver::GetDeviceType(device_info, type);
- if (result != Joycon::DriverResult::Success) {
+ if (result != Common::Input::DriverResult::Success) {
return false;
}
const auto result2 = Joycon::JoyconDriver::GetSerialNumber(device_info, serial_number);
- if (result2 != Joycon::DriverResult::Success) {
+ if (result2 != Common::Input::DriverResult::Success) {
return false;
}
@@ -171,10 +171,10 @@ void Joycons::RegisterNewDevice(SDL_hid_device_info* device_info) {
LOG_WARNING(Input, "No free handles available");
return;
}
- if (result == Joycon::DriverResult::Success) {
+ if (result == Common::Input::DriverResult::Success) {
result = handle->RequestDeviceAccess(device_info);
}
- if (result == Joycon::DriverResult::Success) {
+ if (result == Common::Input::DriverResult::Success) {
LOG_WARNING(Input, "Initialize device");
const std::size_t port = handle->GetDevicePort();
@@ -273,8 +273,7 @@ Common::Input::DriverResult Joycons::SetLeds(const PadIdentifier& identifier,
led_config += led_status.led_3 ? 4 : 0;
led_config += led_status.led_4 ? 8 : 0;
- return static_cast<Common::Input::DriverResult>(
- handle->SetLedConfig(static_cast<u8>(led_config)));
+ return handle->SetLedConfig(static_cast<u8>(led_config));
}
Common::Input::DriverResult Joycons::SetCameraFormat(const PadIdentifier& identifier,
@@ -283,8 +282,8 @@ Common::Input::DriverResult Joycons::SetCameraFormat(const PadIdentifier& identi
if (handle == nullptr) {
return Common::Input::DriverResult::InvalidHandle;
}
- return static_cast<Common::Input::DriverResult>(handle->SetIrsConfig(
- Joycon::IrsMode::ImageTransfer, static_cast<Joycon::IrsResolution>(camera_format)));
+ return handle->SetIrsConfig(Joycon::IrsMode::ImageTransfer,
+ static_cast<Joycon::IrsResolution>(camera_format));
};
Common::Input::NfcState Joycons::SupportsNfc(const PadIdentifier& identifier_) const {
@@ -351,7 +350,7 @@ Common::Input::NfcState Joycons::ReadMifareData(const PadIdentifier& identifier,
std::vector<Joycon::MifareReadData> read_data(read_request.size());
const auto result = handle->ReadMifareData(read_request, read_data);
- if (result == Joycon::DriverResult::Success) {
+ if (result == Common::Input::DriverResult::Success) {
for (std::size_t i = 0; i < read_request.size(); i++) {
data.data[i] = {
.command = static_cast<u8>(command),
@@ -402,15 +401,15 @@ Common::Input::DriverResult Joycons::SetPollingMode(const PadIdentifier& identif
switch (polling_mode) {
case Common::Input::PollingMode::Active:
- return static_cast<Common::Input::DriverResult>(handle->SetActiveMode());
+ return handle->SetActiveMode();
case Common::Input::PollingMode::Passive:
- return static_cast<Common::Input::DriverResult>(handle->SetPassiveMode());
+ return handle->SetPassiveMode();
case Common::Input::PollingMode::IR:
- return static_cast<Common::Input::DriverResult>(handle->SetIrMode());
+ return handle->SetIrMode();
case Common::Input::PollingMode::NFC:
- return static_cast<Common::Input::DriverResult>(handle->SetNfcMode());
+ return handle->SetNfcMode();
case Common::Input::PollingMode::Ring:
- return static_cast<Common::Input::DriverResult>(handle->SetRingConMode());
+ return handle->SetRingConMode();
default:
return Common::Input::DriverResult::NotSupported;
}
@@ -828,13 +827,13 @@ std::string Joycons::JoyconName(Joycon::ControllerType type) const {
}
}
-Common::Input::NfcState Joycons::TranslateDriverResult(Joycon::DriverResult result) const {
+Common::Input::NfcState Joycons::TranslateDriverResult(Common::Input::DriverResult result) const {
switch (result) {
- case Joycon::DriverResult::Success:
+ case Common::Input::DriverResult::Success:
return Common::Input::NfcState::Success;
- case Joycon::DriverResult::Disabled:
+ case Common::Input::DriverResult::Disabled:
return Common::Input::NfcState::WrongDeviceState;
- case Joycon::DriverResult::NotSupported:
+ case Common::Input::DriverResult::NotSupported:
return Common::Input::NfcState::NotSupported;
default:
return Common::Input::NfcState::Unknown;
diff --git a/src/input_common/drivers/joycon.h b/src/input_common/drivers/joycon.h
index 4c323d7d6..112e970e1 100644
--- a/src/input_common/drivers/joycon.h
+++ b/src/input_common/drivers/joycon.h
@@ -17,7 +17,6 @@ struct Color;
struct MotionData;
struct TagInfo;
enum class ControllerType : u8;
-enum class DriverResult;
enum class IrsResolution;
class JoyconDriver;
} // namespace InputCommon::Joycon
@@ -112,7 +111,7 @@ private:
/// Returns the name of the device in text format
std::string JoyconName(Joycon::ControllerType type) const;
- Common::Input::NfcState TranslateDriverResult(Joycon::DriverResult result) const;
+ Common::Input::NfcState TranslateDriverResult(Common::Input::DriverResult result) const;
std::jthread scan_thread;
diff --git a/src/input_common/helpers/joycon_driver.cpp b/src/input_common/helpers/joycon_driver.cpp
index ec984a647..cf51f3481 100644
--- a/src/input_common/helpers/joycon_driver.cpp
+++ b/src/input_common/helpers/joycon_driver.cpp
@@ -1,6 +1,7 @@
// SPDX-FileCopyrightText: Copyright 2022 yuzu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
+#include "common/input.h"
#include "common/logging/log.h"
#include "common/scope_exit.h"
#include "common/swap.h"
@@ -28,13 +29,13 @@ void JoyconDriver::Stop() {
input_thread = {};
}
-DriverResult JoyconDriver::RequestDeviceAccess(SDL_hid_device_info* device_info) {
+Common::Input::DriverResult JoyconDriver::RequestDeviceAccess(SDL_hid_device_info* device_info) {
std::scoped_lock lock{mutex};
handle_device_type = ControllerType::None;
GetDeviceType(device_info, handle_device_type);
if (handle_device_type == ControllerType::None) {
- return DriverResult::UnsupportedControllerType;
+ return Common::Input::DriverResult::UnsupportedControllerType;
}
hidapi_handle->handle =
@@ -43,15 +44,15 @@ DriverResult JoyconDriver::RequestDeviceAccess(SDL_hid_device_info* device_info)
if (!hidapi_handle->handle) {
LOG_ERROR(Input, "Yuzu can't gain access to this device: ID {:04X}:{:04X}.",
device_info->vendor_id, device_info->product_id);
- return DriverResult::HandleInUse;
+ return Common::Input::DriverResult::HandleInUse;
}
SDL_hid_set_nonblocking(hidapi_handle->handle, 1);
- return DriverResult::Success;
+ return Common::Input::DriverResult::Success;
}
-DriverResult JoyconDriver::InitializeDevice() {
+Common::Input::DriverResult JoyconDriver::InitializeDevice() {
if (!hidapi_handle->handle) {
- return DriverResult::InvalidHandle;
+ return Common::Input::DriverResult::InvalidHandle;
}
std::scoped_lock lock{mutex};
disable_input_thread = true;
@@ -87,7 +88,7 @@ DriverResult JoyconDriver::InitializeDevice() {
rumble_protocol = std::make_unique<RumbleProtocol>(hidapi_handle);
// Get fixed joycon info
- if (generic_protocol->GetVersionNumber(version) != DriverResult::Success) {
+ if (generic_protocol->GetVersionNumber(version) != Common::Input::DriverResult::Success) {
// If this command fails the device doesn't accept configuration commands
input_only_device = true;
}
@@ -129,7 +130,7 @@ DriverResult JoyconDriver::InitializeDevice() {
}
disable_input_thread = false;
- return DriverResult::Success;
+ return Common::Input::DriverResult::Success;
}
void JoyconDriver::InputThread(std::stop_token stop_token) {
@@ -229,7 +230,7 @@ void JoyconDriver::OnNewData(std::span<u8> buffer) {
if (!amiibo_detected) {
Joycon::TagInfo tag_info;
const auto result = nfc_protocol->GetTagInfo(tag_info);
- if (result == DriverResult::Success) {
+ if (result == Common::Input::DriverResult::Success) {
joycon_poller->UpdateAmiibo(tag_info);
amiibo_detected = true;
}
@@ -255,7 +256,7 @@ void JoyconDriver::OnNewData(std::span<u8> buffer) {
}
}
-DriverResult JoyconDriver::SetPollingMode() {
+Common::Input::DriverResult JoyconDriver::SetPollingMode() {
SCOPE_EXIT({ disable_input_thread = false; });
disable_input_thread = true;
@@ -270,7 +271,7 @@ DriverResult JoyconDriver::SetPollingMode() {
}
if (input_only_device) {
- return DriverResult::NotSupported;
+ return Common::Input::DriverResult::NotSupported;
}
if (irs_protocol->IsEnabled()) {
@@ -289,7 +290,7 @@ DriverResult JoyconDriver::SetPollingMode() {
if (irs_enabled && supported_features.irs) {
auto result = irs_protocol->EnableIrs();
- if (result == DriverResult::Success) {
+ if (result == Common::Input::DriverResult::Success) {
return result;
}
irs_protocol->DisableIrs();
@@ -299,7 +300,7 @@ DriverResult JoyconDriver::SetPollingMode() {
if (nfc_enabled && supported_features.nfc) {
auto result = nfc_protocol->EnableNfc();
- if (result == DriverResult::Success) {
+ if (result == Common::Input::DriverResult::Success) {
return result;
}
nfc_protocol->DisableNfc();
@@ -309,10 +310,10 @@ DriverResult JoyconDriver::SetPollingMode() {
if (hidbus_enabled && supported_features.hidbus) {
auto result = ring_protocol->EnableRingCon();
- if (result == DriverResult::Success) {
+ if (result == Common::Input::DriverResult::Success) {
result = ring_protocol->StartRingconPolling();
}
- if (result == DriverResult::Success) {
+ if (result == Common::Input::DriverResult::Success) {
ring_connected = true;
return result;
}
@@ -324,7 +325,7 @@ DriverResult JoyconDriver::SetPollingMode() {
if (passive_enabled && supported_features.passive) {
const auto result = generic_protocol->EnablePassiveMode();
- if (result == DriverResult::Success) {
+ if (result == Common::Input::DriverResult::Success) {
return result;
}
LOG_ERROR(Input, "Error enabling passive mode");
@@ -332,7 +333,7 @@ DriverResult JoyconDriver::SetPollingMode() {
// Default Mode
const auto result = generic_protocol->EnableActiveMode();
- if (result != DriverResult::Success) {
+ if (result != Common::Input::DriverResult::Success) {
LOG_ERROR(Input, "Error enabling active mode");
}
// Switch calls this function after enabling active mode
@@ -396,26 +397,26 @@ bool JoyconDriver::IsPayloadCorrect(int status, std::span<const u8> buffer) {
return true;
}
-DriverResult JoyconDriver::SetVibration(const VibrationValue& vibration) {
+Common::Input::DriverResult JoyconDriver::SetVibration(const VibrationValue& vibration) {
std::scoped_lock lock{mutex};
if (disable_input_thread) {
- return DriverResult::HandleInUse;
+ return Common::Input::DriverResult::HandleInUse;
}
return rumble_protocol->SendVibration(vibration);
}
-DriverResult JoyconDriver::SetLedConfig(u8 led_pattern) {
+Common::Input::DriverResult JoyconDriver::SetLedConfig(u8 led_pattern) {
std::scoped_lock lock{mutex};
if (disable_input_thread) {
- return DriverResult::HandleInUse;
+ return Common::Input::DriverResult::HandleInUse;
}
return generic_protocol->SetLedPattern(led_pattern);
}
-DriverResult JoyconDriver::SetIrsConfig(IrsMode mode_, IrsResolution format_) {
+Common::Input::DriverResult JoyconDriver::SetIrsConfig(IrsMode mode_, IrsResolution format_) {
std::scoped_lock lock{mutex};
if (disable_input_thread) {
- return DriverResult::HandleInUse;
+ return Common::Input::DriverResult::HandleInUse;
}
disable_input_thread = true;
const auto result = irs_protocol->SetIrsConfig(mode_, format_);
@@ -423,7 +424,7 @@ DriverResult JoyconDriver::SetIrsConfig(IrsMode mode_, IrsResolution format_) {
return result;
}
-DriverResult JoyconDriver::SetPassiveMode() {
+Common::Input::DriverResult JoyconDriver::SetPassiveMode() {
std::scoped_lock lock{mutex};
motion_enabled = false;
hidbus_enabled = false;
@@ -433,7 +434,7 @@ DriverResult JoyconDriver::SetPassiveMode() {
return SetPollingMode();
}
-DriverResult JoyconDriver::SetActiveMode() {
+Common::Input::DriverResult JoyconDriver::SetActiveMode() {
if (is_ring_disabled_by_irs) {
is_ring_disabled_by_irs = false;
SetActiveMode();
@@ -449,11 +450,11 @@ DriverResult JoyconDriver::SetActiveMode() {
return SetPollingMode();
}
-DriverResult JoyconDriver::SetIrMode() {
+Common::Input::DriverResult JoyconDriver::SetIrMode() {
std::scoped_lock lock{mutex};
if (!supported_features.irs) {
- return DriverResult::NotSupported;
+ return Common::Input::DriverResult::NotSupported;
}
if (ring_connected) {
@@ -468,11 +469,11 @@ DriverResult JoyconDriver::SetIrMode() {
return SetPollingMode();
}
-DriverResult JoyconDriver::SetNfcMode() {
+Common::Input::DriverResult JoyconDriver::SetNfcMode() {
std::scoped_lock lock{mutex};
if (!supported_features.nfc) {
- return DriverResult::NotSupported;
+ return Common::Input::DriverResult::NotSupported;
}
motion_enabled = true;
@@ -483,11 +484,11 @@ DriverResult JoyconDriver::SetNfcMode() {
return SetPollingMode();
}
-DriverResult JoyconDriver::SetRingConMode() {
+Common::Input::DriverResult JoyconDriver::SetRingConMode() {
std::scoped_lock lock{mutex};
if (!supported_features.hidbus) {
- return DriverResult::NotSupported;
+ return Common::Input::DriverResult::NotSupported;
}
motion_enabled = true;
@@ -499,20 +500,20 @@ DriverResult JoyconDriver::SetRingConMode() {
const auto result = SetPollingMode();
if (!ring_connected) {
- return DriverResult::NoDeviceDetected;
+ return Common::Input::DriverResult::NoDeviceDetected;
}
return result;
}
-DriverResult JoyconDriver::StartNfcPolling() {
+Common::Input::DriverResult JoyconDriver::StartNfcPolling() {
std::scoped_lock lock{mutex};
if (!supported_features.nfc) {
- return DriverResult::NotSupported;
+ return Common::Input::DriverResult::NotSupported;
}
if (!nfc_protocol->IsEnabled()) {
- return DriverResult::Disabled;
+ return Common::Input::DriverResult::Disabled;
}
disable_input_thread = true;
@@ -522,14 +523,14 @@ DriverResult JoyconDriver::StartNfcPolling() {
return result;
}
-DriverResult JoyconDriver::StopNfcPolling() {
+Common::Input::DriverResult JoyconDriver::StopNfcPolling() {
std::scoped_lock lock{mutex};
if (!supported_features.nfc) {
- return DriverResult::NotSupported;
+ return Common::Input::DriverResult::NotSupported;
}
if (!nfc_protocol->IsEnabled()) {
- return DriverResult::Disabled;
+ return Common::Input::DriverResult::Disabled;
}
disable_input_thread = true;
@@ -544,17 +545,17 @@ DriverResult JoyconDriver::StopNfcPolling() {
return result;
}
-DriverResult JoyconDriver::ReadAmiiboData(std::vector<u8>& out_data) {
+Common::Input::DriverResult JoyconDriver::ReadAmiiboData(std::vector<u8>& out_data) {
std::scoped_lock lock{mutex};
if (!supported_features.nfc) {
- return DriverResult::NotSupported;
+ return Common::Input::DriverResult::NotSupported;
}
if (!nfc_protocol->IsEnabled()) {
- return DriverResult::Disabled;
+ return Common::Input::DriverResult::Disabled;
}
if (!amiibo_detected) {
- return DriverResult::ErrorWritingData;
+ return Common::Input::DriverResult::ErrorWritingData;
}
out_data.resize(0x21C);
@@ -565,17 +566,17 @@ DriverResult JoyconDriver::ReadAmiiboData(std::vector<u8>& out_data) {
return result;
}
-DriverResult JoyconDriver::WriteNfcData(std::span<const u8> data) {
+Common::Input::DriverResult JoyconDriver::WriteNfcData(std::span<const u8> data) {
std::scoped_lock lock{mutex};
if (!supported_features.nfc) {
- return DriverResult::NotSupported;
+ return Common::Input::DriverResult::NotSupported;
}
if (!nfc_protocol->IsEnabled()) {
- return DriverResult::Disabled;
+ return Common::Input::DriverResult::Disabled;
}
if (!amiibo_detected) {
- return DriverResult::ErrorWritingData;
+ return Common::Input::DriverResult::ErrorWritingData;
}
disable_input_thread = true;
@@ -585,18 +586,18 @@ DriverResult JoyconDriver::WriteNfcData(std::span<const u8> data) {
return result;
}
-DriverResult JoyconDriver::ReadMifareData(std::span<const MifareReadChunk> data,
- std::span<MifareReadData> out_data) {
+Common::Input::DriverResult JoyconDriver::ReadMifareData(std::span<const MifareReadChunk> data,
+ std::span<MifareReadData> out_data) {
std::scoped_lock lock{mutex};
if (!supported_features.nfc) {
- return DriverResult::NotSupported;
+ return Common::Input::DriverResult::NotSupported;
}
if (!nfc_protocol->IsEnabled()) {
- return DriverResult::Disabled;
+ return Common::Input::DriverResult::Disabled;
}
if (!amiibo_detected) {
- return DriverResult::ErrorWritingData;
+ return Common::Input::DriverResult::ErrorWritingData;
}
disable_input_thread = true;
@@ -606,17 +607,17 @@ DriverResult JoyconDriver::ReadMifareData(std::span<const MifareReadChunk> data,
return result;
}
-DriverResult JoyconDriver::WriteMifareData(std::span<const MifareWriteChunk> data) {
+Common::Input::DriverResult JoyconDriver::WriteMifareData(std::span<const MifareWriteChunk> data) {
std::scoped_lock lock{mutex};
if (!supported_features.nfc) {
- return DriverResult::NotSupported;
+ return Common::Input::DriverResult::NotSupported;
}
if (!nfc_protocol->IsEnabled()) {
- return DriverResult::Disabled;
+ return Common::Input::DriverResult::Disabled;
}
if (!amiibo_detected) {
- return DriverResult::ErrorWritingData;
+ return Common::Input::DriverResult::ErrorWritingData;
}
disable_input_thread = true;
@@ -675,8 +676,8 @@ void JoyconDriver::SetCallbacks(const JoyconCallbacks& callbacks) {
joycon_poller->SetCallbacks(callbacks);
}
-DriverResult JoyconDriver::GetDeviceType(SDL_hid_device_info* device_info,
- ControllerType& controller_type) {
+Common::Input::DriverResult JoyconDriver::GetDeviceType(SDL_hid_device_info* device_info,
+ ControllerType& controller_type) {
static constexpr std::array<std::pair<u32, ControllerType>, 6> supported_devices{
std::pair<u32, ControllerType>{0x2006, ControllerType::Left},
{0x2007, ControllerType::Right},
@@ -686,25 +687,25 @@ DriverResult JoyconDriver::GetDeviceType(SDL_hid_device_info* device_info,
controller_type = ControllerType::None;
if (device_info->vendor_id != nintendo_vendor_id) {
- return DriverResult::UnsupportedControllerType;
+ return Common::Input::DriverResult::UnsupportedControllerType;
}
for (const auto& [product_id, type] : supported_devices) {
if (device_info->product_id == static_cast<u16>(product_id)) {
controller_type = type;
- return Joycon::DriverResult::Success;
+ return Common::Input::DriverResult::Success;
}
}
- return Joycon::DriverResult::UnsupportedControllerType;
+ return Common::Input::DriverResult::UnsupportedControllerType;
}
-DriverResult JoyconDriver::GetSerialNumber(SDL_hid_device_info* device_info,
- SerialNumber& serial_number) {
+Common::Input::DriverResult JoyconDriver::GetSerialNumber(SDL_hid_device_info* device_info,
+ SerialNumber& serial_number) {
if (device_info->serial_number == nullptr) {
- return DriverResult::Unknown;
+ return Common::Input::DriverResult::Unknown;
}
std::memcpy(&serial_number, device_info->serial_number, 15);
- return Joycon::DriverResult::Success;
+ return Common::Input::DriverResult::Success;
}
} // namespace InputCommon::Joycon
diff --git a/src/input_common/helpers/joycon_driver.h b/src/input_common/helpers/joycon_driver.h
index 45b32d2f8..335e12cc3 100644
--- a/src/input_common/helpers/joycon_driver.h
+++ b/src/input_common/helpers/joycon_driver.h
@@ -11,6 +11,10 @@
#include "input_common/helpers/joycon_protocol/joycon_types.h"
+namespace Common::Input {
+enum class DriverResult;
+}
+
namespace InputCommon::Joycon {
class CalibrationProtocol;
class GenericProtocol;
@@ -26,8 +30,8 @@ public:
~JoyconDriver();
- DriverResult RequestDeviceAccess(SDL_hid_device_info* device_info);
- DriverResult InitializeDevice();
+ Common::Input::DriverResult RequestDeviceAccess(SDL_hid_device_info* device_info);
+ Common::Input::DriverResult InitializeDevice();
void Stop();
bool IsConnected() const;
@@ -41,31 +45,31 @@ public:
SerialNumber GetSerialNumber() const;
SerialNumber GetHandleSerialNumber() const;
- DriverResult SetVibration(const VibrationValue& vibration);
- DriverResult SetLedConfig(u8 led_pattern);
- DriverResult SetIrsConfig(IrsMode mode_, IrsResolution format_);
- DriverResult SetPassiveMode();
- DriverResult SetActiveMode();
- DriverResult SetIrMode();
- DriverResult SetNfcMode();
- DriverResult SetRingConMode();
- DriverResult StartNfcPolling();
- DriverResult StopNfcPolling();
- DriverResult ReadAmiiboData(std::vector<u8>& out_data);
- DriverResult WriteNfcData(std::span<const u8> data);
- DriverResult ReadMifareData(std::span<const MifareReadChunk> request,
- std::span<MifareReadData> out_data);
- DriverResult WriteMifareData(std::span<const MifareWriteChunk> request);
+ Common::Input::DriverResult SetVibration(const VibrationValue& vibration);
+ Common::Input::DriverResult SetLedConfig(u8 led_pattern);
+ Common::Input::DriverResult SetIrsConfig(IrsMode mode_, IrsResolution format_);
+ Common::Input::DriverResult SetPassiveMode();
+ Common::Input::DriverResult SetActiveMode();
+ Common::Input::DriverResult SetIrMode();
+ Common::Input::DriverResult SetNfcMode();
+ Common::Input::DriverResult SetRingConMode();
+ Common::Input::DriverResult StartNfcPolling();
+ Common::Input::DriverResult StopNfcPolling();
+ Common::Input::DriverResult ReadAmiiboData(std::vector<u8>& out_data);
+ Common::Input::DriverResult WriteNfcData(std::span<const u8> data);
+ Common::Input::DriverResult ReadMifareData(std::span<const MifareReadChunk> request,
+ std::span<MifareReadData> out_data);
+ Common::Input::DriverResult WriteMifareData(std::span<const MifareWriteChunk> request);
void SetCallbacks(const JoyconCallbacks& callbacks);
// Returns device type from hidapi handle
- static DriverResult GetDeviceType(SDL_hid_device_info* device_info,
- ControllerType& controller_type);
+ static Common::Input::DriverResult GetDeviceType(SDL_hid_device_info* device_info,
+ ControllerType& controller_type);
// Returns serial number from hidapi handle
- static DriverResult GetSerialNumber(SDL_hid_device_info* device_info,
- SerialNumber& serial_number);
+ static Common::Input::DriverResult GetSerialNumber(SDL_hid_device_info* device_info,
+ SerialNumber& serial_number);
private:
struct SupportedFeatures {
@@ -84,7 +88,7 @@ private:
void OnNewData(std::span<u8> buffer);
/// Updates device configuration to enable or disable features
- DriverResult SetPollingMode();
+ Common::Input::DriverResult SetPollingMode();
/// Returns true if input thread is valid and doesn't need to be stopped
bool IsInputThreadValid() const;
diff --git a/src/input_common/helpers/joycon_protocol/calibration.cpp b/src/input_common/helpers/joycon_protocol/calibration.cpp
index d8f040f75..1300ecaf5 100644
--- a/src/input_common/helpers/joycon_protocol/calibration.cpp
+++ b/src/input_common/helpers/joycon_protocol/calibration.cpp
@@ -3,6 +3,7 @@
#include <cstring>
+#include "common/input.h"
#include "input_common/helpers/joycon_protocol/calibration.h"
#include "input_common/helpers/joycon_protocol/joycon_types.h"
@@ -11,28 +12,29 @@ namespace InputCommon::Joycon {
CalibrationProtocol::CalibrationProtocol(std::shared_ptr<JoyconHandle> handle)
: JoyconCommonProtocol(std::move(handle)) {}
-DriverResult CalibrationProtocol::GetLeftJoyStickCalibration(JoyStickCalibration& calibration) {
+Common::Input::DriverResult CalibrationProtocol::GetLeftJoyStickCalibration(
+ JoyStickCalibration& calibration) {
ScopedSetBlocking sb(this);
- DriverResult result{DriverResult::Success};
+ Common::Input::DriverResult result{Common::Input::DriverResult::Success};
JoystickLeftSpiCalibration spi_calibration{};
bool has_user_calibration = false;
calibration = {};
- if (result == DriverResult::Success) {
+ if (result == Common::Input::DriverResult::Success) {
result = HasUserCalibration(SpiAddress::USER_LEFT_MAGIC, has_user_calibration);
}
// Read User defined calibration
- if (result == DriverResult::Success && has_user_calibration) {
+ if (result == Common::Input::DriverResult::Success && has_user_calibration) {
result = ReadSPI(SpiAddress::USER_LEFT_DATA, spi_calibration);
}
// Read Factory calibration
- if (result == DriverResult::Success && !has_user_calibration) {
+ if (result == Common::Input::DriverResult::Success && !has_user_calibration) {
result = ReadSPI(SpiAddress::FACT_LEFT_DATA, spi_calibration);
}
- if (result == DriverResult::Success) {
+ if (result == Common::Input::DriverResult::Success) {
calibration.x.center = GetXAxisCalibrationValue(spi_calibration.center);
calibration.y.center = GetYAxisCalibrationValue(spi_calibration.center);
calibration.x.min = GetXAxisCalibrationValue(spi_calibration.min);
@@ -47,28 +49,29 @@ DriverResult CalibrationProtocol::GetLeftJoyStickCalibration(JoyStickCalibration
return result;
}
-DriverResult CalibrationProtocol::GetRightJoyStickCalibration(JoyStickCalibration& calibration) {
+Common::Input::DriverResult CalibrationProtocol::GetRightJoyStickCalibration(
+ JoyStickCalibration& calibration) {
ScopedSetBlocking sb(this);
- DriverResult result{DriverResult::Success};
+ Common::Input::DriverResult result{Common::Input::DriverResult::Success};
JoystickRightSpiCalibration spi_calibration{};
bool has_user_calibration = false;
calibration = {};
- if (result == DriverResult::Success) {
+ if (result == Common::Input::DriverResult::Success) {
result = HasUserCalibration(SpiAddress::USER_RIGHT_MAGIC, has_user_calibration);
}
// Read User defined calibration
- if (result == DriverResult::Success && has_user_calibration) {
+ if (result == Common::Input::DriverResult::Success && has_user_calibration) {
result = ReadSPI(SpiAddress::USER_RIGHT_DATA, spi_calibration);
}
// Read Factory calibration
- if (result == DriverResult::Success && !has_user_calibration) {
+ if (result == Common::Input::DriverResult::Success && !has_user_calibration) {
result = ReadSPI(SpiAddress::FACT_RIGHT_DATA, spi_calibration);
}
- if (result == DriverResult::Success) {
+ if (result == Common::Input::DriverResult::Success) {
calibration.x.center = GetXAxisCalibrationValue(spi_calibration.center);
calibration.y.center = GetYAxisCalibrationValue(spi_calibration.center);
calibration.x.min = GetXAxisCalibrationValue(spi_calibration.min);
@@ -83,28 +86,28 @@ DriverResult CalibrationProtocol::GetRightJoyStickCalibration(JoyStickCalibratio
return result;
}
-DriverResult CalibrationProtocol::GetImuCalibration(MotionCalibration& calibration) {
+Common::Input::DriverResult CalibrationProtocol::GetImuCalibration(MotionCalibration& calibration) {
ScopedSetBlocking sb(this);
- DriverResult result{DriverResult::Success};
+ Common::Input::DriverResult result{Common::Input::DriverResult::Success};
ImuSpiCalibration spi_calibration{};
bool has_user_calibration = false;
calibration = {};
- if (result == DriverResult::Success) {
+ if (result == Common::Input::DriverResult::Success) {
result = HasUserCalibration(SpiAddress::USER_IMU_MAGIC, has_user_calibration);
}
// Read User defined calibration
- if (result == DriverResult::Success && has_user_calibration) {
+ if (result == Common::Input::DriverResult::Success && has_user_calibration) {
result = ReadSPI(SpiAddress::USER_IMU_DATA, spi_calibration);
}
// Read Factory calibration
- if (result == DriverResult::Success && !has_user_calibration) {
+ if (result == Common::Input::DriverResult::Success && !has_user_calibration) {
result = ReadSPI(SpiAddress::FACT_IMU_DATA, spi_calibration);
}
- if (result == DriverResult::Success) {
+ if (result == Common::Input::DriverResult::Success) {
calibration.accelerometer[0].offset = spi_calibration.accelerometer_offset[0];
calibration.accelerometer[1].offset = spi_calibration.accelerometer_offset[1];
calibration.accelerometer[2].offset = spi_calibration.accelerometer_offset[2];
@@ -127,8 +130,8 @@ DriverResult CalibrationProtocol::GetImuCalibration(MotionCalibration& calibrati
return result;
}
-DriverResult CalibrationProtocol::GetRingCalibration(RingCalibration& calibration,
- s16 current_value) {
+Common::Input::DriverResult CalibrationProtocol::GetRingCalibration(RingCalibration& calibration,
+ s16 current_value) {
constexpr s16 DefaultRingRange{800};
// TODO: Get default calibration form ring itself
@@ -144,15 +147,15 @@ DriverResult CalibrationProtocol::GetRingCalibration(RingCalibration& calibratio
.max_value = ring_data_max,
.min_value = ring_data_min,
};
- return DriverResult::Success;
+ return Common::Input::DriverResult::Success;
}
-DriverResult CalibrationProtocol::HasUserCalibration(SpiAddress address,
- bool& has_user_calibration) {
+Common::Input::DriverResult CalibrationProtocol::HasUserCalibration(SpiAddress address,
+ bool& has_user_calibration) {
MagicSpiCalibration spi_magic{};
- const DriverResult result{ReadSPI(address, spi_magic)};
+ const Common::Input::DriverResult result{ReadSPI(address, spi_magic)};
has_user_calibration = false;
- if (result == DriverResult::Success) {
+ if (result == Common::Input::DriverResult::Success) {
has_user_calibration = spi_magic.first == CalibrationMagic::USR_MAGIC_0 &&
spi_magic.second == CalibrationMagic::USR_MAGIC_1;
}
diff --git a/src/input_common/helpers/joycon_protocol/calibration.h b/src/input_common/helpers/joycon_protocol/calibration.h
index c6fd0f729..82d94b366 100644
--- a/src/input_common/helpers/joycon_protocol/calibration.h
+++ b/src/input_common/helpers/joycon_protocol/calibration.h
@@ -12,8 +12,11 @@
#include "input_common/helpers/joycon_protocol/common_protocol.h"
-namespace InputCommon::Joycon {
+namespace Common::Input {
enum class DriverResult;
+}
+
+namespace InputCommon::Joycon {
struct JoyStickCalibration;
struct IMUCalibration;
struct JoyconHandle;
@@ -31,30 +34,30 @@ public:
* @param is_factory_calibration if true factory values will be returned
* @returns JoyStickCalibration of the left joystick
*/
- DriverResult GetLeftJoyStickCalibration(JoyStickCalibration& calibration);
+ Common::Input::DriverResult GetLeftJoyStickCalibration(JoyStickCalibration& calibration);
/**
* Sends a request to obtain the right stick calibration from memory
* @param is_factory_calibration if true factory values will be returned
* @returns JoyStickCalibration of the right joystick
*/
- DriverResult GetRightJoyStickCalibration(JoyStickCalibration& calibration);
+ Common::Input::DriverResult GetRightJoyStickCalibration(JoyStickCalibration& calibration);
/**
* Sends a request to obtain the motion calibration from memory
* @returns ImuCalibration of the motion sensor
*/
- DriverResult GetImuCalibration(MotionCalibration& calibration);
+ Common::Input::DriverResult GetImuCalibration(MotionCalibration& calibration);
/**
* Calculates on run time the proper calibration of the ring controller
* @returns RingCalibration of the ring sensor
*/
- DriverResult GetRingCalibration(RingCalibration& calibration, s16 current_value);
+ Common::Input::DriverResult GetRingCalibration(RingCalibration& calibration, s16 current_value);
private:
/// Returns true if the specified address corresponds to the magic value of user calibration
- DriverResult HasUserCalibration(SpiAddress address, bool& has_user_calibration);
+ Common::Input::DriverResult HasUserCalibration(SpiAddress address, bool& has_user_calibration);
/// Converts a raw calibration block to an u16 value containing the x axis value
u16 GetXAxisCalibrationValue(std::span<u8> block) const;
diff --git a/src/input_common/helpers/joycon_protocol/common_protocol.cpp b/src/input_common/helpers/joycon_protocol/common_protocol.cpp
index 88f4cec1c..a6eecf980 100644
--- a/src/input_common/helpers/joycon_protocol/common_protocol.cpp
+++ b/src/input_common/helpers/joycon_protocol/common_protocol.cpp
@@ -1,6 +1,7 @@
// SPDX-FileCopyrightText: Copyright 2022 yuzu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
+#include "common/input.h"
#include "common/logging/log.h"
#include "input_common/helpers/joycon_protocol/common_protocol.h"
@@ -21,10 +22,10 @@ void JoyconCommonProtocol::SetNonBlocking() {
SDL_hid_set_nonblocking(hidapi_handle->handle, 1);
}
-DriverResult JoyconCommonProtocol::GetDeviceType(ControllerType& controller_type) {
+Common::Input::DriverResult JoyconCommonProtocol::GetDeviceType(ControllerType& controller_type) {
const auto result = ReadSPI(SpiAddress::DEVICE_TYPE, controller_type);
- if (result == DriverResult::Success) {
+ if (result == Common::Input::DriverResult::Success) {
// Fallback to 3rd party pro controllers
if (controller_type == ControllerType::None) {
controller_type = ControllerType::Pro;
@@ -34,12 +35,13 @@ DriverResult JoyconCommonProtocol::GetDeviceType(ControllerType& controller_type
return result;
}
-DriverResult JoyconCommonProtocol::CheckDeviceAccess(SDL_hid_device_info* device_info) {
+Common::Input::DriverResult JoyconCommonProtocol::CheckDeviceAccess(
+ SDL_hid_device_info* device_info) {
ControllerType controller_type{ControllerType::None};
const auto result = GetDeviceType(controller_type);
- if (result != DriverResult::Success || controller_type == ControllerType::None) {
- return DriverResult::UnsupportedControllerType;
+ if (result != Common::Input::DriverResult::Success || controller_type == ControllerType::None) {
+ return Common::Input::DriverResult::UnsupportedControllerType;
}
hidapi_handle->handle =
@@ -48,32 +50,32 @@ DriverResult JoyconCommonProtocol::CheckDeviceAccess(SDL_hid_device_info* device
if (!hidapi_handle->handle) {
LOG_ERROR(Input, "Yuzu can't gain access to this device: ID {:04X}:{:04X}.",
device_info->vendor_id, device_info->product_id);
- return DriverResult::HandleInUse;
+ return Common::Input::DriverResult::HandleInUse;
}
SetNonBlocking();
- return DriverResult::Success;
+ return Common::Input::DriverResult::Success;
}
-DriverResult JoyconCommonProtocol::SetReportMode(ReportMode report_mode) {
+Common::Input::DriverResult JoyconCommonProtocol::SetReportMode(ReportMode report_mode) {
const std::array<u8, 1> buffer{static_cast<u8>(report_mode)};
return SendSubCommand(SubCommand::SET_REPORT_MODE, buffer);
}
-DriverResult JoyconCommonProtocol::SendRawData(std::span<const u8> buffer) {
+Common::Input::DriverResult JoyconCommonProtocol::SendRawData(std::span<const u8> buffer) {
const auto result = SDL_hid_write(hidapi_handle->handle, buffer.data(), buffer.size());
if (result == -1) {
- return DriverResult::ErrorWritingData;
+ return Common::Input::DriverResult::ErrorWritingData;
}
- return DriverResult::Success;
+ return Common::Input::DriverResult::Success;
}
-DriverResult JoyconCommonProtocol::GetSubCommandResponse(SubCommand sc,
- SubCommandResponse& output) {
+Common::Input::DriverResult JoyconCommonProtocol::GetSubCommandResponse(
+ SubCommand sc, SubCommandResponse& output) {
constexpr int timeout_mili = 66;
- constexpr int MaxTries = 3;
+ constexpr int MaxTries = 10;
int tries = 0;
do {
@@ -84,16 +86,17 @@ DriverResult JoyconCommonProtocol::GetSubCommandResponse(SubCommand sc,
LOG_ERROR(Input, "No response from joycon");
}
if (tries++ > MaxTries) {
- return DriverResult::Timeout;
+ return Common::Input::DriverResult::Timeout;
}
} while (output.input_report.report_mode != ReportMode::SUBCMD_REPLY &&
output.sub_command != sc);
- return DriverResult::Success;
+ return Common::Input::DriverResult::Success;
}
-DriverResult JoyconCommonProtocol::SendSubCommand(SubCommand sc, std::span<const u8> buffer,
- SubCommandResponse& output) {
+Common::Input::DriverResult JoyconCommonProtocol::SendSubCommand(SubCommand sc,
+ std::span<const u8> buffer,
+ SubCommandResponse& output) {
SubCommandPacket packet{
.output_report = OutputReport::RUMBLE_AND_SUBCMD,
.packet_counter = GetCounter(),
@@ -102,26 +105,28 @@ DriverResult JoyconCommonProtocol::SendSubCommand(SubCommand sc, std::span<const
};
if (buffer.size() > packet.command_data.size()) {
- return DriverResult::InvalidParameters;
+ return Common::Input::DriverResult::InvalidParameters;
}
memcpy(packet.command_data.data(), buffer.data(), buffer.size());
auto result = SendData(packet);
- if (result != DriverResult::Success) {
+ if (result != Common::Input::DriverResult::Success) {
return result;
}
return GetSubCommandResponse(sc, output);
}
-DriverResult JoyconCommonProtocol::SendSubCommand(SubCommand sc, std::span<const u8> buffer) {
+Common::Input::DriverResult JoyconCommonProtocol::SendSubCommand(SubCommand sc,
+ std::span<const u8> buffer) {
SubCommandResponse output{};
return SendSubCommand(sc, buffer, output);
}
-DriverResult JoyconCommonProtocol::SendMCUCommand(SubCommand sc, std::span<const u8> buffer) {
+Common::Input::DriverResult JoyconCommonProtocol::SendMCUCommand(SubCommand sc,
+ std::span<const u8> buffer) {
SubCommandPacket packet{
.output_report = OutputReport::MCU_DATA,
.packet_counter = GetCounter(),
@@ -130,7 +135,7 @@ DriverResult JoyconCommonProtocol::SendMCUCommand(SubCommand sc, std::span<const
};
if (buffer.size() > packet.command_data.size()) {
- return DriverResult::InvalidParameters;
+ return Common::Input::DriverResult::InvalidParameters;
}
memcpy(packet.command_data.data(), buffer.data(), buffer.size());
@@ -138,7 +143,7 @@ DriverResult JoyconCommonProtocol::SendMCUCommand(SubCommand sc, std::span<const
return SendData(packet);
}
-DriverResult JoyconCommonProtocol::SendVibrationReport(std::span<const u8> buffer) {
+Common::Input::DriverResult JoyconCommonProtocol::SendVibrationReport(std::span<const u8> buffer) {
VibrationPacket packet{
.output_report = OutputReport::RUMBLE_ONLY,
.packet_counter = GetCounter(),
@@ -146,7 +151,7 @@ DriverResult JoyconCommonProtocol::SendVibrationReport(std::span<const u8> buffe
};
if (buffer.size() > packet.vibration_data.size()) {
- return DriverResult::InvalidParameters;
+ return Common::Input::DriverResult::InvalidParameters;
}
memcpy(packet.vibration_data.data(), buffer.data(), buffer.size());
@@ -154,7 +159,8 @@ DriverResult JoyconCommonProtocol::SendVibrationReport(std::span<const u8> buffe
return SendData(packet);
}
-DriverResult JoyconCommonProtocol::ReadRawSPI(SpiAddress addr, std::span<u8> output) {
+Common::Input::DriverResult JoyconCommonProtocol::ReadRawSPI(SpiAddress addr,
+ std::span<u8> output) {
constexpr std::size_t HeaderSize = 5;
constexpr std::size_t MaxTries = 5;
std::size_t tries = 0;
@@ -168,36 +174,36 @@ DriverResult JoyconCommonProtocol::ReadRawSPI(SpiAddress addr, std::span<u8> out
memcpy(buffer.data(), &packet_data, sizeof(ReadSpiPacket));
do {
const auto result = SendSubCommand(SubCommand::SPI_FLASH_READ, buffer, response);
- if (result != DriverResult::Success) {
+ if (result != Common::Input::DriverResult::Success) {
return result;
}
if (tries++ > MaxTries) {
- return DriverResult::Timeout;
+ return Common::Input::DriverResult::Timeout;
}
} while (response.spi_address != addr);
if (response.command_data.size() < packet_data.size + HeaderSize) {
- return DriverResult::WrongReply;
+ return Common::Input::DriverResult::WrongReply;
}
// Remove header from output
memcpy(output.data(), response.command_data.data() + HeaderSize, packet_data.size);
- return DriverResult::Success;
+ return Common::Input::DriverResult::Success;
}
-DriverResult JoyconCommonProtocol::EnableMCU(bool enable) {
+Common::Input::DriverResult JoyconCommonProtocol::EnableMCU(bool enable) {
const std::array<u8, 1> mcu_state{static_cast<u8>(enable ? 1 : 0)};
const auto result = SendSubCommand(SubCommand::SET_MCU_STATE, mcu_state);
- if (result != DriverResult::Success) {
+ if (result != Common::Input::DriverResult::Success) {
LOG_ERROR(Input, "Failed with error {}", result);
}
return result;
}
-DriverResult JoyconCommonProtocol::ConfigureMCU(const MCUConfig& config) {
+Common::Input::DriverResult JoyconCommonProtocol::ConfigureMCU(const MCUConfig& config) {
LOG_DEBUG(Input, "ConfigureMCU");
std::array<u8, sizeof(MCUConfig)> config_buffer;
memcpy(config_buffer.data(), &config, sizeof(MCUConfig));
@@ -205,15 +211,15 @@ DriverResult JoyconCommonProtocol::ConfigureMCU(const MCUConfig& config) {
const auto result = SendSubCommand(SubCommand::SET_MCU_CONFIG, config_buffer);
- if (result != DriverResult::Success) {
+ if (result != Common::Input::DriverResult::Success) {
LOG_ERROR(Input, "Failed with error {}", result);
}
return result;
}
-DriverResult JoyconCommonProtocol::GetMCUDataResponse(ReportMode report_mode,
- MCUCommandResponse& output) {
+Common::Input::DriverResult JoyconCommonProtocol::GetMCUDataResponse(ReportMode report_mode,
+ MCUCommandResponse& output) {
constexpr int TimeoutMili = 200;
constexpr int MaxTries = 9;
int tries = 0;
@@ -226,17 +232,18 @@ DriverResult JoyconCommonProtocol::GetMCUDataResponse(ReportMode report_mode,
LOG_ERROR(Input, "No response from joycon attempt {}", tries);
}
if (tries++ > MaxTries) {
- return DriverResult::Timeout;
+ return Common::Input::DriverResult::Timeout;
}
} while (output.input_report.report_mode != report_mode ||
output.mcu_report == MCUReport::EmptyAwaitingCmd);
- return DriverResult::Success;
+ return Common::Input::DriverResult::Success;
}
-DriverResult JoyconCommonProtocol::SendMCUData(ReportMode report_mode, MCUSubCommand sc,
- std::span<const u8> buffer,
- MCUCommandResponse& output) {
+Common::Input::DriverResult JoyconCommonProtocol::SendMCUData(ReportMode report_mode,
+ MCUSubCommand sc,
+ std::span<const u8> buffer,
+ MCUCommandResponse& output) {
SubCommandPacket packet{
.output_report = OutputReport::MCU_DATA,
.packet_counter = GetCounter(),
@@ -245,23 +252,24 @@ DriverResult JoyconCommonProtocol::SendMCUData(ReportMode report_mode, MCUSubCom
};
if (buffer.size() > packet.command_data.size()) {
- return DriverResult::InvalidParameters;
+ return Common::Input::DriverResult::InvalidParameters;
}
memcpy(packet.command_data.data(), buffer.data(), buffer.size());
auto result = SendData(packet);
- if (result != DriverResult::Success) {
+ if (result != Common::Input::DriverResult::Success) {
return result;
}
result = GetMCUDataResponse(report_mode, output);
- return DriverResult::Success;
+ return Common::Input::DriverResult::Success;
}
-DriverResult JoyconCommonProtocol::WaitSetMCUMode(ReportMode report_mode, MCUMode mode) {
+Common::Input::DriverResult JoyconCommonProtocol::WaitSetMCUMode(ReportMode report_mode,
+ MCUMode mode) {
MCUCommandResponse output{};
constexpr std::size_t MaxTries{16};
std::size_t tries{};
@@ -269,17 +277,17 @@ DriverResult JoyconCommonProtocol::WaitSetMCUMode(ReportMode report_mode, MCUMod
do {
const auto result = SendMCUData(report_mode, MCUSubCommand::SetDeviceMode, {}, output);
- if (result != DriverResult::Success) {
+ if (result != Common::Input::DriverResult::Success) {
return result;
}
if (tries++ > MaxTries) {
- return DriverResult::WrongReply;
+ return Common::Input::DriverResult::WrongReply;
}
} while (output.mcu_report != MCUReport::StateReport ||
output.mcu_data[6] != static_cast<u8>(mode));
- return DriverResult::Success;
+ return Common::Input::DriverResult::Success;
}
// crc-8-ccitt / polynomial 0x07 look up table
diff --git a/src/input_common/helpers/joycon_protocol/common_protocol.h b/src/input_common/helpers/joycon_protocol/common_protocol.h
index 411ec018a..dd667ca2b 100644
--- a/src/input_common/helpers/joycon_protocol/common_protocol.h
+++ b/src/input_common/helpers/joycon_protocol/common_protocol.h
@@ -38,30 +38,30 @@ public:
* Sends a request to obtain the joycon type from device
* @returns controller type of the joycon
*/
- DriverResult GetDeviceType(ControllerType& controller_type);
+ Common::Input::DriverResult GetDeviceType(ControllerType& controller_type);
/**
* Verifies and sets the joycon_handle if device is valid
* @param device info from the driver
* @returns success if the device is valid
*/
- DriverResult CheckDeviceAccess(SDL_hid_device_info* device);
+ Common::Input::DriverResult CheckDeviceAccess(SDL_hid_device_info* device);
/**
* Sends a request to set the polling mode of the joycon
* @param report_mode polling mode to be set
*/
- DriverResult SetReportMode(Joycon::ReportMode report_mode);
+ Common::Input::DriverResult SetReportMode(Joycon::ReportMode report_mode);
/**
* Sends data to the joycon device
* @param buffer data to be send
*/
- DriverResult SendRawData(std::span<const u8> buffer);
+ Common::Input::DriverResult SendRawData(std::span<const u8> buffer);
template <typename Output>
requires std::is_trivially_copyable_v<Output>
- DriverResult SendData(const Output& output) {
+ Common::Input::DriverResult SendData(const Output& output) {
std::array<u8, sizeof(Output)> buffer;
std::memcpy(buffer.data(), &output, sizeof(Output));
return SendRawData(buffer);
@@ -72,7 +72,8 @@ public:
* @param sub_command type of data to be returned
* @returns a buffer containing the response
*/
- DriverResult GetSubCommandResponse(SubCommand sub_command, SubCommandResponse& output);
+ Common::Input::DriverResult GetSubCommandResponse(SubCommand sub_command,
+ SubCommandResponse& output);
/**
* Sends a sub command to the device and waits for it's reply
@@ -80,35 +81,35 @@ public:
* @param buffer data to be send
* @returns output buffer containing the response
*/
- DriverResult SendSubCommand(SubCommand sc, std::span<const u8> buffer,
- SubCommandResponse& output);
+ Common::Input::DriverResult SendSubCommand(SubCommand sc, std::span<const u8> buffer,
+ SubCommandResponse& output);
/**
* Sends a sub command to the device and waits for it's reply and ignores the output
* @param sc sub command to be send
* @param buffer data to be send
*/
- DriverResult SendSubCommand(SubCommand sc, std::span<const u8> buffer);
+ Common::Input::DriverResult SendSubCommand(SubCommand sc, std::span<const u8> buffer);
/**
* Sends a mcu command to the device
* @param sc sub command to be send
* @param buffer data to be send
*/
- DriverResult SendMCUCommand(SubCommand sc, std::span<const u8> buffer);
+ Common::Input::DriverResult SendMCUCommand(SubCommand sc, std::span<const u8> buffer);
/**
* Sends vibration data to the joycon
* @param buffer data to be send
*/
- DriverResult SendVibrationReport(std::span<const u8> buffer);
+ Common::Input::DriverResult SendVibrationReport(std::span<const u8> buffer);
/**
* Reads the SPI memory stored on the joycon
* @param Initial address location
* @returns output buffer containing the response
*/
- DriverResult ReadRawSPI(SpiAddress addr, std::span<u8> output);
+ Common::Input::DriverResult ReadRawSPI(SpiAddress addr, std::span<u8> output);
/**
* Reads the SPI memory stored on the joycon
@@ -117,37 +118,38 @@ public:
*/
template <typename Output>
requires std::is_trivially_copyable_v<Output>
- DriverResult ReadSPI(SpiAddress addr, Output& output) {
+ Common::Input::DriverResult ReadSPI(SpiAddress addr, Output& output) {
std::array<u8, sizeof(Output)> buffer;
output = {};
const auto result = ReadRawSPI(addr, buffer);
- if (result != DriverResult::Success) {
+ if (result != Common::Input::DriverResult::Success) {
return result;
}
std::memcpy(&output, buffer.data(), sizeof(Output));
- return DriverResult::Success;
+ return Common::Input::DriverResult::Success;
}
/**
* Enables MCU chip on the joycon
* @param enable if true the chip will be enabled
*/
- DriverResult EnableMCU(bool enable);
+ Common::Input::DriverResult EnableMCU(bool enable);
/**
* Configures the MCU to the corresponding mode
* @param MCUConfig configuration
*/
- DriverResult ConfigureMCU(const MCUConfig& config);
+ Common::Input::DriverResult ConfigureMCU(const MCUConfig& config);
/**
* Waits until there's MCU data available. On timeout returns error
* @param report mode of the expected reply
* @returns a buffer containing the response
*/
- DriverResult GetMCUDataResponse(ReportMode report_mode_, MCUCommandResponse& output);
+ Common::Input::DriverResult GetMCUDataResponse(ReportMode report_mode_,
+ MCUCommandResponse& output);
/**
* Sends data to the MCU chip and waits for it's reply
@@ -156,15 +158,15 @@ public:
* @param buffer data to be send
* @returns output buffer containing the response
*/
- DriverResult SendMCUData(ReportMode report_mode, MCUSubCommand sc, std::span<const u8> buffer,
- MCUCommandResponse& output);
+ Common::Input::DriverResult SendMCUData(ReportMode report_mode, MCUSubCommand sc,
+ std::span<const u8> buffer, MCUCommandResponse& output);
/**
* Wait's until the MCU chip is on the specified mode
* @param report mode of the expected reply
* @param MCUMode configuration
*/
- DriverResult WaitSetMCUMode(ReportMode report_mode, MCUMode mode);
+ Common::Input::DriverResult WaitSetMCUMode(ReportMode report_mode, MCUMode mode);
/**
* Calculates the checksum from the MCU data
diff --git a/src/input_common/helpers/joycon_protocol/generic_functions.cpp b/src/input_common/helpers/joycon_protocol/generic_functions.cpp
index 548a4b9e3..e9a056448 100644
--- a/src/input_common/helpers/joycon_protocol/generic_functions.cpp
+++ b/src/input_common/helpers/joycon_protocol/generic_functions.cpp
@@ -1,6 +1,7 @@
// SPDX-FileCopyrightText: Copyright 2022 yuzu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
+#include "common/input.h"
#include "common/logging/log.h"
#include "input_common/helpers/joycon_protocol/generic_functions.h"
@@ -9,73 +10,74 @@ namespace InputCommon::Joycon {
GenericProtocol::GenericProtocol(std::shared_ptr<JoyconHandle> handle)
: JoyconCommonProtocol(std::move(handle)) {}
-DriverResult GenericProtocol::EnablePassiveMode() {
+Common::Input::DriverResult GenericProtocol::EnablePassiveMode() {
ScopedSetBlocking sb(this);
return SetReportMode(ReportMode::SIMPLE_HID_MODE);
}
-DriverResult GenericProtocol::EnableActiveMode() {
+Common::Input::DriverResult GenericProtocol::EnableActiveMode() {
ScopedSetBlocking sb(this);
return SetReportMode(ReportMode::STANDARD_FULL_60HZ);
}
-DriverResult GenericProtocol::SetLowPowerMode(bool enable) {
+Common::Input::DriverResult GenericProtocol::SetLowPowerMode(bool enable) {
ScopedSetBlocking sb(this);
const std::array<u8, 1> buffer{static_cast<u8>(enable ? 1 : 0)};
return SendSubCommand(SubCommand::LOW_POWER_MODE, buffer);
}
-DriverResult GenericProtocol::TriggersElapsed() {
+Common::Input::DriverResult GenericProtocol::TriggersElapsed() {
ScopedSetBlocking sb(this);
return SendSubCommand(SubCommand::TRIGGERS_ELAPSED, {});
}
-DriverResult GenericProtocol::GetDeviceInfo(DeviceInfo& device_info) {
+Common::Input::DriverResult GenericProtocol::GetDeviceInfo(DeviceInfo& device_info) {
ScopedSetBlocking sb(this);
SubCommandResponse output{};
const auto result = SendSubCommand(SubCommand::REQ_DEV_INFO, {}, output);
device_info = {};
- if (result == DriverResult::Success) {
+ if (result == Common::Input::DriverResult::Success) {
device_info = output.device_info;
}
return result;
}
-DriverResult GenericProtocol::GetControllerType(ControllerType& controller_type) {
+Common::Input::DriverResult GenericProtocol::GetControllerType(ControllerType& controller_type) {
return GetDeviceType(controller_type);
}
-DriverResult GenericProtocol::EnableImu(bool enable) {
+Common::Input::DriverResult GenericProtocol::EnableImu(bool enable) {
ScopedSetBlocking sb(this);
const std::array<u8, 1> buffer{static_cast<u8>(enable ? 1 : 0)};
return SendSubCommand(SubCommand::ENABLE_IMU, buffer);
}
-DriverResult GenericProtocol::SetImuConfig(GyroSensitivity gsen, GyroPerformance gfrec,
- AccelerometerSensitivity asen,
- AccelerometerPerformance afrec) {
+Common::Input::DriverResult GenericProtocol::SetImuConfig(GyroSensitivity gsen,
+ GyroPerformance gfrec,
+ AccelerometerSensitivity asen,
+ AccelerometerPerformance afrec) {
ScopedSetBlocking sb(this);
const std::array<u8, 4> buffer{static_cast<u8>(gsen), static_cast<u8>(asen),
static_cast<u8>(gfrec), static_cast<u8>(afrec)};
return SendSubCommand(SubCommand::SET_IMU_SENSITIVITY, buffer);
}
-DriverResult GenericProtocol::GetBattery(u32& battery_level) {
+Common::Input::DriverResult GenericProtocol::GetBattery(u32& battery_level) {
// This function is meant to request the high resolution battery status
battery_level = 0;
- return DriverResult::NotSupported;
+ return Common::Input::DriverResult::NotSupported;
}
-DriverResult GenericProtocol::GetColor(Color& color) {
+Common::Input::DriverResult GenericProtocol::GetColor(Color& color) {
ScopedSetBlocking sb(this);
std::array<u8, 12> buffer{};
const auto result = ReadRawSPI(SpiAddress::COLOR_DATA, buffer);
color = {};
- if (result == DriverResult::Success) {
+ if (result == Common::Input::DriverResult::Success) {
color.body = static_cast<u32>((buffer[0] << 16) | (buffer[1] << 8) | buffer[2]);
color.buttons = static_cast<u32>((buffer[3] << 16) | (buffer[4] << 8) | buffer[5]);
color.left_grip = static_cast<u32>((buffer[6] << 16) | (buffer[7] << 8) | buffer[8]);
@@ -85,26 +87,26 @@ DriverResult GenericProtocol::GetColor(Color& color) {
return result;
}
-DriverResult GenericProtocol::GetSerialNumber(SerialNumber& serial_number) {
+Common::Input::DriverResult GenericProtocol::GetSerialNumber(SerialNumber& serial_number) {
ScopedSetBlocking sb(this);
std::array<u8, 16> buffer{};
const auto result = ReadRawSPI(SpiAddress::SERIAL_NUMBER, buffer);
serial_number = {};
- if (result == DriverResult::Success) {
+ if (result == Common::Input::DriverResult::Success) {
memcpy(serial_number.data(), buffer.data() + 1, sizeof(SerialNumber));
}
return result;
}
-DriverResult GenericProtocol::GetTemperature(u32& temperature) {
+Common::Input::DriverResult GenericProtocol::GetTemperature(u32& temperature) {
// Not all devices have temperature sensor
temperature = 25;
- return DriverResult::NotSupported;
+ return Common::Input::DriverResult::NotSupported;
}
-DriverResult GenericProtocol::GetVersionNumber(FirmwareVersion& version) {
+Common::Input::DriverResult GenericProtocol::GetVersionNumber(FirmwareVersion& version) {
DeviceInfo device_info{};
const auto result = GetDeviceInfo(device_info);
@@ -113,23 +115,23 @@ DriverResult GenericProtocol::GetVersionNumber(FirmwareVersion& version) {
return result;
}
-DriverResult GenericProtocol::SetHomeLight() {
+Common::Input::DriverResult GenericProtocol::SetHomeLight() {
ScopedSetBlocking sb(this);
static constexpr std::array<u8, 3> buffer{0x0f, 0xf0, 0x00};
return SendSubCommand(SubCommand::SET_HOME_LIGHT, buffer);
}
-DriverResult GenericProtocol::SetLedBusy() {
- return DriverResult::NotSupported;
+Common::Input::DriverResult GenericProtocol::SetLedBusy() {
+ return Common::Input::DriverResult::NotSupported;
}
-DriverResult GenericProtocol::SetLedPattern(u8 leds) {
+Common::Input::DriverResult GenericProtocol::SetLedPattern(u8 leds) {
ScopedSetBlocking sb(this);
const std::array<u8, 1> buffer{leds};
return SendSubCommand(SubCommand::SET_PLAYER_LIGHTS, buffer);
}
-DriverResult GenericProtocol::SetLedBlinkPattern(u8 leds) {
+Common::Input::DriverResult GenericProtocol::SetLedBlinkPattern(u8 leds) {
return SetLedPattern(static_cast<u8>(leds << 4));
}
diff --git a/src/input_common/helpers/joycon_protocol/generic_functions.h b/src/input_common/helpers/joycon_protocol/generic_functions.h
index 424831e81..90fcd17f6 100644
--- a/src/input_common/helpers/joycon_protocol/generic_functions.h
+++ b/src/input_common/helpers/joycon_protocol/generic_functions.h
@@ -11,6 +11,10 @@
#include "input_common/helpers/joycon_protocol/common_protocol.h"
#include "input_common/helpers/joycon_protocol/joycon_types.h"
+namespace Common::Input {
+enum class DriverResult;
+}
+
namespace InputCommon::Joycon {
/// Joycon driver functions that easily implemented
@@ -20,34 +24,34 @@ public:
/// Enables passive mode. This mode only sends button data on change. Sticks will return digital
/// data instead of analog. Motion will be disabled
- DriverResult EnablePassiveMode();
+ Common::Input::DriverResult EnablePassiveMode();
/// Enables active mode. This mode will return the current status every 5-15ms
- DriverResult EnableActiveMode();
+ Common::Input::DriverResult EnableActiveMode();
/// Enables or disables the low power mode
- DriverResult SetLowPowerMode(bool enable);
+ Common::Input::DriverResult SetLowPowerMode(bool enable);
/// Unknown function used by the switch
- DriverResult TriggersElapsed();
+ Common::Input::DriverResult TriggersElapsed();
/**
* Sends a request to obtain the joycon firmware and mac from handle
* @returns controller device info
*/
- DriverResult GetDeviceInfo(DeviceInfo& controller_type);
+ Common::Input::DriverResult GetDeviceInfo(DeviceInfo& controller_type);
/**
* Sends a request to obtain the joycon type from handle
* @returns controller type of the joycon
*/
- DriverResult GetControllerType(ControllerType& controller_type);
+ Common::Input::DriverResult GetControllerType(ControllerType& controller_type);
/**
* Enables motion input
* @param enable if true motion data will be enabled
*/
- DriverResult EnableImu(bool enable);
+ Common::Input::DriverResult EnableImu(bool enable);
/**
* Configures the motion sensor with the specified parameters
@@ -56,59 +60,60 @@ public:
* @param asen accelerometer sensitivity in G force
* @param afrec accelerometer frequency in hertz
*/
- DriverResult SetImuConfig(GyroSensitivity gsen, GyroPerformance gfrec,
- AccelerometerSensitivity asen, AccelerometerPerformance afrec);
+ Common::Input::DriverResult SetImuConfig(GyroSensitivity gsen, GyroPerformance gfrec,
+ AccelerometerSensitivity asen,
+ AccelerometerPerformance afrec);
/**
* Request battery level from the device
* @returns battery level
*/
- DriverResult GetBattery(u32& battery_level);
+ Common::Input::DriverResult GetBattery(u32& battery_level);
/**
* Request joycon colors from the device
* @returns colors of the body and buttons
*/
- DriverResult GetColor(Color& color);
+ Common::Input::DriverResult GetColor(Color& color);
/**
* Request joycon serial number from the device
* @returns 16 byte serial number
*/
- DriverResult GetSerialNumber(SerialNumber& serial_number);
+ Common::Input::DriverResult GetSerialNumber(SerialNumber& serial_number);
/**
* Request joycon serial number from the device
* @returns 16 byte serial number
*/
- DriverResult GetTemperature(u32& temperature);
+ Common::Input::DriverResult GetTemperature(u32& temperature);
/**
* Request joycon serial number from the device
* @returns 16 byte serial number
*/
- DriverResult GetVersionNumber(FirmwareVersion& version);
+ Common::Input::DriverResult GetVersionNumber(FirmwareVersion& version);
/**
* Sets home led behaviour
*/
- DriverResult SetHomeLight();
+ Common::Input::DriverResult SetHomeLight();
/**
* Sets home led into a slow breathing state
*/
- DriverResult SetLedBusy();
+ Common::Input::DriverResult SetLedBusy();
/**
* Sets the 4 player leds on the joycon on a solid state
* @params bit flag containing the led state
*/
- DriverResult SetLedPattern(u8 leds);
+ Common::Input::DriverResult SetLedPattern(u8 leds);
/**
* Sets the 4 player leds on the joycon on a blinking state
* @returns bit flag containing the led state
*/
- DriverResult SetLedBlinkPattern(u8 leds);
+ Common::Input::DriverResult SetLedBlinkPattern(u8 leds);
};
} // namespace InputCommon::Joycon
diff --git a/src/input_common/helpers/joycon_protocol/irs.cpp b/src/input_common/helpers/joycon_protocol/irs.cpp
index 731fd5981..68b0589e3 100644
--- a/src/input_common/helpers/joycon_protocol/irs.cpp
+++ b/src/input_common/helpers/joycon_protocol/irs.cpp
@@ -1,7 +1,7 @@
// SPDX-FileCopyrightText: Copyright 2022 yuzu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
-#include <thread>
+#include "common/input.h"
#include "common/logging/log.h"
#include "input_common/helpers/joycon_protocol/irs.h"
@@ -10,21 +10,21 @@ namespace InputCommon::Joycon {
IrsProtocol::IrsProtocol(std::shared_ptr<JoyconHandle> handle)
: JoyconCommonProtocol(std::move(handle)) {}
-DriverResult IrsProtocol::EnableIrs() {
+Common::Input::DriverResult IrsProtocol::EnableIrs() {
LOG_INFO(Input, "Enable IRS");
ScopedSetBlocking sb(this);
- DriverResult result{DriverResult::Success};
+ Common::Input::DriverResult result{Common::Input::DriverResult::Success};
- if (result == DriverResult::Success) {
+ if (result == Common::Input::DriverResult::Success) {
result = SetReportMode(ReportMode::NFC_IR_MODE_60HZ);
}
- if (result == DriverResult::Success) {
+ if (result == Common::Input::DriverResult::Success) {
result = EnableMCU(true);
}
- if (result == DriverResult::Success) {
+ if (result == Common::Input::DriverResult::Success) {
result = WaitSetMCUMode(ReportMode::NFC_IR_MODE_60HZ, MCUMode::Standby);
}
- if (result == DriverResult::Success) {
+ if (result == Common::Input::DriverResult::Success) {
const MCUConfig config{
.command = MCUCommand::ConfigureMCU,
.sub_command = MCUSubCommand::SetMCUMode,
@@ -34,16 +34,16 @@ DriverResult IrsProtocol::EnableIrs() {
result = ConfigureMCU(config);
}
- if (result == DriverResult::Success) {
+ if (result == Common::Input::DriverResult::Success) {
result = WaitSetMCUMode(ReportMode::NFC_IR_MODE_60HZ, MCUMode::IR);
}
- if (result == DriverResult::Success) {
+ if (result == Common::Input::DriverResult::Success) {
result = ConfigureIrs();
}
- if (result == DriverResult::Success) {
+ if (result == Common::Input::DriverResult::Success) {
result = WriteRegistersStep1();
}
- if (result == DriverResult::Success) {
+ if (result == Common::Input::DriverResult::Success) {
result = WriteRegistersStep2();
}
@@ -52,12 +52,12 @@ DriverResult IrsProtocol::EnableIrs() {
return result;
}
-DriverResult IrsProtocol::DisableIrs() {
+Common::Input::DriverResult IrsProtocol::DisableIrs() {
LOG_DEBUG(Input, "Disable IRS");
ScopedSetBlocking sb(this);
- DriverResult result{DriverResult::Success};
+ Common::Input::DriverResult result{Common::Input::DriverResult::Success};
- if (result == DriverResult::Success) {
+ if (result == Common::Input::DriverResult::Success) {
result = EnableMCU(false);
}
@@ -66,7 +66,7 @@ DriverResult IrsProtocol::DisableIrs() {
return result;
}
-DriverResult IrsProtocol::SetIrsConfig(IrsMode mode, IrsResolution format) {
+Common::Input::DriverResult IrsProtocol::SetIrsConfig(IrsMode mode, IrsResolution format) {
irs_mode = mode;
switch (format) {
case IrsResolution::Size320x240:
@@ -103,10 +103,10 @@ DriverResult IrsProtocol::SetIrsConfig(IrsMode mode, IrsResolution format) {
return EnableIrs();
}
- return DriverResult::Success;
+ return Common::Input::DriverResult::Success;
}
-DriverResult IrsProtocol::RequestImage(std::span<u8> buffer) {
+Common::Input::DriverResult IrsProtocol::RequestImage(std::span<u8> buffer) {
const u8 next_packet_fragment =
static_cast<u8>((packet_fragment + 1) % (static_cast<u8>(fragments) + 1));
@@ -129,7 +129,7 @@ DriverResult IrsProtocol::RequestImage(std::span<u8> buffer) {
return RequestFrame(packet_fragment);
}
-DriverResult IrsProtocol::ConfigureIrs() {
+Common::Input::DriverResult IrsProtocol::ConfigureIrs() {
LOG_DEBUG(Input, "Configure IRS");
constexpr std::size_t max_tries = 28;
SubCommandResponse output{};
@@ -152,20 +152,20 @@ DriverResult IrsProtocol::ConfigureIrs() {
do {
const auto result = SendSubCommand(SubCommand::SET_MCU_CONFIG, request_data, output);
- if (result != DriverResult::Success) {
+ if (result != Common::Input::DriverResult::Success) {
return result;
}
if (tries++ >= max_tries) {
- return DriverResult::WrongReply;
+ return Common::Input::DriverResult::WrongReply;
}
} while (output.command_data[0] != 0x0b);
- return DriverResult::Success;
+ return Common::Input::DriverResult::Success;
}
-DriverResult IrsProtocol::WriteRegistersStep1() {
+Common::Input::DriverResult IrsProtocol::WriteRegistersStep1() {
LOG_DEBUG(Input, "WriteRegistersStep1");
- DriverResult result{DriverResult::Success};
+ Common::Input::DriverResult result{Common::Input::DriverResult::Success};
constexpr std::size_t max_tries = 28;
SubCommandResponse output{};
std::size_t tries = 0;
@@ -197,7 +197,7 @@ DriverResult IrsProtocol::WriteRegistersStep1() {
mcu_request[36] = CalculateMCU_CRC8(mcu_request.data(), 36);
mcu_request[37] = 0xFF;
- if (result != DriverResult::Success) {
+ if (result != Common::Input::DriverResult::Success) {
return result;
}
@@ -205,26 +205,26 @@ DriverResult IrsProtocol::WriteRegistersStep1() {
result = SendSubCommand(SubCommand::SET_MCU_CONFIG, request_data, output);
// First time we need to set the report mode
- if (result == DriverResult::Success && tries == 0) {
+ if (result == Common::Input::DriverResult::Success && tries == 0) {
result = SendMCUCommand(SubCommand::SET_REPORT_MODE, mcu_request);
}
- if (result == DriverResult::Success && tries == 0) {
+ if (result == Common::Input::DriverResult::Success && tries == 0) {
GetSubCommandResponse(SubCommand::SET_MCU_CONFIG, output);
}
- if (result != DriverResult::Success) {
+ if (result != Common::Input::DriverResult::Success) {
return result;
}
if (tries++ >= max_tries) {
- return DriverResult::WrongReply;
+ return Common::Input::DriverResult::WrongReply;
}
} while (!(output.command_data[0] == 0x13 && output.command_data[2] == 0x07) &&
output.command_data[0] != 0x23);
- return DriverResult::Success;
+ return Common::Input::DriverResult::Success;
}
-DriverResult IrsProtocol::WriteRegistersStep2() {
+Common::Input::DriverResult IrsProtocol::WriteRegistersStep2() {
LOG_DEBUG(Input, "WriteRegistersStep2");
constexpr std::size_t max_tries = 28;
SubCommandResponse output{};
@@ -255,18 +255,18 @@ DriverResult IrsProtocol::WriteRegistersStep2() {
do {
const auto result = SendSubCommand(SubCommand::SET_MCU_CONFIG, request_data, output);
- if (result != DriverResult::Success) {
+ if (result != Common::Input::DriverResult::Success) {
return result;
}
if (tries++ >= max_tries) {
- return DriverResult::WrongReply;
+ return Common::Input::DriverResult::WrongReply;
}
} while (output.command_data[0] != 0x13 && output.command_data[0] != 0x23);
- return DriverResult::Success;
+ return Common::Input::DriverResult::Success;
}
-DriverResult IrsProtocol::RequestFrame(u8 frame) {
+Common::Input::DriverResult IrsProtocol::RequestFrame(u8 frame) {
std::array<u8, 38> mcu_request{};
mcu_request[3] = frame;
mcu_request[36] = CalculateMCU_CRC8(mcu_request.data(), 36);
@@ -274,7 +274,7 @@ DriverResult IrsProtocol::RequestFrame(u8 frame) {
return SendMCUCommand(SubCommand::SET_REPORT_MODE, mcu_request);
}
-DriverResult IrsProtocol::ResendFrame(u8 frame) {
+Common::Input::DriverResult IrsProtocol::ResendFrame(u8 frame) {
std::array<u8, 38> mcu_request{};
mcu_request[1] = 0x1;
mcu_request[2] = frame;
diff --git a/src/input_common/helpers/joycon_protocol/irs.h b/src/input_common/helpers/joycon_protocol/irs.h
index 76dfa02ea..714cbb6b2 100644
--- a/src/input_common/helpers/joycon_protocol/irs.h
+++ b/src/input_common/helpers/joycon_protocol/irs.h
@@ -13,19 +13,23 @@
#include "input_common/helpers/joycon_protocol/common_protocol.h"
#include "input_common/helpers/joycon_protocol/joycon_types.h"
+namespace Common::Input {
+enum class DriverResult;
+}
+
namespace InputCommon::Joycon {
class IrsProtocol final : private JoyconCommonProtocol {
public:
explicit IrsProtocol(std::shared_ptr<JoyconHandle> handle);
- DriverResult EnableIrs();
+ Common::Input::DriverResult EnableIrs();
- DriverResult DisableIrs();
+ Common::Input::DriverResult DisableIrs();
- DriverResult SetIrsConfig(IrsMode mode, IrsResolution format);
+ Common::Input::DriverResult SetIrsConfig(IrsMode mode, IrsResolution format);
- DriverResult RequestImage(std::span<u8> buffer);
+ Common::Input::DriverResult RequestImage(std::span<u8> buffer);
std::vector<u8> GetImage() const;
@@ -34,13 +38,13 @@ public:
bool IsEnabled() const;
private:
- DriverResult ConfigureIrs();
+ Common::Input::DriverResult ConfigureIrs();
- DriverResult WriteRegistersStep1();
- DriverResult WriteRegistersStep2();
+ Common::Input::DriverResult WriteRegistersStep1();
+ Common::Input::DriverResult WriteRegistersStep2();
- DriverResult RequestFrame(u8 frame);
- DriverResult ResendFrame(u8 frame);
+ Common::Input::DriverResult RequestFrame(u8 frame);
+ Common::Input::DriverResult ResendFrame(u8 frame);
IrsMode irs_mode{IrsMode::ImageTransfer};
IrsResolution resolution{IrsResolution::Size40x30};
diff --git a/src/input_common/helpers/joycon_protocol/joycon_types.h b/src/input_common/helpers/joycon_protocol/joycon_types.h
index e0e431156..77a43c67a 100644
--- a/src/input_common/helpers/joycon_protocol/joycon_types.h
+++ b/src/input_common/helpers/joycon_protocol/joycon_types.h
@@ -402,23 +402,6 @@ enum class ExternalDeviceId : u16 {
Starlink = 0x2800,
};
-enum class DriverResult {
- Success,
- WrongReply,
- Timeout,
- InvalidParameters,
- UnsupportedControllerType,
- HandleInUse,
- ErrorReadingData,
- ErrorWritingData,
- NoDeviceDetected,
- InvalidHandle,
- NotSupported,
- Disabled,
- Delayed,
- Unknown,
-};
-
struct MotionSensorCalibration {
s16 offset;
s16 scale;
diff --git a/src/input_common/helpers/joycon_protocol/nfc.cpp b/src/input_common/helpers/joycon_protocol/nfc.cpp
index 261f46255..09953394b 100644
--- a/src/input_common/helpers/joycon_protocol/nfc.cpp
+++ b/src/input_common/helpers/joycon_protocol/nfc.cpp
@@ -1,7 +1,7 @@
// SPDX-FileCopyrightText: Copyright 2022 yuzu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
-#include <thread>
+#include "common/input.h"
#include "common/logging/log.h"
#include "input_common/helpers/joycon_protocol/nfc.h"
@@ -10,21 +10,21 @@ namespace InputCommon::Joycon {
NfcProtocol::NfcProtocol(std::shared_ptr<JoyconHandle> handle)
: JoyconCommonProtocol(std::move(handle)) {}
-DriverResult NfcProtocol::EnableNfc() {
+Common::Input::DriverResult NfcProtocol::EnableNfc() {
LOG_INFO(Input, "Enable NFC");
ScopedSetBlocking sb(this);
- DriverResult result{DriverResult::Success};
+ Common::Input::DriverResult result{Common::Input::DriverResult::Success};
- if (result == DriverResult::Success) {
+ if (result == Common::Input::DriverResult::Success) {
result = SetReportMode(ReportMode::NFC_IR_MODE_60HZ);
}
- if (result == DriverResult::Success) {
+ if (result == Common::Input::DriverResult::Success) {
result = EnableMCU(true);
}
- if (result == DriverResult::Success) {
+ if (result == Common::Input::DriverResult::Success) {
result = WaitSetMCUMode(ReportMode::NFC_IR_MODE_60HZ, MCUMode::Standby);
}
- if (result == DriverResult::Success) {
+ if (result == Common::Input::DriverResult::Success) {
const MCUConfig config{
.command = MCUCommand::ConfigureMCU,
.sub_command = MCUSubCommand::SetMCUMode,
@@ -34,32 +34,32 @@ DriverResult NfcProtocol::EnableNfc() {
result = ConfigureMCU(config);
}
- if (result == DriverResult::Success) {
+ if (result == Common::Input::DriverResult::Success) {
result = WaitSetMCUMode(ReportMode::NFC_IR_MODE_60HZ, MCUMode::NFC);
}
- if (result == DriverResult::Success) {
+ if (result == Common::Input::DriverResult::Success) {
result = WaitUntilNfcIs(NFCStatus::Ready);
}
- if (result == DriverResult::Success) {
+ if (result == Common::Input::DriverResult::Success) {
MCUCommandResponse output{};
result = SendStopPollingRequest(output);
}
- if (result == DriverResult::Success) {
+ if (result == Common::Input::DriverResult::Success) {
result = WaitUntilNfcIs(NFCStatus::Ready);
}
- if (result == DriverResult::Success) {
+ if (result == Common::Input::DriverResult::Success) {
is_enabled = true;
}
return result;
}
-DriverResult NfcProtocol::DisableNfc() {
+Common::Input::DriverResult NfcProtocol::DisableNfc() {
LOG_DEBUG(Input, "Disable NFC");
ScopedSetBlocking sb(this);
- DriverResult result{DriverResult::Success};
+ Common::Input::DriverResult result{Common::Input::DriverResult::Success};
- if (result == DriverResult::Success) {
+ if (result == Common::Input::DriverResult::Success) {
result = EnableMCU(false);
}
@@ -69,60 +69,60 @@ DriverResult NfcProtocol::DisableNfc() {
return result;
}
-DriverResult NfcProtocol::StartNFCPollingMode() {
+Common::Input::DriverResult NfcProtocol::StartNFCPollingMode() {
LOG_DEBUG(Input, "Start NFC polling Mode");
ScopedSetBlocking sb(this);
- DriverResult result{DriverResult::Success};
+ Common::Input::DriverResult result{Common::Input::DriverResult::Success};
- if (result == DriverResult::Success) {
+ if (result == Common::Input::DriverResult::Success) {
MCUCommandResponse output{};
result = SendStartPollingRequest(output);
}
- if (result == DriverResult::Success) {
+ if (result == Common::Input::DriverResult::Success) {
result = WaitUntilNfcIs(NFCStatus::Polling);
}
- if (result == DriverResult::Success) {
+ if (result == Common::Input::DriverResult::Success) {
is_polling = true;
}
return result;
}
-DriverResult NfcProtocol::StopNFCPollingMode() {
+Common::Input::DriverResult NfcProtocol::StopNFCPollingMode() {
LOG_DEBUG(Input, "Stop NFC polling Mode");
ScopedSetBlocking sb(this);
- DriverResult result{DriverResult::Success};
+ Common::Input::DriverResult result{Common::Input::DriverResult::Success};
- if (result == DriverResult::Success) {
+ if (result == Common::Input::DriverResult::Success) {
MCUCommandResponse output{};
result = SendStopPollingRequest(output);
}
- if (result == DriverResult::Success) {
+ if (result == Common::Input::DriverResult::Success) {
result = WaitUntilNfcIs(NFCStatus::WriteReady);
}
- if (result == DriverResult::Success) {
+ if (result == Common::Input::DriverResult::Success) {
is_polling = false;
}
return result;
}
-DriverResult NfcProtocol::GetTagInfo(Joycon::TagInfo& tag_info) {
+Common::Input::DriverResult NfcProtocol::GetTagInfo(Joycon::TagInfo& tag_info) {
if (update_counter++ < AMIIBO_UPDATE_DELAY) {
- return DriverResult::Delayed;
+ return Common::Input::DriverResult::Delayed;
}
update_counter = 0;
LOG_DEBUG(Input, "Scan for amiibos");
ScopedSetBlocking sb(this);
- DriverResult result{DriverResult::Success};
+ Common::Input::DriverResult result{Common::Input::DriverResult::Success};
TagFoundData tag_data{};
- if (result == DriverResult::Success) {
+ if (result == Common::Input::DriverResult::Success) {
result = IsTagInRange(tag_data);
}
- if (result == DriverResult::Success) {
+ if (result == Common::Input::DriverResult::Success) {
tag_info = {
.uuid_length = tag_data.uuid_size,
.protocol = 1,
@@ -147,59 +147,59 @@ DriverResult NfcProtocol::GetTagInfo(Joycon::TagInfo& tag_info) {
return result;
}
-DriverResult NfcProtocol::ReadAmiibo(std::vector<u8>& data) {
+Common::Input::DriverResult NfcProtocol::ReadAmiibo(std::vector<u8>& data) {
LOG_DEBUG(Input, "Scan for amiibos");
ScopedSetBlocking sb(this);
- DriverResult result{DriverResult::Success};
+ Common::Input::DriverResult result{Common::Input::DriverResult::Success};
TagFoundData tag_data{};
- if (result == DriverResult::Success) {
+ if (result == Common::Input::DriverResult::Success) {
result = IsTagInRange(tag_data, 7);
}
- if (result == DriverResult::Success) {
+ if (result == Common::Input::DriverResult::Success) {
result = GetAmiiboData(data);
}
return result;
}
-DriverResult NfcProtocol::WriteAmiibo(std::span<const u8> data) {
+Common::Input::DriverResult NfcProtocol::WriteAmiibo(std::span<const u8> data) {
LOG_DEBUG(Input, "Write amiibo");
ScopedSetBlocking sb(this);
- DriverResult result{DriverResult::Success};
+ Common::Input::DriverResult result{Common::Input::DriverResult::Success};
TagUUID tag_uuid = GetTagUUID(data);
TagFoundData tag_data{};
- if (result == DriverResult::Success) {
+ if (result == Common::Input::DriverResult::Success) {
result = IsTagInRange(tag_data, 7);
}
- if (result == DriverResult::Success) {
+ if (result == Common::Input::DriverResult::Success) {
if (tag_data.uuid != tag_uuid) {
- result = DriverResult::InvalidParameters;
+ result = Common::Input::DriverResult::InvalidParameters;
}
}
- if (result == DriverResult::Success) {
+ if (result == Common::Input::DriverResult::Success) {
MCUCommandResponse output{};
result = SendStopPollingRequest(output);
}
- if (result == DriverResult::Success) {
+ if (result == Common::Input::DriverResult::Success) {
result = WaitUntilNfcIs(NFCStatus::Ready);
}
- if (result == DriverResult::Success) {
+ if (result == Common::Input::DriverResult::Success) {
MCUCommandResponse output{};
result = SendStartPollingRequest(output, true);
}
- if (result == DriverResult::Success) {
+ if (result == Common::Input::DriverResult::Success) {
result = WaitUntilNfcIs(NFCStatus::WriteReady);
}
- if (result == DriverResult::Success) {
+ if (result == Common::Input::DriverResult::Success) {
result = WriteAmiiboData(tag_uuid, data);
}
- if (result == DriverResult::Success) {
+ if (result == Common::Input::DriverResult::Success) {
result = WaitUntilNfcIs(NFCStatus::WriteDone);
}
- if (result == DriverResult::Success) {
+ if (result == Common::Input::DriverResult::Success) {
MCUCommandResponse output{};
result = SendStopPollingRequest(output);
}
@@ -207,64 +207,65 @@ DriverResult NfcProtocol::WriteAmiibo(std::span<const u8> data) {
return result;
}
-DriverResult NfcProtocol::ReadMifare(std::span<const MifareReadChunk> read_request,
- std::span<MifareReadData> out_data) {
+Common::Input::DriverResult NfcProtocol::ReadMifare(std::span<const MifareReadChunk> read_request,
+ std::span<MifareReadData> out_data) {
LOG_DEBUG(Input, "Read mifare");
ScopedSetBlocking sb(this);
- DriverResult result{DriverResult::Success};
+ Common::Input::DriverResult result{Common::Input::DriverResult::Success};
TagFoundData tag_data{};
MifareUUID tag_uuid{};
- if (result == DriverResult::Success) {
+ if (result == Common::Input::DriverResult::Success) {
result = IsTagInRange(tag_data, 7);
}
- if (result == DriverResult::Success) {
+ if (result == Common::Input::DriverResult::Success) {
memcpy(tag_uuid.data(), tag_data.uuid.data(), sizeof(MifareUUID));
result = GetMifareData(tag_uuid, read_request, out_data);
}
- if (result == DriverResult::Success) {
+ if (result == Common::Input::DriverResult::Success) {
MCUCommandResponse output{};
result = SendStopPollingRequest(output);
}
- if (result == DriverResult::Success) {
+ if (result == Common::Input::DriverResult::Success) {
result = WaitUntilNfcIs(NFCStatus::Ready);
}
- if (result == DriverResult::Success) {
+ if (result == Common::Input::DriverResult::Success) {
MCUCommandResponse output{};
result = SendStartPollingRequest(output, true);
}
- if (result == DriverResult::Success) {
+ if (result == Common::Input::DriverResult::Success) {
result = WaitUntilNfcIs(NFCStatus::WriteReady);
}
return result;
}
-DriverResult NfcProtocol::WriteMifare(std::span<const MifareWriteChunk> write_request) {
+Common::Input::DriverResult NfcProtocol::WriteMifare(
+ std::span<const MifareWriteChunk> write_request) {
LOG_DEBUG(Input, "Write mifare");
ScopedSetBlocking sb(this);
- DriverResult result{DriverResult::Success};
+ Common::Input::DriverResult result{Common::Input::DriverResult::Success};
TagFoundData tag_data{};
MifareUUID tag_uuid{};
- if (result == DriverResult::Success) {
+ if (result == Common::Input::DriverResult::Success) {
result = IsTagInRange(tag_data, 7);
}
- if (result == DriverResult::Success) {
+ if (result == Common::Input::DriverResult::Success) {
memcpy(tag_uuid.data(), tag_data.uuid.data(), sizeof(MifareUUID));
result = WriteMifareData(tag_uuid, write_request);
}
- if (result == DriverResult::Success) {
+ if (result == Common::Input::DriverResult::Success) {
MCUCommandResponse output{};
result = SendStopPollingRequest(output);
}
- if (result == DriverResult::Success) {
+ if (result == Common::Input::DriverResult::Success) {
result = WaitUntilNfcIs(NFCStatus::Ready);
}
- if (result == DriverResult::Success) {
+ if (result == Common::Input::DriverResult::Success) {
MCUCommandResponse output{};
result = SendStartPollingRequest(output, true);
}
- if (result == DriverResult::Success) {
+ if (result == Common::Input::DriverResult::Success) {
result = WaitUntilNfcIs(NFCStatus::WriteReady);
}
return result;
@@ -277,17 +278,17 @@ bool NfcProtocol::HasAmiibo() {
update_counter = 0;
ScopedSetBlocking sb(this);
- DriverResult result{DriverResult::Success};
+ Common::Input::DriverResult result{Common::Input::DriverResult::Success};
TagFoundData tag_data{};
- if (result == DriverResult::Success) {
+ if (result == Common::Input::DriverResult::Success) {
result = IsTagInRange(tag_data, 7);
}
- return result == DriverResult::Success;
+ return result == Common::Input::DriverResult::Success;
}
-DriverResult NfcProtocol::WaitUntilNfcIs(NFCStatus status) {
+Common::Input::DriverResult NfcProtocol::WaitUntilNfcIs(NFCStatus status) {
constexpr std::size_t timeout_limit = 10;
MCUCommandResponse output{};
std::size_t tries = 0;
@@ -295,30 +296,31 @@ DriverResult NfcProtocol::WaitUntilNfcIs(NFCStatus status) {
do {
auto result = SendNextPackageRequest(output, {});
- if (result != DriverResult::Success) {
+ if (result != Common::Input::DriverResult::Success) {
return result;
}
if (tries++ > timeout_limit) {
- return DriverResult::Timeout;
+ return Common::Input::DriverResult::Timeout;
}
} while (output.mcu_report != MCUReport::NFCState ||
(output.mcu_data[1] << 8) + output.mcu_data[0] != 0x0500 ||
output.mcu_data[5] != 0x31 || output.mcu_data[6] != static_cast<u8>(status));
- return DriverResult::Success;
+ return Common::Input::DriverResult::Success;
}
-DriverResult NfcProtocol::IsTagInRange(TagFoundData& data, std::size_t timeout_limit) {
+Common::Input::DriverResult NfcProtocol::IsTagInRange(TagFoundData& data,
+ std::size_t timeout_limit) {
MCUCommandResponse output{};
std::size_t tries = 0;
do {
const auto result = SendNextPackageRequest(output, {});
- if (result != DriverResult::Success) {
+ if (result != Common::Input::DriverResult::Success) {
return result;
}
if (tries++ > timeout_limit) {
- return DriverResult::Timeout;
+ return Common::Input::DriverResult::Timeout;
}
} while (output.mcu_report != MCUReport::NFCState ||
(output.mcu_data[1] << 8) + output.mcu_data[0] != 0x0500 ||
@@ -328,10 +330,10 @@ DriverResult NfcProtocol::IsTagInRange(TagFoundData& data, std::size_t timeout_l
data.uuid_size = std::min(output.mcu_data[14], static_cast<u8>(sizeof(TagUUID)));
memcpy(data.uuid.data(), output.mcu_data.data() + 15, data.uuid.size());
- return DriverResult::Success;
+ return Common::Input::DriverResult::Success;
}
-DriverResult NfcProtocol::GetAmiiboData(std::vector<u8>& ntag_data) {
+Common::Input::DriverResult NfcProtocol::GetAmiiboData(std::vector<u8>& ntag_data) {
constexpr std::size_t timeout_limit = 60;
MCUCommandResponse output{};
std::size_t tries = 0;
@@ -340,7 +342,7 @@ DriverResult NfcProtocol::GetAmiiboData(std::vector<u8>& ntag_data) {
std::size_t ntag_buffer_pos = 0;
auto result = SendReadAmiiboRequest(output, NFCPages::Block135);
- if (result != DriverResult::Success) {
+ if (result != Common::Input::DriverResult::Success) {
return result;
}
@@ -349,14 +351,14 @@ DriverResult NfcProtocol::GetAmiiboData(std::vector<u8>& ntag_data) {
result = SendNextPackageRequest(output, package_index);
const auto nfc_status = static_cast<NFCStatus>(output.mcu_data[6]);
- if (result != DriverResult::Success) {
+ if (result != Common::Input::DriverResult::Success) {
return result;
}
if ((output.mcu_report == MCUReport::NFCReadData ||
output.mcu_report == MCUReport::NFCState) &&
nfc_status == NFCStatus::TagLost) {
- return DriverResult::ErrorReadingData;
+ return Common::Input::DriverResult::ErrorReadingData;
}
if (output.mcu_report == MCUReport::NFCReadData && output.mcu_data[1] == 0x07) {
@@ -375,14 +377,15 @@ DriverResult NfcProtocol::GetAmiiboData(std::vector<u8>& ntag_data) {
if (output.mcu_report == MCUReport::NFCState && nfc_status == NFCStatus::LastPackage) {
LOG_INFO(Input, "Finished reading amiibo");
- return DriverResult::Success;
+ return Common::Input::DriverResult::Success;
}
}
- return DriverResult::Timeout;
+ return Common::Input::DriverResult::Timeout;
}
-DriverResult NfcProtocol::WriteAmiiboData(const TagUUID& tag_uuid, std::span<const u8> data) {
+Common::Input::DriverResult NfcProtocol::WriteAmiiboData(const TagUUID& tag_uuid,
+ std::span<const u8> data) {
constexpr std::size_t timeout_limit = 60;
const auto nfc_data = MakeAmiiboWritePackage(tag_uuid, data);
const std::vector<u8> nfc_buffer_data = SerializeWritePackage(nfc_data);
@@ -397,7 +400,7 @@ DriverResult NfcProtocol::WriteAmiiboData(const TagUUID& tag_uuid, std::span<con
auto result = SendWriteAmiiboRequest(output, tag_uuid);
- if (result != DriverResult::Success) {
+ if (result != Common::Input::DriverResult::Success) {
return result;
}
@@ -406,14 +409,14 @@ DriverResult NfcProtocol::WriteAmiiboData(const TagUUID& tag_uuid, std::span<con
result = SendNextPackageRequest(output, package_index);
const auto nfc_status = static_cast<NFCStatus>(output.mcu_data[6]);
- if (result != DriverResult::Success) {
+ if (result != Common::Input::DriverResult::Success) {
return result;
}
if ((output.mcu_report == MCUReport::NFCReadData ||
output.mcu_report == MCUReport::NFCState) &&
nfc_status == NFCStatus::TagLost) {
- return DriverResult::ErrorReadingData;
+ return Common::Input::DriverResult::ErrorReadingData;
}
if (output.mcu_report == MCUReport::NFCReadData && output.mcu_data[1] == 0x07) {
@@ -442,7 +445,7 @@ DriverResult NfcProtocol::WriteAmiiboData(const TagUUID& tag_uuid, std::span<con
if ((output.mcu_report == MCUReport::NFCReadData ||
output.mcu_report == MCUReport::NFCState) &&
nfc_status == NFCStatus::TagLost) {
- return DriverResult::ErrorReadingData;
+ return Common::Input::DriverResult::ErrorReadingData;
}
// Increase position when data is confirmed by the joycon
@@ -457,14 +460,14 @@ DriverResult NfcProtocol::WriteAmiiboData(const TagUUID& tag_uuid, std::span<con
return result;
}
-DriverResult NfcProtocol::GetMifareData(const MifareUUID& tag_uuid,
- std::span<const MifareReadChunk> read_request,
- std::span<MifareReadData> out_data) {
+Common::Input::DriverResult NfcProtocol::GetMifareData(
+ const MifareUUID& tag_uuid, std::span<const MifareReadChunk> read_request,
+ std::span<MifareReadData> out_data) {
constexpr std::size_t timeout_limit = 60;
const auto nfc_data = MakeMifareReadPackage(tag_uuid, read_request);
const std::vector<u8> nfc_buffer_data = SerializeMifareReadPackage(nfc_data);
std::span<const u8> buffer(nfc_buffer_data);
- DriverResult result = DriverResult::Success;
+ Common::Input::DriverResult result = Common::Input::DriverResult::Success;
MCUCommandResponse output{};
u8 block_id = 1;
u8 package_index = 0;
@@ -486,7 +489,7 @@ DriverResult NfcProtocol::GetMifareData(const MifareUUID& tag_uuid,
const auto nfc_status = static_cast<NFCStatus>(output.mcu_data[6]);
if (output.mcu_report == MCUReport::NFCState && nfc_status == NFCStatus::TagLost) {
- return DriverResult::ErrorReadingData;
+ return Common::Input::DriverResult::ErrorReadingData;
}
// Increase position when data is confirmed by the joycon
@@ -498,7 +501,7 @@ DriverResult NfcProtocol::GetMifareData(const MifareUUID& tag_uuid,
}
}
- if (result != DriverResult::Success) {
+ if (result != Common::Input::DriverResult::Success) {
return result;
}
@@ -507,12 +510,12 @@ DriverResult NfcProtocol::GetMifareData(const MifareUUID& tag_uuid,
result = SendNextPackageRequest(output, package_index);
const auto nfc_status = static_cast<NFCStatus>(output.mcu_data[6]);
- if (result != DriverResult::Success) {
+ if (result != Common::Input::DriverResult::Success) {
return result;
}
if (output.mcu_report == MCUReport::NFCState && nfc_status == NFCStatus::TagLost) {
- return DriverResult::ErrorReadingData;
+ return Common::Input::DriverResult::ErrorReadingData;
}
if (output.mcu_report == MCUReport::NFCState && output.mcu_data[1] == 0x10) {
@@ -538,13 +541,13 @@ DriverResult NfcProtocol::GetMifareData(const MifareUUID& tag_uuid,
return result;
}
-DriverResult NfcProtocol::WriteMifareData(const MifareUUID& tag_uuid,
- std::span<const MifareWriteChunk> write_request) {
+Common::Input::DriverResult NfcProtocol::WriteMifareData(
+ const MifareUUID& tag_uuid, std::span<const MifareWriteChunk> write_request) {
constexpr std::size_t timeout_limit = 60;
const auto nfc_data = MakeMifareWritePackage(tag_uuid, write_request);
const std::vector<u8> nfc_buffer_data = SerializeMifareWritePackage(nfc_data);
std::span<const u8> buffer(nfc_buffer_data);
- DriverResult result = DriverResult::Success;
+ Common::Input::DriverResult result = Common::Input::DriverResult::Success;
MCUCommandResponse output{};
u8 block_id = 1;
u8 package_index = 0;
@@ -566,7 +569,7 @@ DriverResult NfcProtocol::WriteMifareData(const MifareUUID& tag_uuid,
const auto nfc_status = static_cast<NFCStatus>(output.mcu_data[6]);
if (output.mcu_report == MCUReport::NFCState && nfc_status == NFCStatus::TagLost) {
- return DriverResult::ErrorReadingData;
+ return Common::Input::DriverResult::ErrorReadingData;
}
// Increase position when data is confirmed by the joycon
@@ -578,7 +581,7 @@ DriverResult NfcProtocol::WriteMifareData(const MifareUUID& tag_uuid,
}
}
- if (result != DriverResult::Success) {
+ if (result != Common::Input::DriverResult::Success) {
return result;
}
@@ -587,12 +590,12 @@ DriverResult NfcProtocol::WriteMifareData(const MifareUUID& tag_uuid,
result = SendNextPackageRequest(output, package_index);
const auto nfc_status = static_cast<NFCStatus>(output.mcu_data[6]);
- if (result != DriverResult::Success) {
+ if (result != Common::Input::DriverResult::Success) {
return result;
}
if (output.mcu_report == MCUReport::NFCState && nfc_status == NFCStatus::TagLost) {
- return DriverResult::ErrorReadingData;
+ return Common::Input::DriverResult::ErrorReadingData;
}
if (output.mcu_report == MCUReport::NFCState && output.mcu_data[1] == 0x10) {
@@ -609,8 +612,8 @@ DriverResult NfcProtocol::WriteMifareData(const MifareUUID& tag_uuid,
return result;
}
-DriverResult NfcProtocol::SendStartPollingRequest(MCUCommandResponse& output,
- bool is_second_attempt) {
+Common::Input::DriverResult NfcProtocol::SendStartPollingRequest(MCUCommandResponse& output,
+ bool is_second_attempt) {
NFCRequestState request{
.command_argument = NFCCommand::StartPolling,
.block_id = {},
@@ -635,7 +638,7 @@ DriverResult NfcProtocol::SendStartPollingRequest(MCUCommandResponse& output,
output);
}
-DriverResult NfcProtocol::SendStopPollingRequest(MCUCommandResponse& output) {
+Common::Input::DriverResult NfcProtocol::SendStopPollingRequest(MCUCommandResponse& output) {
NFCRequestState request{
.command_argument = NFCCommand::StopPolling,
.block_id = {},
@@ -653,7 +656,8 @@ DriverResult NfcProtocol::SendStopPollingRequest(MCUCommandResponse& output) {
output);
}
-DriverResult NfcProtocol::SendNextPackageRequest(MCUCommandResponse& output, u8 packet_id) {
+Common::Input::DriverResult NfcProtocol::SendNextPackageRequest(MCUCommandResponse& output,
+ u8 packet_id) {
NFCRequestState request{
.command_argument = NFCCommand::StartWaitingRecieve,
.block_id = {},
@@ -671,7 +675,8 @@ DriverResult NfcProtocol::SendNextPackageRequest(MCUCommandResponse& output, u8
output);
}
-DriverResult NfcProtocol::SendReadAmiiboRequest(MCUCommandResponse& output, NFCPages ntag_pages) {
+Common::Input::DriverResult NfcProtocol::SendReadAmiiboRequest(MCUCommandResponse& output,
+ NFCPages ntag_pages) {
NFCRequestState request{
.command_argument = NFCCommand::ReadNtag,
.block_id = {},
@@ -696,8 +701,8 @@ DriverResult NfcProtocol::SendReadAmiiboRequest(MCUCommandResponse& output, NFCP
output);
}
-DriverResult NfcProtocol::SendWriteAmiiboRequest(MCUCommandResponse& output,
- const TagUUID& tag_uuid) {
+Common::Input::DriverResult NfcProtocol::SendWriteAmiiboRequest(MCUCommandResponse& output,
+ const TagUUID& tag_uuid) {
NFCRequestState request{
.command_argument = NFCCommand::ReadNtag,
.block_id = {},
@@ -722,9 +727,10 @@ DriverResult NfcProtocol::SendWriteAmiiboRequest(MCUCommandResponse& output,
output);
}
-DriverResult NfcProtocol::SendWriteDataAmiiboRequest(MCUCommandResponse& output, u8 block_id,
- bool is_last_packet,
- std::span<const u8> data) {
+Common::Input::DriverResult NfcProtocol::SendWriteDataAmiiboRequest(MCUCommandResponse& output,
+ u8 block_id,
+ bool is_last_packet,
+ std::span<const u8> data) {
const auto data_size = std::min(data.size(), sizeof(NFCRequestState::raw_data));
NFCRequestState request{
.command_argument = NFCCommand::WriteNtag,
@@ -745,8 +751,9 @@ DriverResult NfcProtocol::SendWriteDataAmiiboRequest(MCUCommandResponse& output,
output);
}
-DriverResult NfcProtocol::SendReadDataMifareRequest(MCUCommandResponse& output, u8 block_id,
- bool is_last_packet, std::span<const u8> data) {
+Common::Input::DriverResult NfcProtocol::SendReadDataMifareRequest(MCUCommandResponse& output,
+ u8 block_id, bool is_last_packet,
+ std::span<const u8> data) {
const auto data_size = std::min(data.size(), sizeof(NFCRequestState::raw_data));
NFCRequestState request{
.command_argument = NFCCommand::Mifare,
diff --git a/src/input_common/helpers/joycon_protocol/nfc.h b/src/input_common/helpers/joycon_protocol/nfc.h
index 0be95e40e..22db95170 100644
--- a/src/input_common/helpers/joycon_protocol/nfc.h
+++ b/src/input_common/helpers/joycon_protocol/nfc.h
@@ -13,30 +13,34 @@
#include "input_common/helpers/joycon_protocol/common_protocol.h"
#include "input_common/helpers/joycon_protocol/joycon_types.h"
+namespace Common::Input {
+enum class DriverResult;
+}
+
namespace InputCommon::Joycon {
class NfcProtocol final : private JoyconCommonProtocol {
public:
explicit NfcProtocol(std::shared_ptr<JoyconHandle> handle);
- DriverResult EnableNfc();
+ Common::Input::DriverResult EnableNfc();
- DriverResult DisableNfc();
+ Common::Input::DriverResult DisableNfc();
- DriverResult StartNFCPollingMode();
+ Common::Input::DriverResult StartNFCPollingMode();
- DriverResult StopNFCPollingMode();
+ Common::Input::DriverResult StopNFCPollingMode();
- DriverResult GetTagInfo(Joycon::TagInfo& tag_info);
+ Common::Input::DriverResult GetTagInfo(Joycon::TagInfo& tag_info);
- DriverResult ReadAmiibo(std::vector<u8>& data);
+ Common::Input::DriverResult ReadAmiibo(std::vector<u8>& data);
- DriverResult WriteAmiibo(std::span<const u8> data);
+ Common::Input::DriverResult WriteAmiibo(std::span<const u8> data);
- DriverResult ReadMifare(std::span<const MifareReadChunk> read_request,
- std::span<MifareReadData> out_data);
+ Common::Input::DriverResult ReadMifare(std::span<const MifareReadChunk> read_request,
+ std::span<MifareReadData> out_data);
- DriverResult WriteMifare(std::span<const MifareWriteChunk> write_request);
+ Common::Input::DriverResult WriteMifare(std::span<const MifareWriteChunk> write_request);
bool HasAmiibo();
@@ -54,37 +58,41 @@ private:
TagUUID uuid;
};
- DriverResult WaitUntilNfcIs(NFCStatus status);
+ Common::Input::DriverResult WaitUntilNfcIs(NFCStatus status);
- DriverResult IsTagInRange(TagFoundData& data, std::size_t timeout_limit = 1);
+ Common::Input::DriverResult IsTagInRange(TagFoundData& data, std::size_t timeout_limit = 1);
- DriverResult GetAmiiboData(std::vector<u8>& data);
+ Common::Input::DriverResult GetAmiiboData(std::vector<u8>& data);
- DriverResult WriteAmiiboData(const TagUUID& tag_uuid, std::span<const u8> data);
+ Common::Input::DriverResult WriteAmiiboData(const TagUUID& tag_uuid, std::span<const u8> data);
- DriverResult GetMifareData(const MifareUUID& tag_uuid,
- std::span<const MifareReadChunk> read_request,
- std::span<MifareReadData> out_data);
+ Common::Input::DriverResult GetMifareData(const MifareUUID& tag_uuid,
+ std::span<const MifareReadChunk> read_request,
+ std::span<MifareReadData> out_data);
- DriverResult WriteMifareData(const MifareUUID& tag_uuid,
- std::span<const MifareWriteChunk> write_request);
+ Common::Input::DriverResult WriteMifareData(const MifareUUID& tag_uuid,
+ std::span<const MifareWriteChunk> write_request);
- DriverResult SendStartPollingRequest(MCUCommandResponse& output,
- bool is_second_attempt = false);
+ Common::Input::DriverResult SendStartPollingRequest(MCUCommandResponse& output,
+ bool is_second_attempt = false);
- DriverResult SendStopPollingRequest(MCUCommandResponse& output);
+ Common::Input::DriverResult SendStopPollingRequest(MCUCommandResponse& output);
- DriverResult SendNextPackageRequest(MCUCommandResponse& output, u8 packet_id);
+ Common::Input::DriverResult SendNextPackageRequest(MCUCommandResponse& output, u8 packet_id);
- DriverResult SendReadAmiiboRequest(MCUCommandResponse& output, NFCPages ntag_pages);
+ Common::Input::DriverResult SendReadAmiiboRequest(MCUCommandResponse& output,
+ NFCPages ntag_pages);
- DriverResult SendWriteAmiiboRequest(MCUCommandResponse& output, const TagUUID& tag_uuid);
+ Common::Input::DriverResult SendWriteAmiiboRequest(MCUCommandResponse& output,
+ const TagUUID& tag_uuid);
- DriverResult SendWriteDataAmiiboRequest(MCUCommandResponse& output, u8 block_id,
- bool is_last_packet, std::span<const u8> data);
+ Common::Input::DriverResult SendWriteDataAmiiboRequest(MCUCommandResponse& output, u8 block_id,
+ bool is_last_packet,
+ std::span<const u8> data);
- DriverResult SendReadDataMifareRequest(MCUCommandResponse& output, u8 block_id,
- bool is_last_packet, std::span<const u8> data);
+ Common::Input::DriverResult SendReadDataMifareRequest(MCUCommandResponse& output, u8 block_id,
+ bool is_last_packet,
+ std::span<const u8> data);
std::vector<u8> SerializeWritePackage(const NFCWritePackage& package) const;
diff --git a/src/input_common/helpers/joycon_protocol/ringcon.cpp b/src/input_common/helpers/joycon_protocol/ringcon.cpp
index 190cef812..96414fb67 100644
--- a/src/input_common/helpers/joycon_protocol/ringcon.cpp
+++ b/src/input_common/helpers/joycon_protocol/ringcon.cpp
@@ -1,6 +1,7 @@
// SPDX-FileCopyrightText: Copyright 2022 yuzu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
+#include "common/input.h"
#include "common/logging/log.h"
#include "input_common/helpers/joycon_protocol/ringcon.h"
@@ -9,18 +10,18 @@ namespace InputCommon::Joycon {
RingConProtocol::RingConProtocol(std::shared_ptr<JoyconHandle> handle)
: JoyconCommonProtocol(std::move(handle)) {}
-DriverResult RingConProtocol::EnableRingCon() {
+Common::Input::DriverResult RingConProtocol::EnableRingCon() {
LOG_DEBUG(Input, "Enable Ringcon");
ScopedSetBlocking sb(this);
- DriverResult result{DriverResult::Success};
+ Common::Input::DriverResult result{Common::Input::DriverResult::Success};
- if (result == DriverResult::Success) {
+ if (result == Common::Input::DriverResult::Success) {
result = SetReportMode(ReportMode::STANDARD_FULL_60HZ);
}
- if (result == DriverResult::Success) {
+ if (result == Common::Input::DriverResult::Success) {
result = EnableMCU(true);
}
- if (result == DriverResult::Success) {
+ if (result == Common::Input::DriverResult::Success) {
const MCUConfig config{
.command = MCUCommand::ConfigureMCU,
.sub_command = MCUSubCommand::SetDeviceMode,
@@ -33,12 +34,12 @@ DriverResult RingConProtocol::EnableRingCon() {
return result;
}
-DriverResult RingConProtocol::DisableRingCon() {
+Common::Input::DriverResult RingConProtocol::DisableRingCon() {
LOG_DEBUG(Input, "Disable RingCon");
ScopedSetBlocking sb(this);
- DriverResult result{DriverResult::Success};
+ Common::Input::DriverResult result{Common::Input::DriverResult::Success};
- if (result == DriverResult::Success) {
+ if (result == Common::Input::DriverResult::Success) {
result = EnableMCU(false);
}
@@ -47,29 +48,29 @@ DriverResult RingConProtocol::DisableRingCon() {
return result;
}
-DriverResult RingConProtocol::StartRingconPolling() {
+Common::Input::DriverResult RingConProtocol::StartRingconPolling() {
LOG_DEBUG(Input, "Enable Ringcon");
ScopedSetBlocking sb(this);
- DriverResult result{DriverResult::Success};
+ Common::Input::DriverResult result{Common::Input::DriverResult::Success};
bool is_connected = false;
- if (result == DriverResult::Success) {
+ if (result == Common::Input::DriverResult::Success) {
result = IsRingConnected(is_connected);
}
- if (result == DriverResult::Success && is_connected) {
+ if (result == Common::Input::DriverResult::Success && is_connected) {
LOG_INFO(Input, "Ringcon detected");
result = ConfigureRing();
}
- if (result == DriverResult::Success) {
+ if (result == Common::Input::DriverResult::Success) {
is_enabled = true;
}
return result;
}
-DriverResult RingConProtocol::IsRingConnected(bool& is_connected) {
+Common::Input::DriverResult RingConProtocol::IsRingConnected(bool& is_connected) {
LOG_DEBUG(Input, "IsRingConnected");
- constexpr std::size_t max_tries = 28;
+ constexpr std::size_t max_tries = 42;
SubCommandResponse output{};
std::size_t tries = 0;
is_connected = false;
@@ -77,20 +78,21 @@ DriverResult RingConProtocol::IsRingConnected(bool& is_connected) {
do {
const auto result = SendSubCommand(SubCommand::GET_EXTERNAL_DEVICE_INFO, {}, output);
- if (result != DriverResult::Success) {
+ if (result != Common::Input::DriverResult::Success &&
+ result != Common::Input::DriverResult::Timeout) {
return result;
}
if (tries++ >= max_tries) {
- return DriverResult::NoDeviceDetected;
+ return Common::Input::DriverResult::NoDeviceDetected;
}
} while (output.external_device_id != ExternalDeviceId::RingController);
is_connected = true;
- return DriverResult::Success;
+ return Common::Input::DriverResult::Success;
}
-DriverResult RingConProtocol::ConfigureRing() {
+Common::Input::DriverResult RingConProtocol::ConfigureRing() {
LOG_DEBUG(Input, "ConfigureRing");
static constexpr std::array<u8, 37> ring_config{
@@ -98,9 +100,10 @@ DriverResult RingConProtocol::ConfigureRing() {
0x00, 0x00, 0x00, 0x0A, 0x64, 0x0B, 0xE6, 0xA9, 0x22, 0x00, 0x00, 0x04, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x90, 0xA8, 0xE1, 0x34, 0x36};
- const DriverResult result = SendSubCommand(SubCommand::SET_EXTERNAL_FORMAT_CONFIG, ring_config);
+ const Common::Input::DriverResult result =
+ SendSubCommand(SubCommand::SET_EXTERNAL_FORMAT_CONFIG, ring_config);
- if (result != DriverResult::Success) {
+ if (result != Common::Input::DriverResult::Success) {
return result;
}
diff --git a/src/input_common/helpers/joycon_protocol/ringcon.h b/src/input_common/helpers/joycon_protocol/ringcon.h
index 6e858f3fc..9f0888de3 100644
--- a/src/input_common/helpers/joycon_protocol/ringcon.h
+++ b/src/input_common/helpers/joycon_protocol/ringcon.h
@@ -13,24 +13,28 @@
#include "input_common/helpers/joycon_protocol/common_protocol.h"
#include "input_common/helpers/joycon_protocol/joycon_types.h"
+namespace Common::Input {
+enum class DriverResult;
+}
+
namespace InputCommon::Joycon {
class RingConProtocol final : private JoyconCommonProtocol {
public:
explicit RingConProtocol(std::shared_ptr<JoyconHandle> handle);
- DriverResult EnableRingCon();
+ Common::Input::DriverResult EnableRingCon();
- DriverResult DisableRingCon();
+ Common::Input::DriverResult DisableRingCon();
- DriverResult StartRingconPolling();
+ Common::Input::DriverResult StartRingconPolling();
bool IsEnabled() const;
private:
- DriverResult IsRingConnected(bool& is_connected);
+ Common::Input::DriverResult IsRingConnected(bool& is_connected);
- DriverResult ConfigureRing();
+ Common::Input::DriverResult ConfigureRing();
bool is_enabled{};
};
diff --git a/src/input_common/helpers/joycon_protocol/rumble.cpp b/src/input_common/helpers/joycon_protocol/rumble.cpp
index 63b60c946..7647f505e 100644
--- a/src/input_common/helpers/joycon_protocol/rumble.cpp
+++ b/src/input_common/helpers/joycon_protocol/rumble.cpp
@@ -4,6 +4,7 @@
#include <algorithm>
#include <cmath>
+#include "common/input.h"
#include "common/logging/log.h"
#include "input_common/helpers/joycon_protocol/rumble.h"
@@ -12,14 +13,14 @@ namespace InputCommon::Joycon {
RumbleProtocol::RumbleProtocol(std::shared_ptr<JoyconHandle> handle)
: JoyconCommonProtocol(std::move(handle)) {}
-DriverResult RumbleProtocol::EnableRumble(bool is_enabled) {
+Common::Input::DriverResult RumbleProtocol::EnableRumble(bool is_enabled) {
LOG_DEBUG(Input, "Enable Rumble");
ScopedSetBlocking sb(this);
const std::array<u8, 1> buffer{static_cast<u8>(is_enabled ? 1 : 0)};
return SendSubCommand(SubCommand::ENABLE_VIBRATION, buffer);
}
-DriverResult RumbleProtocol::SendVibration(const VibrationValue& vibration) {
+Common::Input::DriverResult RumbleProtocol::SendVibration(const VibrationValue& vibration) {
std::array<u8, sizeof(DefaultVibrationBuffer)> buffer{};
if (vibration.high_amplitude <= 0.0f && vibration.low_amplitude <= 0.0f) {
diff --git a/src/input_common/helpers/joycon_protocol/rumble.h b/src/input_common/helpers/joycon_protocol/rumble.h
index 6c12b7925..5e50e531a 100644
--- a/src/input_common/helpers/joycon_protocol/rumble.h
+++ b/src/input_common/helpers/joycon_protocol/rumble.h
@@ -13,15 +13,19 @@
#include "input_common/helpers/joycon_protocol/common_protocol.h"
#include "input_common/helpers/joycon_protocol/joycon_types.h"
+namespace Common::Input {
+enum class DriverResult;
+}
+
namespace InputCommon::Joycon {
class RumbleProtocol final : private JoyconCommonProtocol {
public:
explicit RumbleProtocol(std::shared_ptr<JoyconHandle> handle);
- DriverResult EnableRumble(bool is_enabled);
+ Common::Input::DriverResult EnableRumble(bool is_enabled);
- DriverResult SendVibration(const VibrationValue& vibration);
+ Common::Input::DriverResult SendVibration(const VibrationValue& vibration);
private:
u16 EncodeHighFrequency(f32 frequency) const;
diff --git a/src/video_core/CMakeLists.txt b/src/video_core/CMakeLists.txt
index e9e6f278d..3b2fe01da 100644
--- a/src/video_core/CMakeLists.txt
+++ b/src/video_core/CMakeLists.txt
@@ -220,8 +220,8 @@ add_library(video_core STATIC
surface.h
texture_cache/accelerated_swizzle.cpp
texture_cache/accelerated_swizzle.h
- texture_cache/decode_bc4.cpp
- texture_cache/decode_bc4.h
+ texture_cache/decode_bc.cpp
+ texture_cache/decode_bc.h
texture_cache/descriptor_table.h
texture_cache/formatter.cpp
texture_cache/formatter.h
@@ -279,7 +279,7 @@ add_library(video_core STATIC
create_target_directory_groups(video_core)
target_link_libraries(video_core PUBLIC common core)
-target_link_libraries(video_core PUBLIC glad shader_recompiler stb)
+target_link_libraries(video_core PUBLIC glad shader_recompiler stb bc_decoder)
if (YUZU_USE_BUNDLED_FFMPEG AND NOT (WIN32 OR ANDROID))
add_dependencies(video_core ffmpeg-build)
diff --git a/src/video_core/renderer_vulkan/blit_image.cpp b/src/video_core/renderer_vulkan/blit_image.cpp
index cf2964a3f..28d4b15a0 100644
--- a/src/video_core/renderer_vulkan/blit_image.cpp
+++ b/src/video_core/renderer_vulkan/blit_image.cpp
@@ -495,6 +495,9 @@ void BlitImageHelper::BlitDepthStencil(const Framebuffer* dst_framebuffer,
const Region2D& dst_region, const Region2D& src_region,
Tegra::Engines::Fermi2D::Filter filter,
Tegra::Engines::Fermi2D::Operation operation) {
+ if (!device.IsExtShaderStencilExportSupported()) {
+ return;
+ }
ASSERT(filter == Tegra::Engines::Fermi2D::Filter::Point);
ASSERT(operation == Tegra::Engines::Fermi2D::Operation::SrcCopy);
const BlitImagePipelineKey key{
diff --git a/src/video_core/renderer_vulkan/maxwell_to_vk.cpp b/src/video_core/renderer_vulkan/maxwell_to_vk.cpp
index 9a0b10568..a8540339d 100644
--- a/src/video_core/renderer_vulkan/maxwell_to_vk.cpp
+++ b/src/video_core/renderer_vulkan/maxwell_to_vk.cpp
@@ -259,6 +259,26 @@ FormatInfo SurfaceFormat(const Device& device, FormatType format_type, bool with
break;
}
}
+ // Transcode on hardware that doesn't support BCn natively
+ if (!device.IsOptimalBcnSupported() && VideoCore::Surface::IsPixelFormatBCn(pixel_format)) {
+ const bool is_srgb = with_srgb && VideoCore::Surface::IsPixelFormatSRGB(pixel_format);
+ if (pixel_format == PixelFormat::BC4_SNORM) {
+ tuple.format = VK_FORMAT_R8_SNORM;
+ } else if (pixel_format == PixelFormat::BC4_UNORM) {
+ tuple.format = VK_FORMAT_R8_UNORM;
+ } else if (pixel_format == PixelFormat::BC5_SNORM) {
+ tuple.format = VK_FORMAT_R8G8_SNORM;
+ } else if (pixel_format == PixelFormat::BC5_UNORM) {
+ tuple.format = VK_FORMAT_R8G8_UNORM;
+ } else if (pixel_format == PixelFormat::BC6H_SFLOAT ||
+ pixel_format == PixelFormat::BC6H_UFLOAT) {
+ tuple.format = VK_FORMAT_R16G16B16A16_SFLOAT;
+ } else if (is_srgb) {
+ tuple.format = VK_FORMAT_A8B8G8R8_SRGB_PACK32;
+ } else {
+ tuple.format = VK_FORMAT_A8B8G8R8_UNORM_PACK32;
+ }
+ }
const bool attachable = (tuple.usage & Attachable) != 0;
const bool storage = (tuple.usage & Storage) != 0;
diff --git a/src/video_core/renderer_vulkan/renderer_vulkan.cpp b/src/video_core/renderer_vulkan/renderer_vulkan.cpp
index ddf28ca28..454bb66a4 100644
--- a/src/video_core/renderer_vulkan/renderer_vulkan.cpp
+++ b/src/video_core/renderer_vulkan/renderer_vulkan.cpp
@@ -12,6 +12,7 @@
#include <fmt/format.h>
#include "common/logging/log.h"
+#include "common/polyfill_ranges.h"
#include "common/scope_exit.h"
#include "common/settings.h"
#include "common/telemetry.h"
@@ -65,6 +66,21 @@ std::string BuildCommaSeparatedExtensions(
return fmt::format("{}", fmt::join(available_extensions, ","));
}
+DebugCallback MakeDebugCallback(const vk::Instance& instance, const vk::InstanceDispatch& dld) {
+ if (!Settings::values.renderer_debug) {
+ return DebugCallback{};
+ }
+ const std::optional properties = vk::EnumerateInstanceExtensionProperties(dld);
+ const auto it = std::ranges::find_if(*properties, [](const auto& prop) {
+ return std::strcmp(VK_EXT_DEBUG_UTILS_EXTENSION_NAME, prop.extensionName) == 0;
+ });
+ if (it != properties->end()) {
+ return CreateDebugUtilsCallback(instance);
+ } else {
+ return CreateDebugReportCallback(instance);
+ }
+}
+
} // Anonymous namespace
Device CreateDevice(const vk::Instance& instance, const vk::InstanceDispatch& dld,
@@ -87,7 +103,7 @@ RendererVulkan::RendererVulkan(Core::TelemetrySession& telemetry_session_,
cpu_memory(cpu_memory_), gpu(gpu_), library(OpenLibrary(context.get())),
instance(CreateInstance(*library, dld, VK_API_VERSION_1_1, render_window.GetWindowInfo().type,
Settings::values.renderer_debug.GetValue())),
- debug_callback(Settings::values.renderer_debug ? CreateDebugCallback(instance) : nullptr),
+ debug_callback(MakeDebugCallback(instance, dld)),
surface(CreateSurface(instance, render_window.GetWindowInfo())),
device(CreateDevice(instance, dld, *surface)), memory_allocator(device), state_tracker(),
scheduler(device, state_tracker),
diff --git a/src/video_core/renderer_vulkan/renderer_vulkan.h b/src/video_core/renderer_vulkan/renderer_vulkan.h
index b2e8cbd1b..ca22c0baa 100644
--- a/src/video_core/renderer_vulkan/renderer_vulkan.h
+++ b/src/video_core/renderer_vulkan/renderer_vulkan.h
@@ -5,6 +5,7 @@
#include <memory>
#include <string>
+#include <variant>
#include "common/dynamic_library.h"
#include "video_core/renderer_base.h"
@@ -33,6 +34,8 @@ class GPU;
namespace Vulkan {
+using DebugCallback = std::variant<vk::DebugUtilsMessenger, vk::DebugReportCallback>;
+
Device CreateDevice(const vk::Instance& instance, const vk::InstanceDispatch& dld,
VkSurfaceKHR surface);
@@ -71,7 +74,7 @@ private:
vk::InstanceDispatch dld;
vk::Instance instance;
- vk::DebugUtilsMessenger debug_callback;
+ DebugCallback debug_callback;
vk::SurfaceKHR surface;
ScreenInfo screen_info;
diff --git a/src/video_core/renderer_vulkan/vk_buffer_cache.cpp b/src/video_core/renderer_vulkan/vk_buffer_cache.cpp
index 660f7c9ff..b72f95235 100644
--- a/src/video_core/renderer_vulkan/vk_buffer_cache.cpp
+++ b/src/video_core/renderer_vulkan/vk_buffer_cache.cpp
@@ -590,7 +590,8 @@ void BufferCacheRuntime::ReserveNullBuffer() {
.pNext = nullptr,
.flags = 0,
.size = 4,
- .usage = VK_BUFFER_USAGE_INDEX_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT,
+ .usage = VK_BUFFER_USAGE_VERTEX_BUFFER_BIT | VK_BUFFER_USAGE_INDEX_BUFFER_BIT |
+ VK_BUFFER_USAGE_TRANSFER_DST_BIT,
.sharingMode = VK_SHARING_MODE_EXCLUSIVE,
.queueFamilyIndexCount = 0,
.pQueueFamilyIndices = nullptr,
diff --git a/src/video_core/renderer_vulkan/vk_graphics_pipeline.cpp b/src/video_core/renderer_vulkan/vk_graphics_pipeline.cpp
index c1595642e..ad35cacac 100644
--- a/src/video_core/renderer_vulkan/vk_graphics_pipeline.cpp
+++ b/src/video_core/renderer_vulkan/vk_graphics_pipeline.cpp
@@ -652,13 +652,14 @@ void GraphicsPipeline::MakePipeline(VkRenderPass render_pass) {
.pNext = nullptr,
.negativeOneToOne = key.state.ndc_minus_one_to_one.Value() != 0 ? VK_TRUE : VK_FALSE,
};
+ const u32 num_viewports = std::min<u32>(device.GetMaxViewports(), Maxwell::NumViewports);
VkPipelineViewportStateCreateInfo viewport_ci{
.sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO,
.pNext = nullptr,
.flags = 0,
- .viewportCount = Maxwell::NumViewports,
+ .viewportCount = num_viewports,
.pViewports = nullptr,
- .scissorCount = Maxwell::NumViewports,
+ .scissorCount = num_viewports,
.pScissors = nullptr,
};
if (device.IsNvViewportSwizzleSupported()) {
diff --git a/src/video_core/renderer_vulkan/vk_pipeline_cache.cpp b/src/video_core/renderer_vulkan/vk_pipeline_cache.cpp
index 9f316113c..d600c4e61 100644
--- a/src/video_core/renderer_vulkan/vk_pipeline_cache.cpp
+++ b/src/video_core/renderer_vulkan/vk_pipeline_cache.cpp
@@ -309,7 +309,7 @@ PipelineCache::PipelineCache(RasterizerVulkan& rasterizer_, const Device& device
.support_int16 = device.IsShaderInt16Supported(),
.support_int64 = device.IsShaderInt64Supported(),
.support_vertex_instance_id = false,
- .support_float_controls = true,
+ .support_float_controls = device.IsKhrShaderFloatControlsSupported(),
.support_separate_denorm_behavior =
float_control.denormBehaviorIndependence == VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_ALL,
.support_separate_rounding_mode =
@@ -325,12 +325,13 @@ PipelineCache::PipelineCache(RasterizerVulkan& rasterizer_, const Device& device
.support_fp64_signed_zero_nan_preserve =
float_control.shaderSignedZeroInfNanPreserveFloat64 != VK_FALSE,
.support_explicit_workgroup_layout = device.IsKhrWorkgroupMemoryExplicitLayoutSupported(),
- .support_vote = true,
+ .support_vote = device.IsSubgroupFeatureSupported(VK_SUBGROUP_FEATURE_VOTE_BIT),
.support_viewport_index_layer_non_geometry =
device.IsExtShaderViewportIndexLayerSupported(),
.support_viewport_mask = device.IsNvViewportArray2Supported(),
.support_typeless_image_loads = device.IsFormatlessImageLoadSupported(),
- .support_demote_to_helper_invocation = true,
+ .support_demote_to_helper_invocation =
+ device.IsExtShaderDemoteToHelperInvocationSupported(),
.support_int64_atomics = device.IsExtShaderAtomicInt64Supported(),
.support_derivative_control = true,
.support_geometry_shader_passthrough = device.IsNvGeometryShaderPassthroughSupported(),
diff --git a/src/video_core/renderer_vulkan/vk_rasterizer.cpp b/src/video_core/renderer_vulkan/vk_rasterizer.cpp
index 84e3a30cc..f7c0d939a 100644
--- a/src/video_core/renderer_vulkan/vk_rasterizer.cpp
+++ b/src/video_core/renderer_vulkan/vk_rasterizer.cpp
@@ -315,7 +315,14 @@ void RasterizerVulkan::Clear(u32 layer_count) {
FlushWork();
gpu_memory->FlushCaching();
+#if ANDROID
+ if (Settings::IsGPULevelHigh()) {
+ // This is problematic on Android, disable on GPU Normal.
+ query_cache.UpdateCounters();
+ }
+#else
query_cache.UpdateCounters();
+#endif
auto& regs = maxwell3d->regs;
const bool use_color = regs.clear_surface.R || regs.clear_surface.G || regs.clear_surface.B ||
@@ -925,7 +932,7 @@ void RasterizerVulkan::UpdateViewportsState(Tegra::Engines::Maxwell3D::Regs& reg
}
const bool is_rescaling{texture_cache.IsRescaling()};
const float scale = is_rescaling ? Settings::values.resolution_info.up_factor : 1.0f;
- const std::array viewports{
+ const std::array viewport_list{
GetViewportState(device, regs, 0, scale), GetViewportState(device, regs, 1, scale),
GetViewportState(device, regs, 2, scale), GetViewportState(device, regs, 3, scale),
GetViewportState(device, regs, 4, scale), GetViewportState(device, regs, 5, scale),
@@ -935,7 +942,11 @@ void RasterizerVulkan::UpdateViewportsState(Tegra::Engines::Maxwell3D::Regs& reg
GetViewportState(device, regs, 12, scale), GetViewportState(device, regs, 13, scale),
GetViewportState(device, regs, 14, scale), GetViewportState(device, regs, 15, scale),
};
- scheduler.Record([viewports](vk::CommandBuffer cmdbuf) { cmdbuf.SetViewport(0, viewports); });
+ scheduler.Record([this, viewport_list](vk::CommandBuffer cmdbuf) {
+ const u32 num_viewports = std::min<u32>(device.GetMaxViewports(), Maxwell::NumViewports);
+ const vk::Span<VkViewport> viewports(viewport_list.data(), num_viewports);
+ cmdbuf.SetViewport(0, viewports);
+ });
}
void RasterizerVulkan::UpdateScissorsState(Tegra::Engines::Maxwell3D::Regs& regs) {
@@ -948,7 +959,7 @@ void RasterizerVulkan::UpdateScissorsState(Tegra::Engines::Maxwell3D::Regs& regs
up_scale = Settings::values.resolution_info.up_scale;
down_shift = Settings::values.resolution_info.down_shift;
}
- const std::array scissors{
+ const std::array scissor_list{
GetScissorState(regs, 0, up_scale, down_shift),
GetScissorState(regs, 1, up_scale, down_shift),
GetScissorState(regs, 2, up_scale, down_shift),
@@ -966,7 +977,11 @@ void RasterizerVulkan::UpdateScissorsState(Tegra::Engines::Maxwell3D::Regs& regs
GetScissorState(regs, 14, up_scale, down_shift),
GetScissorState(regs, 15, up_scale, down_shift),
};
- scheduler.Record([scissors](vk::CommandBuffer cmdbuf) { cmdbuf.SetScissor(0, scissors); });
+ scheduler.Record([this, scissor_list](vk::CommandBuffer cmdbuf) {
+ const u32 num_scissors = std::min<u32>(device.GetMaxViewports(), Maxwell::NumViewports);
+ const vk::Span<VkRect2D> scissors(scissor_list.data(), num_scissors);
+ cmdbuf.SetScissor(0, scissors);
+ });
}
void RasterizerVulkan::UpdateDepthBias(Tegra::Engines::Maxwell3D::Regs& regs) {
diff --git a/src/video_core/renderer_vulkan/vk_staging_buffer_pool.cpp b/src/video_core/renderer_vulkan/vk_staging_buffer_pool.cpp
index 62b251a9b..ce92f66ab 100644
--- a/src/video_core/renderer_vulkan/vk_staging_buffer_pool.cpp
+++ b/src/video_core/renderer_vulkan/vk_staging_buffer_pool.cpp
@@ -38,18 +38,20 @@ size_t Region(size_t iterator) noexcept {
StagingBufferPool::StagingBufferPool(const Device& device_, MemoryAllocator& memory_allocator_,
Scheduler& scheduler_)
: device{device_}, memory_allocator{memory_allocator_}, scheduler{scheduler_} {
- const VkBufferCreateInfo stream_ci = {
+ VkBufferCreateInfo stream_ci = {
.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO,
.pNext = nullptr,
.flags = 0,
.size = STREAM_BUFFER_SIZE,
.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT |
- VK_BUFFER_USAGE_INDEX_BUFFER_BIT | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT |
- VK_BUFFER_USAGE_TRANSFORM_FEEDBACK_BUFFER_BIT_EXT,
+ VK_BUFFER_USAGE_INDEX_BUFFER_BIT | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT,
.sharingMode = VK_SHARING_MODE_EXCLUSIVE,
.queueFamilyIndexCount = 0,
.pQueueFamilyIndices = nullptr,
};
+ if (device.IsExtTransformFeedbackSupported()) {
+ stream_ci.usage |= VK_BUFFER_USAGE_TRANSFORM_FEEDBACK_BUFFER_BIT_EXT;
+ }
stream_buffer = memory_allocator.CreateBuffer(stream_ci, MemoryUsage::Stream);
if (device.HasDebuggingToolAttached()) {
stream_buffer.SetObjectNameEXT("Stream Buffer");
@@ -164,19 +166,21 @@ std::optional<StagingBufferRef> StagingBufferPool::TryGetReservedBuffer(size_t s
StagingBufferRef StagingBufferPool::CreateStagingBuffer(size_t size, MemoryUsage usage,
bool deferred) {
const u32 log2 = Common::Log2Ceil64(size);
- const VkBufferCreateInfo buffer_ci = {
+ VkBufferCreateInfo buffer_ci = {
.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO,
.pNext = nullptr,
.flags = 0,
.size = 1ULL << log2,
.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT |
VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT |
- VK_BUFFER_USAGE_INDEX_BUFFER_BIT | VK_BUFFER_USAGE_VERTEX_BUFFER_BIT |
- VK_BUFFER_USAGE_TRANSFORM_FEEDBACK_BUFFER_BIT_EXT,
+ VK_BUFFER_USAGE_INDEX_BUFFER_BIT | VK_BUFFER_USAGE_VERTEX_BUFFER_BIT,
.sharingMode = VK_SHARING_MODE_EXCLUSIVE,
.queueFamilyIndexCount = 0,
.pQueueFamilyIndices = nullptr,
};
+ if (device.IsExtTransformFeedbackSupported()) {
+ buffer_ci.usage |= VK_BUFFER_USAGE_TRANSFORM_FEEDBACK_BUFFER_BIT_EXT;
+ }
vk::Buffer buffer = memory_allocator.CreateBuffer(buffer_ci, usage);
if (device.HasDebuggingToolAttached()) {
++buffer_index;
diff --git a/src/video_core/renderer_vulkan/vk_texture_cache.cpp b/src/video_core/renderer_vulkan/vk_texture_cache.cpp
index ce6acc30c..8385b5509 100644
--- a/src/video_core/renderer_vulkan/vk_texture_cache.cpp
+++ b/src/video_core/renderer_vulkan/vk_texture_cache.cpp
@@ -1279,6 +1279,10 @@ Image::Image(TextureCacheRuntime& runtime_, const ImageInfo& info_, GPUVAddr gpu
flags |= VideoCommon::ImageFlagBits::Converted;
flags |= VideoCommon::ImageFlagBits::CostlyLoad;
}
+ if (IsPixelFormatBCn(info.format) && !runtime->device.IsOptimalBcnSupported()) {
+ flags |= VideoCommon::ImageFlagBits::Converted;
+ flags |= VideoCommon::ImageFlagBits::CostlyLoad;
+ }
if (runtime->device.HasDebuggingToolAttached()) {
original_image.SetObjectNameEXT(VideoCommon::Name(*this).c_str());
}
diff --git a/src/video_core/surface.cpp b/src/video_core/surface.cpp
index cb51529e4..e16cd5e73 100644
--- a/src/video_core/surface.cpp
+++ b/src/video_core/surface.cpp
@@ -269,6 +269,28 @@ bool IsPixelFormatASTC(PixelFormat format) {
}
}
+bool IsPixelFormatBCn(PixelFormat format) {
+ switch (format) {
+ case PixelFormat::BC1_RGBA_UNORM:
+ case PixelFormat::BC2_UNORM:
+ case PixelFormat::BC3_UNORM:
+ case PixelFormat::BC4_UNORM:
+ case PixelFormat::BC4_SNORM:
+ case PixelFormat::BC5_UNORM:
+ case PixelFormat::BC5_SNORM:
+ case PixelFormat::BC1_RGBA_SRGB:
+ case PixelFormat::BC2_SRGB:
+ case PixelFormat::BC3_SRGB:
+ case PixelFormat::BC7_UNORM:
+ case PixelFormat::BC6H_UFLOAT:
+ case PixelFormat::BC6H_SFLOAT:
+ case PixelFormat::BC7_SRGB:
+ return true;
+ default:
+ return false;
+ }
+}
+
bool IsPixelFormatSRGB(PixelFormat format) {
switch (format) {
case PixelFormat::A8B8G8R8_SRGB:
diff --git a/src/video_core/surface.h b/src/video_core/surface.h
index 0225d3287..9b9c4d9bc 100644
--- a/src/video_core/surface.h
+++ b/src/video_core/surface.h
@@ -501,6 +501,8 @@ SurfaceType GetFormatType(PixelFormat pixel_format);
bool IsPixelFormatASTC(PixelFormat format);
+bool IsPixelFormatBCn(PixelFormat format);
+
bool IsPixelFormatSRGB(PixelFormat format);
bool IsPixelFormatInteger(PixelFormat format);
diff --git a/src/video_core/texture_cache/decode_bc.cpp b/src/video_core/texture_cache/decode_bc.cpp
new file mode 100644
index 000000000..3e26474a3
--- /dev/null
+++ b/src/video_core/texture_cache/decode_bc.cpp
@@ -0,0 +1,129 @@
+// SPDX-FileCopyrightText: Copyright 2020 yuzu Emulator Project
+// SPDX-License-Identifier: GPL-2.0-or-later
+
+#include <algorithm>
+#include <array>
+#include <span>
+#include <bc_decoder.h>
+
+#include "common/common_types.h"
+#include "video_core/texture_cache/decode_bc.h"
+
+namespace VideoCommon {
+
+namespace {
+constexpr u32 BLOCK_SIZE = 4;
+
+using VideoCore::Surface::PixelFormat;
+
+constexpr bool IsSigned(PixelFormat pixel_format) {
+ switch (pixel_format) {
+ case PixelFormat::BC4_SNORM:
+ case PixelFormat::BC4_UNORM:
+ case PixelFormat::BC5_SNORM:
+ case PixelFormat::BC5_UNORM:
+ case PixelFormat::BC6H_SFLOAT:
+ case PixelFormat::BC6H_UFLOAT:
+ return true;
+ default:
+ return false;
+ }
+}
+
+constexpr u32 BlockSize(PixelFormat pixel_format) {
+ switch (pixel_format) {
+ case PixelFormat::BC1_RGBA_SRGB:
+ case PixelFormat::BC1_RGBA_UNORM:
+ case PixelFormat::BC4_SNORM:
+ case PixelFormat::BC4_UNORM:
+ return 8;
+ default:
+ return 16;
+ }
+}
+} // Anonymous namespace
+
+u32 ConvertedBytesPerBlock(VideoCore::Surface::PixelFormat pixel_format) {
+ switch (pixel_format) {
+ case PixelFormat::BC4_SNORM:
+ case PixelFormat::BC4_UNORM:
+ return 1;
+ case PixelFormat::BC5_SNORM:
+ case PixelFormat::BC5_UNORM:
+ return 2;
+ case PixelFormat::BC6H_SFLOAT:
+ case PixelFormat::BC6H_UFLOAT:
+ return 8;
+ default:
+ return 4;
+ }
+}
+
+template <auto decompress, PixelFormat pixel_format>
+void DecompressBlocks(std::span<const u8> input, std::span<u8> output, Extent3D extent,
+ bool is_signed = false) {
+ const u32 out_bpp = ConvertedBytesPerBlock(pixel_format);
+ const u32 block_width = std::min(extent.width, BLOCK_SIZE);
+ const u32 block_height = std::min(extent.height, BLOCK_SIZE);
+ const u32 pitch = extent.width * out_bpp;
+ size_t input_offset = 0;
+ size_t output_offset = 0;
+ for (u32 slice = 0; slice < extent.depth; ++slice) {
+ for (u32 y = 0; y < extent.height; y += block_height) {
+ size_t row_offset = 0;
+ for (u32 x = 0; x < extent.width;
+ x += block_width, row_offset += block_width * out_bpp) {
+ const u8* src = input.data() + input_offset;
+ u8* const dst = output.data() + output_offset + row_offset;
+ if constexpr (IsSigned(pixel_format)) {
+ decompress(src, dst, x, y, extent.width, extent.height, is_signed);
+ } else {
+ decompress(src, dst, x, y, extent.width, extent.height);
+ }
+ input_offset += BlockSize(pixel_format);
+ }
+ output_offset += block_height * pitch;
+ }
+ }
+}
+
+void DecompressBCn(std::span<const u8> input, std::span<u8> output, Extent3D extent,
+ VideoCore::Surface::PixelFormat pixel_format) {
+ switch (pixel_format) {
+ case PixelFormat::BC1_RGBA_UNORM:
+ case PixelFormat::BC1_RGBA_SRGB:
+ DecompressBlocks<bcn::DecodeBc1, PixelFormat::BC1_RGBA_UNORM>(input, output, extent);
+ break;
+ case PixelFormat::BC2_UNORM:
+ case PixelFormat::BC2_SRGB:
+ DecompressBlocks<bcn::DecodeBc2, PixelFormat::BC2_UNORM>(input, output, extent);
+ break;
+ case PixelFormat::BC3_UNORM:
+ case PixelFormat::BC3_SRGB:
+ DecompressBlocks<bcn::DecodeBc3, PixelFormat::BC3_UNORM>(input, output, extent);
+ break;
+ case PixelFormat::BC4_SNORM:
+ case PixelFormat::BC4_UNORM:
+ DecompressBlocks<bcn::DecodeBc4, PixelFormat::BC4_UNORM>(
+ input, output, extent, pixel_format == PixelFormat::BC4_SNORM);
+ break;
+ case PixelFormat::BC5_SNORM:
+ case PixelFormat::BC5_UNORM:
+ DecompressBlocks<bcn::DecodeBc5, PixelFormat::BC5_UNORM>(
+ input, output, extent, pixel_format == PixelFormat::BC5_SNORM);
+ break;
+ case PixelFormat::BC6H_SFLOAT:
+ case PixelFormat::BC6H_UFLOAT:
+ DecompressBlocks<bcn::DecodeBc6, PixelFormat::BC6H_UFLOAT>(
+ input, output, extent, pixel_format == PixelFormat::BC6H_SFLOAT);
+ break;
+ case PixelFormat::BC7_SRGB:
+ case PixelFormat::BC7_UNORM:
+ DecompressBlocks<bcn::DecodeBc7, PixelFormat::BC7_UNORM>(input, output, extent);
+ break;
+ default:
+ LOG_WARNING(HW_GPU, "Unimplemented BCn decompression {}", pixel_format);
+ }
+}
+
+} // namespace VideoCommon
diff --git a/src/video_core/texture_cache/decode_bc4.h b/src/video_core/texture_cache/decode_bc.h
index ab2f735be..41d1ec0a3 100644
--- a/src/video_core/texture_cache/decode_bc4.h
+++ b/src/video_core/texture_cache/decode_bc.h
@@ -6,10 +6,14 @@
#include <span>
#include "common/common_types.h"
+#include "video_core/surface.h"
#include "video_core/texture_cache/types.h"
namespace VideoCommon {
-void DecompressBC4(std::span<const u8> data, Extent3D extent, std::span<u8> output);
+[[nodiscard]] u32 ConvertedBytesPerBlock(VideoCore::Surface::PixelFormat pixel_format);
+
+void DecompressBCn(std::span<const u8> input, std::span<u8> output, Extent3D extent,
+ VideoCore::Surface::PixelFormat pixel_format);
} // namespace VideoCommon
diff --git a/src/video_core/texture_cache/decode_bc4.cpp b/src/video_core/texture_cache/decode_bc4.cpp
deleted file mode 100644
index ef98afdca..000000000
--- a/src/video_core/texture_cache/decode_bc4.cpp
+++ /dev/null
@@ -1,96 +0,0 @@
-// SPDX-FileCopyrightText: Copyright 2020 yuzu Emulator Project
-// SPDX-License-Identifier: GPL-2.0-or-later
-
-#include <algorithm>
-#include <array>
-#include <span>
-
-#include "common/assert.h"
-#include "common/common_types.h"
-#include "video_core/texture_cache/decode_bc4.h"
-#include "video_core/texture_cache/types.h"
-
-namespace VideoCommon {
-
-// https://www.khronos.org/registry/OpenGL/extensions/ARB/ARB_texture_compression_rgtc.txt
-[[nodiscard]] constexpr u32 DecompressBlock(u64 bits, u32 x, u32 y) {
- const u32 code_offset = 16 + 3 * (4 * y + x);
- const u32 code = (bits >> code_offset) & 7;
- const u32 red0 = (bits >> 0) & 0xff;
- const u32 red1 = (bits >> 8) & 0xff;
- if (red0 > red1) {
- switch (code) {
- case 0:
- return red0;
- case 1:
- return red1;
- case 2:
- return (6 * red0 + 1 * red1) / 7;
- case 3:
- return (5 * red0 + 2 * red1) / 7;
- case 4:
- return (4 * red0 + 3 * red1) / 7;
- case 5:
- return (3 * red0 + 4 * red1) / 7;
- case 6:
- return (2 * red0 + 5 * red1) / 7;
- case 7:
- return (1 * red0 + 6 * red1) / 7;
- }
- } else {
- switch (code) {
- case 0:
- return red0;
- case 1:
- return red1;
- case 2:
- return (4 * red0 + 1 * red1) / 5;
- case 3:
- return (3 * red0 + 2 * red1) / 5;
- case 4:
- return (2 * red0 + 3 * red1) / 5;
- case 5:
- return (1 * red0 + 4 * red1) / 5;
- case 6:
- return 0;
- case 7:
- return 0xff;
- }
- }
- return 0;
-}
-
-void DecompressBC4(std::span<const u8> input, Extent3D extent, std::span<u8> output) {
- UNIMPLEMENTED_IF_MSG(extent.width % 4 != 0, "Unaligned width={}", extent.width);
- UNIMPLEMENTED_IF_MSG(extent.height % 4 != 0, "Unaligned height={}", extent.height);
- static constexpr u32 BLOCK_SIZE = 4;
- size_t input_offset = 0;
- for (u32 slice = 0; slice < extent.depth; ++slice) {
- for (u32 block_y = 0; block_y < extent.height / 4; ++block_y) {
- for (u32 block_x = 0; block_x < extent.width / 4; ++block_x) {
- u64 bits;
- std::memcpy(&bits, &input[input_offset], sizeof(bits));
- input_offset += sizeof(bits);
-
- for (u32 y = 0; y < BLOCK_SIZE; ++y) {
- for (u32 x = 0; x < BLOCK_SIZE; ++x) {
- const u32 linear_z = slice;
- const u32 linear_y = block_y * BLOCK_SIZE + y;
- const u32 linear_x = block_x * BLOCK_SIZE + x;
- const u32 offset_z = linear_z * extent.width * extent.height;
- const u32 offset_y = linear_y * extent.width;
- const u32 offset_x = linear_x;
- const u32 output_offset = (offset_z + offset_y + offset_x) * 4ULL;
- const u32 color = DecompressBlock(bits, x, y);
- output[output_offset + 0] = static_cast<u8>(color);
- output[output_offset + 1] = 0;
- output[output_offset + 2] = 0;
- output[output_offset + 3] = 0xff;
- }
- }
- }
- }
- }
-}
-
-} // namespace VideoCommon
diff --git a/src/video_core/texture_cache/util.cpp b/src/video_core/texture_cache/util.cpp
index f781cb7a0..9a618a57a 100644
--- a/src/video_core/texture_cache/util.cpp
+++ b/src/video_core/texture_cache/util.cpp
@@ -24,7 +24,7 @@
#include "video_core/engines/maxwell_3d.h"
#include "video_core/memory_manager.h"
#include "video_core/surface.h"
-#include "video_core/texture_cache/decode_bc4.h"
+#include "video_core/texture_cache/decode_bc.h"
#include "video_core/texture_cache/format_lookup_table.h"
#include "video_core/texture_cache/formatter.h"
#include "video_core/texture_cache/samples_helper.h"
@@ -61,8 +61,6 @@ using VideoCore::Surface::PixelFormatFromDepthFormat;
using VideoCore::Surface::PixelFormatFromRenderTargetFormat;
using VideoCore::Surface::SurfaceType;
-constexpr u32 CONVERTED_BYTES_PER_BLOCK = BytesPerBlock(PixelFormat::A8B8G8R8_UNORM);
-
struct LevelInfo {
Extent3D size;
Extent3D block;
@@ -612,7 +610,8 @@ u32 CalculateConvertedSizeBytes(const ImageInfo& info) noexcept {
}
return output_size;
}
- return NumBlocksPerLayer(info, TILE_SIZE) * info.resources.layers * CONVERTED_BYTES_PER_BLOCK;
+ return NumBlocksPerLayer(info, TILE_SIZE) * info.resources.layers *
+ ConvertedBytesPerBlock(info.format);
}
u32 CalculateLayerStride(const ImageInfo& info) noexcept {
@@ -945,7 +944,8 @@ void ConvertImage(std::span<const u8> input, const ImageInfo& info, std::span<u8
tile_size.height, output.subspan(output_offset));
output_offset += copy.image_extent.width * copy.image_extent.height *
- copy.image_subresource.num_layers * CONVERTED_BYTES_PER_BLOCK;
+ copy.image_subresource.num_layers *
+ BytesPerBlock(PixelFormat::A8B8G8R8_UNORM);
} else if (astc) {
// BC1 uses 0.5 bytes per texel
// BC3 uses 1 byte per texel
@@ -956,7 +956,8 @@ void ConvertImage(std::span<const u8> input, const ImageInfo& info, std::span<u8
const u32 plane_dim = copy.image_extent.width * copy.image_extent.height;
const u32 level_size = plane_dim * copy.image_extent.depth *
- copy.image_subresource.num_layers * CONVERTED_BYTES_PER_BLOCK;
+ copy.image_subresource.num_layers *
+ BytesPerBlock(PixelFormat::A8B8G8R8_UNORM);
decode_scratch.resize_destructive(level_size);
Tegra::Texture::ASTC::Decompress(
@@ -976,10 +977,15 @@ void ConvertImage(std::span<const u8> input, const ImageInfo& info, std::span<u8
bpp_div;
output_offset += static_cast<u32>(copy.buffer_size);
} else {
- DecompressBC4(input_offset, copy.image_extent, output.subspan(output_offset));
-
+ const Extent3D image_extent{
+ .width = copy.image_extent.width,
+ .height = copy.image_extent.height * copy.image_subresource.num_layers,
+ .depth = copy.image_extent.depth,
+ };
+ DecompressBCn(input_offset, output.subspan(output_offset), image_extent, info.format);
output_offset += copy.image_extent.width * copy.image_extent.height *
- copy.image_subresource.num_layers * CONVERTED_BYTES_PER_BLOCK;
+ copy.image_subresource.num_layers *
+ ConvertedBytesPerBlock(info.format);
}
}
}
diff --git a/src/video_core/textures/bcn.cpp b/src/video_core/textures/bcn.cpp
index 671212a49..16ddbe320 100644
--- a/src/video_core/textures/bcn.cpp
+++ b/src/video_core/textures/bcn.cpp
@@ -3,7 +3,6 @@
#include <stb_dxt.h>
#include <string.h>
-
#include "common/alignment.h"
#include "video_core/textures/bcn.h"
#include "video_core/textures/workers.h"
diff --git a/src/video_core/textures/bcn.h b/src/video_core/textures/bcn.h
index 6464af885..d5d2a16c9 100644
--- a/src/video_core/textures/bcn.h
+++ b/src/video_core/textures/bcn.h
@@ -4,14 +4,13 @@
#pragma once
#include <span>
-#include <stdint.h>
+
+#include "common/common_types.h"
namespace Tegra::Texture::BCN {
-void CompressBC1(std::span<const uint8_t> data, uint32_t width, uint32_t height, uint32_t depth,
- std::span<uint8_t> output);
+void CompressBC1(std::span<const u8> data, u32 width, u32 height, u32 depth, std::span<u8> output);
-void CompressBC3(std::span<const uint8_t> data, uint32_t width, uint32_t height, uint32_t depth,
- std::span<uint8_t> output);
+void CompressBC3(std::span<const u8> data, u32 width, u32 height, u32 depth, std::span<u8> output);
} // namespace Tegra::Texture::BCN
diff --git a/src/video_core/vulkan_common/vulkan_debug_callback.cpp b/src/video_core/vulkan_common/vulkan_debug_callback.cpp
index 9de484c29..67e8065a4 100644
--- a/src/video_core/vulkan_common/vulkan_debug_callback.cpp
+++ b/src/video_core/vulkan_common/vulkan_debug_callback.cpp
@@ -7,10 +7,10 @@
namespace Vulkan {
namespace {
-VkBool32 Callback(VkDebugUtilsMessageSeverityFlagBitsEXT severity,
- VkDebugUtilsMessageTypeFlagsEXT type,
- const VkDebugUtilsMessengerCallbackDataEXT* data,
- [[maybe_unused]] void* user_data) {
+VkBool32 DebugUtilCallback(VkDebugUtilsMessageSeverityFlagBitsEXT severity,
+ VkDebugUtilsMessageTypeFlagsEXT type,
+ const VkDebugUtilsMessengerCallbackDataEXT* data,
+ [[maybe_unused]] void* user_data) {
// Skip logging known false-positive validation errors
switch (static_cast<u32>(data->messageIdNumber)) {
#ifdef ANDROID
@@ -62,9 +62,26 @@ VkBool32 Callback(VkDebugUtilsMessageSeverityFlagBitsEXT severity,
}
return VK_FALSE;
}
+
+VkBool32 DebugReportCallback(VkDebugReportFlagsEXT flags, VkDebugReportObjectTypeEXT objectType,
+ uint64_t object, size_t location, int32_t messageCode,
+ const char* pLayerPrefix, const char* pMessage, void* pUserData) {
+ const VkDebugReportFlagBitsEXT severity = static_cast<VkDebugReportFlagBitsEXT>(flags);
+ const std::string_view message{pMessage};
+ if (severity & VK_DEBUG_REPORT_ERROR_BIT_EXT) {
+ LOG_CRITICAL(Render_Vulkan, "{}", message);
+ } else if (severity & VK_DEBUG_REPORT_WARNING_BIT_EXT) {
+ LOG_WARNING(Render_Vulkan, "{}", message);
+ } else if (severity & VK_DEBUG_REPORT_INFORMATION_BIT_EXT) {
+ LOG_INFO(Render_Vulkan, "{}", message);
+ } else if (severity & VK_DEBUG_REPORT_DEBUG_BIT_EXT) {
+ LOG_DEBUG(Render_Vulkan, "{}", message);
+ }
+ return VK_FALSE;
+}
} // Anonymous namespace
-vk::DebugUtilsMessenger CreateDebugCallback(const vk::Instance& instance) {
+vk::DebugUtilsMessenger CreateDebugUtilsCallback(const vk::Instance& instance) {
return instance.CreateDebugUtilsMessenger(VkDebugUtilsMessengerCreateInfoEXT{
.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_MESSENGER_CREATE_INFO_EXT,
.pNext = nullptr,
@@ -76,7 +93,18 @@ vk::DebugUtilsMessenger CreateDebugCallback(const vk::Instance& instance) {
.messageType = VK_DEBUG_UTILS_MESSAGE_TYPE_GENERAL_BIT_EXT |
VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT |
VK_DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT,
- .pfnUserCallback = Callback,
+ .pfnUserCallback = DebugUtilCallback,
+ .pUserData = nullptr,
+ });
+}
+
+vk::DebugReportCallback CreateDebugReportCallback(const vk::Instance& instance) {
+ return instance.CreateDebugReportCallback({
+ .sType = VK_STRUCTURE_TYPE_DEBUG_REPORT_CALLBACK_CREATE_INFO_EXT,
+ .pNext = nullptr,
+ .flags = VK_DEBUG_REPORT_DEBUG_BIT_EXT | VK_DEBUG_REPORT_INFORMATION_BIT_EXT |
+ VK_DEBUG_REPORT_ERROR_BIT_EXT | VK_DEBUG_REPORT_WARNING_BIT_EXT,
+ .pfnCallback = DebugReportCallback,
.pUserData = nullptr,
});
}
diff --git a/src/video_core/vulkan_common/vulkan_debug_callback.h b/src/video_core/vulkan_common/vulkan_debug_callback.h
index 71b1f69ec..a8af7b406 100644
--- a/src/video_core/vulkan_common/vulkan_debug_callback.h
+++ b/src/video_core/vulkan_common/vulkan_debug_callback.h
@@ -7,6 +7,8 @@
namespace Vulkan {
-vk::DebugUtilsMessenger CreateDebugCallback(const vk::Instance& instance);
+vk::DebugUtilsMessenger CreateDebugUtilsCallback(const vk::Instance& instance);
+
+vk::DebugReportCallback CreateDebugReportCallback(const vk::Instance& instance);
} // namespace Vulkan
diff --git a/src/video_core/vulkan_common/vulkan_device.cpp b/src/video_core/vulkan_common/vulkan_device.cpp
index e4ca65b58..421e71e5a 100644
--- a/src/video_core/vulkan_common/vulkan_device.cpp
+++ b/src/video_core/vulkan_common/vulkan_device.cpp
@@ -349,7 +349,7 @@ Device::Device(VkInstance instance_, vk::PhysicalDevice physical_, VkSurfaceKHR
const bool is_s8gen2 = device_id == 0x43050a01;
const bool is_arm = driver_id == VK_DRIVER_ID_ARM_PROPRIETARY;
- if ((is_mvk || is_qualcomm || is_turnip) && !is_suitable) {
+ if ((is_mvk || is_qualcomm || is_turnip || is_arm) && !is_suitable) {
LOG_WARNING(Render_Vulkan, "Unsuitable driver, continuing anyway");
} else if (!is_suitable) {
throw vk::Exception(VK_ERROR_INCOMPATIBLE_DRIVER);
@@ -528,6 +528,14 @@ Device::Device(VkInstance instance_, vk::PhysicalDevice physical_, VkSurfaceKHR
}
sets_per_pool = 64;
+ if (extensions.extended_dynamic_state3 && is_amd_driver &&
+ properties.properties.driverVersion >= VK_MAKE_API_VERSION(0, 2, 0, 270)) {
+ LOG_WARNING(Render_Vulkan,
+ "AMD drivers after 23.5.2 have broken extendedDynamicState3ColorBlendEquation");
+ features.extended_dynamic_state3.extendedDynamicState3ColorBlendEnable = false;
+ features.extended_dynamic_state3.extendedDynamicState3ColorBlendEquation = false;
+ dynamic_state3_blending = false;
+ }
if (is_amd_driver) {
// AMD drivers need a higher amount of Sets per Pool in certain circumstances like in XC2.
sets_per_pool = 96;
@@ -905,6 +913,10 @@ bool Device::GetSuitability(bool requires_swapchain) {
properties.driver.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DRIVER_PROPERTIES;
SetNext(next, properties.driver);
+ // Retrieve subgroup properties.
+ properties.subgroup_properties.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SUBGROUP_PROPERTIES;
+ SetNext(next, properties.subgroup_properties);
+
// Retrieve relevant extension properties.
if (extensions.shader_float_controls) {
properties.float_controls.sType =
diff --git a/src/video_core/vulkan_common/vulkan_device.h b/src/video_core/vulkan_common/vulkan_device.h
index b84af3dfb..1f17265d5 100644
--- a/src/video_core/vulkan_common/vulkan_device.h
+++ b/src/video_core/vulkan_common/vulkan_device.h
@@ -293,6 +293,11 @@ public:
return features.features.textureCompressionASTC_LDR;
}
+ /// Returns true if BCn is natively supported.
+ bool IsOptimalBcnSupported() const {
+ return features.features.textureCompressionBC;
+ }
+
/// Returns true if descriptor aliasing is natively supported.
bool IsDescriptorAliasingSupported() const {
return GetDriverID() != VK_DRIVER_ID_QUALCOMM_PROPRIETARY;
@@ -323,6 +328,11 @@ public:
return properties.subgroup_size_control.requiredSubgroupSizeStages & stage;
}
+ /// Returns true if the device supports the provided subgroup feature.
+ bool IsSubgroupFeatureSupported(VkSubgroupFeatureFlagBits feature) const {
+ return properties.subgroup_properties.supportedOperations & feature;
+ }
+
/// Returns the maximum number of push descriptors.
u32 MaxPushDescriptors() const {
return properties.push_descriptor.maxPushDescriptors;
@@ -388,6 +398,11 @@ public:
return extensions.swapchain_mutable_format;
}
+ /// Returns true if VK_KHR_shader_float_controls is enabled.
+ bool IsKhrShaderFloatControlsSupported() const {
+ return extensions.shader_float_controls;
+ }
+
/// Returns true if the device supports VK_KHR_workgroup_memory_explicit_layout.
bool IsKhrWorkgroupMemoryExplicitLayoutSupported() const {
return extensions.workgroup_memory_explicit_layout;
@@ -413,6 +428,11 @@ public:
return extensions.sampler_filter_minmax;
}
+ /// Returns true if the device supports VK_EXT_shader_stencil_export.
+ bool IsExtShaderStencilExportSupported() const {
+ return extensions.shader_stencil_export;
+ }
+
/// Returns true if the device supports VK_EXT_depth_range_unrestricted.
bool IsExtDepthRangeUnrestrictedSupported() const {
return extensions.depth_range_unrestricted;
@@ -482,9 +502,9 @@ public:
return extensions.vertex_input_dynamic_state;
}
- /// Returns true if the device supports VK_EXT_shader_stencil_export.
- bool IsExtShaderStencilExportSupported() const {
- return extensions.shader_stencil_export;
+ /// Returns true if the device supports VK_EXT_shader_demote_to_helper_invocation
+ bool IsExtShaderDemoteToHelperInvocationSupported() const {
+ return extensions.shader_demote_to_helper_invocation;
}
/// Returns true if the device supports VK_EXT_conservative_rasterization.
@@ -518,12 +538,12 @@ public:
if (extensions.spirv_1_4) {
return 0x00010400U;
}
- return 0x00010000U;
+ return 0x00010300U;
}
/// Returns true when a known debugging tool is attached.
bool HasDebuggingToolAttached() const {
- return has_renderdoc || has_nsight_graphics || Settings::values.renderer_debug.GetValue();
+ return has_renderdoc || has_nsight_graphics;
}
/// @returns True if compute pipelines can cause crashing.
@@ -588,6 +608,10 @@ public:
return properties.properties.limits.maxVertexInputBindings;
}
+ u32 GetMaxViewports() const {
+ return properties.properties.limits.maxViewports;
+ }
+
bool SupportsConditionalBarriers() const {
return supports_conditional_barriers;
}
@@ -680,6 +704,7 @@ private:
struct Properties {
VkPhysicalDeviceDriverProperties driver{};
+ VkPhysicalDeviceSubgroupProperties subgroup_properties{};
VkPhysicalDeviceFloatControlsProperties float_controls{};
VkPhysicalDevicePushDescriptorPropertiesKHR push_descriptor{};
VkPhysicalDeviceSubgroupSizeControlProperties subgroup_size_control{};
diff --git a/src/video_core/vulkan_common/vulkan_instance.cpp b/src/video_core/vulkan_common/vulkan_instance.cpp
index b6d83e446..7624a9b32 100644
--- a/src/video_core/vulkan_common/vulkan_instance.cpp
+++ b/src/video_core/vulkan_common/vulkan_instance.cpp
@@ -31,10 +31,34 @@
namespace Vulkan {
namespace {
+
+[[nodiscard]] bool AreExtensionsSupported(const vk::InstanceDispatch& dld,
+ std::span<const char* const> extensions) {
+ const std::optional properties = vk::EnumerateInstanceExtensionProperties(dld);
+ if (!properties) {
+ LOG_ERROR(Render_Vulkan, "Failed to query extension properties");
+ return false;
+ }
+ for (const char* extension : extensions) {
+ const auto it = std::ranges::find_if(*properties, [extension](const auto& prop) {
+ return std::strcmp(extension, prop.extensionName) == 0;
+ });
+ if (it == properties->end()) {
+ LOG_ERROR(Render_Vulkan, "Required instance extension {} is not available", extension);
+ return false;
+ }
+ }
+ return true;
+}
+
[[nodiscard]] std::vector<const char*> RequiredExtensions(
- Core::Frontend::WindowSystemType window_type, bool enable_validation) {
+ const vk::InstanceDispatch& dld, Core::Frontend::WindowSystemType window_type,
+ bool enable_validation) {
std::vector<const char*> extensions;
extensions.reserve(6);
+#ifdef __APPLE__
+ extensions.push_back(VK_KHR_PORTABILITY_ENUMERATION_EXTENSION_NAME);
+#endif
switch (window_type) {
case Core::Frontend::WindowSystemType::Headless:
break;
@@ -66,35 +90,14 @@ namespace {
extensions.push_back(VK_KHR_SURFACE_EXTENSION_NAME);
}
if (enable_validation) {
- extensions.push_back(VK_EXT_DEBUG_UTILS_EXTENSION_NAME);
+ const bool debug_utils =
+ AreExtensionsSupported(dld, std::array{VK_EXT_DEBUG_UTILS_EXTENSION_NAME});
+ extensions.push_back(debug_utils ? VK_EXT_DEBUG_UTILS_EXTENSION_NAME
+ : VK_EXT_DEBUG_REPORT_EXTENSION_NAME);
}
- extensions.push_back(VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME);
-
-#ifdef __APPLE__
- extensions.push_back(VK_KHR_PORTABILITY_ENUMERATION_EXTENSION_NAME);
-#endif
return extensions;
}
-[[nodiscard]] bool AreExtensionsSupported(const vk::InstanceDispatch& dld,
- std::span<const char* const> extensions) {
- const std::optional properties = vk::EnumerateInstanceExtensionProperties(dld);
- if (!properties) {
- LOG_ERROR(Render_Vulkan, "Failed to query extension properties");
- return false;
- }
- for (const char* extension : extensions) {
- const auto it = std::ranges::find_if(*properties, [extension](const auto& prop) {
- return std::strcmp(extension, prop.extensionName) == 0;
- });
- if (it == properties->end()) {
- LOG_ERROR(Render_Vulkan, "Required instance extension {} is not available", extension);
- return false;
- }
- }
- return true;
-}
-
[[nodiscard]] std::vector<const char*> Layers(bool enable_validation) {
std::vector<const char*> layers;
if (enable_validation) {
@@ -138,7 +141,8 @@ vk::Instance CreateInstance(const Common::DynamicLibrary& library, vk::InstanceD
LOG_ERROR(Render_Vulkan, "Failed to load Vulkan function pointers");
throw vk::Exception(VK_ERROR_INITIALIZATION_FAILED);
}
- const std::vector<const char*> extensions = RequiredExtensions(window_type, enable_validation);
+ const std::vector<const char*> extensions =
+ RequiredExtensions(dld, window_type, enable_validation);
if (!AreExtensionsSupported(dld, extensions)) {
throw vk::Exception(VK_ERROR_EXTENSION_NOT_PRESENT);
}
diff --git a/src/video_core/vulkan_common/vulkan_wrapper.cpp b/src/video_core/vulkan_common/vulkan_wrapper.cpp
index 28fcb21a0..2fa29793a 100644
--- a/src/video_core/vulkan_common/vulkan_wrapper.cpp
+++ b/src/video_core/vulkan_common/vulkan_wrapper.cpp
@@ -259,7 +259,9 @@ bool Load(VkInstance instance, InstanceDispatch& dld) noexcept {
// These functions may fail to load depending on the enabled extensions.
// Don't return a failure on these.
X(vkCreateDebugUtilsMessengerEXT);
+ X(vkCreateDebugReportCallbackEXT);
X(vkDestroyDebugUtilsMessengerEXT);
+ X(vkDestroyDebugReportCallbackEXT);
X(vkDestroySurfaceKHR);
X(vkGetPhysicalDeviceFeatures2);
X(vkGetPhysicalDeviceProperties2);
@@ -481,6 +483,11 @@ void Destroy(VkInstance instance, VkDebugUtilsMessengerEXT handle,
dld.vkDestroyDebugUtilsMessengerEXT(instance, handle, nullptr);
}
+void Destroy(VkInstance instance, VkDebugReportCallbackEXT handle,
+ const InstanceDispatch& dld) noexcept {
+ dld.vkDestroyDebugReportCallbackEXT(instance, handle, nullptr);
+}
+
void Destroy(VkInstance instance, VkSurfaceKHR handle, const InstanceDispatch& dld) noexcept {
dld.vkDestroySurfaceKHR(instance, handle, nullptr);
}
@@ -549,6 +556,13 @@ DebugUtilsMessenger Instance::CreateDebugUtilsMessenger(
return DebugUtilsMessenger(object, handle, *dld);
}
+DebugReportCallback Instance::CreateDebugReportCallback(
+ const VkDebugReportCallbackCreateInfoEXT& create_info) const {
+ VkDebugReportCallbackEXT object;
+ Check(dld->vkCreateDebugReportCallbackEXT(handle, &create_info, nullptr, &object));
+ return DebugReportCallback(object, handle, *dld);
+}
+
void Image::SetObjectNameEXT(const char* name) const {
SetObjectName(dld, owner, handle, VK_OBJECT_TYPE_IMAGE, name);
}
diff --git a/src/video_core/vulkan_common/vulkan_wrapper.h b/src/video_core/vulkan_common/vulkan_wrapper.h
index 44fce47a5..b5e70fcd4 100644
--- a/src/video_core/vulkan_common/vulkan_wrapper.h
+++ b/src/video_core/vulkan_common/vulkan_wrapper.h
@@ -164,8 +164,10 @@ struct InstanceDispatch {
PFN_vkEnumerateInstanceLayerProperties vkEnumerateInstanceLayerProperties{};
PFN_vkCreateDebugUtilsMessengerEXT vkCreateDebugUtilsMessengerEXT{};
+ PFN_vkCreateDebugReportCallbackEXT vkCreateDebugReportCallbackEXT{};
PFN_vkCreateDevice vkCreateDevice{};
PFN_vkDestroyDebugUtilsMessengerEXT vkDestroyDebugUtilsMessengerEXT{};
+ PFN_vkDestroyDebugReportCallbackEXT vkDestroyDebugReportCallbackEXT{};
PFN_vkDestroyDevice vkDestroyDevice{};
PFN_vkDestroySurfaceKHR vkDestroySurfaceKHR{};
PFN_vkEnumerateDeviceExtensionProperties vkEnumerateDeviceExtensionProperties{};
@@ -366,6 +368,7 @@ void Destroy(VkDevice, VkSwapchainKHR, const DeviceDispatch&) noexcept;
void Destroy(VkDevice, VkSemaphore, const DeviceDispatch&) noexcept;
void Destroy(VkDevice, VkShaderModule, const DeviceDispatch&) noexcept;
void Destroy(VkInstance, VkDebugUtilsMessengerEXT, const InstanceDispatch&) noexcept;
+void Destroy(VkInstance, VkDebugReportCallbackEXT, const InstanceDispatch&) noexcept;
void Destroy(VkInstance, VkSurfaceKHR, const InstanceDispatch&) noexcept;
VkResult Free(VkDevice, VkDescriptorPool, Span<VkDescriptorSet>, const DeviceDispatch&) noexcept;
@@ -581,6 +584,7 @@ private:
};
using DebugUtilsMessenger = Handle<VkDebugUtilsMessengerEXT, VkInstance, InstanceDispatch>;
+using DebugReportCallback = Handle<VkDebugReportCallbackEXT, VkInstance, InstanceDispatch>;
using DescriptorSetLayout = Handle<VkDescriptorSetLayout, VkDevice, DeviceDispatch>;
using DescriptorUpdateTemplate = Handle<VkDescriptorUpdateTemplate, VkDevice, DeviceDispatch>;
using Pipeline = Handle<VkPipeline, VkDevice, DeviceDispatch>;
@@ -613,6 +617,11 @@ public:
DebugUtilsMessenger CreateDebugUtilsMessenger(
const VkDebugUtilsMessengerCreateInfoEXT& create_info) const;
+ /// Creates a debug report callback.
+ /// @throw Exception on creation failure.
+ DebugReportCallback CreateDebugReportCallback(
+ const VkDebugReportCallbackCreateInfoEXT& create_info) const;
+
/// Returns dispatch table.
const InstanceDispatch& Dispatch() const noexcept {
return *dld;
diff --git a/src/yuzu/configuration/configure_ringcon.cpp b/src/yuzu/configuration/configure_ringcon.cpp
index 71afbc423..f83705544 100644
--- a/src/yuzu/configuration/configure_ringcon.cpp
+++ b/src/yuzu/configuration/configure_ringcon.cpp
@@ -305,6 +305,9 @@ void ConfigureRingController::EnableRingController() {
QMessageBox::warning(this, dialog_title,
tr("The current mapped device doesn't have a ring attached"));
break;
+ case Common::Input::DriverResult::InvalidHandle:
+ QMessageBox::warning(this, dialog_title, tr("The current mapped device is not connected"));
+ break;
default:
QMessageBox::warning(this, dialog_title,
tr("Unexpected driver result %1").arg(static_cast<int>(result)));