summaryrefslogtreecommitdiffstats
path: root/src
diff options
context:
space:
mode:
Diffstat (limited to 'src')
-rw-r--r--src/audio_core/audio_renderer.h2
-rw-r--r--src/audio_core/stream.cpp4
-rw-r--r--src/common/CMakeLists.txt6
-rw-r--r--src/common/assert.h5
-rw-r--r--src/common/bit_field.h19
-rw-r--r--src/common/bit_set.h244
-rw-r--r--src/common/logging/backend.cpp11
-rw-r--r--src/common/logging/backend.h14
-rw-r--r--src/common/math_util.h16
-rw-r--r--src/common/string_util.cpp66
-rw-r--r--src/common/string_util.h41
-rw-r--r--src/common/thread.cpp35
-rw-r--r--src/common/thread.h20
-rw-r--r--src/common/x64/xbyak_abi.h222
-rw-r--r--src/common/x64/xbyak_util.h47
-rw-r--r--src/core/CMakeLists.txt10
-rw-r--r--src/core/core.cpp136
-rw-r--r--src/core/core.h5
-rw-r--r--src/core/cpu_core_manager.cpp142
-rw-r--r--src/core/cpu_core_manager.h59
-rw-r--r--src/core/file_sys/bis_factory.cpp9
-rw-r--r--src/core/file_sys/bis_factory.h4
-rw-r--r--src/core/file_sys/card_image.cpp2
-rw-r--r--src/core/file_sys/card_image.h16
-rw-r--r--src/core/file_sys/content_archive.cpp5
-rw-r--r--src/core/file_sys/content_archive.h3
-rw-r--r--src/core/file_sys/control_metadata.cpp6
-rw-r--r--src/core/file_sys/control_metadata.h1
-rw-r--r--src/core/file_sys/errors.h25
-rw-r--r--src/core/file_sys/patch_manager.cpp62
-rw-r--r--src/core/file_sys/registered_cache.cpp13
-rw-r--r--src/core/file_sys/registered_cache.h3
-rw-r--r--src/core/file_sys/savedata_factory.cpp32
-rw-r--r--src/core/file_sys/savedata_factory.h3
-rw-r--r--src/core/file_sys/submission_package.cpp2
-rw-r--r--src/core/file_sys/submission_package.h2
-rw-r--r--src/core/frontend/applets/software_keyboard.cpp29
-rw-r--r--src/core/frontend/applets/software_keyboard.h54
-rw-r--r--src/core/frontend/input.h7
-rw-r--r--src/core/gdbstub/gdbstub.cpp123
-rw-r--r--src/core/hle/kernel/errors.h74
-rw-r--r--src/core/hle/kernel/handle_table.cpp11
-rw-r--r--src/core/hle/kernel/handle_table.h15
-rw-r--r--src/core/hle/kernel/kernel.cpp79
-rw-r--r--src/core/hle/kernel/kernel.h6
-rw-r--r--src/core/hle/kernel/process.cpp87
-rw-r--r--src/core/hle/kernel/process.h24
-rw-r--r--src/core/hle/kernel/resource_limit.cpp75
-rw-r--r--src/core/hle/kernel/resource_limit.h98
-rw-r--r--src/core/hle/kernel/shared_memory.cpp22
-rw-r--r--src/core/hle/kernel/shared_memory.h48
-rw-r--r--src/core/hle/kernel/svc.cpp155
-rw-r--r--src/core/hle/kernel/svc_wrap.h5
-rw-r--r--src/core/hle/kernel/thread.cpp48
-rw-r--r--src/core/hle/kernel/thread.h2
-rw-r--r--src/core/hle/kernel/vm_manager.cpp82
-rw-r--r--src/core/hle/kernel/vm_manager.h16
-rw-r--r--src/core/hle/result.h2
-rw-r--r--src/core/hle/service/acc/acc.cpp24
-rw-r--r--src/core/hle/service/acc/acc.h1
-rw-r--r--src/core/hle/service/acc/acc_su.cpp2
-rw-r--r--src/core/hle/service/acc/acc_u0.cpp2
-rw-r--r--src/core/hle/service/acc/acc_u1.cpp2
-rw-r--r--src/core/hle/service/acc/profile_manager.cpp25
-rw-r--r--src/core/hle/service/acc/profile_manager.h13
-rw-r--r--src/core/hle/service/am/am.cpp443
-rw-r--r--src/core/hle/service/am/am.h59
-rw-r--r--src/core/hle/service/am/applet_ae.cpp34
-rw-r--r--src/core/hle/service/am/applet_ae.h6
-rw-r--r--src/core/hle/service/am/applet_oe.cpp21
-rw-r--r--src/core/hle/service/am/applet_oe.h6
-rw-r--r--src/core/hle/service/am/applets/applets.cpp113
-rw-r--r--src/core/hle/service/am/applets/applets.h112
-rw-r--r--src/core/hle/service/am/applets/software_keyboard.cpp161
-rw-r--r--src/core/hle/service/am/applets/software_keyboard.h74
-rw-r--r--src/core/hle/service/am/applets/stub_applet.cpp70
-rw-r--r--src/core/hle/service/am/applets/stub_applet.h24
-rw-r--r--src/core/hle/service/audio/audout_u.cpp28
-rw-r--r--src/core/hle/service/audio/audout_u.h3
-rw-r--r--src/core/hle/service/audio/audren_u.cpp31
-rw-r--r--src/core/hle/service/audio/hwopus.cpp2
-rw-r--r--src/core/hle/service/btdrv/btdrv.cpp38
-rw-r--r--src/core/hle/service/btm/btm.cpp108
-rw-r--r--src/core/hle/service/filesystem/filesystem.cpp57
-rw-r--r--src/core/hle/service/filesystem/filesystem.h5
-rw-r--r--src/core/hle/service/filesystem/fsp_srv.cpp169
-rw-r--r--src/core/hle/service/filesystem/fsp_srv.h1
-rw-r--r--src/core/hle/service/hid/controllers/debug_pad.cpp43
-rw-r--r--src/core/hle/service/hid/controllers/debug_pad.h41
-rw-r--r--src/core/hle/service/hid/controllers/keyboard.cpp20
-rw-r--r--src/core/hle/service/hid/controllers/keyboard.h7
-rw-r--r--src/core/hle/service/hid/controllers/mouse.cpp25
-rw-r--r--src/core/hle/service/hid/controllers/mouse.h9
-rw-r--r--src/core/hle/service/hid/controllers/npad.cpp510
-rw-r--r--src/core/hle/service/hid/controllers/npad.h45
-rw-r--r--src/core/hle/service/hid/controllers/touchscreen.cpp13
-rw-r--r--src/core/hle/service/hid/controllers/touchscreen.h12
-rw-r--r--src/core/hle/service/hid/hid.cpp22
-rw-r--r--src/core/hle/service/ldr/ldr.cpp380
-rw-r--r--src/core/hle/service/lm/lm.cpp13
-rw-r--r--src/core/hle/service/nfp/nfp.cpp2
-rw-r--r--src/core/hle/service/ns/ns.cpp64
-rw-r--r--src/core/hle/service/ns/pl_u.cpp8
-rw-r--r--src/core/hle/service/nvdrv/devices/nvhost_ctrl_gpu.cpp13
-rw-r--r--src/core/hle/service/nvdrv/devices/nvhost_ctrl_gpu.h6
-rw-r--r--src/core/hle/service/nvflinger/buffer_queue.h4
-rw-r--r--src/core/hle/service/service.cpp4
-rw-r--r--src/core/hle/service/spl/module.cpp10
-rw-r--r--src/core/hle/service/spl/module.h4
-rw-r--r--src/core/hle/service/time/interface.cpp5
-rw-r--r--src/core/hle/service/time/time.cpp147
-rw-r--r--src/core/hle/service/time/time.h20
-rw-r--r--src/core/hle/service/vi/vi.cpp54
-rw-r--r--src/core/loader/nro.cpp12
-rw-r--r--src/core/loader/nso.cpp2
-rw-r--r--src/core/settings.cpp50
-rw-r--r--src/core/settings.h326
-rw-r--r--src/video_core/CMakeLists.txt2
-rw-r--r--src/video_core/engines/maxwell_3d.cpp53
-rw-r--r--src/video_core/engines/maxwell_3d.h212
-rw-r--r--src/video_core/engines/shader_bytecode.h8
-rw-r--r--src/video_core/gpu.cpp2
-rw-r--r--src/video_core/macro_interpreter.cpp29
-rw-r--r--src/video_core/macro_interpreter.h4
-rw-r--r--src/video_core/memory_manager.cpp75
-rw-r--r--src/video_core/memory_manager.h8
-rw-r--r--src/video_core/rasterizer_cache.cpp7
-rw-r--r--src/video_core/rasterizer_cache.h44
-rw-r--r--src/video_core/renderer_base.cpp1
-rw-r--r--src/video_core/renderer_opengl/gl_buffer_cache.cpp4
-rw-r--r--src/video_core/renderer_opengl/gl_buffer_cache.h4
-rw-r--r--src/video_core/renderer_opengl/gl_primitive_assembler.cpp1
-rw-r--r--src/video_core/renderer_opengl/gl_rasterizer.cpp338
-rw-r--r--src/video_core/renderer_opengl/gl_rasterizer.h52
-rw-r--r--src/video_core/renderer_opengl/gl_rasterizer_cache.cpp149
-rw-r--r--src/video_core/renderer_opengl/gl_rasterizer_cache.h9
-rw-r--r--src/video_core/renderer_opengl/gl_resource_manager.cpp186
-rw-r--r--src/video_core/renderer_opengl/gl_resource_manager.h132
-rw-r--r--src/video_core/renderer_opengl/gl_shader_cache.cpp13
-rw-r--r--src/video_core/renderer_opengl/gl_shader_cache.h20
-rw-r--r--src/video_core/renderer_opengl/gl_shader_decompiler.cpp920
-rw-r--r--src/video_core/renderer_opengl/gl_shader_gen.cpp4
-rw-r--r--src/video_core/renderer_opengl/gl_shader_gen.h1
-rw-r--r--src/video_core/renderer_opengl/gl_shader_manager.h2
-rw-r--r--src/video_core/renderer_opengl/gl_state.cpp318
-rw-r--r--src/video_core/renderer_opengl/gl_state.h85
-rw-r--r--src/video_core/renderer_opengl/gl_stream_buffer.cpp5
-rw-r--r--src/video_core/renderer_opengl/maxwell_to_gl.h77
-rw-r--r--src/video_core/renderer_opengl/renderer_opengl.cpp8
-rw-r--r--src/video_core/surface.cpp33
-rw-r--r--src/video_core/surface.h118
-rw-r--r--src/video_core/textures/astc.cpp32
-rw-r--r--src/video_core/textures/astc.h2
-rw-r--r--src/video_core/textures/decoders.cpp103
-rw-r--r--src/video_core/textures/decoders.h11
-rw-r--r--src/video_core/textures/texture.h28
-rw-r--r--src/yuzu/CMakeLists.txt11
-rw-r--r--src/yuzu/applets/software_keyboard.cpp152
-rw-r--r--src/yuzu/applets/software_keyboard.h79
-rw-r--r--src/yuzu/bootmanager.cpp2
-rw-r--r--src/yuzu/configuration/config.cpp403
-rw-r--r--src/yuzu/configuration/config.h14
-rw-r--r--src/yuzu/configuration/configure_debug.cpp4
-rw-r--r--src/yuzu/configuration/configure_debug.ui31
-rw-r--r--src/yuzu/configuration/configure_gamelist.cpp16
-rw-r--r--src/yuzu/configuration/configure_gamelist.h2
-rw-r--r--src/yuzu/configuration/configure_gamelist.ui223
-rw-r--r--src/yuzu/configuration/configure_general.cpp6
-rw-r--r--src/yuzu/configuration/configure_general.ui9
-rw-r--r--src/yuzu/configuration/configure_graphics.ui94
-rw-r--r--src/yuzu/configuration/configure_input.cpp436
-rw-r--r--src/yuzu/configuration/configure_input.h52
-rw-r--r--src/yuzu/configuration/configure_input.ui1064
-rw-r--r--src/yuzu/configuration/configure_input_player.cpp508
-rw-r--r--src/yuzu/configuration/configure_input_player.h103
-rw-r--r--src/yuzu/configuration/configure_input_player.ui1164
-rw-r--r--src/yuzu/configuration/configure_mouse_advanced.cpp213
-rw-r--r--src/yuzu/configuration/configure_mouse_advanced.h68
-rw-r--r--src/yuzu/configuration/configure_mouse_advanced.ui261
-rw-r--r--src/yuzu/configuration/configure_system.cpp21
-rw-r--r--src/yuzu/configuration/configure_system.ui228
-rw-r--r--src/yuzu/configuration/configure_touchscreen_advanced.cpp42
-rw-r--r--src/yuzu/configuration/configure_touchscreen_advanced.h32
-rw-r--r--src/yuzu/configuration/configure_touchscreen_advanced.ui199
-rw-r--r--src/yuzu/debugger/graphics/graphics_surface.cpp6
-rw-r--r--src/yuzu/game_list.cpp33
-rw-r--r--src/yuzu/game_list_worker.cpp24
-rw-r--r--src/yuzu/main.cpp83
-rw-r--r--src/yuzu/main.h12
-rw-r--r--src/yuzu/main.ui7
-rw-r--r--src/yuzu/ui_settings.h3
-rw-r--r--src/yuzu_cmd/config.cpp285
-rw-r--r--src/yuzu_cmd/default_ini.h9
-rw-r--r--src/yuzu_cmd/emu_window/emu_window_sdl2.cpp16
-rw-r--r--src/yuzu_cmd/yuzu.cpp3
195 files changed, 10558 insertions, 4319 deletions
diff --git a/src/audio_core/audio_renderer.h b/src/audio_core/audio_renderer.h
index 046417da3..71ba4be40 100644
--- a/src/audio_core/audio_renderer.h
+++ b/src/audio_core/audio_renderer.h
@@ -143,7 +143,7 @@ struct AuxInfo {
std::array<u8, 24> output_mix_buffers;
u32_le mix_buffer_count;
u32_le sample_rate; // Stored in the aux buffer currently
- u32_le sampe_count;
+ u32_le sample_count;
u64_le send_buffer_info;
u64_le send_buffer_base;
diff --git a/src/audio_core/stream.cpp b/src/audio_core/stream.cpp
index 742a5e0a0..f35628e45 100644
--- a/src/audio_core/stream.cpp
+++ b/src/audio_core/stream.cpp
@@ -11,7 +11,6 @@
#include "audio_core/stream.h"
#include "common/assert.h"
#include "common/logging/log.h"
-#include "common/microprofile.h"
#include "core/core_timing.h"
#include "core/core_timing_util.h"
#include "core/settings.h"
@@ -104,10 +103,7 @@ void Stream::PlayNextBuffer() {
CoreTiming::ScheduleEventThreadsafe(GetBufferReleaseCycles(*active_buffer), release_event, {});
}
-MICROPROFILE_DEFINE(AudioOutput, "Audio", "ReleaseActiveBuffer", MP_RGB(100, 100, 255));
-
void Stream::ReleaseActiveBuffer() {
- MICROPROFILE_SCOPE(AudioOutput);
ASSERT(active_buffer);
released_buffers.push(std::move(active_buffer));
release_callback();
diff --git a/src/common/CMakeLists.txt b/src/common/CMakeLists.txt
index eccd8f64a..a5e71d879 100644
--- a/src/common/CMakeLists.txt
+++ b/src/common/CMakeLists.txt
@@ -44,7 +44,6 @@ add_library(common STATIC
detached_tasks.cpp
detached_tasks.h
bit_field.h
- bit_set.h
cityhash.cpp
cityhash.h
color.h
@@ -95,14 +94,9 @@ if(ARCHITECTURE_x86_64)
PRIVATE
x64/cpu_detect.cpp
x64/cpu_detect.h
- x64/xbyak_abi.h
- x64/xbyak_util.h
)
endif()
create_target_directory_groups(common)
target_link_libraries(common PUBLIC Boost::boost fmt microprofile)
-if (ARCHITECTURE_x86_64)
- target_link_libraries(common PRIVATE xbyak)
-endif()
diff --git a/src/common/assert.h b/src/common/assert.h
index 0d4eddc19..6002f7ab1 100644
--- a/src/common/assert.h
+++ b/src/common/assert.h
@@ -52,5 +52,8 @@ __declspec(noinline, noreturn)
#define DEBUG_ASSERT_MSG(_a_, _desc_, ...)
#endif
-#define UNIMPLEMENTED() LOG_CRITICAL(Debug, "Unimplemented code!")
+#define UNIMPLEMENTED() ASSERT_MSG(false, "Unimplemented code!")
#define UNIMPLEMENTED_MSG(...) ASSERT_MSG(false, __VA_ARGS__)
+
+#define UNIMPLEMENTED_IF(cond) ASSERT_MSG(!(cond), "Unimplemented code!")
+#define UNIMPLEMENTED_IF_MSG(cond, ...) ASSERT_MSG(!(cond), __VA_ARGS__)
diff --git a/src/common/bit_field.h b/src/common/bit_field.h
index bf803da8d..21e07925d 100644
--- a/src/common/bit_field.h
+++ b/src/common/bit_field.h
@@ -117,21 +117,21 @@ private:
// We don't delete it because we want BitField to be trivially copyable.
constexpr BitField& operator=(const BitField&) = default;
- // StorageType is T for non-enum types and the underlying type of T if
+ // UnderlyingType is T for non-enum types and the underlying type of T if
// T is an enumeration. Note that T is wrapped within an enable_if in the
// former case to workaround compile errors which arise when using
// std::underlying_type<T>::type directly.
- using StorageType = typename std::conditional_t<std::is_enum<T>::value, std::underlying_type<T>,
- std::enable_if<true, T>>::type;
+ using UnderlyingType = typename std::conditional_t<std::is_enum_v<T>, std::underlying_type<T>,
+ std::enable_if<true, T>>::type;
- // Unsigned version of StorageType
- using StorageTypeU = std::make_unsigned_t<StorageType>;
+ // We store the value as the unsigned type to avoid undefined behaviour on value shifting
+ using StorageType = std::make_unsigned_t<UnderlyingType>;
public:
/// Constants to allow limited introspection of fields if needed
static constexpr std::size_t position = Position;
static constexpr std::size_t bits = Bits;
- static constexpr StorageType mask = (((StorageTypeU)~0) >> (8 * sizeof(T) - bits)) << position;
+ static constexpr StorageType mask = (((StorageType)~0) >> (8 * sizeof(T) - bits)) << position;
/**
* Formats a value by masking and shifting it according to the field parameters. A value
@@ -148,11 +148,12 @@ public:
* union in a constexpr context.
*/
static constexpr FORCE_INLINE T ExtractValue(const StorageType& storage) {
- if (std::numeric_limits<T>::is_signed) {
+ if constexpr (std::numeric_limits<UnderlyingType>::is_signed) {
std::size_t shift = 8 * sizeof(T) - bits;
- return (T)((storage << (shift - position)) >> shift);
+ return static_cast<T>(static_cast<UnderlyingType>(storage << (shift - position)) >>
+ shift);
} else {
- return (T)((storage & mask) >> position);
+ return static_cast<T>((storage & mask) >> position);
}
}
diff --git a/src/common/bit_set.h b/src/common/bit_set.h
deleted file mode 100644
index 5cd1352b2..000000000
--- a/src/common/bit_set.h
+++ /dev/null
@@ -1,244 +0,0 @@
-// This file is under the public domain.
-
-#pragma once
-
-#include <cstddef>
-#ifdef _WIN32
-#include <intrin.h>
-#endif
-#include <initializer_list>
-#include <new>
-#include <type_traits>
-#include "common/common_types.h"
-
-// namespace avoids conflict with OS X Carbon; don't use BitSet<T> directly
-namespace Common {
-
-// Helper functions:
-
-#ifdef _MSC_VER
-template <typename T>
-static inline int CountSetBits(T v) {
- // from https://graphics.stanford.edu/~seander/bithacks.html
- // GCC has this built in, but MSVC's intrinsic will only emit the actual
- // POPCNT instruction, which we're not depending on
- v = v - ((v >> 1) & (T) ~(T)0 / 3);
- v = (v & (T) ~(T)0 / 15 * 3) + ((v >> 2) & (T) ~(T)0 / 15 * 3);
- v = (v + (v >> 4)) & (T) ~(T)0 / 255 * 15;
- return (T)(v * ((T) ~(T)0 / 255)) >> (sizeof(T) - 1) * 8;
-}
-static inline int LeastSignificantSetBit(u8 val) {
- unsigned long index;
- _BitScanForward(&index, val);
- return (int)index;
-}
-static inline int LeastSignificantSetBit(u16 val) {
- unsigned long index;
- _BitScanForward(&index, val);
- return (int)index;
-}
-static inline int LeastSignificantSetBit(u32 val) {
- unsigned long index;
- _BitScanForward(&index, val);
- return (int)index;
-}
-static inline int LeastSignificantSetBit(u64 val) {
- unsigned long index;
- _BitScanForward64(&index, val);
- return (int)index;
-}
-#else
-static inline int CountSetBits(u8 val) {
- return __builtin_popcount(val);
-}
-static inline int CountSetBits(u16 val) {
- return __builtin_popcount(val);
-}
-static inline int CountSetBits(u32 val) {
- return __builtin_popcount(val);
-}
-static inline int CountSetBits(u64 val) {
- return __builtin_popcountll(val);
-}
-static inline int LeastSignificantSetBit(u8 val) {
- return __builtin_ctz(val);
-}
-static inline int LeastSignificantSetBit(u16 val) {
- return __builtin_ctz(val);
-}
-static inline int LeastSignificantSetBit(u32 val) {
- return __builtin_ctz(val);
-}
-static inline int LeastSignificantSetBit(u64 val) {
- return __builtin_ctzll(val);
-}
-#endif
-
-// Similar to std::bitset, this is a class which encapsulates a bitset, i.e.
-// using the set bits of an integer to represent a set of integers. Like that
-// class, it acts like an array of bools:
-// BitSet32 bs;
-// bs[1] = true;
-// but also like the underlying integer ([0] = least significant bit):
-// BitSet32 bs2 = ...;
-// bs = (bs ^ bs2) & BitSet32(0xffff);
-// The following additional functionality is provided:
-// - Construction using an initializer list.
-// BitSet bs { 1, 2, 4, 8 };
-// - Efficiently iterating through the set bits:
-// for (int i : bs)
-// [i is the *index* of a set bit]
-// (This uses the appropriate CPU instruction to find the next set bit in one
-// operation.)
-// - Counting set bits using .Count() - see comment on that method.
-
-// TODO: use constexpr when MSVC gets out of the Dark Ages
-
-template <typename IntTy>
-class BitSet {
- static_assert(!std::is_signed_v<IntTy>, "BitSet should not be used with signed types");
-
-public:
- // A reference to a particular bit, returned from operator[].
- class Ref {
- public:
- Ref(Ref&& other) : m_bs(other.m_bs), m_mask(other.m_mask) {}
- Ref(BitSet* bs, IntTy mask) : m_bs(bs), m_mask(mask) {}
- operator bool() const {
- return (m_bs->m_val & m_mask) != 0;
- }
- bool operator=(bool set) {
- m_bs->m_val = (m_bs->m_val & ~m_mask) | (set ? m_mask : 0);
- return set;
- }
-
- private:
- BitSet* m_bs;
- IntTy m_mask;
- };
-
- // A STL-like iterator is required to be able to use range-based for loops.
- class Iterator {
- public:
- Iterator(const Iterator& other) : m_val(other.m_val), m_bit(other.m_bit) {}
- Iterator(IntTy val) : m_val(val), m_bit(0) {}
- Iterator& operator=(Iterator other) {
- new (this) Iterator(other);
- return *this;
- }
- int operator*() {
- return m_bit + ComputeLsb();
- }
- Iterator& operator++() {
- int lsb = ComputeLsb();
- m_val >>= lsb + 1;
- m_bit += lsb + 1;
- m_has_lsb = false;
- return *this;
- }
- Iterator operator++(int _) {
- Iterator other(*this);
- ++*this;
- return other;
- }
- bool operator==(Iterator other) const {
- return m_val == other.m_val;
- }
- bool operator!=(Iterator other) const {
- return m_val != other.m_val;
- }
-
- private:
- int ComputeLsb() {
- if (!m_has_lsb) {
- m_lsb = LeastSignificantSetBit(m_val);
- m_has_lsb = true;
- }
- return m_lsb;
- }
- IntTy m_val;
- int m_bit;
- int m_lsb = -1;
- bool m_has_lsb = false;
- };
-
- BitSet() : m_val(0) {}
- explicit BitSet(IntTy val) : m_val(val) {}
- BitSet(std::initializer_list<int> init) {
- m_val = 0;
- for (int bit : init)
- m_val |= (IntTy)1 << bit;
- }
-
- static BitSet AllTrue(std::size_t count) {
- return BitSet(count == sizeof(IntTy) * 8 ? ~(IntTy)0 : (((IntTy)1 << count) - 1));
- }
-
- Ref operator[](std::size_t bit) {
- return Ref(this, (IntTy)1 << bit);
- }
- const Ref operator[](std::size_t bit) const {
- return (*const_cast<BitSet*>(this))[bit];
- }
- bool operator==(BitSet other) const {
- return m_val == other.m_val;
- }
- bool operator!=(BitSet other) const {
- return m_val != other.m_val;
- }
- bool operator<(BitSet other) const {
- return m_val < other.m_val;
- }
- bool operator>(BitSet other) const {
- return m_val > other.m_val;
- }
- BitSet operator|(BitSet other) const {
- return BitSet(m_val | other.m_val);
- }
- BitSet operator&(BitSet other) const {
- return BitSet(m_val & other.m_val);
- }
- BitSet operator^(BitSet other) const {
- return BitSet(m_val ^ other.m_val);
- }
- BitSet operator~() const {
- return BitSet(~m_val);
- }
- BitSet& operator|=(BitSet other) {
- return *this = *this | other;
- }
- BitSet& operator&=(BitSet other) {
- return *this = *this & other;
- }
- BitSet& operator^=(BitSet other) {
- return *this = *this ^ other;
- }
- operator u32() = delete;
- operator bool() {
- return m_val != 0;
- }
-
- // Warning: Even though on modern CPUs this is a single fast instruction,
- // Dolphin's official builds do not currently assume POPCNT support on x86,
- // so slower explicit bit twiddling is generated. Still should generally
- // be faster than a loop.
- unsigned int Count() const {
- return CountSetBits(m_val);
- }
-
- Iterator begin() const {
- return Iterator(m_val);
- }
- Iterator end() const {
- return Iterator(0);
- }
-
- IntTy m_val;
-};
-
-} // namespace Common
-
-typedef Common::BitSet<u8> BitSet8;
-typedef Common::BitSet<u16> BitSet16;
-typedef Common::BitSet<u32> BitSet32;
-typedef Common::BitSet<u64> BitSet64;
diff --git a/src/common/logging/backend.cpp b/src/common/logging/backend.cpp
index 6d5218465..5753b871a 100644
--- a/src/common/logging/backend.cpp
+++ b/src/common/logging/backend.cpp
@@ -12,7 +12,8 @@
#include <thread>
#include <vector>
#ifdef _WIN32
-#include <share.h> // For _SH_DENYWR
+#include <share.h> // For _SH_DENYWR
+#include <windows.h> // For OutputDebugStringA
#else
#define _SH_DENYWR 0
#endif
@@ -139,12 +140,18 @@ void FileBackend::Write(const Entry& entry) {
if (!file.IsOpen() || bytes_written > MAX_BYTES_WRITTEN) {
return;
}
- bytes_written += file.WriteString(FormatLogMessage(entry) + '\n');
+ bytes_written += file.WriteString(FormatLogMessage(entry).append(1, '\n'));
if (entry.log_level >= Level::Error) {
file.Flush();
}
}
+void DebuggerBackend::Write(const Entry& entry) {
+#ifdef _WIN32
+ ::OutputDebugStringA(FormatLogMessage(entry).append(1, '\n').c_str());
+#endif
+}
+
/// Macro listing all log classes. Code should define CLS and SUB as desired before invoking this.
#define ALL_LOG_CLASSES() \
CLS(Log) \
diff --git a/src/common/logging/backend.h b/src/common/logging/backend.h
index 11edbf1b6..91bb0c309 100644
--- a/src/common/logging/backend.h
+++ b/src/common/logging/backend.h
@@ -103,6 +103,20 @@ private:
std::size_t bytes_written;
};
+/**
+ * Backend that writes to Visual Studio's output window
+ */
+class DebuggerBackend : public Backend {
+public:
+ static const char* Name() {
+ return "debugger";
+ }
+ const char* GetName() const override {
+ return Name();
+ }
+ void Write(const Entry& entry) override;
+};
+
void AddBackend(std::unique_ptr<Backend> backend);
void RemoveBackend(std::string_view backend_name);
diff --git a/src/common/math_util.h b/src/common/math_util.h
index 343cdd902..94b4394c5 100644
--- a/src/common/math_util.h
+++ b/src/common/math_util.h
@@ -4,18 +4,12 @@
#pragma once
-#include <algorithm>
#include <cstdlib>
#include <type_traits>
namespace MathUtil {
-static constexpr float PI = 3.14159265f;
-
-inline bool IntervalsIntersect(unsigned start0, unsigned length0, unsigned start1,
- unsigned length1) {
- return (std::max(start0, start1) < std::min(start0 + length0, start1 + length1));
-}
+constexpr float PI = 3.14159265f;
template <class T>
struct Rectangle {
@@ -24,16 +18,16 @@ struct Rectangle {
T right{};
T bottom{};
- Rectangle() = default;
+ constexpr Rectangle() = default;
- Rectangle(T left, T top, T right, T bottom)
+ constexpr Rectangle(T left, T top, T right, T bottom)
: left(left), top(top), right(right), bottom(bottom) {}
T GetWidth() const {
- return std::abs(static_cast<typename std::make_signed<T>::type>(right - left));
+ return std::abs(static_cast<std::make_signed_t<T>>(right - left));
}
T GetHeight() const {
- return std::abs(static_cast<typename std::make_signed<T>::type>(bottom - top));
+ return std::abs(static_cast<std::make_signed_t<T>>(bottom - top));
}
Rectangle<T> TranslateX(const T x) const {
return Rectangle{left + x, top, right + x, bottom};
diff --git a/src/common/string_util.cpp b/src/common/string_util.cpp
index 731d1db34..959f278aa 100644
--- a/src/common/string_util.cpp
+++ b/src/common/string_util.cpp
@@ -4,11 +4,10 @@
#include <algorithm>
#include <cctype>
-#include <cerrno>
#include <codecvt>
-#include <cstdio>
#include <cstdlib>
-#include <cstring>
+#include <locale>
+#include <sstream>
#include "common/common_paths.h"
#include "common/logging/log.h"
#include "common/string_util.h"
@@ -33,24 +32,6 @@ std::string ToUpper(std::string str) {
return str;
}
-// For Debugging. Read out an u8 array.
-std::string ArrayToString(const u8* data, std::size_t size, int line_len, bool spaces) {
- std::ostringstream oss;
- oss << std::setfill('0') << std::hex;
-
- for (int line = 0; size; ++data, --size) {
- oss << std::setw(2) << (int)*data;
-
- if (line_len == ++line) {
- oss << '\n';
- line = 0;
- } else if (spaces)
- oss << ' ';
- }
-
- return oss.str();
-}
-
std::string StringFromBuffer(const std::vector<u8>& data) {
return std::string(data.begin(), std::find(data.begin(), data.end(), '\0'));
}
@@ -75,40 +56,6 @@ std::string StripQuotes(const std::string& s) {
return s;
}
-bool TryParse(const std::string& str, u32* const output) {
- char* endptr = nullptr;
-
- // Reset errno to a value other than ERANGE
- errno = 0;
-
- unsigned long value = strtoul(str.c_str(), &endptr, 0);
-
- if (!endptr || *endptr)
- return false;
-
- if (errno == ERANGE)
- return false;
-
-#if ULONG_MAX > UINT_MAX
- if (value >= 0x100000000ull && value <= 0xFFFFFFFF00000000ull)
- return false;
-#endif
-
- *output = static_cast<u32>(value);
- return true;
-}
-
-bool TryParse(const std::string& str, bool* const output) {
- if ("1" == str || "true" == ToLower(str))
- *output = true;
- else if ("0" == str || "false" == ToLower(str))
- *output = false;
- else
- return false;
-
- return true;
-}
-
std::string StringFromBool(bool value) {
return value ? "True" : "False";
}
@@ -267,6 +214,15 @@ std::string StringFromFixedZeroTerminatedBuffer(const char* buffer, std::size_t
return std::string(buffer, len);
}
+std::u16string UTF16StringFromFixedZeroTerminatedBuffer(std::u16string_view buffer,
+ std::size_t max_len) {
+ std::size_t len = 0;
+ while (len < max_len && buffer[len] != '\0')
+ ++len;
+
+ return std::u16string(buffer.begin(), buffer.begin() + len);
+}
+
const char* TrimSourcePath(const char* path, const char* root) {
const char* p = path;
diff --git a/src/common/string_util.h b/src/common/string_util.h
index 32bf6a19c..583fd05e6 100644
--- a/src/common/string_util.h
+++ b/src/common/string_util.h
@@ -5,8 +5,6 @@
#pragma once
#include <cstddef>
-#include <iomanip>
-#include <sstream>
#include <string>
#include <vector>
#include "common/common_types.h"
@@ -19,44 +17,13 @@ std::string ToLower(std::string str);
/// Make a string uppercase
std::string ToUpper(std::string str);
-std::string ArrayToString(const u8* data, std::size_t size, int line_len = 20, bool spaces = true);
-
std::string StringFromBuffer(const std::vector<u8>& data);
std::string StripSpaces(const std::string& s);
std::string StripQuotes(const std::string& s);
-// Thousand separator. Turns 12345678 into 12,345,678
-template <typename I>
-std::string ThousandSeparate(I value, int spaces = 0) {
- std::ostringstream oss;
-
-// std::locale("") seems to be broken on many platforms
-#if defined _WIN32 || (defined __linux__ && !defined __clang__)
- oss.imbue(std::locale(""));
-#endif
- oss << std::setw(spaces) << value;
-
- return oss.str();
-}
-
std::string StringFromBool(bool value);
-bool TryParse(const std::string& str, bool* output);
-bool TryParse(const std::string& str, u32* output);
-
-template <typename N>
-static bool TryParse(const std::string& str, N* const output) {
- std::istringstream iss(str);
-
- N tmp = 0;
- if (iss >> tmp) {
- *output = tmp;
- return true;
- } else
- return false;
-}
-
std::string TabsToSpaces(int tab_size, std::string in);
void SplitString(const std::string& str, char delim, std::vector<std::string>& output);
@@ -100,6 +67,14 @@ bool ComparePartialString(InIt begin, InIt end, const char* other) {
std::string StringFromFixedZeroTerminatedBuffer(const char* buffer, std::size_t max_len);
/**
+ * Creates a UTF-16 std::u16string from a fixed-size NUL-terminated char buffer. If the buffer isn't
+ * null-terminated, then the string ends at the greatest multiple of two less then or equal to
+ * max_len_bytes.
+ */
+std::u16string UTF16StringFromFixedZeroTerminatedBuffer(std::u16string_view buffer,
+ std::size_t max_len);
+
+/**
* Attempts to trim an arbitrary prefix from `path`, leaving only the part starting at `root`. It's
* intended to be used to strip a system-specific build directory from the `__FILE__` macro,
* leaving only the path relative to the sources root.
diff --git a/src/common/thread.cpp b/src/common/thread.cpp
index 9e207118f..5144c0d9f 100644
--- a/src/common/thread.cpp
+++ b/src/common/thread.cpp
@@ -25,23 +25,6 @@
namespace Common {
-int CurrentThreadId() {
-#ifdef _MSC_VER
- return GetCurrentThreadId();
-#elif defined __APPLE__
- return mach_thread_self();
-#else
- return 0;
-#endif
-}
-
-#ifdef _WIN32
-// Supporting functions
-void SleepCurrentThread(int ms) {
- Sleep(ms);
-}
-#endif
-
#ifdef _MSC_VER
void SetThreadAffinity(std::thread::native_handle_type thread, u32 mask) {
@@ -62,7 +45,7 @@ void SwitchCurrentThread() {
// This is implemented much nicer in upcoming msvc++, see:
// http://msdn.microsoft.com/en-us/library/xcb2z8hs(VS.100).aspx
-void SetCurrentThreadName(const char* szThreadName) {
+void SetCurrentThreadName(const char* name) {
static const DWORD MS_VC_EXCEPTION = 0x406D1388;
#pragma pack(push, 8)
@@ -75,7 +58,7 @@ void SetCurrentThreadName(const char* szThreadName) {
#pragma pack(pop)
info.dwType = 0x1000;
- info.szName = szThreadName;
+ info.szName = name;
info.dwThreadID = -1; // dwThreadID;
info.dwFlags = 0;
@@ -107,10 +90,6 @@ void SetCurrentThreadAffinity(u32 mask) {
}
#ifndef _WIN32
-void SleepCurrentThread(int ms) {
- usleep(1000 * ms);
-}
-
void SwitchCurrentThread() {
usleep(1000 * 1);
}
@@ -118,15 +97,15 @@ void SwitchCurrentThread() {
// MinGW with the POSIX threading model does not support pthread_setname_np
#if !defined(_WIN32) || defined(_MSC_VER)
-void SetCurrentThreadName(const char* szThreadName) {
+void SetCurrentThreadName(const char* name) {
#ifdef __APPLE__
- pthread_setname_np(szThreadName);
+ pthread_setname_np(name);
#elif defined(__Bitrig__) || defined(__DragonFly__) || defined(__FreeBSD__) || defined(__OpenBSD__)
- pthread_set_name_np(pthread_self(), szThreadName);
+ pthread_set_name_np(pthread_self(), name);
#elif defined(__NetBSD__)
- pthread_setname_np(pthread_self(), "%s", (void*)szThreadName);
+ pthread_setname_np(pthread_self(), "%s", (void*)name);
#else
- pthread_setname_np(pthread_self(), szThreadName);
+ pthread_setname_np(pthread_self(), name);
#endif
}
#endif
diff --git a/src/common/thread.h b/src/common/thread.h
index 6cbdb96a3..2cf74452d 100644
--- a/src/common/thread.h
+++ b/src/common/thread.h
@@ -13,15 +13,8 @@
namespace Common {
-int CurrentThreadId();
-
-void SetThreadAffinity(std::thread::native_handle_type thread, u32 mask);
-void SetCurrentThreadAffinity(u32 mask);
-
class Event {
public:
- Event() : is_set(false) {}
-
void Set() {
std::lock_guard<std::mutex> lk(mutex);
if (!is_set) {
@@ -53,14 +46,14 @@ public:
}
private:
- bool is_set;
+ bool is_set = false;
std::condition_variable condvar;
std::mutex mutex;
};
class Barrier {
public:
- explicit Barrier(std::size_t count_) : count(count_), waiting(0), generation(0) {}
+ explicit Barrier(std::size_t count_) : count(count_) {}
/// Blocks until all "count" threads have called Sync()
void Sync() {
@@ -80,12 +73,13 @@ public:
private:
std::condition_variable condvar;
std::mutex mutex;
- const std::size_t count;
- std::size_t waiting;
- std::size_t generation; // Incremented once each time the barrier is used
+ std::size_t count;
+ std::size_t waiting = 0;
+ std::size_t generation = 0; // Incremented once each time the barrier is used
};
-void SleepCurrentThread(int ms);
+void SetThreadAffinity(std::thread::native_handle_type thread, u32 mask);
+void SetCurrentThreadAffinity(u32 mask);
void SwitchCurrentThread(); // On Linux, this is equal to sleep 1ms
void SetCurrentThreadName(const char* name);
diff --git a/src/common/x64/xbyak_abi.h b/src/common/x64/xbyak_abi.h
deleted file mode 100644
index 636a5c0f9..000000000
--- a/src/common/x64/xbyak_abi.h
+++ /dev/null
@@ -1,222 +0,0 @@
-// Copyright 2016 Citra Emulator Project
-// Licensed under GPLv2 or any later version
-// Refer to the license.txt file included.
-
-#pragma once
-
-#include <initializer_list>
-#include <xbyak.h>
-#include "common/assert.h"
-#include "common/bit_set.h"
-
-namespace Common::X64 {
-
-inline int RegToIndex(const Xbyak::Reg& reg) {
- using Kind = Xbyak::Reg::Kind;
- ASSERT_MSG((reg.getKind() & (Kind::REG | Kind::XMM)) != 0,
- "RegSet only support GPRs and XMM registers.");
- ASSERT_MSG(reg.getIdx() < 16, "RegSet only supports XXM0-15.");
- return reg.getIdx() + (reg.getKind() == Kind::REG ? 0 : 16);
-}
-
-inline Xbyak::Reg64 IndexToReg64(int reg_index) {
- ASSERT(reg_index < 16);
- return Xbyak::Reg64(reg_index);
-}
-
-inline Xbyak::Xmm IndexToXmm(int reg_index) {
- ASSERT(reg_index >= 16 && reg_index < 32);
- return Xbyak::Xmm(reg_index - 16);
-}
-
-inline Xbyak::Reg IndexToReg(int reg_index) {
- if (reg_index < 16) {
- return IndexToReg64(reg_index);
- } else {
- return IndexToXmm(reg_index);
- }
-}
-
-inline BitSet32 BuildRegSet(std::initializer_list<Xbyak::Reg> regs) {
- BitSet32 bits;
- for (const Xbyak::Reg& reg : regs) {
- bits[RegToIndex(reg)] = true;
- }
- return bits;
-}
-
-const BitSet32 ABI_ALL_GPRS(0x0000FFFF);
-const BitSet32 ABI_ALL_XMMS(0xFFFF0000);
-
-#ifdef _WIN32
-
-// Microsoft x64 ABI
-const Xbyak::Reg ABI_RETURN = Xbyak::util::rax;
-const Xbyak::Reg ABI_PARAM1 = Xbyak::util::rcx;
-const Xbyak::Reg ABI_PARAM2 = Xbyak::util::rdx;
-const Xbyak::Reg ABI_PARAM3 = Xbyak::util::r8;
-const Xbyak::Reg ABI_PARAM4 = Xbyak::util::r9;
-
-const BitSet32 ABI_ALL_CALLER_SAVED = BuildRegSet({
- // GPRs
- Xbyak::util::rcx,
- Xbyak::util::rdx,
- Xbyak::util::r8,
- Xbyak::util::r9,
- Xbyak::util::r10,
- Xbyak::util::r11,
- // XMMs
- Xbyak::util::xmm0,
- Xbyak::util::xmm1,
- Xbyak::util::xmm2,
- Xbyak::util::xmm3,
- Xbyak::util::xmm4,
- Xbyak::util::xmm5,
-});
-
-const BitSet32 ABI_ALL_CALLEE_SAVED = BuildRegSet({
- // GPRs
- Xbyak::util::rbx,
- Xbyak::util::rsi,
- Xbyak::util::rdi,
- Xbyak::util::rbp,
- Xbyak::util::r12,
- Xbyak::util::r13,
- Xbyak::util::r14,
- Xbyak::util::r15,
- // XMMs
- Xbyak::util::xmm6,
- Xbyak::util::xmm7,
- Xbyak::util::xmm8,
- Xbyak::util::xmm9,
- Xbyak::util::xmm10,
- Xbyak::util::xmm11,
- Xbyak::util::xmm12,
- Xbyak::util::xmm13,
- Xbyak::util::xmm14,
- Xbyak::util::xmm15,
-});
-
-constexpr std::size_t ABI_SHADOW_SPACE = 0x20;
-
-#else
-
-// System V x86-64 ABI
-const Xbyak::Reg ABI_RETURN = Xbyak::util::rax;
-const Xbyak::Reg ABI_PARAM1 = Xbyak::util::rdi;
-const Xbyak::Reg ABI_PARAM2 = Xbyak::util::rsi;
-const Xbyak::Reg ABI_PARAM3 = Xbyak::util::rdx;
-const Xbyak::Reg ABI_PARAM4 = Xbyak::util::rcx;
-
-const BitSet32 ABI_ALL_CALLER_SAVED = BuildRegSet({
- // GPRs
- Xbyak::util::rcx,
- Xbyak::util::rdx,
- Xbyak::util::rdi,
- Xbyak::util::rsi,
- Xbyak::util::r8,
- Xbyak::util::r9,
- Xbyak::util::r10,
- Xbyak::util::r11,
- // XMMs
- Xbyak::util::xmm0,
- Xbyak::util::xmm1,
- Xbyak::util::xmm2,
- Xbyak::util::xmm3,
- Xbyak::util::xmm4,
- Xbyak::util::xmm5,
- Xbyak::util::xmm6,
- Xbyak::util::xmm7,
- Xbyak::util::xmm8,
- Xbyak::util::xmm9,
- Xbyak::util::xmm10,
- Xbyak::util::xmm11,
- Xbyak::util::xmm12,
- Xbyak::util::xmm13,
- Xbyak::util::xmm14,
- Xbyak::util::xmm15,
-});
-
-const BitSet32 ABI_ALL_CALLEE_SAVED = BuildRegSet({
- // GPRs
- Xbyak::util::rbx,
- Xbyak::util::rbp,
- Xbyak::util::r12,
- Xbyak::util::r13,
- Xbyak::util::r14,
- Xbyak::util::r15,
-});
-
-constexpr std::size_t ABI_SHADOW_SPACE = 0;
-
-#endif
-
-inline void ABI_CalculateFrameSize(BitSet32 regs, std::size_t rsp_alignment,
- std::size_t needed_frame_size, s32* out_subtraction,
- s32* out_xmm_offset) {
- int count = (regs & ABI_ALL_GPRS).Count();
- rsp_alignment -= count * 8;
- std::size_t subtraction = 0;
- int xmm_count = (regs & ABI_ALL_XMMS).Count();
- if (xmm_count) {
- // If we have any XMMs to save, we must align the stack here.
- subtraction = rsp_alignment & 0xF;
- }
- subtraction += 0x10 * xmm_count;
- std::size_t xmm_base_subtraction = subtraction;
- subtraction += needed_frame_size;
- subtraction += ABI_SHADOW_SPACE;
- // Final alignment.
- rsp_alignment -= subtraction;
- subtraction += rsp_alignment & 0xF;
-
- *out_subtraction = (s32)subtraction;
- *out_xmm_offset = (s32)(subtraction - xmm_base_subtraction);
-}
-
-inline std::size_t ABI_PushRegistersAndAdjustStack(Xbyak::CodeGenerator& code, BitSet32 regs,
- std::size_t rsp_alignment,
- std::size_t needed_frame_size = 0) {
- s32 subtraction, xmm_offset;
- ABI_CalculateFrameSize(regs, rsp_alignment, needed_frame_size, &subtraction, &xmm_offset);
-
- for (int reg_index : (regs & ABI_ALL_GPRS)) {
- code.push(IndexToReg64(reg_index));
- }
-
- if (subtraction != 0) {
- code.sub(code.rsp, subtraction);
- }
-
- for (int reg_index : (regs & ABI_ALL_XMMS)) {
- code.movaps(code.xword[code.rsp + xmm_offset], IndexToXmm(reg_index));
- xmm_offset += 0x10;
- }
-
- return ABI_SHADOW_SPACE;
-}
-
-inline void ABI_PopRegistersAndAdjustStack(Xbyak::CodeGenerator& code, BitSet32 regs,
- std::size_t rsp_alignment,
- std::size_t needed_frame_size = 0) {
- s32 subtraction, xmm_offset;
- ABI_CalculateFrameSize(regs, rsp_alignment, needed_frame_size, &subtraction, &xmm_offset);
-
- for (int reg_index : (regs & ABI_ALL_XMMS)) {
- code.movaps(IndexToXmm(reg_index), code.xword[code.rsp + xmm_offset]);
- xmm_offset += 0x10;
- }
-
- if (subtraction != 0) {
- code.add(code.rsp, subtraction);
- }
-
- // GPRs need to be popped in reverse order
- for (int reg_index = 15; reg_index >= 0; reg_index--) {
- if (regs[reg_index]) {
- code.pop(IndexToReg64(reg_index));
- }
- }
-}
-
-} // namespace Common::X64
diff --git a/src/common/x64/xbyak_util.h b/src/common/x64/xbyak_util.h
deleted file mode 100644
index 5cc8a8c76..000000000
--- a/src/common/x64/xbyak_util.h
+++ /dev/null
@@ -1,47 +0,0 @@
-// Copyright 2016 Citra Emulator Project
-// Licensed under GPLv2 or any later version
-// Refer to the license.txt file included.
-
-#pragma once
-
-#include <type_traits>
-#include <xbyak.h>
-#include "common/x64/xbyak_abi.h"
-
-namespace Common::X64 {
-
-// Constants for use with cmpps/cmpss
-enum {
- CMP_EQ = 0,
- CMP_LT = 1,
- CMP_LE = 2,
- CMP_UNORD = 3,
- CMP_NEQ = 4,
- CMP_NLT = 5,
- CMP_NLE = 6,
- CMP_ORD = 7,
-};
-
-inline bool IsWithin2G(uintptr_t ref, uintptr_t target) {
- u64 distance = target - (ref + 5);
- return !(distance >= 0x8000'0000ULL && distance <= ~0x8000'0000ULL);
-}
-
-inline bool IsWithin2G(const Xbyak::CodeGenerator& code, uintptr_t target) {
- return IsWithin2G(reinterpret_cast<uintptr_t>(code.getCurr()), target);
-}
-
-template <typename T>
-inline void CallFarFunction(Xbyak::CodeGenerator& code, const T f) {
- static_assert(std::is_pointer_v<T>, "Argument must be a (function) pointer.");
- std::size_t addr = reinterpret_cast<std::size_t>(f);
- if (IsWithin2G(code, addr)) {
- code.call(f);
- } else {
- // ABI_RETURN is a safe temp register to use before a call
- code.mov(ABI_RETURN, addr);
- code.call(ABI_RETURN);
- }
-}
-
-} // namespace Common::X64
diff --git a/src/core/CMakeLists.txt b/src/core/CMakeLists.txt
index 64fdf38cd..e1f21a764 100644
--- a/src/core/CMakeLists.txt
+++ b/src/core/CMakeLists.txt
@@ -12,6 +12,8 @@ add_library(core STATIC
core_timing.h
core_timing_util.cpp
core_timing_util.h
+ cpu_core_manager.cpp
+ cpu_core_manager.h
crypto/aes_util.cpp
crypto/aes_util.h
crypto/encryption_layer.cpp
@@ -77,6 +79,8 @@ add_library(core STATIC
file_sys/vfs_vector.h
file_sys/xts_archive.cpp
file_sys/xts_archive.h
+ frontend/applets/software_keyboard.cpp
+ frontend/applets/software_keyboard.h
frontend/emu_window.cpp
frontend/emu_window.h
frontend/framebuffer_layout.cpp
@@ -150,6 +154,12 @@ add_library(core STATIC
hle/service/am/applet_ae.h
hle/service/am/applet_oe.cpp
hle/service/am/applet_oe.h
+ hle/service/am/applets/applets.cpp
+ hle/service/am/applets/applets.h
+ hle/service/am/applets/software_keyboard.cpp
+ hle/service/am/applets/software_keyboard.h
+ hle/service/am/applets/stub_applet.cpp
+ hle/service/am/applets/stub_applet.h
hle/service/am/idle.cpp
hle/service/am/idle.h
hle/service/am/omm.cpp
diff --git a/src/core/core.cpp b/src/core/core.cpp
index 6d5b5a2d0..795fabc65 100644
--- a/src/core/core.cpp
+++ b/src/core/core.cpp
@@ -14,6 +14,7 @@
#include "core/core.h"
#include "core/core_cpu.h"
#include "core/core_timing.h"
+#include "core/cpu_core_manager.h"
#include "core/file_sys/mode.h"
#include "core/file_sys/vfs_concat.h"
#include "core/file_sys/vfs_real.h"
@@ -23,12 +24,13 @@
#include "core/hle/kernel/process.h"
#include "core/hle/kernel/scheduler.h"
#include "core/hle/kernel/thread.h"
+#include "core/hle/service/am/applets/software_keyboard.h"
#include "core/hle/service/service.h"
#include "core/hle/service/sm/sm.h"
#include "core/loader/loader.h"
#include "core/perf_stats.h"
-#include "core/settings.h"
#include "core/telemetry_session.h"
+#include "frontend/applets/software_keyboard.h"
#include "video_core/debug_utils/debug_utils.h"
#include "video_core/gpu.h"
#include "video_core/renderer_base.h"
@@ -69,64 +71,22 @@ FileSys::VirtualFile GetGameFileFromPath(const FileSys::VirtualFilesystem& vfs,
return vfs->OpenFile(path, FileSys::Mode::Read);
}
-
-/// Runs a CPU core while the system is powered on
-void RunCpuCore(Cpu& cpu_state) {
- while (Core::System::GetInstance().IsPoweredOn()) {
- cpu_state.RunLoop(true);
- }
-}
} // Anonymous namespace
struct System::Impl {
Cpu& CurrentCpuCore() {
- if (Settings::values.use_multi_core) {
- const auto& search = thread_to_cpu.find(std::this_thread::get_id());
- ASSERT(search != thread_to_cpu.end());
- ASSERT(search->second);
- return *search->second;
- }
-
- // Otherwise, use single-threaded mode active_core variable
- return *cpu_cores[active_core];
+ return cpu_core_manager.GetCurrentCore();
}
ResultStatus RunLoop(bool tight_loop) {
status = ResultStatus::Success;
- // Update thread_to_cpu in case Core 0 is run from a different host thread
- thread_to_cpu[std::this_thread::get_id()] = cpu_cores[0].get();
-
- if (GDBStub::IsServerEnabled()) {
- GDBStub::HandlePacket();
-
- // If the loop is halted and we want to step, use a tiny (1) number of instructions to
- // execute. Otherwise, get out of the loop function.
- if (GDBStub::GetCpuHaltFlag()) {
- if (GDBStub::GetCpuStepFlag()) {
- tight_loop = false;
- } else {
- return ResultStatus::Success;
- }
- }
- }
-
- for (active_core = 0; active_core < NUM_CPU_CORES; ++active_core) {
- cpu_cores[active_core]->RunLoop(tight_loop);
- if (Settings::values.use_multi_core) {
- // Cores 1-3 are run on other threads in this mode
- break;
- }
- }
-
- if (GDBStub::IsServerEnabled()) {
- GDBStub::SetCpuStepFlag(false);
- }
+ cpu_core_manager.RunLoop(tight_loop);
return status;
}
- ResultStatus Init(Frontend::EmuWindow& emu_window) {
+ ResultStatus Init(System& system, Frontend::EmuWindow& emu_window) {
LOG_DEBUG(HW_Memory, "initialized OK");
CoreTiming::Init();
@@ -136,15 +96,13 @@ struct System::Impl {
if (virtual_filesystem == nullptr)
virtual_filesystem = std::make_shared<FileSys::RealVfsFilesystem>();
+ /// Create default implementations of applets if one is not provided.
+ if (software_keyboard == nullptr)
+ software_keyboard = std::make_unique<Core::Frontend::DefaultSoftwareKeyboardApplet>();
+
auto main_process = Kernel::Process::Create(kernel, "main");
kernel.MakeCurrentProcess(main_process.get());
- cpu_barrier = std::make_unique<CpuBarrier>();
- cpu_exclusive_monitor = Cpu::MakeExclusiveMonitor(cpu_cores.size());
- for (std::size_t index = 0; index < cpu_cores.size(); ++index) {
- cpu_cores[index] = std::make_unique<Cpu>(*cpu_exclusive_monitor, *cpu_barrier, index);
- }
-
telemetry_session = std::make_unique<Core::TelemetrySession>();
service_manager = std::make_shared<Service::SM::ServiceManager>();
@@ -158,17 +116,8 @@ struct System::Impl {
gpu_core = std::make_unique<Tegra::GPU>(renderer->Rasterizer());
- // Create threads for CPU cores 1-3, and build thread_to_cpu map
- // CPU core 0 is run on the main thread
- thread_to_cpu[std::this_thread::get_id()] = cpu_cores[0].get();
- if (Settings::values.use_multi_core) {
- for (std::size_t index = 0; index < cpu_core_threads.size(); ++index) {
- cpu_core_threads[index] =
- std::make_unique<std::thread>(RunCpuCore, std::ref(*cpu_cores[index + 1]));
- thread_to_cpu[cpu_core_threads[index]->get_id()] = cpu_cores[index + 1].get();
- }
- }
-
+ cpu_core_manager.Initialize(system);
+ is_powered_on = true;
LOG_DEBUG(Core, "Initialized OK");
// Reset counters and set time origin to current frame
@@ -178,7 +127,8 @@ struct System::Impl {
return ResultStatus::Success;
}
- ResultStatus Load(Frontend::EmuWindow& emu_window, const std::string& filepath) {
+ ResultStatus Load(System& system, Frontend::EmuWindow& emu_window,
+ const std::string& filepath) {
app_loader = Loader::GetLoader(GetGameFileFromPath(virtual_filesystem, filepath));
if (!app_loader) {
@@ -195,7 +145,7 @@ struct System::Impl {
return ResultStatus::ErrorSystemMode;
}
- ResultStatus init_result{Init(emu_window)};
+ ResultStatus init_result{Init(system, emu_window)};
if (init_result != ResultStatus::Success) {
LOG_CRITICAL(Core, "Failed to initialize system (Error {})!",
static_cast<int>(init_result));
@@ -225,6 +175,8 @@ struct System::Impl {
Telemetry().AddField(Telemetry::FieldType::Performance, "Shutdown_Frametime",
perf_results.frametime * 1000.0);
+ is_powered_on = false;
+
// Shutdown emulation session
renderer.reset();
GDBStub::Shutdown();
@@ -234,19 +186,7 @@ struct System::Impl {
gpu_core.reset();
// Close all CPU/threading state
- cpu_barrier->NotifyEnd();
- if (Settings::values.use_multi_core) {
- for (auto& thread : cpu_core_threads) {
- thread->join();
- thread.reset();
- }
- }
- thread_to_cpu.clear();
- for (auto& cpu_core : cpu_cores) {
- cpu_core.reset();
- }
- cpu_exclusive_monitor.reset();
- cpu_barrier.reset();
+ cpu_core_manager.Shutdown();
// Shutdown kernel and core timing
kernel.Shutdown();
@@ -283,11 +223,11 @@ struct System::Impl {
std::unique_ptr<VideoCore::RendererBase> renderer;
std::unique_ptr<Tegra::GPU> gpu_core;
std::shared_ptr<Tegra::DebugContext> debug_context;
- std::unique_ptr<ExclusiveMonitor> cpu_exclusive_monitor;
- std::unique_ptr<CpuBarrier> cpu_barrier;
- std::array<std::unique_ptr<Cpu>, NUM_CPU_CORES> cpu_cores;
- std::array<std::unique_ptr<std::thread>, NUM_CPU_CORES - 1> cpu_core_threads;
- std::size_t active_core{}; ///< Active core, only used in single thread mode
+ CpuCoreManager cpu_core_manager;
+ bool is_powered_on = false;
+
+ /// Frontend applets
+ std::unique_ptr<Core::Frontend::SoftwareKeyboardApplet> software_keyboard;
/// Service manager
std::shared_ptr<Service::SM::ServiceManager> service_manager;
@@ -298,9 +238,6 @@ struct System::Impl {
ResultStatus status = ResultStatus::Success;
std::string status_details = "";
- /// Map of guest threads to CPU cores
- std::map<std::thread::id, Cpu*> thread_to_cpu;
-
Core::PerfStats perf_stats;
Core::FrameLimiter frame_limiter;
};
@@ -325,17 +262,15 @@ System::ResultStatus System::SingleStep() {
}
void System::InvalidateCpuInstructionCaches() {
- for (auto& cpu : impl->cpu_cores) {
- cpu->ArmInterface().ClearInstructionCache();
- }
+ impl->cpu_core_manager.InvalidateAllInstructionCaches();
}
System::ResultStatus System::Load(Frontend::EmuWindow& emu_window, const std::string& filepath) {
- return impl->Load(emu_window, filepath);
+ return impl->Load(*this, emu_window, filepath);
}
bool System::IsPoweredOn() const {
- return impl->cpu_barrier && impl->cpu_barrier->IsAlive();
+ return impl->is_powered_on;
}
void System::PrepareReschedule() {
@@ -399,21 +334,20 @@ const ARM_Interface& System::ArmInterface(std::size_t core_index) const {
}
Cpu& System::CpuCore(std::size_t core_index) {
- ASSERT(core_index < NUM_CPU_CORES);
- return *impl->cpu_cores[core_index];
+ return impl->cpu_core_manager.GetCore(core_index);
}
const Cpu& System::CpuCore(std::size_t core_index) const {
ASSERT(core_index < NUM_CPU_CORES);
- return *impl->cpu_cores[core_index];
+ return impl->cpu_core_manager.GetCore(core_index);
}
ExclusiveMonitor& System::Monitor() {
- return *impl->cpu_exclusive_monitor;
+ return impl->cpu_core_manager.GetExclusiveMonitor();
}
const ExclusiveMonitor& System::Monitor() const {
- return *impl->cpu_exclusive_monitor;
+ return impl->cpu_core_manager.GetExclusiveMonitor();
}
Tegra::GPU& System::GPU() {
@@ -488,8 +422,16 @@ std::shared_ptr<FileSys::VfsFilesystem> System::GetFilesystem() const {
return impl->virtual_filesystem;
}
+void System::SetSoftwareKeyboard(std::unique_ptr<Core::Frontend::SoftwareKeyboardApplet> applet) {
+ impl->software_keyboard = std::move(applet);
+}
+
+const Core::Frontend::SoftwareKeyboardApplet& System::GetSoftwareKeyboard() const {
+ return *impl->software_keyboard;
+}
+
System::ResultStatus System::Init(Frontend::EmuWindow& emu_window) {
- return impl->Init(emu_window);
+ return impl->Init(*this, emu_window);
}
void System::Shutdown() {
diff --git a/src/core/core.h b/src/core/core.h
index cfacceb81..be71bd437 100644
--- a/src/core/core.h
+++ b/src/core/core.h
@@ -13,6 +13,7 @@
namespace Core::Frontend {
class EmuWindow;
+class SoftwareKeyboardApplet;
} // namespace Core::Frontend
namespace FileSys {
@@ -236,6 +237,10 @@ public:
std::shared_ptr<FileSys::VfsFilesystem> GetFilesystem() const;
+ void SetSoftwareKeyboard(std::unique_ptr<Core::Frontend::SoftwareKeyboardApplet> applet);
+
+ const Core::Frontend::SoftwareKeyboardApplet& GetSoftwareKeyboard() const;
+
private:
System();
diff --git a/src/core/cpu_core_manager.cpp b/src/core/cpu_core_manager.cpp
new file mode 100644
index 000000000..769a6fefa
--- /dev/null
+++ b/src/core/cpu_core_manager.cpp
@@ -0,0 +1,142 @@
+// Copyright 2018 yuzu emulator team
+// Licensed under GPLv2 or any later version
+// Refer to the license.txt file included.
+
+#include "common/assert.h"
+#include "core/arm/exclusive_monitor.h"
+#include "core/core.h"
+#include "core/core_cpu.h"
+#include "core/cpu_core_manager.h"
+#include "core/gdbstub/gdbstub.h"
+#include "core/settings.h"
+
+namespace Core {
+namespace {
+void RunCpuCore(const System& system, Cpu& cpu_state) {
+ while (system.IsPoweredOn()) {
+ cpu_state.RunLoop(true);
+ }
+}
+} // Anonymous namespace
+
+CpuCoreManager::CpuCoreManager() = default;
+CpuCoreManager::~CpuCoreManager() = default;
+
+void CpuCoreManager::Initialize(System& system) {
+ barrier = std::make_unique<CpuBarrier>();
+ exclusive_monitor = Cpu::MakeExclusiveMonitor(cores.size());
+
+ for (std::size_t index = 0; index < cores.size(); ++index) {
+ cores[index] = std::make_unique<Cpu>(*exclusive_monitor, *barrier, index);
+ }
+
+ // Create threads for CPU cores 1-3, and build thread_to_cpu map
+ // CPU core 0 is run on the main thread
+ thread_to_cpu[std::this_thread::get_id()] = cores[0].get();
+ if (!Settings::values.use_multi_core) {
+ return;
+ }
+
+ for (std::size_t index = 0; index < core_threads.size(); ++index) {
+ core_threads[index] = std::make_unique<std::thread>(RunCpuCore, std::cref(system),
+ std::ref(*cores[index + 1]));
+ thread_to_cpu[core_threads[index]->get_id()] = cores[index + 1].get();
+ }
+}
+
+void CpuCoreManager::Shutdown() {
+ barrier->NotifyEnd();
+ if (Settings::values.use_multi_core) {
+ for (auto& thread : core_threads) {
+ thread->join();
+ thread.reset();
+ }
+ }
+
+ thread_to_cpu.clear();
+ for (auto& cpu_core : cores) {
+ cpu_core.reset();
+ }
+
+ exclusive_monitor.reset();
+ barrier.reset();
+}
+
+Cpu& CpuCoreManager::GetCore(std::size_t index) {
+ return *cores.at(index);
+}
+
+const Cpu& CpuCoreManager::GetCore(std::size_t index) const {
+ return *cores.at(index);
+}
+
+ExclusiveMonitor& CpuCoreManager::GetExclusiveMonitor() {
+ return *exclusive_monitor;
+}
+
+const ExclusiveMonitor& CpuCoreManager::GetExclusiveMonitor() const {
+ return *exclusive_monitor;
+}
+
+Cpu& CpuCoreManager::GetCurrentCore() {
+ if (Settings::values.use_multi_core) {
+ const auto& search = thread_to_cpu.find(std::this_thread::get_id());
+ ASSERT(search != thread_to_cpu.end());
+ ASSERT(search->second);
+ return *search->second;
+ }
+
+ // Otherwise, use single-threaded mode active_core variable
+ return *cores[active_core];
+}
+
+const Cpu& CpuCoreManager::GetCurrentCore() const {
+ if (Settings::values.use_multi_core) {
+ const auto& search = thread_to_cpu.find(std::this_thread::get_id());
+ ASSERT(search != thread_to_cpu.end());
+ ASSERT(search->second);
+ return *search->second;
+ }
+
+ // Otherwise, use single-threaded mode active_core variable
+ return *cores[active_core];
+}
+
+void CpuCoreManager::RunLoop(bool tight_loop) {
+ // Update thread_to_cpu in case Core 0 is run from a different host thread
+ thread_to_cpu[std::this_thread::get_id()] = cores[0].get();
+
+ if (GDBStub::IsServerEnabled()) {
+ GDBStub::HandlePacket();
+
+ // If the loop is halted and we want to step, use a tiny (1) number of instructions to
+ // execute. Otherwise, get out of the loop function.
+ if (GDBStub::GetCpuHaltFlag()) {
+ if (GDBStub::GetCpuStepFlag()) {
+ tight_loop = false;
+ } else {
+ return;
+ }
+ }
+ }
+
+ for (active_core = 0; active_core < NUM_CPU_CORES; ++active_core) {
+ cores[active_core]->RunLoop(tight_loop);
+ if (Settings::values.use_multi_core) {
+ // Cores 1-3 are run on other threads in this mode
+ break;
+ }
+ }
+
+ if (GDBStub::IsServerEnabled()) {
+ GDBStub::SetCpuStepFlag(false);
+ }
+}
+
+void CpuCoreManager::InvalidateAllInstructionCaches() {
+ for (auto& cpu : cores) {
+ cpu->ArmInterface().ClearInstructionCache();
+ }
+}
+
+} // namespace Core
diff --git a/src/core/cpu_core_manager.h b/src/core/cpu_core_manager.h
new file mode 100644
index 000000000..a4d70ec56
--- /dev/null
+++ b/src/core/cpu_core_manager.h
@@ -0,0 +1,59 @@
+// Copyright 2018 yuzu emulator team
+// Licensed under GPLv2 or any later version
+// Refer to the license.txt file included.
+
+#pragma once
+
+#include <array>
+#include <map>
+#include <memory>
+#include <thread>
+
+namespace Core {
+
+class Cpu;
+class CpuBarrier;
+class ExclusiveMonitor;
+class System;
+
+class CpuCoreManager {
+public:
+ CpuCoreManager();
+ CpuCoreManager(const CpuCoreManager&) = delete;
+ CpuCoreManager(CpuCoreManager&&) = delete;
+
+ ~CpuCoreManager();
+
+ CpuCoreManager& operator=(const CpuCoreManager&) = delete;
+ CpuCoreManager& operator=(CpuCoreManager&&) = delete;
+
+ void Initialize(System& system);
+ void Shutdown();
+
+ Cpu& GetCore(std::size_t index);
+ const Cpu& GetCore(std::size_t index) const;
+
+ Cpu& GetCurrentCore();
+ const Cpu& GetCurrentCore() const;
+
+ ExclusiveMonitor& GetExclusiveMonitor();
+ const ExclusiveMonitor& GetExclusiveMonitor() const;
+
+ void RunLoop(bool tight_loop);
+
+ void InvalidateAllInstructionCaches();
+
+private:
+ static constexpr std::size_t NUM_CPU_CORES = 4;
+
+ std::unique_ptr<ExclusiveMonitor> exclusive_monitor;
+ std::unique_ptr<CpuBarrier> barrier;
+ std::array<std::unique_ptr<Cpu>, NUM_CPU_CORES> cores;
+ std::array<std::unique_ptr<std::thread>, NUM_CPU_CORES - 1> core_threads;
+ std::size_t active_core{}; ///< Active core, only used in single thread mode
+
+ /// Map of guest threads to CPU cores
+ std::map<std::thread::id, Cpu*> thread_to_cpu;
+};
+
+} // namespace Core
diff --git a/src/core/file_sys/bis_factory.cpp b/src/core/file_sys/bis_factory.cpp
index 76a2b7e86..e29f70b3a 100644
--- a/src/core/file_sys/bis_factory.cpp
+++ b/src/core/file_sys/bis_factory.cpp
@@ -8,8 +8,9 @@
namespace FileSys {
-BISFactory::BISFactory(VirtualDir nand_root_, VirtualDir load_root_)
+BISFactory::BISFactory(VirtualDir nand_root_, VirtualDir load_root_, VirtualDir dump_root_)
: nand_root(std::move(nand_root_)), load_root(std::move(load_root_)),
+ dump_root(std::move(dump_root_)),
sysnand_cache(std::make_unique<RegisteredCache>(
GetOrCreateDirectoryRelative(nand_root, "/system/Contents/registered"))),
usrnand_cache(std::make_unique<RegisteredCache>(
@@ -32,4 +33,10 @@ VirtualDir BISFactory::GetModificationLoadRoot(u64 title_id) const {
return GetOrCreateDirectoryRelative(load_root, fmt::format("/{:016X}", title_id));
}
+VirtualDir BISFactory::GetModificationDumpRoot(u64 title_id) const {
+ if (title_id == 0)
+ return nullptr;
+ return GetOrCreateDirectoryRelative(dump_root, fmt::format("/{:016X}", title_id));
+}
+
} // namespace FileSys
diff --git a/src/core/file_sys/bis_factory.h b/src/core/file_sys/bis_factory.h
index 364d309bd..453c11ad2 100644
--- a/src/core/file_sys/bis_factory.h
+++ b/src/core/file_sys/bis_factory.h
@@ -17,17 +17,19 @@ class RegisteredCache;
/// registered caches.
class BISFactory {
public:
- explicit BISFactory(VirtualDir nand_root, VirtualDir load_root);
+ explicit BISFactory(VirtualDir nand_root, VirtualDir load_root, VirtualDir dump_root);
~BISFactory();
RegisteredCache* GetSystemNANDContents() const;
RegisteredCache* GetUserNANDContents() const;
VirtualDir GetModificationLoadRoot(u64 title_id) const;
+ VirtualDir GetModificationDumpRoot(u64 title_id) const;
private:
VirtualDir nand_root;
VirtualDir load_root;
+ VirtualDir dump_root;
std::unique_ptr<RegisteredCache> sysnand_cache;
std::unique_ptr<RegisteredCache> usrnand_cache;
diff --git a/src/core/file_sys/card_image.cpp b/src/core/file_sys/card_image.cpp
index 1ece55731..2c145bd09 100644
--- a/src/core/file_sys/card_image.cpp
+++ b/src/core/file_sys/card_image.cpp
@@ -176,7 +176,7 @@ Loader::ResultStatus XCI::AddNCAFromPartition(XCIPartition part) {
for (const VirtualFile& file : partitions[static_cast<std::size_t>(part)]->GetFiles()) {
if (file->GetExtension() != "nca")
continue;
- auto nca = std::make_shared<NCA>(file);
+ auto nca = std::make_shared<NCA>(file, nullptr, 0, keys);
// TODO(DarkLordZach): Add proper Rev1+ Support
if (nca->IsUpdate())
continue;
diff --git a/src/core/file_sys/card_image.h b/src/core/file_sys/card_image.h
index 8f62571cf..a350496f7 100644
--- a/src/core/file_sys/card_image.h
+++ b/src/core/file_sys/card_image.h
@@ -9,6 +9,7 @@
#include <vector>
#include "common/common_types.h"
#include "common/swap.h"
+#include "core/crypto/key_manager.h"
#include "core/file_sys/vfs.h"
namespace Loader {
@@ -31,7 +32,18 @@ enum class GamecardSize : u8 {
};
struct GamecardInfo {
- std::array<u8, 0x70> data;
+ u64_le firmware_version;
+ u32_le access_control_flags;
+ u32_le read_wait_time1;
+ u32_le read_wait_time2;
+ u32_le write_wait_time1;
+ u32_le write_wait_time2;
+ u32_le firmware_mode;
+ u32_le cup_version;
+ std::array<u8, 4> reserved1;
+ u64_le update_partition_hash;
+ u64_le cup_id;
+ std::array<u8, 0x38> reserved2;
};
static_assert(sizeof(GamecardInfo) == 0x70, "GamecardInfo has incorrect size.");
@@ -107,5 +119,7 @@ private:
std::shared_ptr<NSP> secure_partition;
std::shared_ptr<NCA> program;
std::vector<std::shared_ptr<NCA>> ncas;
+
+ Core::Crypto::KeyManager keys;
};
} // namespace FileSys
diff --git a/src/core/file_sys/content_archive.cpp b/src/core/file_sys/content_archive.cpp
index b46fe893c..19b6f8600 100644
--- a/src/core/file_sys/content_archive.cpp
+++ b/src/core/file_sys/content_archive.cpp
@@ -101,8 +101,9 @@ static bool IsValidNCA(const NCAHeader& header) {
return header.magic == Common::MakeMagic('N', 'C', 'A', '3');
}
-NCA::NCA(VirtualFile file_, VirtualFile bktr_base_romfs_, u64 bktr_base_ivfc_offset)
- : file(std::move(file_)), bktr_base_romfs(std::move(bktr_base_romfs_)) {
+NCA::NCA(VirtualFile file_, VirtualFile bktr_base_romfs_, u64 bktr_base_ivfc_offset,
+ Core::Crypto::KeyManager keys_)
+ : file(std::move(file_)), bktr_base_romfs(std::move(bktr_base_romfs_)), keys(std::move(keys_)) {
if (file == nullptr) {
status = Loader::ResultStatus::ErrorNullFile;
return;
diff --git a/src/core/file_sys/content_archive.h b/src/core/file_sys/content_archive.h
index 4bba55607..99294cbb4 100644
--- a/src/core/file_sys/content_archive.h
+++ b/src/core/file_sys/content_archive.h
@@ -79,7 +79,8 @@ inline bool IsDirectoryExeFS(const std::shared_ptr<VfsDirectory>& pfs) {
class NCA : public ReadOnlyVfsDirectory {
public:
explicit NCA(VirtualFile file, VirtualFile bktr_base_romfs = nullptr,
- u64 bktr_base_ivfc_offset = 0);
+ u64 bktr_base_ivfc_offset = 0,
+ Core::Crypto::KeyManager keys = Core::Crypto::KeyManager());
~NCA() override;
Loader::ResultStatus GetStatus() const;
diff --git a/src/core/file_sys/control_metadata.cpp b/src/core/file_sys/control_metadata.cpp
index a012c2be9..c8fa912bf 100644
--- a/src/core/file_sys/control_metadata.cpp
+++ b/src/core/file_sys/control_metadata.cpp
@@ -66,4 +66,10 @@ std::string NACP::GetVersionString() const {
return Common::StringFromFixedZeroTerminatedBuffer(raw->version_string.data(),
raw->version_string.size());
}
+
+std::vector<u8> NACP::GetRawBytes() const {
+ std::vector<u8> out(sizeof(RawNACP));
+ std::memcpy(out.data(), raw.get(), sizeof(RawNACP));
+ return out;
+}
} // namespace FileSys
diff --git a/src/core/file_sys/control_metadata.h b/src/core/file_sys/control_metadata.h
index 141f7e056..bfaad46b4 100644
--- a/src/core/file_sys/control_metadata.h
+++ b/src/core/file_sys/control_metadata.h
@@ -81,6 +81,7 @@ public:
u64 GetTitleId() const;
u64 GetDLCBaseTitleId() const;
std::string GetVersionString() const;
+ std::vector<u8> GetRawBytes() const;
private:
std::unique_ptr<RawNACP> raw;
diff --git a/src/core/file_sys/errors.h b/src/core/file_sys/errors.h
index fea0593c7..e4a4ee4ab 100644
--- a/src/core/file_sys/errors.h
+++ b/src/core/file_sys/errors.h
@@ -8,25 +8,10 @@
namespace FileSys {
-namespace ErrCodes {
-enum {
- NotFound = 1,
- TitleNotFound = 1002,
- SdCardNotFound = 2001,
- RomFSNotFound = 2520,
-};
-}
-
-constexpr ResultCode ERROR_PATH_NOT_FOUND(ErrorModule::FS, ErrCodes::NotFound);
-
-// TODO(bunnei): Replace these with correct errors for Switch OS
-constexpr ResultCode ERROR_INVALID_PATH(-1);
-constexpr ResultCode ERROR_UNSUPPORTED_OPEN_FLAGS(-1);
-constexpr ResultCode ERROR_INVALID_OPEN_FLAGS(-1);
-constexpr ResultCode ERROR_FILE_NOT_FOUND(-1);
-constexpr ResultCode ERROR_UNEXPECTED_FILE_OR_DIRECTORY(-1);
-constexpr ResultCode ERROR_DIRECTORY_ALREADY_EXISTS(-1);
-constexpr ResultCode ERROR_FILE_ALREADY_EXISTS(-1);
-constexpr ResultCode ERROR_DIRECTORY_NOT_EMPTY(-1);
+constexpr ResultCode ERROR_PATH_NOT_FOUND{ErrorModule::FS, 1};
+constexpr ResultCode ERROR_ENTITY_NOT_FOUND{ErrorModule::FS, 1002};
+constexpr ResultCode ERROR_SD_CARD_NOT_FOUND{ErrorModule::FS, 2001};
+constexpr ResultCode ERROR_INVALID_OFFSET{ErrorModule::FS, 6061};
+constexpr ResultCode ERROR_INVALID_SIZE{ErrorModule::FS, 6062};
} // namespace FileSys
diff --git a/src/core/file_sys/patch_manager.cpp b/src/core/file_sys/patch_manager.cpp
index 0c1156989..e8df08724 100644
--- a/src/core/file_sys/patch_manager.cpp
+++ b/src/core/file_sys/patch_manager.cpp
@@ -19,12 +19,18 @@
#include "core/file_sys/vfs_vector.h"
#include "core/hle/service/filesystem/filesystem.h"
#include "core/loader/loader.h"
+#include "core/settings.h"
namespace FileSys {
constexpr u64 SINGLE_BYTE_MODULUS = 0x100;
constexpr u64 DLC_BASE_TITLE_ID_MASK = 0xFFFFFFFFFFFFE000;
+constexpr std::array<const char*, 14> EXEFS_FILE_NAMES{
+ "main", "main.npdm", "rtld", "sdk", "subsdk0", "subsdk1", "subsdk2",
+ "subsdk3", "subsdk4", "subsdk5", "subsdk6", "subsdk7", "subsdk8", "subsdk9",
+};
+
struct NSOBuildHeader {
u32_le magic;
INSERT_PADDING_BYTES(0x3C);
@@ -56,6 +62,15 @@ VirtualDir PatchManager::PatchExeFS(VirtualDir exefs) const {
if (exefs == nullptr)
return exefs;
+ if (Settings::values.dump_exefs) {
+ LOG_INFO(Loader, "Dumping ExeFS for title_id={:016X}", title_id);
+ const auto dump_dir = Service::FileSystem::GetModificationDumpRoot(title_id);
+ if (dump_dir != nullptr) {
+ const auto exefs_dir = GetOrCreateDirectoryRelative(dump_dir, "/exefs");
+ VfsRawCopyD(exefs, exefs_dir);
+ }
+ }
+
const auto installed = Service::FileSystem::GetUnionContents();
// Game Updates
@@ -69,6 +84,30 @@ VirtualDir PatchManager::PatchExeFS(VirtualDir exefs) const {
exefs = update->GetExeFS();
}
+ // LayeredExeFS
+ const auto load_dir = Service::FileSystem::GetModificationLoadRoot(title_id);
+ if (load_dir != nullptr && load_dir->GetSize() > 0) {
+ auto patch_dirs = load_dir->GetSubdirectories();
+ std::sort(
+ patch_dirs.begin(), patch_dirs.end(),
+ [](const VirtualDir& l, const VirtualDir& r) { return l->GetName() < r->GetName(); });
+
+ std::vector<VirtualDir> layers;
+ layers.reserve(patch_dirs.size() + 1);
+ for (const auto& subdir : patch_dirs) {
+ auto exefs_dir = subdir->GetSubdirectory("exefs");
+ if (exefs_dir != nullptr)
+ layers.push_back(std::move(exefs_dir));
+ }
+ layers.push_back(exefs);
+
+ auto layered = LayeredVfsDirectory::MakeLayeredDirectory(std::move(layers));
+ if (layered != nullptr) {
+ LOG_INFO(Loader, " ExeFS: LayeredExeFS patches applied successfully");
+ exefs = std::move(layered);
+ }
+ }
+
return exefs;
}
@@ -119,6 +158,18 @@ std::vector<u8> PatchManager::PatchNSO(const std::vector<u8>& nso) const {
const auto build_id_raw = Common::HexArrayToString(header.build_id);
const auto build_id = build_id_raw.substr(0, build_id_raw.find_last_not_of('0') + 1);
+ if (Settings::values.dump_nso) {
+ LOG_INFO(Loader, "Dumping NSO for build_id={}, title_id={:016X}", build_id, title_id);
+ const auto dump_dir = Service::FileSystem::GetModificationDumpRoot(title_id);
+ if (dump_dir != nullptr) {
+ const auto nso_dir = GetOrCreateDirectoryRelative(dump_dir, "/nso");
+ const auto file = nso_dir->CreateFile(fmt::format("{}.nso", build_id));
+
+ file->Resize(nso.size());
+ file->WriteBytes(nso);
+ }
+ }
+
LOG_INFO(Loader, "Patching NSO for build_id={}", build_id);
const auto load_dir = Service::FileSystem::GetModificationLoadRoot(title_id);
@@ -301,18 +352,25 @@ std::map<std::string, std::string, std::less<>> PatchManager::GetPatchVersionNam
if (IsDirValidAndNonEmpty(exefs_dir)) {
bool ips = false;
bool ipswitch = false;
+ bool layeredfs = false;
for (const auto& file : exefs_dir->GetFiles()) {
- if (file->GetExtension() == "ips")
+ if (file->GetExtension() == "ips") {
ips = true;
- else if (file->GetExtension() == "pchtxt")
+ } else if (file->GetExtension() == "pchtxt") {
ipswitch = true;
+ } else if (std::find(EXEFS_FILE_NAMES.begin(), EXEFS_FILE_NAMES.end(),
+ file->GetName()) != EXEFS_FILE_NAMES.end()) {
+ layeredfs = true;
+ }
}
if (ips)
AppendCommaIfNotEmpty(types, "IPS");
if (ipswitch)
AppendCommaIfNotEmpty(types, "IPSwitch");
+ if (layeredfs)
+ AppendCommaIfNotEmpty(types, "LayeredExeFS");
}
if (IsDirValidAndNonEmpty(mod->GetSubdirectory("romfs")))
AppendCommaIfNotEmpty(types, "LayeredFS");
diff --git a/src/core/file_sys/registered_cache.cpp b/src/core/file_sys/registered_cache.cpp
index 96302a241..a3f8f2f73 100644
--- a/src/core/file_sys/registered_cache.cpp
+++ b/src/core/file_sys/registered_cache.cpp
@@ -106,9 +106,12 @@ static ContentRecordType GetCRTypeFromNCAType(NCAContentType type) {
VirtualFile RegisteredCache::OpenFileOrDirectoryConcat(const VirtualDir& dir,
std::string_view path) const {
- if (dir->GetFileRelative(path) != nullptr)
- return dir->GetFileRelative(path);
- if (dir->GetDirectoryRelative(path) != nullptr) {
+ const auto file = dir->GetFileRelative(path);
+ if (file != nullptr)
+ return file;
+
+ const auto nca_dir = dir->GetDirectoryRelative(path);
+ if (nca_dir != nullptr) {
const auto nca_dir = dir->GetDirectoryRelative(path);
VirtualFile file = nullptr;
@@ -225,7 +228,7 @@ void RegisteredCache::ProcessFiles(const std::vector<NcaID>& ids) {
if (file == nullptr)
continue;
- const auto nca = std::make_shared<NCA>(parser(file, id));
+ const auto nca = std::make_shared<NCA>(parser(file, id), nullptr, 0, keys);
if (nca->GetStatus() != Loader::ResultStatus::Success ||
nca->GetType() != NCAContentType::Meta) {
continue;
@@ -315,7 +318,7 @@ std::unique_ptr<NCA> RegisteredCache::GetEntry(u64 title_id, ContentRecordType t
const auto raw = GetEntryRaw(title_id, type);
if (raw == nullptr)
return nullptr;
- return std::make_unique<NCA>(raw);
+ return std::make_unique<NCA>(raw, nullptr, 0, keys);
}
std::unique_ptr<NCA> RegisteredCache::GetEntry(RegisteredCacheEntry entry) const {
diff --git a/src/core/file_sys/registered_cache.h b/src/core/file_sys/registered_cache.h
index 6cfb16017..6b89db8de 100644
--- a/src/core/file_sys/registered_cache.h
+++ b/src/core/file_sys/registered_cache.h
@@ -12,6 +12,7 @@
#include <vector>
#include <boost/container/flat_map.hpp>
#include "common/common_types.h"
+#include "core/crypto/key_manager.h"
#include "core/file_sys/vfs.h"
namespace FileSys {
@@ -133,6 +134,8 @@ private:
VirtualDir dir;
RegisteredCacheParsingFunction parser;
+ Core::Crypto::KeyManager keys;
+
// maps tid -> NcaID of meta
boost::container::flat_map<u64, NcaID> meta_id;
// maps tid -> meta
diff --git a/src/core/file_sys/savedata_factory.cpp b/src/core/file_sys/savedata_factory.cpp
index ef1aaebbb..5434f2149 100644
--- a/src/core/file_sys/savedata_factory.cpp
+++ b/src/core/file_sys/savedata_factory.cpp
@@ -83,28 +83,32 @@ ResultVal<VirtualDir> SaveDataFactory::Open(SaveDataSpaceId space, SaveDataDescr
return MakeResult<VirtualDir>(std::move(out));
}
-std::string SaveDataFactory::GetFullPath(SaveDataSpaceId space, SaveDataType type, u64 title_id,
- u128 user_id, u64 save_id) {
- // According to switchbrew, if a save is of type SaveData and the title id field is 0, it should
- // be interpreted as the title id of the current process.
- if (type == SaveDataType::SaveData && title_id == 0)
- title_id = Core::CurrentProcess()->GetTitleID();
-
- std::string out;
+VirtualDir SaveDataFactory::GetSaveDataSpaceDirectory(SaveDataSpaceId space) const {
+ return dir->GetDirectoryRelative(GetSaveDataSpaceIdPath(space));
+}
+std::string SaveDataFactory::GetSaveDataSpaceIdPath(SaveDataSpaceId space) {
switch (space) {
case SaveDataSpaceId::NandSystem:
- out = "/system/";
- break;
+ return "/system/";
case SaveDataSpaceId::NandUser:
- out = "/user/";
- break;
+ return "/user/";
case SaveDataSpaceId::TemporaryStorage:
- out = "/temp/";
- break;
+ return "/temp/";
default:
ASSERT_MSG(false, "Unrecognized SaveDataSpaceId: {:02X}", static_cast<u8>(space));
+ return "/unrecognized/"; ///< To prevent corruption when ignoring asserts.
}
+}
+
+std::string SaveDataFactory::GetFullPath(SaveDataSpaceId space, SaveDataType type, u64 title_id,
+ u128 user_id, u64 save_id) {
+ // According to switchbrew, if a save is of type SaveData and the title id field is 0, it should
+ // be interpreted as the title id of the current process.
+ if (type == SaveDataType::SaveData && title_id == 0)
+ title_id = Core::CurrentProcess()->GetTitleID();
+
+ std::string out = GetSaveDataSpaceIdPath(space);
switch (type) {
case SaveDataType::SystemSaveData:
diff --git a/src/core/file_sys/savedata_factory.h b/src/core/file_sys/savedata_factory.h
index d69ef6741..2a0088040 100644
--- a/src/core/file_sys/savedata_factory.h
+++ b/src/core/file_sys/savedata_factory.h
@@ -52,6 +52,9 @@ public:
ResultVal<VirtualDir> Open(SaveDataSpaceId space, SaveDataDescriptor meta);
+ VirtualDir GetSaveDataSpaceDirectory(SaveDataSpaceId space) const;
+
+ static std::string GetSaveDataSpaceIdPath(SaveDataSpaceId space);
static std::string GetFullPath(SaveDataSpaceId space, SaveDataType type, u64 title_id,
u128 user_id, u64 save_id);
diff --git a/src/core/file_sys/submission_package.cpp b/src/core/file_sys/submission_package.cpp
index 2aaba4179..e1a4210db 100644
--- a/src/core/file_sys/submission_package.cpp
+++ b/src/core/file_sys/submission_package.cpp
@@ -252,7 +252,7 @@ void NSP::ReadNCAs(const std::vector<VirtualFile>& files) {
continue;
}
- auto next_nca = std::make_shared<NCA>(next_file);
+ auto next_nca = std::make_shared<NCA>(next_file, nullptr, 0, keys);
if (next_nca->GetType() == NCAContentType::Program)
program_status[cnmt.GetTitleID()] = next_nca->GetStatus();
if (next_nca->GetStatus() == Loader::ResultStatus::Success ||
diff --git a/src/core/file_sys/submission_package.h b/src/core/file_sys/submission_package.h
index 338080b7e..9a28ed5bb 100644
--- a/src/core/file_sys/submission_package.h
+++ b/src/core/file_sys/submission_package.h
@@ -70,6 +70,8 @@ private:
std::map<u64, std::map<ContentRecordType, std::shared_ptr<NCA>>> ncas;
std::vector<VirtualFile> ticket_files;
+ Core::Crypto::KeyManager keys;
+
VirtualFile romfs;
VirtualDir exefs;
};
diff --git a/src/core/frontend/applets/software_keyboard.cpp b/src/core/frontend/applets/software_keyboard.cpp
new file mode 100644
index 000000000..856ed33da
--- /dev/null
+++ b/src/core/frontend/applets/software_keyboard.cpp
@@ -0,0 +1,29 @@
+// Copyright 2018 yuzu emulator team
+// Licensed under GPLv2 or any later version
+// Refer to the license.txt file included.
+
+#include "common/logging/backend.h"
+#include "common/string_util.h"
+#include "core/frontend/applets/software_keyboard.h"
+
+namespace Core::Frontend {
+SoftwareKeyboardApplet::~SoftwareKeyboardApplet() = default;
+
+void DefaultSoftwareKeyboardApplet::RequestText(
+ std::function<void(std::optional<std::u16string>)> out,
+ SoftwareKeyboardParameters parameters) const {
+ if (parameters.initial_text.empty())
+ out(u"yuzu");
+
+ out(parameters.initial_text);
+}
+
+void DefaultSoftwareKeyboardApplet::SendTextCheckDialog(
+ std::u16string error_message, std::function<void()> finished_check) const {
+ LOG_WARNING(Service_AM,
+ "(STUBBED) called - Default fallback software keyboard does not support text "
+ "check! (error_message={})",
+ Common::UTF16ToUTF8(error_message));
+ finished_check();
+}
+} // namespace Core::Frontend
diff --git a/src/core/frontend/applets/software_keyboard.h b/src/core/frontend/applets/software_keyboard.h
new file mode 100644
index 000000000..f9b202664
--- /dev/null
+++ b/src/core/frontend/applets/software_keyboard.h
@@ -0,0 +1,54 @@
+// Copyright 2018 yuzu emulator team
+// Licensed under GPLv2 or any later version
+// Refer to the license.txt file included.
+
+#pragma once
+
+#include <functional>
+#include <optional>
+#include <string>
+#include "common/bit_field.h"
+#include "common/common_types.h"
+
+namespace Core::Frontend {
+struct SoftwareKeyboardParameters {
+ std::u16string submit_text;
+ std::u16string header_text;
+ std::u16string sub_text;
+ std::u16string guide_text;
+ std::u16string initial_text;
+ std::size_t max_length;
+ bool password;
+ bool cursor_at_beginning;
+
+ union {
+ u8 value;
+
+ BitField<1, 1, u8> disable_space;
+ BitField<2, 1, u8> disable_address;
+ BitField<3, 1, u8> disable_percent;
+ BitField<4, 1, u8> disable_slash;
+ BitField<6, 1, u8> disable_number;
+ BitField<7, 1, u8> disable_download_code;
+ };
+};
+
+class SoftwareKeyboardApplet {
+public:
+ virtual ~SoftwareKeyboardApplet();
+
+ virtual void RequestText(std::function<void(std::optional<std::u16string>)> out,
+ SoftwareKeyboardParameters parameters) const = 0;
+ virtual void SendTextCheckDialog(std::u16string error_message,
+ std::function<void()> finished_check) const = 0;
+};
+
+class DefaultSoftwareKeyboardApplet final : public SoftwareKeyboardApplet {
+public:
+ void RequestText(std::function<void(std::optional<std::u16string>)> out,
+ SoftwareKeyboardParameters parameters) const override;
+ void SendTextCheckDialog(std::u16string error_message,
+ std::function<void()> finished_check) const override;
+};
+
+} // namespace Core::Frontend
diff --git a/src/core/frontend/input.h b/src/core/frontend/input.h
index 39bdf4e21..16fdcd376 100644
--- a/src/core/frontend/input.h
+++ b/src/core/frontend/input.h
@@ -132,4 +132,11 @@ using MotionDevice = InputDevice<std::tuple<Math::Vec3<float>, Math::Vec3<float>
*/
using TouchDevice = InputDevice<std::tuple<float, float, bool>>;
+/**
+ * A mouse device is an input device that returns a tuple of two floats and four ints.
+ * The first two floats are X and Y device coordinates of the mouse (from 0-1).
+ * The s32s are the mouse wheel.
+ */
+using MouseDevice = InputDevice<std::tuple<float, float, s32, s32>>;
+
} // namespace Input
diff --git a/src/core/gdbstub/gdbstub.cpp b/src/core/gdbstub/gdbstub.cpp
index bdcc889e0..687dea409 100644
--- a/src/core/gdbstub/gdbstub.cpp
+++ b/src/core/gdbstub/gdbstub.cpp
@@ -71,10 +71,6 @@ constexpr u32 PSTATE_REGISTER = 33;
constexpr u32 UC_ARM64_REG_Q0 = 34;
constexpr u32 FPCR_REGISTER = 66;
-// TODO/WiP - Used while working on support for FPU
-constexpr u32 TODO_DUMMY_REG_997 = 997;
-constexpr u32 TODO_DUMMY_REG_998 = 998;
-
// For sample XML files see the GDB source /gdb/features
// GDB also wants the l character at the start
// This XML defines what the registers are for this specific ARM device
@@ -260,6 +256,36 @@ static void RegWrite(std::size_t id, u64 val, Kernel::Thread* thread = nullptr)
}
}
+static u128 FpuRead(std::size_t id, Kernel::Thread* thread = nullptr) {
+ if (!thread) {
+ return u128{0};
+ }
+
+ auto& thread_context = thread->GetContext();
+
+ if (id >= UC_ARM64_REG_Q0 && id < FPCR_REGISTER) {
+ return thread_context.vector_registers[id - UC_ARM64_REG_Q0];
+ } else if (id == FPCR_REGISTER) {
+ return u128{thread_context.fpcr, 0};
+ } else {
+ return u128{0};
+ }
+}
+
+static void FpuWrite(std::size_t id, u128 val, Kernel::Thread* thread = nullptr) {
+ if (!thread) {
+ return;
+ }
+
+ auto& thread_context = thread->GetContext();
+
+ if (id >= UC_ARM64_REG_Q0 && id < FPCR_REGISTER) {
+ thread_context.vector_registers[id - UC_ARM64_REG_Q0] = val;
+ } else if (id == FPCR_REGISTER) {
+ thread_context.fpcr = val[0];
+ }
+}
+
/**
* Turns hex string character into the equivalent byte.
*
@@ -409,6 +435,27 @@ static u64 GdbHexToLong(const u8* src) {
return output;
}
+/**
+ * Convert a gdb-formatted hex string into a u128.
+ *
+ * @param src Pointer to hex string.
+ */
+static u128 GdbHexToU128(const u8* src) {
+ u128 output;
+
+ for (int i = 0; i < 16; i += 2) {
+ output[0] = (output[0] << 4) | HexCharToValue(src[15 - i - 1]);
+ output[0] = (output[0] << 4) | HexCharToValue(src[15 - i]);
+ }
+
+ for (int i = 0; i < 16; i += 2) {
+ output[1] = (output[1] << 4) | HexCharToValue(src[16 + 15 - i - 1]);
+ output[1] = (output[1] << 4) | HexCharToValue(src[16 + 15 - i]);
+ }
+
+ return output;
+}
+
/// Read a byte from the gdb client.
static u8 ReadByte() {
u8 c;
@@ -599,8 +646,7 @@ static void HandleQuery() {
for (u32 core = 0; core < Core::NUM_CPU_CORES; core++) {
const auto& threads = Core::System::GetInstance().Scheduler(core).GetThreadList();
for (const auto& thread : threads) {
- val += fmt::format("{:x}", thread->GetThreadID());
- val += ",";
+ val += fmt::format("{:x},", thread->GetThreadID());
}
}
val.pop_back();
@@ -791,11 +837,15 @@ static void ReadRegister() {
} else if (id == PSTATE_REGISTER) {
IntToGdbHex(reply, static_cast<u32>(RegRead(id, current_thread)));
} else if (id >= UC_ARM64_REG_Q0 && id < FPCR_REGISTER) {
- LongToGdbHex(reply, RegRead(id, current_thread));
+ u128 r = FpuRead(id, current_thread);
+ LongToGdbHex(reply, r[0]);
+ LongToGdbHex(reply + 16, r[1]);
} else if (id == FPCR_REGISTER) {
- LongToGdbHex(reply, RegRead(TODO_DUMMY_REG_998, current_thread));
- } else {
- LongToGdbHex(reply, RegRead(TODO_DUMMY_REG_997, current_thread));
+ u128 r = FpuRead(id, current_thread);
+ IntToGdbHex(reply, static_cast<u32>(r[0]));
+ } else if (id == FPCR_REGISTER + 1) {
+ u128 r = FpuRead(id, current_thread);
+ IntToGdbHex(reply, static_cast<u32>(r[0] >> 32));
}
SendReply(reinterpret_cast<char*>(reply));
@@ -822,13 +872,18 @@ static void ReadRegisters() {
bufptr += 8;
- for (u32 reg = UC_ARM64_REG_Q0; reg <= UC_ARM64_REG_Q0 + 31; reg++) {
- LongToGdbHex(bufptr + reg * 16, RegRead(reg, current_thread));
+ u128 r;
+
+ for (u32 reg = UC_ARM64_REG_Q0; reg < FPCR_REGISTER; reg++) {
+ r = FpuRead(reg, current_thread);
+ LongToGdbHex(bufptr + reg * 32, r[0]);
+ LongToGdbHex(bufptr + reg * 32 + 16, r[1]);
}
bufptr += 32 * 32;
- LongToGdbHex(bufptr, RegRead(TODO_DUMMY_REG_998, current_thread));
+ r = FpuRead(FPCR_REGISTER, current_thread);
+ IntToGdbHex(bufptr, static_cast<u32>(r[0]));
bufptr += 8;
@@ -853,14 +908,12 @@ static void WriteRegister() {
} else if (id == PSTATE_REGISTER) {
RegWrite(id, GdbHexToInt(buffer_ptr), current_thread);
} else if (id >= UC_ARM64_REG_Q0 && id < FPCR_REGISTER) {
- RegWrite(id, GdbHexToLong(buffer_ptr), current_thread);
+ FpuWrite(id, GdbHexToU128(buffer_ptr), current_thread);
} else if (id == FPCR_REGISTER) {
- RegWrite(TODO_DUMMY_REG_998, GdbHexToLong(buffer_ptr), current_thread);
- } else {
- RegWrite(TODO_DUMMY_REG_997, GdbHexToLong(buffer_ptr), current_thread);
+ } else if (id == FPCR_REGISTER + 1) {
}
- // Update Unicorn context skipping scheduler, no running threads at this point
+ // Update ARM context, skipping scheduler - no running threads at this point
Core::System::GetInstance()
.ArmInterface(current_core)
.LoadContext(current_thread->GetContext());
@@ -885,13 +938,13 @@ static void WriteRegisters() {
} else if (reg >= UC_ARM64_REG_Q0 && reg < FPCR_REGISTER) {
RegWrite(reg, GdbHexToLong(buffer_ptr + i * 16), current_thread);
} else if (reg == FPCR_REGISTER) {
- RegWrite(TODO_DUMMY_REG_998, GdbHexToLong(buffer_ptr + i * 16), current_thread);
- } else {
- UNIMPLEMENTED();
+ RegWrite(FPCR_REGISTER, GdbHexToLong(buffer_ptr + i * 16), current_thread);
+ } else if (reg == FPCR_REGISTER + 1) {
+ RegWrite(FPCR_REGISTER, GdbHexToLong(buffer_ptr + i * 16), current_thread);
}
}
- // Update Unicorn context skipping scheduler, no running threads at this point
+ // Update ARM context, skipping scheduler - no running threads at this point
Core::System::GetInstance()
.ArmInterface(current_core)
.LoadContext(current_thread->GetContext());
@@ -917,12 +970,6 @@ static void ReadMemory() {
SendReply("E01");
}
- const auto& vm_manager = Core::CurrentProcess()->VMManager();
- if (addr < vm_manager.GetCodeRegionBaseAddress() ||
- addr >= vm_manager.GetMapRegionEndAddress()) {
- return SendReply("E00");
- }
-
if (!Memory::IsValidVirtualAddress(addr)) {
return SendReply("E00");
}
@@ -967,7 +1014,7 @@ void Break(bool is_memory_break) {
static void Step() {
if (command_length > 1) {
RegWrite(PC_REGISTER, GdbHexToLong(command_buffer + 1), current_thread);
- // Update Unicorn context skipping scheduler, no running threads at this point
+ // Update ARM context, skipping scheduler - no running threads at this point
Core::System::GetInstance()
.ArmInterface(current_core)
.LoadContext(current_thread->GetContext());
@@ -1010,7 +1057,7 @@ static bool CommitBreakpoint(BreakpointType type, VAddr addr, u64 len) {
breakpoint.addr = addr;
breakpoint.len = len;
Memory::ReadBlock(addr, breakpoint.inst.data(), breakpoint.inst.size());
- static constexpr std::array<u8, 4> btrap{{0x00, 0x7d, 0x20, 0xd4}};
+ static constexpr std::array<u8, 4> btrap{0x00, 0x7d, 0x20, 0xd4};
Memory::WriteBlock(addr, btrap.data(), btrap.size());
Core::System::GetInstance().InvalidateCpuInstructionCaches();
p.insert({addr, breakpoint});
@@ -1321,13 +1368,15 @@ void SetCpuStepFlag(bool is_step) {
}
void SendTrap(Kernel::Thread* thread, int trap) {
- if (send_trap) {
- if (!halt_loop || current_thread == thread) {
- current_thread = thread;
- SendSignal(thread, trap);
- }
- halt_loop = true;
- send_trap = false;
+ if (!send_trap) {
+ return;
}
+
+ if (!halt_loop || current_thread == thread) {
+ current_thread = thread;
+ SendSignal(thread, trap);
+ }
+ halt_loop = true;
+ send_trap = false;
}
}; // namespace GDBStub
diff --git a/src/core/hle/kernel/errors.h b/src/core/hle/kernel/errors.h
index ee698c8a7..8b58d701d 100644
--- a/src/core/hle/kernel/errors.h
+++ b/src/core/hle/kernel/errors.h
@@ -8,58 +8,28 @@
namespace Kernel {
-namespace ErrCodes {
-enum {
- // Confirmed Switch OS error codes
- MaxConnectionsReached = 7,
- InvalidSize = 101,
- InvalidAddress = 102,
- HandleTableFull = 105,
- InvalidMemoryState = 106,
- InvalidMemoryPermissions = 108,
- InvalidMemoryRange = 110,
- InvalidThreadPriority = 112,
- InvalidProcessorId = 113,
- InvalidHandle = 114,
- InvalidPointer = 115,
- InvalidCombination = 116,
- Timeout = 117,
- SynchronizationCanceled = 118,
- TooLarge = 119,
- InvalidEnumValue = 120,
- NoSuchEntry = 121,
- AlreadyRegistered = 122,
- SessionClosed = 123,
- InvalidState = 125,
- ResourceLimitExceeded = 132,
-};
-}
+// Confirmed Switch kernel error codes
-// WARNING: The kernel is quite inconsistent in it's usage of errors code. Make sure to always
-// double check that the code matches before re-using the constant.
-
-constexpr ResultCode ERR_HANDLE_TABLE_FULL(ErrorModule::Kernel, ErrCodes::HandleTableFull);
-constexpr ResultCode ERR_SESSION_CLOSED_BY_REMOTE(ErrorModule::Kernel, ErrCodes::SessionClosed);
-constexpr ResultCode ERR_PORT_NAME_TOO_LONG(ErrorModule::Kernel, ErrCodes::TooLarge);
-constexpr ResultCode ERR_MAX_CONNECTIONS_REACHED(ErrorModule::Kernel,
- ErrCodes::MaxConnectionsReached);
-constexpr ResultCode ERR_INVALID_ENUM_VALUE(ErrorModule::Kernel, ErrCodes::InvalidEnumValue);
-constexpr ResultCode ERR_INVALID_COMBINATION_KERNEL(ErrorModule::Kernel,
- ErrCodes::InvalidCombination);
-constexpr ResultCode ERR_INVALID_ADDRESS(ErrorModule::Kernel, ErrCodes::InvalidAddress);
-constexpr ResultCode ERR_INVALID_ADDRESS_STATE(ErrorModule::Kernel, ErrCodes::InvalidMemoryState);
-constexpr ResultCode ERR_INVALID_MEMORY_PERMISSIONS(ErrorModule::Kernel,
- ErrCodes::InvalidMemoryPermissions);
-constexpr ResultCode ERR_INVALID_MEMORY_RANGE(ErrorModule::Kernel, ErrCodes::InvalidMemoryRange);
-constexpr ResultCode ERR_INVALID_HANDLE(ErrorModule::Kernel, ErrCodes::InvalidHandle);
-constexpr ResultCode ERR_INVALID_PROCESSOR_ID(ErrorModule::Kernel, ErrCodes::InvalidProcessorId);
-constexpr ResultCode ERR_INVALID_SIZE(ErrorModule::Kernel, ErrCodes::InvalidSize);
-constexpr ResultCode ERR_ALREADY_REGISTERED(ErrorModule::Kernel, ErrCodes::AlreadyRegistered);
-constexpr ResultCode ERR_INVALID_STATE(ErrorModule::Kernel, ErrCodes::InvalidState);
-constexpr ResultCode ERR_INVALID_THREAD_PRIORITY(ErrorModule::Kernel,
- ErrCodes::InvalidThreadPriority);
-constexpr ResultCode ERR_INVALID_POINTER(ErrorModule::Kernel, ErrCodes::InvalidPointer);
-constexpr ResultCode ERR_NOT_FOUND(ErrorModule::Kernel, ErrCodes::NoSuchEntry);
-constexpr ResultCode RESULT_TIMEOUT(ErrorModule::Kernel, ErrCodes::Timeout);
+constexpr ResultCode ERR_MAX_CONNECTIONS_REACHED{ErrorModule::Kernel, 7};
+constexpr ResultCode ERR_INVALID_SIZE{ErrorModule::Kernel, 101};
+constexpr ResultCode ERR_INVALID_ADDRESS{ErrorModule::Kernel, 102};
+constexpr ResultCode ERR_HANDLE_TABLE_FULL{ErrorModule::Kernel, 105};
+constexpr ResultCode ERR_INVALID_ADDRESS_STATE{ErrorModule::Kernel, 106};
+constexpr ResultCode ERR_INVALID_MEMORY_PERMISSIONS{ErrorModule::Kernel, 108};
+constexpr ResultCode ERR_INVALID_MEMORY_RANGE{ErrorModule::Kernel, 110};
+constexpr ResultCode ERR_INVALID_PROCESSOR_ID{ErrorModule::Kernel, 113};
+constexpr ResultCode ERR_INVALID_THREAD_PRIORITY{ErrorModule::Kernel, 112};
+constexpr ResultCode ERR_INVALID_HANDLE{ErrorModule::Kernel, 114};
+constexpr ResultCode ERR_INVALID_POINTER{ErrorModule::Kernel, 115};
+constexpr ResultCode ERR_INVALID_COMBINATION{ErrorModule::Kernel, 116};
+constexpr ResultCode RESULT_TIMEOUT{ErrorModule::Kernel, 117};
+constexpr ResultCode ERR_SYNCHRONIZATION_CANCELED{ErrorModule::Kernel, 118};
+constexpr ResultCode ERR_OUT_OF_RANGE{ErrorModule::Kernel, 119};
+constexpr ResultCode ERR_INVALID_ENUM_VALUE{ErrorModule::Kernel, 120};
+constexpr ResultCode ERR_NOT_FOUND{ErrorModule::Kernel, 121};
+constexpr ResultCode ERR_ALREADY_REGISTERED{ErrorModule::Kernel, 122};
+constexpr ResultCode ERR_SESSION_CLOSED_BY_REMOTE{ErrorModule::Kernel, 123};
+constexpr ResultCode ERR_INVALID_STATE{ErrorModule::Kernel, 125};
+constexpr ResultCode ERR_RESOURCE_LIMIT_EXCEEDED{ErrorModule::Kernel, 132};
} // namespace Kernel
diff --git a/src/core/hle/kernel/handle_table.cpp b/src/core/hle/kernel/handle_table.cpp
index 5ee5c05e3..1bf79b692 100644
--- a/src/core/hle/kernel/handle_table.cpp
+++ b/src/core/hle/kernel/handle_table.cpp
@@ -12,12 +12,23 @@
#include "core/hle/kernel/thread.h"
namespace Kernel {
+namespace {
+constexpr u16 GetSlot(Handle handle) {
+ return handle >> 15;
+}
+
+constexpr u16 GetGeneration(Handle handle) {
+ return handle & 0x7FFF;
+}
+} // Anonymous namespace
HandleTable::HandleTable() {
next_generation = 1;
Clear();
}
+HandleTable::~HandleTable() = default;
+
ResultVal<Handle> HandleTable::Create(SharedPtr<Object> obj) {
DEBUG_ASSERT(obj != nullptr);
diff --git a/src/core/hle/kernel/handle_table.h b/src/core/hle/kernel/handle_table.h
index 9e2f33e8a..e3f3e3fb8 100644
--- a/src/core/hle/kernel/handle_table.h
+++ b/src/core/hle/kernel/handle_table.h
@@ -43,6 +43,7 @@ enum KernelHandle : Handle {
class HandleTable final : NonCopyable {
public:
HandleTable();
+ ~HandleTable();
/**
* Allocates a handle for the given object.
@@ -89,18 +90,8 @@ public:
void Clear();
private:
- /**
- * This is the maximum limit of handles allowed per process in CTR-OS. It can be further
- * reduced by ExHeader values, but this is not emulated here.
- */
- static const std::size_t MAX_COUNT = 4096;
-
- static u16 GetSlot(Handle handle) {
- return handle >> 15;
- }
- static u16 GetGeneration(Handle handle) {
- return handle & 0x7FFF;
- }
+ /// This is the maximum limit of handles allowed per process in Horizon
+ static constexpr std::size_t MAX_COUNT = 1024;
/// Stores the Object referenced by the handle or null if the slot is empty.
std::array<SharedPtr<Object>, MAX_COUNT> objects;
diff --git a/src/core/hle/kernel/kernel.cpp b/src/core/hle/kernel/kernel.cpp
index 1fd4ba5d2..e441c5bc6 100644
--- a/src/core/hle/kernel/kernel.cpp
+++ b/src/core/hle/kernel/kernel.cpp
@@ -105,7 +105,7 @@ struct KernelCore::Impl {
void Initialize(KernelCore& kernel) {
Shutdown();
- InitializeResourceLimits(kernel);
+ InitializeSystemResourceLimit(kernel);
InitializeThreads();
InitializeTimers();
}
@@ -118,7 +118,7 @@ struct KernelCore::Impl {
process_list.clear();
current_process = nullptr;
- resource_limits.fill(nullptr);
+ system_resource_limit = nullptr;
thread_wakeup_callback_handle_table.Clear();
thread_wakeup_event_type = nullptr;
@@ -129,63 +129,17 @@ struct KernelCore::Impl {
named_ports.clear();
}
- void InitializeResourceLimits(KernelCore& kernel) {
- // Create the four resource limits that the system uses
- // Create the APPLICATION resource limit
- SharedPtr<ResourceLimit> resource_limit = ResourceLimit::Create(kernel, "Applications");
- resource_limit->max_priority = 0x18;
- resource_limit->max_commit = 0x4000000;
- resource_limit->max_threads = 0x20;
- resource_limit->max_events = 0x20;
- resource_limit->max_mutexes = 0x20;
- resource_limit->max_semaphores = 0x8;
- resource_limit->max_timers = 0x8;
- resource_limit->max_shared_mems = 0x10;
- resource_limit->max_address_arbiters = 0x2;
- resource_limit->max_cpu_time = 0x1E;
- resource_limits[static_cast<u8>(ResourceLimitCategory::APPLICATION)] = resource_limit;
-
- // Create the SYS_APPLET resource limit
- resource_limit = ResourceLimit::Create(kernel, "System Applets");
- resource_limit->max_priority = 0x4;
- resource_limit->max_commit = 0x5E00000;
- resource_limit->max_threads = 0x1D;
- resource_limit->max_events = 0xB;
- resource_limit->max_mutexes = 0x8;
- resource_limit->max_semaphores = 0x4;
- resource_limit->max_timers = 0x4;
- resource_limit->max_shared_mems = 0x8;
- resource_limit->max_address_arbiters = 0x3;
- resource_limit->max_cpu_time = 0x2710;
- resource_limits[static_cast<u8>(ResourceLimitCategory::SYS_APPLET)] = resource_limit;
-
- // Create the LIB_APPLET resource limit
- resource_limit = ResourceLimit::Create(kernel, "Library Applets");
- resource_limit->max_priority = 0x4;
- resource_limit->max_commit = 0x600000;
- resource_limit->max_threads = 0xE;
- resource_limit->max_events = 0x8;
- resource_limit->max_mutexes = 0x8;
- resource_limit->max_semaphores = 0x4;
- resource_limit->max_timers = 0x4;
- resource_limit->max_shared_mems = 0x8;
- resource_limit->max_address_arbiters = 0x1;
- resource_limit->max_cpu_time = 0x2710;
- resource_limits[static_cast<u8>(ResourceLimitCategory::LIB_APPLET)] = resource_limit;
-
- // Create the OTHER resource limit
- resource_limit = ResourceLimit::Create(kernel, "Others");
- resource_limit->max_priority = 0x4;
- resource_limit->max_commit = 0x2180000;
- resource_limit->max_threads = 0xE1;
- resource_limit->max_events = 0x108;
- resource_limit->max_mutexes = 0x25;
- resource_limit->max_semaphores = 0x43;
- resource_limit->max_timers = 0x2C;
- resource_limit->max_shared_mems = 0x1F;
- resource_limit->max_address_arbiters = 0x2D;
- resource_limit->max_cpu_time = 0x3E8;
- resource_limits[static_cast<u8>(ResourceLimitCategory::OTHER)] = resource_limit;
+ // Creates the default system resource limit
+ void InitializeSystemResourceLimit(KernelCore& kernel) {
+ system_resource_limit = ResourceLimit::Create(kernel, "System");
+
+ // If setting the default system values fails, then something seriously wrong has occurred.
+ ASSERT(system_resource_limit->SetLimitValue(ResourceType::PhysicalMemory, 0x200000000)
+ .IsSuccess());
+ ASSERT(system_resource_limit->SetLimitValue(ResourceType::Threads, 800).IsSuccess());
+ ASSERT(system_resource_limit->SetLimitValue(ResourceType::Events, 700).IsSuccess());
+ ASSERT(system_resource_limit->SetLimitValue(ResourceType::TransferMemory, 200).IsSuccess());
+ ASSERT(system_resource_limit->SetLimitValue(ResourceType::Sessions, 900).IsSuccess());
}
void InitializeThreads() {
@@ -208,7 +162,7 @@ struct KernelCore::Impl {
std::vector<SharedPtr<Process>> process_list;
Process* current_process = nullptr;
- std::array<SharedPtr<ResourceLimit>, 4> resource_limits;
+ SharedPtr<ResourceLimit> system_resource_limit;
/// The event type of the generic timer callback event
CoreTiming::EventType* timer_callback_event_type = nullptr;
@@ -239,9 +193,8 @@ void KernelCore::Shutdown() {
impl->Shutdown();
}
-SharedPtr<ResourceLimit> KernelCore::ResourceLimitForCategory(
- ResourceLimitCategory category) const {
- return impl->resource_limits.at(static_cast<std::size_t>(category));
+SharedPtr<ResourceLimit> KernelCore::GetSystemResourceLimit() const {
+ return impl->system_resource_limit;
}
SharedPtr<Thread> KernelCore::RetrieveThreadFromWakeupCallbackHandleTable(Handle handle) const {
diff --git a/src/core/hle/kernel/kernel.h b/src/core/hle/kernel/kernel.h
index 7f822d524..ea00c89f5 100644
--- a/src/core/hle/kernel/kernel.h
+++ b/src/core/hle/kernel/kernel.h
@@ -24,8 +24,6 @@ class ResourceLimit;
class Thread;
class Timer;
-enum class ResourceLimitCategory : u8;
-
/// Represents a single instance of the kernel.
class KernelCore {
private:
@@ -47,8 +45,8 @@ public:
/// Clears all resources in use by the kernel instance.
void Shutdown();
- /// Retrieves a shared pointer to a ResourceLimit identified by the given category.
- SharedPtr<ResourceLimit> ResourceLimitForCategory(ResourceLimitCategory category) const;
+ /// Retrieves a shared pointer to the system resource limit instance.
+ SharedPtr<ResourceLimit> GetSystemResourceLimit() const;
/// Retrieves a shared pointer to a Thread instance within the thread wakeup handle table.
SharedPtr<Thread> RetrieveThreadFromWakeupCallbackHandleTable(Handle handle) const;
diff --git a/src/core/hle/kernel/process.cpp b/src/core/hle/kernel/process.cpp
index 420218d59..7ca538401 100644
--- a/src/core/hle/kernel/process.cpp
+++ b/src/core/hle/kernel/process.cpp
@@ -4,12 +4,11 @@
#include <algorithm>
#include <memory>
+#include <random>
#include "common/assert.h"
-#include "common/common_funcs.h"
#include "common/logging/log.h"
#include "core/core.h"
#include "core/file_sys/program_metadata.h"
-#include "core/hle/kernel/errors.h"
#include "core/hle/kernel/kernel.h"
#include "core/hle/kernel/process.h"
#include "core/hle/kernel/resource_limit.h"
@@ -17,6 +16,7 @@
#include "core/hle/kernel/thread.h"
#include "core/hle/kernel/vm_manager.h"
#include "core/memory.h"
+#include "core/settings.h"
namespace Kernel {
@@ -29,12 +29,17 @@ SharedPtr<Process> Process::Create(KernelCore& kernel, std::string&& name) {
process->name = std::move(name);
process->flags.raw = 0;
process->flags.memory_region.Assign(MemoryRegion::APPLICATION);
- process->resource_limit = kernel.ResourceLimitForCategory(ResourceLimitCategory::APPLICATION);
+ process->resource_limit = kernel.GetSystemResourceLimit();
process->status = ProcessStatus::Created;
process->program_id = 0;
process->process_id = kernel.CreateNewProcessID();
process->svc_access_mask.set();
+ std::mt19937 rng(Settings::values.rng_seed.value_or(0));
+ std::uniform_int_distribution<u64> distribution;
+ std::generate(process->random_entropy.begin(), process->random_entropy.end(),
+ [&] { return distribution(rng); });
+
kernel.AppendNewProcess(process);
return process;
}
@@ -241,83 +246,15 @@ void Process::LoadModule(CodeSet module_, VAddr base_addr) {
}
ResultVal<VAddr> Process::HeapAllocate(VAddr target, u64 size, VMAPermission perms) {
- if (target < vm_manager.GetHeapRegionBaseAddress() ||
- target + size > vm_manager.GetHeapRegionEndAddress() || target + size < target) {
- return ERR_INVALID_ADDRESS;
- }
-
- if (heap_memory == nullptr) {
- // Initialize heap
- heap_memory = std::make_shared<std::vector<u8>>();
- heap_start = heap_end = target;
- } else {
- vm_manager.UnmapRange(heap_start, heap_end - heap_start);
- }
-
- // If necessary, expand backing vector to cover new heap extents.
- if (target < heap_start) {
- heap_memory->insert(begin(*heap_memory), heap_start - target, 0);
- heap_start = target;
- vm_manager.RefreshMemoryBlockMappings(heap_memory.get());
- }
- if (target + size > heap_end) {
- heap_memory->insert(end(*heap_memory), (target + size) - heap_end, 0);
- heap_end = target + size;
- vm_manager.RefreshMemoryBlockMappings(heap_memory.get());
- }
- ASSERT(heap_end - heap_start == heap_memory->size());
-
- CASCADE_RESULT(auto vma, vm_manager.MapMemoryBlock(target, heap_memory, target - heap_start,
- size, MemoryState::Heap));
- vm_manager.Reprotect(vma, perms);
-
- heap_used = size;
-
- return MakeResult<VAddr>(heap_end - size);
+ return vm_manager.HeapAllocate(target, size, perms);
}
ResultCode Process::HeapFree(VAddr target, u32 size) {
- if (target < vm_manager.GetHeapRegionBaseAddress() ||
- target + size > vm_manager.GetHeapRegionEndAddress() || target + size < target) {
- return ERR_INVALID_ADDRESS;
- }
-
- if (size == 0) {
- return RESULT_SUCCESS;
- }
-
- ResultCode result = vm_manager.UnmapRange(target, size);
- if (result.IsError())
- return result;
-
- heap_used -= size;
-
- return RESULT_SUCCESS;
+ return vm_manager.HeapFree(target, size);
}
-ResultCode Process::MirrorMemory(VAddr dst_addr, VAddr src_addr, u64 size) {
- auto vma = vm_manager.FindVMA(src_addr);
-
- ASSERT_MSG(vma != vm_manager.vma_map.end(), "Invalid memory address");
- ASSERT_MSG(vma->second.backing_block, "Backing block doesn't exist for address");
-
- // The returned VMA might be a bigger one encompassing the desired address.
- auto vma_offset = src_addr - vma->first;
- ASSERT_MSG(vma_offset + size <= vma->second.size,
- "Shared memory exceeds bounds of mapped block");
-
- const std::shared_ptr<std::vector<u8>>& backing_block = vma->second.backing_block;
- std::size_t backing_block_offset = vma->second.offset + vma_offset;
-
- CASCADE_RESULT(auto new_vma,
- vm_manager.MapMemoryBlock(dst_addr, backing_block, backing_block_offset, size,
- MemoryState::Mapped));
- // Protect mirror with permissions from old region
- vm_manager.Reprotect(new_vma, vma->second.permissions);
- // Remove permissions from old region
- vm_manager.Reprotect(vma, VMAPermission::None);
-
- return RESULT_SUCCESS;
+ResultCode Process::MirrorMemory(VAddr dst_addr, VAddr src_addr, u64 size, MemoryState state) {
+ return vm_manager.MirrorMemory(dst_addr, src_addr, size, state);
}
ResultCode Process::UnmapMemory(VAddr dst_addr, VAddr /*src_addr*/, u64 size) {
diff --git a/src/core/hle/kernel/process.h b/src/core/hle/kernel/process.h
index 8d2616c79..ada845c7f 100644
--- a/src/core/hle/kernel/process.h
+++ b/src/core/hle/kernel/process.h
@@ -119,6 +119,8 @@ struct CodeSet final {
class Process final : public Object {
public:
+ static constexpr std::size_t RANDOM_ENTROPY_SIZE = 4;
+
static SharedPtr<Process> Create(KernelCore& kernel, std::string&& name);
std::string GetTypeName() const override {
@@ -212,6 +214,11 @@ public:
total_process_running_time_ticks += ticks;
}
+ /// Gets 8 bytes of random data for svcGetInfo RandomEntropy
+ u64 GetRandomEntropy(std::size_t index) const {
+ return random_entropy.at(index);
+ }
+
/**
* Loads process-specifics configuration info with metadata provided
* by an executable.
@@ -251,7 +258,8 @@ public:
ResultVal<VAddr> HeapAllocate(VAddr target, u64 size, VMAPermission perms);
ResultCode HeapFree(VAddr target, u32 size);
- ResultCode MirrorMemory(VAddr dst_addr, VAddr src_addr, u64 size);
+ ResultCode MirrorMemory(VAddr dst_addr, VAddr src_addr, u64 size,
+ MemoryState state = MemoryState::Mapped);
ResultCode UnmapMemory(VAddr dst_addr, VAddr src_addr, u64 size);
@@ -292,17 +300,6 @@ private:
u32 allowed_thread_priority_mask = 0xFFFFFFFF;
u32 is_virtual_address_memory_enabled = 0;
- // Memory used to back the allocations in the regular heap. A single vector is used to cover
- // the entire virtual address space extents that bound the allocations, including any holes.
- // This makes deallocation and reallocation of holes fast and keeps process memory contiguous
- // in the emulator address space, allowing Memory::GetPointer to be reasonably safe.
- std::shared_ptr<std::vector<u8>> heap_memory;
-
- // The left/right bounds of the address space covered by heap_memory.
- VAddr heap_start = 0;
- VAddr heap_end = 0;
- u64 heap_used = 0;
-
/// The Thread Local Storage area is allocated as processes create threads,
/// each TLS area is 0x200 bytes, so one page (0x1000) is split up in 8 parts, and each part
/// holds the TLS for a specific thread. This vector contains which parts are in use for each
@@ -321,6 +318,9 @@ private:
/// Per-process handle table for storing created object handles in.
HandleTable handle_table;
+ /// Random values for svcGetInfo RandomEntropy
+ std::array<u64, RANDOM_ENTROPY_SIZE> random_entropy;
+
std::string name;
};
diff --git a/src/core/hle/kernel/resource_limit.cpp b/src/core/hle/kernel/resource_limit.cpp
index b253a680f..2f9695005 100644
--- a/src/core/hle/kernel/resource_limit.cpp
+++ b/src/core/hle/kernel/resource_limit.cpp
@@ -2,12 +2,16 @@
// Licensed under GPLv2 or any later version
// Refer to the license.txt file included.
-#include <cstring>
-#include "common/assert.h"
-#include "common/logging/log.h"
+#include "core/hle/kernel/errors.h"
#include "core/hle/kernel/resource_limit.h"
+#include "core/hle/result.h"
namespace Kernel {
+namespace {
+constexpr std::size_t ResourceTypeToIndex(ResourceType type) {
+ return static_cast<std::size_t>(type);
+}
+} // Anonymous namespace
ResourceLimit::ResourceLimit(KernelCore& kernel) : Object{kernel} {}
ResourceLimit::~ResourceLimit() = default;
@@ -19,59 +23,22 @@ SharedPtr<ResourceLimit> ResourceLimit::Create(KernelCore& kernel, std::string n
return resource_limit;
}
-s32 ResourceLimit::GetCurrentResourceValue(ResourceType resource) const {
- switch (resource) {
- case ResourceType::Commit:
- return current_commit;
- case ResourceType::Thread:
- return current_threads;
- case ResourceType::Event:
- return current_events;
- case ResourceType::Mutex:
- return current_mutexes;
- case ResourceType::Semaphore:
- return current_semaphores;
- case ResourceType::Timer:
- return current_timers;
- case ResourceType::SharedMemory:
- return current_shared_mems;
- case ResourceType::AddressArbiter:
- return current_address_arbiters;
- case ResourceType::CPUTime:
- return current_cpu_time;
- default:
- LOG_ERROR(Kernel, "Unknown resource type={:08X}", static_cast<u32>(resource));
- UNIMPLEMENTED();
- return 0;
- }
+s64 ResourceLimit::GetCurrentResourceValue(ResourceType resource) const {
+ return values.at(ResourceTypeToIndex(resource));
+}
+
+s64 ResourceLimit::GetMaxResourceValue(ResourceType resource) const {
+ return limits.at(ResourceTypeToIndex(resource));
}
-u32 ResourceLimit::GetMaxResourceValue(ResourceType resource) const {
- switch (resource) {
- case ResourceType::Priority:
- return max_priority;
- case ResourceType::Commit:
- return max_commit;
- case ResourceType::Thread:
- return max_threads;
- case ResourceType::Event:
- return max_events;
- case ResourceType::Mutex:
- return max_mutexes;
- case ResourceType::Semaphore:
- return max_semaphores;
- case ResourceType::Timer:
- return max_timers;
- case ResourceType::SharedMemory:
- return max_shared_mems;
- case ResourceType::AddressArbiter:
- return max_address_arbiters;
- case ResourceType::CPUTime:
- return max_cpu_time;
- default:
- LOG_ERROR(Kernel, "Unknown resource type={:08X}", static_cast<u32>(resource));
- UNIMPLEMENTED();
- return 0;
+ResultCode ResourceLimit::SetLimitValue(ResourceType resource, s64 value) {
+ const auto index = ResourceTypeToIndex(resource);
+
+ if (value < values[index]) {
+ return ERR_INVALID_STATE;
}
+
+ values[index] = value;
+ return RESULT_SUCCESS;
}
} // namespace Kernel
diff --git a/src/core/hle/kernel/resource_limit.h b/src/core/hle/kernel/resource_limit.h
index 219e49562..bec065543 100644
--- a/src/core/hle/kernel/resource_limit.h
+++ b/src/core/hle/kernel/resource_limit.h
@@ -4,31 +4,25 @@
#pragma once
+#include <array>
#include "common/common_types.h"
#include "core/hle/kernel/object.h"
+union ResultCode;
+
namespace Kernel {
class KernelCore;
-enum class ResourceLimitCategory : u8 {
- APPLICATION = 0,
- SYS_APPLET = 1,
- LIB_APPLET = 2,
- OTHER = 3
-};
-
enum class ResourceType {
- Priority = 0,
- Commit = 1,
- Thread = 2,
- Event = 3,
- Mutex = 4,
- Semaphore = 5,
- Timer = 6,
- SharedMemory = 7,
- AddressArbiter = 8,
- CPUTime = 9,
+ PhysicalMemory,
+ Threads,
+ Events,
+ TransferMemory,
+ Sessions,
+
+ // Used as a count, not an actual type.
+ ResourceTypeCount
};
class ResourceLimit final : public Object {
@@ -55,61 +49,51 @@ public:
* @param resource Requested resource type
* @returns The current value of the resource type
*/
- s32 GetCurrentResourceValue(ResourceType resource) const;
+ s64 GetCurrentResourceValue(ResourceType resource) const;
/**
* Gets the max value for the specified resource.
* @param resource Requested resource type
* @returns The max value of the resource type
*/
- u32 GetMaxResourceValue(ResourceType resource) const;
-
- /// Name of resource limit object.
- std::string name;
-
- /// Max thread priority that a process in this category can create
- s32 max_priority = 0;
-
- /// Max memory that processes in this category can use
- s32 max_commit = 0;
+ s64 GetMaxResourceValue(ResourceType resource) const;
- ///< Max number of objects that can be collectively created by the processes in this category
- s32 max_threads = 0;
- s32 max_events = 0;
- s32 max_mutexes = 0;
- s32 max_semaphores = 0;
- s32 max_timers = 0;
- s32 max_shared_mems = 0;
- s32 max_address_arbiters = 0;
+ /**
+ * Sets the limit value for a given resource type.
+ *
+ * @param resource The resource type to apply the limit to.
+ * @param value The limit to apply to the given resource type.
+ *
+ * @return A result code indicating if setting the limit value
+ * was successful or not.
+ *
+ * @note The supplied limit value *must* be greater than or equal to
+ * the current resource value for the given resource type,
+ * otherwise ERR_INVALID_STATE will be returned.
+ */
+ ResultCode SetLimitValue(ResourceType resource, s64 value);
- /// Max CPU time that the processes in this category can utilize
- s32 max_cpu_time = 0;
+private:
+ explicit ResourceLimit(KernelCore& kernel);
+ ~ResourceLimit() override;
- // TODO(Subv): Increment these in their respective Kernel::T::Create functions, keeping in mind
- // that APPLICATION resource limits should not be affected by the objects created by service
- // modules.
+ // TODO(Subv): Increment resource limit current values in their respective Kernel::T::Create
+ // functions
+ //
// Currently we have no way of distinguishing if a Create was called by the running application,
// or by a service module. Approach this once we have separated the service modules into their
// own processes
- /// Current memory that the processes in this category are using
- s32 current_commit = 0;
+ using ResourceArray =
+ std::array<s64, static_cast<std::size_t>(ResourceType::ResourceTypeCount)>;
- ///< Current number of objects among all processes in this category
- s32 current_threads = 0;
- s32 current_events = 0;
- s32 current_mutexes = 0;
- s32 current_semaphores = 0;
- s32 current_timers = 0;
- s32 current_shared_mems = 0;
- s32 current_address_arbiters = 0;
+ /// Maximum values a resource type may reach.
+ ResourceArray limits{};
+ /// Current resource limit values.
+ ResourceArray values{};
- /// Current CPU time that the processes in this category are utilizing
- s32 current_cpu_time = 0;
-
-private:
- explicit ResourceLimit(KernelCore& kernel);
- ~ResourceLimit() override;
+ /// Name of resource limit object.
+ std::string name;
};
} // namespace Kernel
diff --git a/src/core/hle/kernel/shared_memory.cpp b/src/core/hle/kernel/shared_memory.cpp
index a016a86b6..0494581f5 100644
--- a/src/core/hle/kernel/shared_memory.cpp
+++ b/src/core/hle/kernel/shared_memory.cpp
@@ -61,7 +61,7 @@ SharedPtr<SharedMemory> SharedMemory::Create(KernelCore& kernel, SharedPtr<Proce
}
SharedPtr<SharedMemory> SharedMemory::CreateForApplet(
- KernelCore& kernel, std::shared_ptr<std::vector<u8>> heap_block, u32 offset, u32 size,
+ KernelCore& kernel, std::shared_ptr<std::vector<u8>> heap_block, std::size_t offset, u64 size,
MemoryPermission permissions, MemoryPermission other_permissions, std::string name) {
SharedPtr<SharedMemory> shared_memory(new SharedMemory(kernel));
@@ -78,10 +78,10 @@ SharedPtr<SharedMemory> SharedMemory::CreateForApplet(
return shared_memory;
}
-ResultCode SharedMemory::Map(Process* target_process, VAddr address, MemoryPermission permissions,
+ResultCode SharedMemory::Map(Process& target_process, VAddr address, MemoryPermission permissions,
MemoryPermission other_permissions) {
const MemoryPermission own_other_permissions =
- target_process == owner_process ? this->permissions : this->other_permissions;
+ &target_process == owner_process ? this->permissions : this->other_permissions;
// Automatically allocated memory blocks can only be mapped with other_permissions = DontCare
if (base_address == 0 && other_permissions != MemoryPermission::DontCare) {
@@ -106,7 +106,7 @@ ResultCode SharedMemory::Map(Process* target_process, VAddr address, MemoryPermi
VAddr target_address = address;
// Map the memory block into the target process
- auto result = target_process->VMManager().MapMemoryBlock(
+ auto result = target_process.VMManager().MapMemoryBlock(
target_address, backing_block, backing_block_offset, size, MemoryState::Shared);
if (result.Failed()) {
LOG_ERROR(
@@ -116,14 +116,14 @@ ResultCode SharedMemory::Map(Process* target_process, VAddr address, MemoryPermi
return result.Code();
}
- return target_process->VMManager().ReprotectRange(target_address, size,
- ConvertPermissions(permissions));
+ return target_process.VMManager().ReprotectRange(target_address, size,
+ ConvertPermissions(permissions));
}
-ResultCode SharedMemory::Unmap(Process* target_process, VAddr address) {
+ResultCode SharedMemory::Unmap(Process& target_process, VAddr address) {
// TODO(Subv): Verify what happens if the application tries to unmap an address that is not
// mapped to a SharedMemory.
- return target_process->VMManager().UnmapRange(address, size);
+ return target_process.VMManager().UnmapRange(address, size);
}
VMAPermission SharedMemory::ConvertPermissions(MemoryPermission permission) {
@@ -132,7 +132,11 @@ VMAPermission SharedMemory::ConvertPermissions(MemoryPermission permission) {
return static_cast<VMAPermission>(masked_permissions);
}
-u8* SharedMemory::GetPointer(u32 offset) {
+u8* SharedMemory::GetPointer(std::size_t offset) {
+ return backing_block->data() + backing_block_offset + offset;
+}
+
+const u8* SharedMemory::GetPointer(std::size_t offset) const {
return backing_block->data() + backing_block_offset + offset;
}
diff --git a/src/core/hle/kernel/shared_memory.h b/src/core/hle/kernel/shared_memory.h
index 2c06bb7ce..0b48db699 100644
--- a/src/core/hle/kernel/shared_memory.h
+++ b/src/core/hle/kernel/shared_memory.h
@@ -64,7 +64,7 @@ public:
*/
static SharedPtr<SharedMemory> CreateForApplet(KernelCore& kernel,
std::shared_ptr<std::vector<u8>> heap_block,
- u32 offset, u32 size,
+ std::size_t offset, u64 size,
MemoryPermission permissions,
MemoryPermission other_permissions,
std::string name = "Unknown Applet");
@@ -81,6 +81,11 @@ public:
return HANDLE_TYPE;
}
+ /// Gets the size of the underlying memory block in bytes.
+ u64 GetSize() const {
+ return size;
+ }
+
/**
* Converts the specified MemoryPermission into the equivalent VMAPermission.
* @param permission The MemoryPermission to convert.
@@ -94,44 +99,51 @@ public:
* @param permissions Memory block map permissions (specified by SVC field)
* @param other_permissions Memory block map other permissions (specified by SVC field)
*/
- ResultCode Map(Process* target_process, VAddr address, MemoryPermission permissions,
+ ResultCode Map(Process& target_process, VAddr address, MemoryPermission permissions,
MemoryPermission other_permissions);
/**
* Unmaps a shared memory block from the specified address in system memory
- * @param target_process Process from which to umap the memory block.
+ * @param target_process Process from which to unmap the memory block.
* @param address Address in system memory where the shared memory block is mapped
* @return Result code of the unmap operation
*/
- ResultCode Unmap(Process* target_process, VAddr address);
+ ResultCode Unmap(Process& target_process, VAddr address);
/**
* Gets a pointer to the shared memory block
* @param offset Offset from the start of the shared memory block to get pointer
- * @return Pointer to the shared memory block from the specified offset
+ * @return A pointer to the shared memory block from the specified offset
*/
- u8* GetPointer(u32 offset = 0);
+ u8* GetPointer(std::size_t offset = 0);
+
+ /**
+ * Gets a constant pointer to the shared memory block
+ * @param offset Offset from the start of the shared memory block to get pointer
+ * @return A constant pointer to the shared memory block from the specified offset
+ */
+ const u8* GetPointer(std::size_t offset = 0) const;
+
+private:
+ explicit SharedMemory(KernelCore& kernel);
+ ~SharedMemory() override;
- /// Process that created this shared memory block.
- SharedPtr<Process> owner_process;
- /// Address of shared memory block in the owner process if specified.
- VAddr base_address;
/// Backing memory for this shared memory block.
std::shared_ptr<std::vector<u8>> backing_block;
/// Offset into the backing block for this shared memory.
- std::size_t backing_block_offset;
+ std::size_t backing_block_offset = 0;
/// Size of the memory block. Page-aligned.
- u64 size;
+ u64 size = 0;
/// Permission restrictions applied to the process which created the block.
- MemoryPermission permissions;
+ MemoryPermission permissions{};
/// Permission restrictions applied to other processes mapping the block.
- MemoryPermission other_permissions;
+ MemoryPermission other_permissions{};
+ /// Process that created this shared memory block.
+ SharedPtr<Process> owner_process;
+ /// Address of shared memory block in the owner process if specified.
+ VAddr base_address = 0;
/// Name of shared memory object.
std::string name;
-
-private:
- explicit SharedMemory(KernelCore& kernel);
- ~SharedMemory() override;
};
} // namespace Kernel
diff --git a/src/core/hle/kernel/svc.cpp b/src/core/hle/kernel/svc.cpp
index c7c579aaf..b8b6b4d49 100644
--- a/src/core/hle/kernel/svc.cpp
+++ b/src/core/hle/kernel/svc.cpp
@@ -34,6 +34,7 @@
#include "core/hle/lock.h"
#include "core/hle/result.h"
#include "core/hle/service/service.h"
+#include "core/settings.h"
namespace Kernel {
namespace {
@@ -122,6 +123,48 @@ static ResultCode SetHeapSize(VAddr* heap_addr, u64 heap_size) {
return RESULT_SUCCESS;
}
+static ResultCode SetMemoryPermission(VAddr addr, u64 size, u32 prot) {
+ LOG_TRACE(Kernel_SVC, "called, addr=0x{:X}, size=0x{:X}, prot=0x{:X}", addr, size, prot);
+
+ if (!Common::Is4KBAligned(addr)) {
+ return ERR_INVALID_ADDRESS;
+ }
+
+ if (size == 0 || !Common::Is4KBAligned(size)) {
+ return ERR_INVALID_SIZE;
+ }
+
+ if (!IsValidAddressRange(addr, size)) {
+ return ERR_INVALID_ADDRESS_STATE;
+ }
+
+ const auto permission = static_cast<MemoryPermission>(prot);
+ if (permission != MemoryPermission::None && permission != MemoryPermission::Read &&
+ permission != MemoryPermission::ReadWrite) {
+ return ERR_INVALID_MEMORY_PERMISSIONS;
+ }
+
+ auto* const current_process = Core::CurrentProcess();
+ auto& vm_manager = current_process->VMManager();
+
+ if (!IsInsideAddressSpace(vm_manager, addr, size)) {
+ return ERR_INVALID_ADDRESS_STATE;
+ }
+
+ const VMManager::VMAHandle iter = vm_manager.FindVMA(addr);
+ if (iter == vm_manager.vma_map.end()) {
+ return ERR_INVALID_ADDRESS_STATE;
+ }
+
+ LOG_WARNING(Kernel_SVC, "Uniformity check on protected memory is not implemented.");
+ // TODO: Performs a uniformity check to make sure only protected memory is changed (it doesn't
+ // make sense to allow changing permissions on kernel memory itself, etc).
+
+ const auto converted_permissions = SharedMemory::ConvertPermissions(permission);
+
+ return vm_manager.ReprotectRange(addr, size, converted_permissions);
+}
+
static ResultCode SetMemoryAttribute(VAddr addr, u64 size, u32 state0, u32 state1) {
LOG_WARNING(Kernel_SVC,
"(STUBBED) called, addr=0x{:X}, size=0x{:X}, state0=0x{:X}, state1=0x{:X}", addr,
@@ -171,7 +214,7 @@ static ResultCode ConnectToNamedPort(Handle* out_handle, VAddr port_name_address
// Read 1 char beyond the max allowed port name to detect names that are too long.
std::string port_name = Memory::ReadCString(port_name_address, PortNameMaxLength + 1);
if (port_name.size() > PortNameMaxLength) {
- return ERR_PORT_NAME_TOO_LONG;
+ return ERR_OUT_OF_RANGE;
}
LOG_TRACE(Kernel_SVC, "called port_name={}", port_name);
@@ -267,8 +310,9 @@ static ResultCode WaitSynchronization(Handle* index, VAddr handles_address, u64
static constexpr u64 MaxHandles = 0x40;
- if (handle_count > MaxHandles)
- return ResultCode(ErrorModule::Kernel, ErrCodes::TooLarge);
+ if (handle_count > MaxHandles) {
+ return ERR_OUT_OF_RANGE;
+ }
auto* const thread = GetCurrentThread();
@@ -333,8 +377,7 @@ static ResultCode CancelSynchronization(Handle thread_handle) {
}
ASSERT(thread->GetStatus() == ThreadStatus::WaitSynchAny);
- thread->SetWaitSynchronizationResult(
- ResultCode(ErrorModule::Kernel, ErrCodes::SynchronizationCanceled));
+ thread->SetWaitSynchronizationResult(ERR_SYNCHRONIZATION_CANCELED);
thread->ResumeFromWait();
return RESULT_SUCCESS;
}
@@ -395,16 +438,42 @@ struct BreakReason {
/// Break program execution
static void Break(u32 reason, u64 info1, u64 info2) {
BreakReason break_reason{reason};
+ bool has_dumped_buffer{};
+
+ const auto handle_debug_buffer = [&](VAddr addr, u64 sz) {
+ if (sz == 0 || addr == 0 || has_dumped_buffer) {
+ return;
+ }
+ // This typically is an error code so we're going to assume this is the case
+ if (sz == sizeof(u32)) {
+ LOG_CRITICAL(Debug_Emulated, "debug_buffer_err_code={:X}", Memory::Read32(addr));
+ } else {
+ // We don't know what's in here so we'll hexdump it
+ std::vector<u8> debug_buffer(sz);
+ Memory::ReadBlock(addr, debug_buffer.data(), sz);
+ std::string hexdump;
+ for (std::size_t i = 0; i < debug_buffer.size(); i++) {
+ hexdump += fmt::format("{:02X} ", debug_buffer[i]);
+ if (i != 0 && i % 16 == 0) {
+ hexdump += '\n';
+ }
+ }
+ LOG_CRITICAL(Debug_Emulated, "debug_buffer=\n{}", hexdump);
+ }
+ has_dumped_buffer = true;
+ };
switch (break_reason.break_type) {
case BreakType::Panic:
LOG_CRITICAL(Debug_Emulated, "Signalling debugger, PANIC! info1=0x{:016X}, info2=0x{:016X}",
info1, info2);
+ handle_debug_buffer(info1, info2);
break;
case BreakType::AssertionFailed:
LOG_CRITICAL(Debug_Emulated,
"Signalling debugger, Assertion failed! info1=0x{:016X}, info2=0x{:016X}",
info1, info2);
+ handle_debug_buffer(info1, info2);
break;
case BreakType::PreNROLoad:
LOG_WARNING(
@@ -433,6 +502,7 @@ static void Break(u32 reason, u64 info1, u64 info2) {
Debug_Emulated,
"Signalling debugger, Unknown break reason {}, info1=0x{:016X}, info2=0x{:016X}",
static_cast<u32>(break_reason.break_type.Value()), info1, info2);
+ handle_debug_buffer(info1, info2);
break;
}
@@ -441,6 +511,7 @@ static void Break(u32 reason, u64 info1, u64 info2) {
Debug_Emulated,
"Emulated program broke execution! reason=0x{:016X}, info1=0x{:016X}, info2=0x{:016X}",
reason, info1, info2);
+ handle_debug_buffer(info1, info2);
ASSERT(false);
Core::CurrentProcess()->PrepareForTermination();
@@ -530,7 +601,16 @@ static ResultCode GetInfo(u64* result, u64 info_id, u64 handle, u64 info_sub_id)
*result = 0;
break;
case GetInfoType::RandomEntropy:
- *result = 0;
+ if (handle != 0) {
+ return ERR_INVALID_HANDLE;
+ }
+
+ if (info_sub_id >= Process::RANDOM_ENTROPY_SIZE) {
+ return ERR_INVALID_COMBINATION;
+ }
+
+ *result = current_process->GetRandomEntropy(info_sub_id);
+ return RESULT_SUCCESS;
break;
case GetInfoType::ASLRRegionBaseAddr:
*result = vm_manager.GetASLRRegionBaseAddress();
@@ -563,7 +643,7 @@ static ResultCode GetInfo(u64* result, u64 info_id, u64 handle, u64 info_sub_id)
case GetInfoType::ThreadTickCount: {
constexpr u64 num_cpus = 4;
if (info_sub_id != 0xFFFFFFFFFFFFFFFF && info_sub_id >= num_cpus) {
- return ERR_INVALID_COMBINATION_KERNEL;
+ return ERR_INVALID_COMBINATION;
}
const auto thread =
@@ -656,13 +736,6 @@ static ResultCode SetThreadPriority(Handle handle, u32 priority) {
const auto* const current_process = Core::CurrentProcess();
- // Note: The kernel uses the current process's resource limit instead of
- // the one from the thread owner's resource limit.
- const ResourceLimit& resource_limit = current_process->GetResourceLimit();
- if (resource_limit.GetMaxResourceValue(ResourceType::Priority) > priority) {
- return ERR_INVALID_THREAD_PRIORITY;
- }
-
SharedPtr<Thread> thread = current_process->GetHandleTable().Get<Thread>(handle);
if (!thread) {
return ERR_INVALID_HANDLE;
@@ -716,7 +789,7 @@ static ResultCode MapSharedMemory(Handle shared_memory_handle, VAddr addr, u64 s
return ERR_INVALID_MEMORY_RANGE;
}
- return shared_memory->Map(current_process, addr, permissions_type, MemoryPermission::DontCare);
+ return shared_memory->Map(*current_process, addr, permissions_type, MemoryPermission::DontCare);
}
static ResultCode UnmapSharedMemory(Handle shared_memory_handle, VAddr addr, u64 size) {
@@ -746,7 +819,7 @@ static ResultCode UnmapSharedMemory(Handle shared_memory_handle, VAddr addr, u64
return ERR_INVALID_MEMORY_RANGE;
}
- return shared_memory->Unmap(current_process, addr);
+ return shared_memory->Unmap(*current_process, addr);
}
/// Query process memory
@@ -805,10 +878,6 @@ static ResultCode CreateThread(Handle* out_handle, VAddr entry_point, u64 arg, V
}
auto* const current_process = Core::CurrentProcess();
- const ResourceLimit& resource_limit = current_process->GetResourceLimit();
- if (resource_limit.GetMaxResourceValue(ResourceType::Priority) > priority) {
- return ERR_INVALID_THREAD_PRIORITY;
- }
if (processor_id == THREADPROCESSORID_DEFAULT) {
// Set the target CPU to the one specified in the process' exheader.
@@ -1101,7 +1170,7 @@ static ResultCode CloseHandle(Handle handle) {
/// Reset an event
static ResultCode ResetSignal(Handle handle) {
- LOG_WARNING(Kernel_SVC, "(STUBBED) called handle 0x{:08X}", handle);
+ LOG_DEBUG(Kernel_SVC, "called handle 0x{:08X}", handle);
const auto& handle_table = Core::CurrentProcess()->GetHandleTable();
auto event = handle_table.Get<Event>(handle);
@@ -1114,9 +1183,39 @@ static ResultCode ResetSignal(Handle handle) {
/// Creates a TransferMemory object
static ResultCode CreateTransferMemory(Handle* handle, VAddr addr, u64 size, u32 permissions) {
- LOG_WARNING(Kernel_SVC, "(STUBBED) called addr=0x{:X}, size=0x{:X}, perms=0x{:08X}", addr, size,
- permissions);
- *handle = 0;
+ LOG_DEBUG(Kernel_SVC, "called addr=0x{:X}, size=0x{:X}, perms=0x{:08X}", addr, size,
+ permissions);
+
+ if (!Common::Is4KBAligned(addr)) {
+ LOG_ERROR(Kernel_SVC, "Address ({:016X}) is not page aligned!", addr);
+ return ERR_INVALID_ADDRESS;
+ }
+
+ if (!Common::Is4KBAligned(size) || size == 0) {
+ LOG_ERROR(Kernel_SVC, "Size ({:016X}) is not page aligned or equal to zero!", size);
+ return ERR_INVALID_ADDRESS;
+ }
+
+ if (!IsValidAddressRange(addr, size)) {
+ LOG_ERROR(Kernel_SVC, "Address and size cause overflow! (address={:016X}, size={:016X})",
+ addr, size);
+ return ERR_INVALID_ADDRESS_STATE;
+ }
+
+ const auto perms = static_cast<MemoryPermission>(permissions);
+ if (perms != MemoryPermission::None && perms != MemoryPermission::Read &&
+ perms != MemoryPermission::ReadWrite) {
+ LOG_ERROR(Kernel_SVC, "Invalid memory permissions for transfer memory! (perms={:08X})",
+ permissions);
+ return ERR_INVALID_MEMORY_PERMISSIONS;
+ }
+
+ auto& kernel = Core::System::GetInstance().Kernel();
+ auto& handle_table = Core::CurrentProcess()->GetHandleTable();
+ const auto shared_mem_handle = SharedMemory::Create(
+ kernel, handle_table.Get<Process>(CurrentProcess), size, perms, perms, addr);
+
+ CASCADE_RESULT(*handle, handle_table.Create(shared_mem_handle));
return RESULT_SUCCESS;
}
@@ -1156,7 +1255,7 @@ static ResultCode SetThreadCoreMask(Handle thread_handle, u32 core, u64 mask) {
}
if (mask == 0) {
- return ResultCode(ErrorModule::Kernel, ErrCodes::InvalidCombination);
+ return ERR_INVALID_COMBINATION;
}
/// This value is used to only change the affinity mask without changing the current ideal core.
@@ -1165,12 +1264,12 @@ static ResultCode SetThreadCoreMask(Handle thread_handle, u32 core, u64 mask) {
if (core == OnlyChangeMask) {
core = thread->GetIdealCore();
} else if (core >= Core::NUM_CPU_CORES && core != static_cast<u32>(-1)) {
- return ResultCode(ErrorModule::Kernel, ErrCodes::InvalidProcessorId);
+ return ERR_INVALID_PROCESSOR_ID;
}
// Error out if the input core isn't enabled in the input mask.
if (core < Core::NUM_CPU_CORES && (mask & (1ull << core)) == 0) {
- return ResultCode(ErrorModule::Kernel, ErrCodes::InvalidCombination);
+ return ERR_INVALID_COMBINATION;
}
thread->ChangeCore(core, mask);
@@ -1259,7 +1358,7 @@ struct FunctionDef {
static const FunctionDef SVC_Table[] = {
{0x00, nullptr, "Unknown"},
{0x01, SvcWrap<SetHeapSize>, "SetHeapSize"},
- {0x02, nullptr, "SetMemoryPermission"},
+ {0x02, SvcWrap<SetMemoryPermission>, "SetMemoryPermission"},
{0x03, SvcWrap<SetMemoryAttribute>, "SetMemoryAttribute"},
{0x04, SvcWrap<MapMemory>, "MapMemory"},
{0x05, SvcWrap<UnmapMemory>, "UnmapMemory"},
diff --git a/src/core/hle/kernel/svc_wrap.h b/src/core/hle/kernel/svc_wrap.h
index b09753c80..233a99fb0 100644
--- a/src/core/hle/kernel/svc_wrap.h
+++ b/src/core/hle/kernel/svc_wrap.h
@@ -121,6 +121,11 @@ void SvcWrap() {
FuncReturn(func(Param(0), Param(1), Param(2)).raw);
}
+template <ResultCode func(u64, u64, u32)>
+void SvcWrap() {
+ FuncReturn(func(Param(0), Param(1), static_cast<u32>(Param(2))).raw);
+}
+
template <ResultCode func(u32, u64, u64, u32)>
void SvcWrap() {
FuncReturn(
diff --git a/src/core/hle/kernel/thread.cpp b/src/core/hle/kernel/thread.cpp
index dd5cd9ced..4ffb76818 100644
--- a/src/core/hle/kernel/thread.cpp
+++ b/src/core/hle/kernel/thread.cpp
@@ -142,36 +142,7 @@ void Thread::ResumeFromWait() {
status = ThreadStatus::Ready;
- std::optional<s32> new_processor_id = GetNextProcessorId(affinity_mask);
- if (!new_processor_id) {
- new_processor_id = processor_id;
- }
- if (ideal_core != -1 &&
- Core::System::GetInstance().Scheduler(ideal_core).GetCurrentThread() == nullptr) {
- new_processor_id = ideal_core;
- }
-
- ASSERT(*new_processor_id < 4);
-
- // Add thread to new core's scheduler
- auto* next_scheduler = &Core::System::GetInstance().Scheduler(*new_processor_id);
-
- if (*new_processor_id != processor_id) {
- // Remove thread from previous core's scheduler
- scheduler->RemoveThread(this);
- next_scheduler->AddThread(this, current_priority);
- }
-
- processor_id = *new_processor_id;
-
- // If the thread was ready, unschedule from the previous core and schedule on the new core
- scheduler->UnscheduleThread(this, current_priority);
- next_scheduler->ScheduleThread(this, current_priority);
-
- // Change thread's scheduler
- scheduler = next_scheduler;
-
- Core::System::GetInstance().CpuCore(processor_id).PrepareReschedule();
+ ChangeScheduler();
}
/**
@@ -364,42 +335,45 @@ void Thread::UpdatePriority() {
void Thread::ChangeCore(u32 core, u64 mask) {
ideal_core = core;
affinity_mask = mask;
+ ChangeScheduler();
+}
+void Thread::ChangeScheduler() {
if (status != ThreadStatus::Ready) {
return;
}
+ auto& system = Core::System::GetInstance();
std::optional<s32> new_processor_id{GetNextProcessorId(affinity_mask)};
if (!new_processor_id) {
new_processor_id = processor_id;
}
- if (ideal_core != -1 &&
- Core::System::GetInstance().Scheduler(ideal_core).GetCurrentThread() == nullptr) {
+ if (ideal_core != -1 && system.Scheduler(ideal_core).GetCurrentThread() == nullptr) {
new_processor_id = ideal_core;
}
ASSERT(*new_processor_id < 4);
// Add thread to new core's scheduler
- auto* next_scheduler = &Core::System::GetInstance().Scheduler(*new_processor_id);
+ auto& next_scheduler = system.Scheduler(*new_processor_id);
if (*new_processor_id != processor_id) {
// Remove thread from previous core's scheduler
scheduler->RemoveThread(this);
- next_scheduler->AddThread(this, current_priority);
+ next_scheduler.AddThread(this, current_priority);
}
processor_id = *new_processor_id;
// If the thread was ready, unschedule from the previous core and schedule on the new core
scheduler->UnscheduleThread(this, current_priority);
- next_scheduler->ScheduleThread(this, current_priority);
+ next_scheduler.ScheduleThread(this, current_priority);
// Change thread's scheduler
- scheduler = next_scheduler;
+ scheduler = &next_scheduler;
- Core::System::GetInstance().CpuCore(processor_id).PrepareReschedule();
+ system.CpuCore(processor_id).PrepareReschedule();
}
bool Thread::AllWaitObjectsReady() {
diff --git a/src/core/hle/kernel/thread.h b/src/core/hle/kernel/thread.h
index 4a6e11239..d384d50db 100644
--- a/src/core/hle/kernel/thread.h
+++ b/src/core/hle/kernel/thread.h
@@ -374,6 +374,8 @@ private:
explicit Thread(KernelCore& kernel);
~Thread() override;
+ void ChangeScheduler();
+
Core::ARM_Interface::ThreadContext context{};
u32 thread_id = 0;
diff --git a/src/core/hle/kernel/vm_manager.cpp b/src/core/hle/kernel/vm_manager.cpp
index 1a92c8f70..100f8f6bf 100644
--- a/src/core/hle/kernel/vm_manager.cpp
+++ b/src/core/hle/kernel/vm_manager.cpp
@@ -243,6 +243,85 @@ ResultCode VMManager::ReprotectRange(VAddr target, u64 size, VMAPermission new_p
return RESULT_SUCCESS;
}
+ResultVal<VAddr> VMManager::HeapAllocate(VAddr target, u64 size, VMAPermission perms) {
+ if (target < GetHeapRegionBaseAddress() || target + size > GetHeapRegionEndAddress() ||
+ target + size < target) {
+ return ERR_INVALID_ADDRESS;
+ }
+
+ if (heap_memory == nullptr) {
+ // Initialize heap
+ heap_memory = std::make_shared<std::vector<u8>>();
+ heap_start = heap_end = target;
+ } else {
+ UnmapRange(heap_start, heap_end - heap_start);
+ }
+
+ // If necessary, expand backing vector to cover new heap extents.
+ if (target < heap_start) {
+ heap_memory->insert(begin(*heap_memory), heap_start - target, 0);
+ heap_start = target;
+ RefreshMemoryBlockMappings(heap_memory.get());
+ }
+ if (target + size > heap_end) {
+ heap_memory->insert(end(*heap_memory), (target + size) - heap_end, 0);
+ heap_end = target + size;
+ RefreshMemoryBlockMappings(heap_memory.get());
+ }
+ ASSERT(heap_end - heap_start == heap_memory->size());
+
+ CASCADE_RESULT(auto vma, MapMemoryBlock(target, heap_memory, target - heap_start, size,
+ MemoryState::Heap));
+ Reprotect(vma, perms);
+
+ heap_used = size;
+
+ return MakeResult<VAddr>(heap_end - size);
+}
+
+ResultCode VMManager::HeapFree(VAddr target, u64 size) {
+ if (target < GetHeapRegionBaseAddress() || target + size > GetHeapRegionEndAddress() ||
+ target + size < target) {
+ return ERR_INVALID_ADDRESS;
+ }
+
+ if (size == 0) {
+ return RESULT_SUCCESS;
+ }
+
+ const ResultCode result = UnmapRange(target, size);
+ if (result.IsError()) {
+ return result;
+ }
+
+ heap_used -= size;
+ return RESULT_SUCCESS;
+}
+
+ResultCode VMManager::MirrorMemory(VAddr dst_addr, VAddr src_addr, u64 size, MemoryState state) {
+ const auto vma = FindVMA(src_addr);
+
+ ASSERT_MSG(vma != vma_map.end(), "Invalid memory address");
+ ASSERT_MSG(vma->second.backing_block, "Backing block doesn't exist for address");
+
+ // The returned VMA might be a bigger one encompassing the desired address.
+ const auto vma_offset = src_addr - vma->first;
+ ASSERT_MSG(vma_offset + size <= vma->second.size,
+ "Shared memory exceeds bounds of mapped block");
+
+ const std::shared_ptr<std::vector<u8>>& backing_block = vma->second.backing_block;
+ const std::size_t backing_block_offset = vma->second.offset + vma_offset;
+
+ CASCADE_RESULT(auto new_vma,
+ MapMemoryBlock(dst_addr, backing_block, backing_block_offset, size, state));
+ // Protect mirror with permissions from old region
+ Reprotect(new_vma, vma->second.permissions);
+ // Remove permissions from old region
+ Reprotect(vma, VMAPermission::None);
+
+ return RESULT_SUCCESS;
+}
+
void VMManager::RefreshMemoryBlockMappings(const std::vector<u8>* block) {
// If this ever proves to have a noticeable performance impact, allow users of the function to
// specify a specific range of addresses to limit the scan to.
@@ -495,8 +574,7 @@ u64 VMManager::GetTotalMemoryUsage() const {
}
u64 VMManager::GetTotalHeapUsage() const {
- LOG_WARNING(Kernel, "(STUBBED) called");
- return 0x0;
+ return heap_used;
}
VAddr VMManager::GetAddressSpaceBaseAddress() const {
diff --git a/src/core/hle/kernel/vm_manager.h b/src/core/hle/kernel/vm_manager.h
index 2447cbb8f..d522404fe 100644
--- a/src/core/hle/kernel/vm_manager.h
+++ b/src/core/hle/kernel/vm_manager.h
@@ -186,6 +186,12 @@ public:
/// Changes the permissions of a range of addresses, splitting VMAs as necessary.
ResultCode ReprotectRange(VAddr target, u64 size, VMAPermission new_perms);
+ ResultVal<VAddr> HeapAllocate(VAddr target, u64 size, VMAPermission perms);
+ ResultCode HeapFree(VAddr target, u64 size);
+
+ ResultCode MirrorMemory(VAddr dst_addr, VAddr src_addr, u64 size,
+ MemoryState state = MemoryState::Mapped);
+
/**
* Scans all VMAs and updates the page table range of any that use the given vector as backing
* memory. This should be called after any operation that causes reallocation of the vector.
@@ -343,5 +349,15 @@ private:
VAddr tls_io_region_base = 0;
VAddr tls_io_region_end = 0;
+
+ // Memory used to back the allocations in the regular heap. A single vector is used to cover
+ // the entire virtual address space extents that bound the allocations, including any holes.
+ // This makes deallocation and reallocation of holes fast and keeps process memory contiguous
+ // in the emulator address space, allowing Memory::GetPointer to be reasonably safe.
+ std::shared_ptr<std::vector<u8>> heap_memory;
+ // The left/right bounds of the address space covered by heap_memory.
+ VAddr heap_start = 0;
+ VAddr heap_end = 0;
+ u64 heap_used = 0;
};
} // namespace Kernel
diff --git a/src/core/hle/result.h b/src/core/hle/result.h
index c6b18cfba..bfb77cc31 100644
--- a/src/core/hle/result.h
+++ b/src/core/hle/result.h
@@ -19,8 +19,6 @@
enum class ErrorDescription : u32 {
Success = 0,
RemoteProcessDead = 301,
- InvalidOffset = 6061,
- InvalidLength = 6062,
};
/**
diff --git a/src/core/hle/service/acc/acc.cpp b/src/core/hle/service/acc/acc.cpp
index c6437a671..c629f9357 100644
--- a/src/core/hle/service/acc/acc.cpp
+++ b/src/core/hle/service/acc/acc.cpp
@@ -242,6 +242,30 @@ void Module::Interface::GetBaasAccountManagerForApplication(Kernel::HLERequestCo
LOG_DEBUG(Service_ACC, "called");
}
+void Module::Interface::TrySelectUserWithoutInteraction(Kernel::HLERequestContext& ctx) {
+ LOG_DEBUG(Service_ACC, "called");
+ // A u8 is passed into this function which we can safely ignore. It's to determine if we have
+ // access to use the network or not by the looks of it
+ IPC::ResponseBuilder rb{ctx, 6};
+ if (profile_manager->GetUserCount() != 1) {
+ rb.Push(RESULT_SUCCESS);
+ rb.PushRaw<u128>(INVALID_UUID);
+ return;
+ }
+
+ const auto user_list = profile_manager->GetAllUsers();
+ if (std::all_of(user_list.begin(), user_list.end(),
+ [](const auto& user) { return user.uuid == INVALID_UUID; })) {
+ rb.Push(ResultCode(-1)); // TODO(ogniK): Find the correct error code
+ rb.PushRaw<u128>(INVALID_UUID);
+ return;
+ }
+
+ // Select the first user we have
+ rb.Push(RESULT_SUCCESS);
+ rb.PushRaw<u128>(profile_manager->GetUser(0)->uuid);
+}
+
Module::Interface::Interface(std::shared_ptr<Module> module,
std::shared_ptr<ProfileManager> profile_manager, const char* name)
: ServiceFramework(name), module(std::move(module)),
diff --git a/src/core/hle/service/acc/acc.h b/src/core/hle/service/acc/acc.h
index c7ed74351..89b2104fa 100644
--- a/src/core/hle/service/acc/acc.h
+++ b/src/core/hle/service/acc/acc.h
@@ -27,6 +27,7 @@ public:
void InitializeApplicationInfo(Kernel::HLERequestContext& ctx);
void GetBaasAccountManagerForApplication(Kernel::HLERequestContext& ctx);
void IsUserRegistrationRequestPermitted(Kernel::HLERequestContext& ctx);
+ void TrySelectUserWithoutInteraction(Kernel::HLERequestContext& ctx);
protected:
std::shared_ptr<Module> module;
diff --git a/src/core/hle/service/acc/acc_su.cpp b/src/core/hle/service/acc/acc_su.cpp
index ad455c3a7..5e2030355 100644
--- a/src/core/hle/service/acc/acc_su.cpp
+++ b/src/core/hle/service/acc/acc_su.cpp
@@ -17,7 +17,7 @@ ACC_SU::ACC_SU(std::shared_ptr<Module> module, std::shared_ptr<ProfileManager> p
{5, &ACC_SU::GetProfile, "GetProfile"},
{6, nullptr, "GetProfileDigest"},
{50, &ACC_SU::IsUserRegistrationRequestPermitted, "IsUserRegistrationRequestPermitted"},
- {51, nullptr, "TrySelectUserWithoutInteraction"},
+ {51, &ACC_SU::TrySelectUserWithoutInteraction, "TrySelectUserWithoutInteraction"},
{60, nullptr, "ListOpenContextStoredUsers"},
{100, nullptr, "GetUserRegistrationNotifier"},
{101, nullptr, "GetUserStateChangeNotifier"},
diff --git a/src/core/hle/service/acc/acc_u0.cpp b/src/core/hle/service/acc/acc_u0.cpp
index 72d4adf35..a4d705b45 100644
--- a/src/core/hle/service/acc/acc_u0.cpp
+++ b/src/core/hle/service/acc/acc_u0.cpp
@@ -17,7 +17,7 @@ ACC_U0::ACC_U0(std::shared_ptr<Module> module, std::shared_ptr<ProfileManager> p
{5, &ACC_U0::GetProfile, "GetProfile"},
{6, nullptr, "GetProfileDigest"},
{50, &ACC_U0::IsUserRegistrationRequestPermitted, "IsUserRegistrationRequestPermitted"},
- {51, nullptr, "TrySelectUserWithoutInteraction"},
+ {51, &ACC_U0::TrySelectUserWithoutInteraction, "TrySelectUserWithoutInteraction"},
{60, nullptr, "ListOpenContextStoredUsers"},
{100, &ACC_U0::InitializeApplicationInfo, "InitializeApplicationInfo"},
{101, &ACC_U0::GetBaasAccountManagerForApplication, "GetBaasAccountManagerForApplication"},
diff --git a/src/core/hle/service/acc/acc_u1.cpp b/src/core/hle/service/acc/acc_u1.cpp
index d480f08e5..8fffc93b5 100644
--- a/src/core/hle/service/acc/acc_u1.cpp
+++ b/src/core/hle/service/acc/acc_u1.cpp
@@ -17,7 +17,7 @@ ACC_U1::ACC_U1(std::shared_ptr<Module> module, std::shared_ptr<ProfileManager> p
{5, &ACC_U1::GetProfile, "GetProfile"},
{6, nullptr, "GetProfileDigest"},
{50, &ACC_U1::IsUserRegistrationRequestPermitted, "IsUserRegistrationRequestPermitted"},
- {51, nullptr, "TrySelectUserWithoutInteraction"},
+ {51, &ACC_U1::TrySelectUserWithoutInteraction, "TrySelectUserWithoutInteraction"},
{60, nullptr, "ListOpenContextStoredUsers"},
{100, nullptr, "GetUserRegistrationNotifier"},
{101, nullptr, "GetUserStateChangeNotifier"},
diff --git a/src/core/hle/service/acc/profile_manager.cpp b/src/core/hle/service/acc/profile_manager.cpp
index c08394e4c..968263846 100644
--- a/src/core/hle/service/acc/profile_manager.cpp
+++ b/src/core/hle/service/acc/profile_manager.cpp
@@ -2,8 +2,11 @@
// Licensed under GPLv2 or any later version
// Refer to the license.txt file included.
+#include <cstring>
#include <random>
+#include <fmt/format.h>
+
#include "common/file_util.h"
#include "core/hle/service/acc/profile_manager.h"
#include "core/settings.h"
@@ -39,6 +42,19 @@ UUID UUID::Generate() {
return UUID{distribution(gen), distribution(gen)};
}
+std::string UUID::Format() const {
+ return fmt::format("0x{:016X}{:016X}", uuid[1], uuid[0]);
+}
+
+std::string UUID::FormatSwitch() const {
+ std::array<u8, 16> s{};
+ std::memcpy(s.data(), uuid.data(), sizeof(u128));
+ return fmt::format("{:02x}{:02x}{:02x}{:02x}-{:02x}{:02x}-{:02x}{:02x}-{:02x}{:02x}-{:02x}{"
+ ":02x}{:02x}{:02x}{:02x}{:02x}",
+ s[0], s[1], s[2], s[3], s[4], s[5], s[6], s[7], s[8], s[9], s[10], s[11],
+ s[12], s[13], s[14], s[15]);
+}
+
ProfileManager::ProfileManager() {
ParseUserSaveFile();
@@ -325,11 +341,12 @@ void ProfileManager::ParseUserSaveFile() {
return;
}
- for (std::size_t i = 0; i < MAX_USERS; ++i) {
- const auto& user = data.users[i];
+ for (const auto& user : data.users) {
+ if (user.uuid == UUID(INVALID_UUID)) {
+ continue;
+ }
- if (user.uuid != UUID(INVALID_UUID))
- AddUser({user.uuid, user.username, user.timestamp, {}, false});
+ AddUser({user.uuid, user.username, user.timestamp, {}, false});
}
std::stable_partition(profiles.begin(), profiles.end(),
diff --git a/src/core/hle/service/acc/profile_manager.h b/src/core/hle/service/acc/profile_manager.h
index 747c46c20..d2d8e6c6b 100644
--- a/src/core/hle/service/acc/profile_manager.h
+++ b/src/core/hle/service/acc/profile_manager.h
@@ -42,18 +42,9 @@ struct UUID {
void Invalidate() {
uuid = INVALID_UUID;
}
- std::string Format() const {
- return fmt::format("0x{:016X}{:016X}", uuid[1], uuid[0]);
- }
- std::string FormatSwitch() const {
- std::array<u8, 16> s{};
- std::memcpy(s.data(), uuid.data(), sizeof(u128));
- return fmt::format("{:02x}{:02x}{:02x}{:02x}-{:02x}{:02x}-{:02x}{:02x}-{:02x}{:02x}-{:02x}{"
- ":02x}{:02x}{:02x}{:02x}{:02x}",
- s[0], s[1], s[2], s[3], s[4], s[5], s[6], s[7], s[8], s[9], s[10], s[11],
- s[12], s[13], s[14], s[15]);
- }
+ std::string Format() const;
+ std::string FormatSwitch() const;
};
static_assert(sizeof(UUID) == 16, "UUID is an invalid size!");
diff --git a/src/core/hle/service/am/am.cpp b/src/core/hle/service/am/am.cpp
index ac3ff9f20..4f17b52f9 100644
--- a/src/core/hle/service/am/am.cpp
+++ b/src/core/hle/service/am/am.cpp
@@ -6,14 +6,19 @@
#include <cinttypes>
#include <cstring>
#include <stack>
+#include "audio_core/audio_renderer.h"
#include "core/core.h"
#include "core/hle/ipc_helpers.h"
#include "core/hle/kernel/event.h"
#include "core/hle/kernel/process.h"
+#include "core/hle/kernel/shared_memory.h"
#include "core/hle/service/acc/profile_manager.h"
#include "core/hle/service/am/am.h"
#include "core/hle/service/am/applet_ae.h"
#include "core/hle/service/am/applet_oe.h"
+#include "core/hle/service/am/applets/applets.h"
+#include "core/hle/service/am/applets/software_keyboard.h"
+#include "core/hle/service/am/applets/stub_applet.h"
#include "core/hle/service/am/idle.h"
#include "core/hle/service/am/omm.h"
#include "core/hle/service/am/spsm.h"
@@ -28,6 +33,13 @@
namespace Service::AM {
+constexpr ResultCode ERR_NO_DATA_IN_CHANNEL{ErrorModule::AM, 0x2};
+constexpr ResultCode ERR_SIZE_OUT_OF_BOUNDS{ErrorModule::AM, 0x1F7};
+
+enum class AppletId : u32 {
+ SoftwareKeyboard = 0x11,
+};
+
constexpr u32 POP_LAUNCH_PARAMETER_MAGIC = 0xC79497CA;
struct LaunchParameters {
@@ -203,8 +215,8 @@ ISelfController::ISelfController(std::shared_ptr<NVFlinger::NVFlinger> nvflinger
ISelfController::~ISelfController() = default;
void ISelfController::SetFocusHandlingMode(Kernel::HLERequestContext& ctx) {
- // Takes 3 input u8s with each field located immediately after the previous u8, these are
- // bool flags. No output.
+ // Takes 3 input u8s with each field located immediately after the previous
+ // u8, these are bool flags. No output.
IPC::RequestParser rp{ctx};
@@ -258,8 +270,8 @@ void ISelfController::SetOperationModeChangedNotification(Kernel::HLERequestCont
}
void ISelfController::SetOutOfFocusSuspendingEnabled(Kernel::HLERequestContext& ctx) {
- // Takes 3 input u8s with each field located immediately after the previous u8, these are
- // bool flags. No output.
+ // Takes 3 input u8s with each field located immediately after the previous
+ // u8, these are bool flags. No output.
IPC::RequestParser rp{ctx};
bool enabled = rp.Pop<bool>();
@@ -302,8 +314,8 @@ void ISelfController::SetScreenShotImageOrientation(Kernel::HLERequestContext& c
}
void ISelfController::CreateManagedDisplayLayer(Kernel::HLERequestContext& ctx) {
- // TODO(Subv): Find out how AM determines the display to use, for now just create the layer
- // in the Default display.
+ // TODO(Subv): Find out how AM determines the display to use, for now just
+ // create the layer in the Default display.
u64 display_id = nvflinger->OpenDisplay("Default");
u64 layer_id = nvflinger->CreateLayer(display_id);
@@ -338,7 +350,54 @@ void ISelfController::GetIdleTimeDetectionExtension(Kernel::HLERequestContext& c
LOG_WARNING(Service_AM, "(STUBBED) called");
}
-ICommonStateGetter::ICommonStateGetter() : ServiceFramework("ICommonStateGetter") {
+AppletMessageQueue::AppletMessageQueue() {
+ auto& kernel = Core::System::GetInstance().Kernel();
+ on_new_message = Kernel::Event::Create(kernel, Kernel::ResetType::Sticky,
+ "AMMessageQueue:OnMessageRecieved");
+ on_operation_mode_changed = Kernel::Event::Create(kernel, Kernel::ResetType::OneShot,
+ "AMMessageQueue:OperationModeChanged");
+}
+
+AppletMessageQueue::~AppletMessageQueue() = default;
+
+const Kernel::SharedPtr<Kernel::Event>& AppletMessageQueue::GetMesssageRecieveEvent() const {
+ return on_new_message;
+}
+
+const Kernel::SharedPtr<Kernel::Event>& AppletMessageQueue::GetOperationModeChangedEvent() const {
+ return on_operation_mode_changed;
+}
+
+void AppletMessageQueue::PushMessage(AppletMessage msg) {
+ messages.push(msg);
+ on_new_message->Signal();
+}
+
+AppletMessageQueue::AppletMessage AppletMessageQueue::PopMessage() {
+ if (messages.empty()) {
+ on_new_message->Clear();
+ return AppletMessage::NoMessage;
+ }
+ auto msg = messages.front();
+ messages.pop();
+ if (messages.empty()) {
+ on_new_message->Clear();
+ }
+ return msg;
+}
+
+std::size_t AppletMessageQueue::GetMessageCount() const {
+ return messages.size();
+}
+
+void AppletMessageQueue::OperationModeChanged() {
+ PushMessage(AppletMessage::OperationModeChanged);
+ PushMessage(AppletMessage::PerformanceModeChanged);
+ on_operation_mode_changed->Signal();
+}
+
+ICommonStateGetter::ICommonStateGetter(std::shared_ptr<AppletMessageQueue> msg_queue)
+ : ServiceFramework("ICommonStateGetter"), msg_queue(std::move(msg_queue)) {
// clang-format off
static const FunctionInfo functions[] = {
{0, &ICommonStateGetter::GetEventHandle, "GetEventHandle"},
@@ -388,21 +447,19 @@ void ICommonStateGetter::GetBootMode(Kernel::HLERequestContext& ctx) {
}
void ICommonStateGetter::GetEventHandle(Kernel::HLERequestContext& ctx) {
- event->Signal();
-
IPC::ResponseBuilder rb{ctx, 2, 1};
rb.Push(RESULT_SUCCESS);
- rb.PushCopyObjects(event);
+ rb.PushCopyObjects(msg_queue->GetMesssageRecieveEvent());
- LOG_WARNING(Service_AM, "(STUBBED) called");
+ LOG_DEBUG(Service_AM, "called");
}
void ICommonStateGetter::ReceiveMessage(Kernel::HLERequestContext& ctx) {
IPC::ResponseBuilder rb{ctx, 3};
rb.Push(RESULT_SUCCESS);
- rb.Push<u32>(15);
+ rb.PushEnum<AppletMessageQueue::AppletMessage>(msg_queue->PopMessage());
- LOG_WARNING(Service_AM, "(STUBBED) called");
+ LOG_DEBUG(Service_AM, "called");
}
void ICommonStateGetter::GetCurrentFocusState(Kernel::HLERequestContext& ctx) {
@@ -414,13 +471,11 @@ void ICommonStateGetter::GetCurrentFocusState(Kernel::HLERequestContext& ctx) {
}
void ICommonStateGetter::GetDefaultDisplayResolutionChangeEvent(Kernel::HLERequestContext& ctx) {
- event->Signal();
-
IPC::ResponseBuilder rb{ctx, 2, 1};
rb.Push(RESULT_SUCCESS);
- rb.PushCopyObjects(event);
+ rb.PushCopyObjects(msg_queue->GetOperationModeChangedEvent());
- LOG_WARNING(Service_AM, "(STUBBED) called");
+ LOG_DEBUG(Service_AM, "called");
}
void ICommonStateGetter::GetDefaultDisplayResolution(Kernel::HLERequestContext& ctx) {
@@ -428,23 +483,45 @@ void ICommonStateGetter::GetDefaultDisplayResolution(Kernel::HLERequestContext&
rb.Push(RESULT_SUCCESS);
if (Settings::values.use_docked_mode) {
- rb.Push(static_cast<u32>(Service::VI::DisplayResolution::DockedWidth));
- rb.Push(static_cast<u32>(Service::VI::DisplayResolution::DockedHeight));
+ rb.Push(static_cast<u32>(Service::VI::DisplayResolution::DockedWidth) *
+ static_cast<u32>(Settings::values.resolution_factor));
+ rb.Push(static_cast<u32>(Service::VI::DisplayResolution::DockedHeight) *
+ static_cast<u32>(Settings::values.resolution_factor));
} else {
- rb.Push(static_cast<u32>(Service::VI::DisplayResolution::UndockedWidth));
- rb.Push(static_cast<u32>(Service::VI::DisplayResolution::UndockedHeight));
+ rb.Push(static_cast<u32>(Service::VI::DisplayResolution::UndockedWidth) *
+ static_cast<u32>(Settings::values.resolution_factor));
+ rb.Push(static_cast<u32>(Service::VI::DisplayResolution::UndockedHeight) *
+ static_cast<u32>(Settings::values.resolution_factor));
}
LOG_DEBUG(Service_AM, "called");
}
+IStorage::IStorage(std::vector<u8> buffer)
+ : ServiceFramework("IStorage"), buffer(std::move(buffer)) {
+ // clang-format off
+ static const FunctionInfo functions[] = {
+ {0, &IStorage::Open, "Open"},
+ {1, nullptr, "OpenTransferStorage"},
+ };
+ // clang-format on
+
+ RegisterHandlers(functions);
+}
+
+IStorage::~IStorage() = default;
+
+const std::vector<u8>& IStorage::GetData() const {
+ return buffer;
+}
+
void ICommonStateGetter::GetOperationMode(Kernel::HLERequestContext& ctx) {
const bool use_docked_mode{Settings::values.use_docked_mode};
IPC::ResponseBuilder rb{ctx, 3};
rb.Push(RESULT_SUCCESS);
rb.Push(static_cast<u8>(use_docked_mode ? OperationMode::Docked : OperationMode::Handheld));
- LOG_WARNING(Service_AM, "(STUBBED) called");
+ LOG_DEBUG(Service_AM, "called");
}
void ICommonStateGetter::GetPerformanceMode(Kernel::HLERequestContext& ctx) {
@@ -454,18 +531,33 @@ void ICommonStateGetter::GetPerformanceMode(Kernel::HLERequestContext& ctx) {
rb.Push(static_cast<u32>(use_docked_mode ? APM::PerformanceMode::Docked
: APM::PerformanceMode::Handheld));
- LOG_WARNING(Service_AM, "(STUBBED) called");
+ LOG_DEBUG(Service_AM, "called");
}
-class IStorageAccessor final : public ServiceFramework<IStorageAccessor> {
+class ILibraryAppletAccessor final : public ServiceFramework<ILibraryAppletAccessor> {
public:
- explicit IStorageAccessor(std::vector<u8> buffer)
- : ServiceFramework("IStorageAccessor"), buffer(std::move(buffer)) {
+ explicit ILibraryAppletAccessor(std::shared_ptr<Applets::Applet> applet)
+ : ServiceFramework("ILibraryAppletAccessor"), applet(std::move(applet)) {
// clang-format off
static const FunctionInfo functions[] = {
- {0, &IStorageAccessor::GetSize, "GetSize"},
- {10, &IStorageAccessor::Write, "Write"},
- {11, &IStorageAccessor::Read, "Read"},
+ {0, &ILibraryAppletAccessor::GetAppletStateChangedEvent, "GetAppletStateChangedEvent"},
+ {1, &ILibraryAppletAccessor::IsCompleted, "IsCompleted"},
+ {10, &ILibraryAppletAccessor::Start, "Start"},
+ {20, nullptr, "RequestExit"},
+ {25, nullptr, "Terminate"},
+ {30, &ILibraryAppletAccessor::GetResult, "GetResult"},
+ {50, nullptr, "SetOutOfFocusApplicationSuspendingEnabled"},
+ {100, &ILibraryAppletAccessor::PushInData, "PushInData"},
+ {101, &ILibraryAppletAccessor::PopOutData, "PopOutData"},
+ {102, nullptr, "PushExtraStorage"},
+ {103, &ILibraryAppletAccessor::PushInteractiveInData, "PushInteractiveInData"},
+ {104, &ILibraryAppletAccessor::PopInteractiveOutData, "PopInteractiveOutData"},
+ {105, &ILibraryAppletAccessor::GetPopOutDataEvent, "GetPopOutDataEvent"},
+ {106, &ILibraryAppletAccessor::GetPopInteractiveOutDataEvent, "GetPopInteractiveOutDataEvent"},
+ {110, nullptr, "NeedsToExitProcess"},
+ {120, nullptr, "GetLibraryAppletInfo"},
+ {150, nullptr, "RequestForAppletToGetForeground"},
+ {160, nullptr, "GetIndirectLayerConsumerHandle"},
};
// clang-format on
@@ -473,158 +565,187 @@ public:
}
private:
- std::vector<u8> buffer;
+ void GetAppletStateChangedEvent(Kernel::HLERequestContext& ctx) {
+ const auto event = applet->GetBroker().GetStateChangedEvent();
+ event->Signal();
- void GetSize(Kernel::HLERequestContext& ctx) {
- IPC::ResponseBuilder rb{ctx, 4};
+ IPC::ResponseBuilder rb{ctx, 2, 1};
+ rb.Push(RESULT_SUCCESS);
+ rb.PushCopyObjects(event);
+ LOG_DEBUG(Service_AM, "called");
+ }
+
+ void IsCompleted(Kernel::HLERequestContext& ctx) {
+ IPC::ResponseBuilder rb{ctx, 3};
rb.Push(RESULT_SUCCESS);
- rb.Push(static_cast<u64>(buffer.size()));
+ rb.Push<u32>(applet->TransactionComplete());
LOG_DEBUG(Service_AM, "called");
}
- void Write(Kernel::HLERequestContext& ctx) {
- IPC::RequestParser rp{ctx};
+ void GetResult(Kernel::HLERequestContext& ctx) {
+ IPC::ResponseBuilder rb{ctx, 2};
+ rb.Push(applet->GetStatus());
- const u64 offset{rp.Pop<u64>()};
- const std::vector<u8> data{ctx.ReadBuffer()};
+ LOG_DEBUG(Service_AM, "called");
+ }
- ASSERT(offset + data.size() <= buffer.size());
+ void Start(Kernel::HLERequestContext& ctx) {
+ ASSERT(applet != nullptr);
- std::memcpy(&buffer[offset], data.data(), data.size());
+ applet->Initialize();
+ applet->Execute();
IPC::ResponseBuilder rb{ctx, 2};
rb.Push(RESULT_SUCCESS);
- LOG_DEBUG(Service_AM, "called, offset={}", offset);
+ LOG_DEBUG(Service_AM, "called");
}
- void Read(Kernel::HLERequestContext& ctx) {
+ void PushInData(Kernel::HLERequestContext& ctx) {
IPC::RequestParser rp{ctx};
+ applet->GetBroker().PushNormalDataFromGame(*rp.PopIpcInterface<IStorage>());
- const u64 offset{rp.Pop<u64>()};
- const std::size_t size{ctx.GetWriteBufferSize()};
+ IPC::ResponseBuilder rb{ctx, 2};
+ rb.Push(RESULT_SUCCESS);
- ASSERT(offset + size <= buffer.size());
+ LOG_DEBUG(Service_AM, "called");
+ }
- ctx.WriteBuffer(buffer.data() + offset, size);
+ void PopOutData(Kernel::HLERequestContext& ctx) {
+ IPC::ResponseBuilder rb{ctx, 2, 0, 1};
+
+ const auto storage = applet->GetBroker().PopNormalDataToGame();
+ if (storage == nullptr) {
+ rb.Push(ERR_NO_DATA_IN_CHANNEL);
+ return;
+ }
+
+ rb.Push(RESULT_SUCCESS);
+ rb.PushIpcInterface<IStorage>(std::move(*storage));
+
+ LOG_DEBUG(Service_AM, "called");
+ }
+
+ void PushInteractiveInData(Kernel::HLERequestContext& ctx) {
+ IPC::RequestParser rp{ctx};
+ applet->GetBroker().PushInteractiveDataFromGame(*rp.PopIpcInterface<IStorage>());
+
+ ASSERT(applet->IsInitialized());
+ applet->ExecuteInteractive();
+ applet->Execute();
IPC::ResponseBuilder rb{ctx, 2};
rb.Push(RESULT_SUCCESS);
- LOG_DEBUG(Service_AM, "called, offset={}", offset);
+ LOG_DEBUG(Service_AM, "called");
}
-};
-class IStorage final : public ServiceFramework<IStorage> {
-public:
- explicit IStorage(std::vector<u8> buffer)
- : ServiceFramework("IStorage"), buffer(std::move(buffer)) {
- // clang-format off
- static const FunctionInfo functions[] = {
- {0, &IStorage::Open, "Open"},
- {1, nullptr, "OpenTransferStorage"},
- };
- // clang-format on
+ void PopInteractiveOutData(Kernel::HLERequestContext& ctx) {
+ IPC::ResponseBuilder rb{ctx, 2, 0, 1};
- RegisterHandlers(functions);
+ const auto storage = applet->GetBroker().PopInteractiveDataToGame();
+ if (storage == nullptr) {
+ rb.Push(ERR_NO_DATA_IN_CHANNEL);
+ return;
+ }
+
+ rb.Push(RESULT_SUCCESS);
+ rb.PushIpcInterface<IStorage>(std::move(*storage));
+
+ LOG_DEBUG(Service_AM, "called");
}
-private:
- std::vector<u8> buffer;
+ void GetPopOutDataEvent(Kernel::HLERequestContext& ctx) {
+ IPC::ResponseBuilder rb{ctx, 2, 1};
+ rb.Push(RESULT_SUCCESS);
+ rb.PushCopyObjects(applet->GetBroker().GetNormalDataEvent());
- void Open(Kernel::HLERequestContext& ctx) {
- IPC::ResponseBuilder rb{ctx, 2, 0, 1};
+ LOG_DEBUG(Service_AM, "called");
+ }
+ void GetPopInteractiveOutDataEvent(Kernel::HLERequestContext& ctx) {
+ IPC::ResponseBuilder rb{ctx, 2, 1};
rb.Push(RESULT_SUCCESS);
- rb.PushIpcInterface<AM::IStorageAccessor>(buffer);
+ rb.PushCopyObjects(applet->GetBroker().GetInteractiveDataEvent());
LOG_DEBUG(Service_AM, "called");
}
+
+ std::shared_ptr<Applets::Applet> applet;
};
-class ILibraryAppletAccessor final : public ServiceFramework<ILibraryAppletAccessor> {
-public:
- explicit ILibraryAppletAccessor() : ServiceFramework("ILibraryAppletAccessor") {
- // clang-format off
+void IStorage::Open(Kernel::HLERequestContext& ctx) {
+ IPC::ResponseBuilder rb{ctx, 2, 0, 1};
+
+ rb.Push(RESULT_SUCCESS);
+ rb.PushIpcInterface<IStorageAccessor>(*this);
+
+ LOG_DEBUG(Service_AM, "called");
+}
+
+IStorageAccessor::IStorageAccessor(IStorage& storage)
+ : ServiceFramework("IStorageAccessor"), backing(storage) {
+ // clang-format off
static const FunctionInfo functions[] = {
- {0, &ILibraryAppletAccessor::GetAppletStateChangedEvent, "GetAppletStateChangedEvent"},
- {1, nullptr, "IsCompleted"},
- {10, &ILibraryAppletAccessor::Start, "Start"},
- {20, nullptr, "RequestExit"},
- {25, nullptr, "Terminate"},
- {30, &ILibraryAppletAccessor::GetResult, "GetResult"},
- {50, nullptr, "SetOutOfFocusApplicationSuspendingEnabled"},
- {100, &ILibraryAppletAccessor::PushInData, "PushInData"},
- {101, &ILibraryAppletAccessor::PopOutData, "PopOutData"},
- {102, nullptr, "PushExtraStorage"},
- {103, nullptr, "PushInteractiveInData"},
- {104, nullptr, "PopInteractiveOutData"},
- {105, nullptr, "GetPopOutDataEvent"},
- {106, nullptr, "GetPopInteractiveOutDataEvent"},
- {110, nullptr, "NeedsToExitProcess"},
- {120, nullptr, "GetLibraryAppletInfo"},
- {150, nullptr, "RequestForAppletToGetForeground"},
- {160, nullptr, "GetIndirectLayerConsumerHandle"},
+ {0, &IStorageAccessor::GetSize, "GetSize"},
+ {10, &IStorageAccessor::Write, "Write"},
+ {11, &IStorageAccessor::Read, "Read"},
};
- // clang-format on
+ // clang-format on
- RegisterHandlers(functions);
+ RegisterHandlers(functions);
+}
- auto& kernel = Core::System::GetInstance().Kernel();
- state_changed_event = Kernel::Event::Create(kernel, Kernel::ResetType::OneShot,
- "ILibraryAppletAccessor:StateChangedEvent");
- }
+IStorageAccessor::~IStorageAccessor() = default;
-private:
- void GetAppletStateChangedEvent(Kernel::HLERequestContext& ctx) {
- state_changed_event->Signal();
+void IStorageAccessor::GetSize(Kernel::HLERequestContext& ctx) {
+ IPC::ResponseBuilder rb{ctx, 4};
- IPC::ResponseBuilder rb{ctx, 2, 1};
- rb.Push(RESULT_SUCCESS);
- rb.PushCopyObjects(state_changed_event);
+ rb.Push(RESULT_SUCCESS);
+ rb.Push(static_cast<u64>(backing.buffer.size()));
- LOG_WARNING(Service_AM, "(STUBBED) called");
- }
+ LOG_DEBUG(Service_AM, "called");
+}
- void GetResult(Kernel::HLERequestContext& ctx) {
- IPC::ResponseBuilder rb{ctx, 2};
- rb.Push(RESULT_SUCCESS);
+void IStorageAccessor::Write(Kernel::HLERequestContext& ctx) {
+ IPC::RequestParser rp{ctx};
- LOG_WARNING(Service_AM, "(STUBBED) called");
- }
+ const u64 offset{rp.Pop<u64>()};
+ const std::vector<u8> data{ctx.ReadBuffer()};
- void Start(Kernel::HLERequestContext& ctx) {
+ if (data.size() > backing.buffer.size() - offset) {
IPC::ResponseBuilder rb{ctx, 2};
- rb.Push(RESULT_SUCCESS);
-
- LOG_WARNING(Service_AM, "(STUBBED) called");
+ rb.Push(ERR_SIZE_OUT_OF_BOUNDS);
}
- void PushInData(Kernel::HLERequestContext& ctx) {
- IPC::RequestParser rp{ctx};
- storage_stack.push(rp.PopIpcInterface<AM::IStorage>());
+ std::memcpy(backing.buffer.data() + offset, data.data(), data.size());
- IPC::ResponseBuilder rb{ctx, 2};
- rb.Push(RESULT_SUCCESS);
+ IPC::ResponseBuilder rb{ctx, 2};
+ rb.Push(RESULT_SUCCESS);
- LOG_DEBUG(Service_AM, "called");
- }
+ LOG_DEBUG(Service_AM, "called, offset={}", offset);
+}
- void PopOutData(Kernel::HLERequestContext& ctx) {
- IPC::ResponseBuilder rb{ctx, 2, 0, 1};
- rb.Push(RESULT_SUCCESS);
- rb.PushIpcInterface<AM::IStorage>(std::move(storage_stack.top()));
+void IStorageAccessor::Read(Kernel::HLERequestContext& ctx) {
+ IPC::RequestParser rp{ctx};
- storage_stack.pop();
+ const u64 offset{rp.Pop<u64>()};
+ const std::size_t size{ctx.GetWriteBufferSize()};
- LOG_DEBUG(Service_AM, "called");
+ if (size > backing.buffer.size() - offset) {
+ IPC::ResponseBuilder rb{ctx, 2};
+ rb.Push(ERR_SIZE_OUT_OF_BOUNDS);
}
- std::stack<std::shared_ptr<AM::IStorage>> storage_stack;
- Kernel::SharedPtr<Kernel::Event> state_changed_event;
-};
+ ctx.WriteBuffer(backing.buffer.data() + offset, size);
+
+ IPC::ResponseBuilder rb{ctx, 2};
+ rb.Push(RESULT_SUCCESS);
+
+ LOG_DEBUG(Service_AM, "called, offset={}", offset);
+}
ILibraryAppletCreator::ILibraryAppletCreator() : ServiceFramework("ILibraryAppletCreator") {
static const FunctionInfo functions[] = {
@@ -632,7 +753,7 @@ ILibraryAppletCreator::ILibraryAppletCreator() : ServiceFramework("ILibraryApple
{1, nullptr, "TerminateAllLibraryApplets"},
{2, nullptr, "AreAnyLibraryAppletsLeft"},
{10, &ILibraryAppletCreator::CreateStorage, "CreateStorage"},
- {11, nullptr, "CreateTransferMemoryStorage"},
+ {11, &ILibraryAppletCreator::CreateTransferMemoryStorage, "CreateTransferMemoryStorage"},
{12, nullptr, "CreateHandleStorage"},
};
RegisterHandlers(functions);
@@ -640,11 +761,37 @@ ILibraryAppletCreator::ILibraryAppletCreator() : ServiceFramework("ILibraryApple
ILibraryAppletCreator::~ILibraryAppletCreator() = default;
+static std::shared_ptr<Applets::Applet> GetAppletFromId(AppletId id) {
+ switch (id) {
+ case AppletId::SoftwareKeyboard:
+ return std::make_shared<Applets::SoftwareKeyboard>();
+ default:
+ LOG_ERROR(Service_AM, "Unimplemented AppletId [{:08X}]! -- Falling back to stub!",
+ static_cast<u32>(id));
+ return std::make_shared<Applets::StubApplet>();
+ }
+}
+
void ILibraryAppletCreator::CreateLibraryApplet(Kernel::HLERequestContext& ctx) {
+ IPC::RequestParser rp{ctx};
+ const auto applet_id = rp.PopRaw<AppletId>();
+ const auto applet_mode = rp.PopRaw<u32>();
+
+ LOG_DEBUG(Service_AM, "called with applet_id={:08X}, applet_mode={:08X}",
+ static_cast<u32>(applet_id), applet_mode);
+
+ const auto applet = GetAppletFromId(applet_id);
+
+ if (applet == nullptr) {
+ IPC::ResponseBuilder rb{ctx, 2};
+ rb.Push(ResultCode(-1));
+ return;
+ }
+
IPC::ResponseBuilder rb{ctx, 2, 0, 1};
rb.Push(RESULT_SUCCESS);
- rb.PushIpcInterface<AM::ILibraryAppletAccessor>();
+ rb.PushIpcInterface<AM::ILibraryAppletAccessor>(applet);
LOG_DEBUG(Service_AM, "called");
}
@@ -661,6 +808,31 @@ void ILibraryAppletCreator::CreateStorage(Kernel::HLERequestContext& ctx) {
LOG_DEBUG(Service_AM, "called, size={}", size);
}
+void ILibraryAppletCreator::CreateTransferMemoryStorage(Kernel::HLERequestContext& ctx) {
+ IPC::RequestParser rp{ctx};
+
+ rp.SetCurrentOffset(3);
+ const auto handle{rp.Pop<Kernel::Handle>()};
+
+ const auto shared_mem =
+ Core::System::GetInstance().CurrentProcess()->GetHandleTable().Get<Kernel::SharedMemory>(
+ handle);
+
+ if (shared_mem == nullptr) {
+ IPC::ResponseBuilder rb{ctx, 2};
+ rb.Push(ResultCode(-1));
+ return;
+ }
+
+ const u8* mem_begin = shared_mem->GetPointer();
+ const u8* mem_end = mem_begin + shared_mem->GetSize();
+ std::vector<u8> memory{mem_begin, mem_end};
+
+ IPC::ResponseBuilder rb{ctx, 2, 0, 1};
+ rb.Push(RESULT_SUCCESS);
+ rb.PushIpcInterface(std::make_shared<IStorage>(std::move(memory)));
+}
+
IApplicationFunctions::IApplicationFunctions() : ServiceFramework("IApplicationFunctions") {
// clang-format off
static const FunctionInfo functions[] = {
@@ -690,7 +862,7 @@ IApplicationFunctions::IApplicationFunctions() : ServiceFramework("IApplicationF
{70, nullptr, "RequestToShutdown"},
{71, nullptr, "RequestToReboot"},
{80, nullptr, "ExitAndRequestToShowThanksMessage"},
- {90, nullptr, "EnableApplicationCrashReport"},
+ {90, &IApplicationFunctions::EnableApplicationCrashReport, "EnableApplicationCrashReport"},
{100, nullptr, "InitializeApplicationCopyrightFrameBuffer"},
{101, nullptr, "SetApplicationCopyrightImage"},
{102, nullptr, "SetApplicationCopyrightVisibility"},
@@ -709,6 +881,12 @@ IApplicationFunctions::IApplicationFunctions() : ServiceFramework("IApplicationF
IApplicationFunctions::~IApplicationFunctions() = default;
+void IApplicationFunctions::EnableApplicationCrashReport(Kernel::HLERequestContext& ctx) {
+ IPC::ResponseBuilder rb{ctx, 2};
+ rb.Push(RESULT_SUCCESS);
+ LOG_WARNING(Service_AM, "(STUBBED) called");
+}
+
void IApplicationFunctions::BeginBlockingHomeButtonShortAndLongPressed(
Kernel::HLERequestContext& ctx) {
IPC::ResponseBuilder rb{ctx, 2};
@@ -778,7 +956,8 @@ void IApplicationFunctions::EnsureSaveData(Kernel::HLERequestContext& ctx) {
void IApplicationFunctions::SetTerminateResult(Kernel::HLERequestContext& ctx) {
// Takes an input u32 Result, no output.
- // For example, in some cases official apps use this with error 0x2A2 then uses svcBreak.
+ // For example, in some cases official apps use this with error 0x2A2 then
+ // uses svcBreak.
IPC::RequestParser rp{ctx};
u32 result = rp.Pop<u32>();
@@ -840,8 +1019,12 @@ void IApplicationFunctions::GetPseudoDeviceId(Kernel::HLERequestContext& ctx) {
void InstallInterfaces(SM::ServiceManager& service_manager,
std::shared_ptr<NVFlinger::NVFlinger> nvflinger) {
- std::make_shared<AppletAE>(nvflinger)->InstallAsService(service_manager);
- std::make_shared<AppletOE>(nvflinger)->InstallAsService(service_manager);
+ auto message_queue = std::make_shared<AppletMessageQueue>();
+ message_queue->PushMessage(AppletMessageQueue::AppletMessage::FocusStateChanged); // Needed on
+ // game boot
+
+ std::make_shared<AppletAE>(nvflinger, message_queue)->InstallAsService(service_manager);
+ std::make_shared<AppletOE>(nvflinger, message_queue)->InstallAsService(service_manager);
std::make_shared<IdleSys>()->InstallAsService(service_manager);
std::make_shared<OMM>()->InstallAsService(service_manager);
std::make_shared<SPSM>()->InstallAsService(service_manager);
diff --git a/src/core/hle/service/am/am.h b/src/core/hle/service/am/am.h
index 095f94851..44c1bcde5 100644
--- a/src/core/hle/service/am/am.h
+++ b/src/core/hle/service/am/am.h
@@ -5,6 +5,7 @@
#pragma once
#include <memory>
+#include <queue>
#include "core/hle/service/service.h"
namespace Kernel {
@@ -39,6 +40,31 @@ enum SystemLanguage {
TraditionalChinese = 16,
};
+class AppletMessageQueue {
+public:
+ enum class AppletMessage : u32 {
+ NoMessage = 0,
+ FocusStateChanged = 15,
+ OperationModeChanged = 30,
+ PerformanceModeChanged = 31,
+ };
+
+ AppletMessageQueue();
+ ~AppletMessageQueue();
+
+ const Kernel::SharedPtr<Kernel::Event>& GetMesssageRecieveEvent() const;
+ const Kernel::SharedPtr<Kernel::Event>& GetOperationModeChangedEvent() const;
+ void PushMessage(AppletMessage msg);
+ AppletMessage PopMessage();
+ std::size_t GetMessageCount() const;
+ void OperationModeChanged();
+
+private:
+ std::queue<AppletMessage> messages;
+ Kernel::SharedPtr<Kernel::Event> on_new_message;
+ Kernel::SharedPtr<Kernel::Event> on_operation_mode_changed;
+};
+
class IWindowController final : public ServiceFramework<IWindowController> {
public:
IWindowController();
@@ -102,7 +128,7 @@ private:
class ICommonStateGetter final : public ServiceFramework<ICommonStateGetter> {
public:
- ICommonStateGetter();
+ explicit ICommonStateGetter(std::shared_ptr<AppletMessageQueue> msg_queue);
~ICommonStateGetter() override;
private:
@@ -126,6 +152,35 @@ private:
void GetDefaultDisplayResolution(Kernel::HLERequestContext& ctx);
Kernel::SharedPtr<Kernel::Event> event;
+ std::shared_ptr<AppletMessageQueue> msg_queue;
+};
+
+class IStorage final : public ServiceFramework<IStorage> {
+public:
+ explicit IStorage(std::vector<u8> buffer);
+ ~IStorage() override;
+
+ const std::vector<u8>& GetData() const;
+
+private:
+ void Open(Kernel::HLERequestContext& ctx);
+
+ std::vector<u8> buffer;
+
+ friend class IStorageAccessor;
+};
+
+class IStorageAccessor final : public ServiceFramework<IStorageAccessor> {
+public:
+ explicit IStorageAccessor(IStorage& backing);
+ ~IStorageAccessor() override;
+
+private:
+ void GetSize(Kernel::HLERequestContext& ctx);
+ void Write(Kernel::HLERequestContext& ctx);
+ void Read(Kernel::HLERequestContext& ctx);
+
+ IStorage& backing;
};
class ILibraryAppletCreator final : public ServiceFramework<ILibraryAppletCreator> {
@@ -136,6 +191,7 @@ public:
private:
void CreateLibraryApplet(Kernel::HLERequestContext& ctx);
void CreateStorage(Kernel::HLERequestContext& ctx);
+ void CreateTransferMemoryStorage(Kernel::HLERequestContext& ctx);
};
class IApplicationFunctions final : public ServiceFramework<IApplicationFunctions> {
@@ -158,6 +214,7 @@ private:
void EndBlockingHomeButtonShortAndLongPressed(Kernel::HLERequestContext& ctx);
void BeginBlockingHomeButton(Kernel::HLERequestContext& ctx);
void EndBlockingHomeButton(Kernel::HLERequestContext& ctx);
+ void EnableApplicationCrashReport(Kernel::HLERequestContext& ctx);
};
class IHomeMenuFunctions final : public ServiceFramework<IHomeMenuFunctions> {
diff --git a/src/core/hle/service/am/applet_ae.cpp b/src/core/hle/service/am/applet_ae.cpp
index 68ea778e8..ec93e3529 100644
--- a/src/core/hle/service/am/applet_ae.cpp
+++ b/src/core/hle/service/am/applet_ae.cpp
@@ -12,8 +12,10 @@ namespace Service::AM {
class ILibraryAppletProxy final : public ServiceFramework<ILibraryAppletProxy> {
public:
- explicit ILibraryAppletProxy(std::shared_ptr<NVFlinger::NVFlinger> nvflinger)
- : ServiceFramework("ILibraryAppletProxy"), nvflinger(std::move(nvflinger)) {
+ explicit ILibraryAppletProxy(std::shared_ptr<NVFlinger::NVFlinger> nvflinger,
+ std::shared_ptr<AppletMessageQueue> msg_queue)
+ : ServiceFramework("ILibraryAppletProxy"), nvflinger(std::move(nvflinger)),
+ msg_queue(std::move(msg_queue)) {
static const FunctionInfo functions[] = {
{0, &ILibraryAppletProxy::GetCommonStateGetter, "GetCommonStateGetter"},
{1, &ILibraryAppletProxy::GetSelfController, "GetSelfController"},
@@ -32,7 +34,7 @@ private:
void GetCommonStateGetter(Kernel::HLERequestContext& ctx) {
IPC::ResponseBuilder rb{ctx, 2, 0, 1};
rb.Push(RESULT_SUCCESS);
- rb.PushIpcInterface<ICommonStateGetter>();
+ rb.PushIpcInterface<ICommonStateGetter>(msg_queue);
LOG_DEBUG(Service_AM, "called");
}
@@ -93,12 +95,15 @@ private:
}
std::shared_ptr<NVFlinger::NVFlinger> nvflinger;
+ std::shared_ptr<AppletMessageQueue> msg_queue;
};
class ISystemAppletProxy final : public ServiceFramework<ISystemAppletProxy> {
public:
- explicit ISystemAppletProxy(std::shared_ptr<NVFlinger::NVFlinger> nvflinger)
- : ServiceFramework("ISystemAppletProxy"), nvflinger(std::move(nvflinger)) {
+ explicit ISystemAppletProxy(std::shared_ptr<NVFlinger::NVFlinger> nvflinger,
+ std::shared_ptr<AppletMessageQueue> msg_queue)
+ : ServiceFramework("ISystemAppletProxy"), nvflinger(std::move(nvflinger)),
+ msg_queue(std::move(msg_queue)) {
static const FunctionInfo functions[] = {
{0, &ISystemAppletProxy::GetCommonStateGetter, "GetCommonStateGetter"},
{1, &ISystemAppletProxy::GetSelfController, "GetSelfController"},
@@ -119,7 +124,7 @@ private:
void GetCommonStateGetter(Kernel::HLERequestContext& ctx) {
IPC::ResponseBuilder rb{ctx, 2, 0, 1};
rb.Push(RESULT_SUCCESS);
- rb.PushIpcInterface<ICommonStateGetter>();
+ rb.PushIpcInterface<ICommonStateGetter>(msg_queue);
LOG_DEBUG(Service_AM, "called");
}
@@ -186,31 +191,34 @@ private:
LOG_DEBUG(Service_AM, "called");
}
std::shared_ptr<NVFlinger::NVFlinger> nvflinger;
+ std::shared_ptr<AppletMessageQueue> msg_queue;
};
void AppletAE::OpenSystemAppletProxy(Kernel::HLERequestContext& ctx) {
IPC::ResponseBuilder rb{ctx, 2, 0, 1};
rb.Push(RESULT_SUCCESS);
- rb.PushIpcInterface<ISystemAppletProxy>(nvflinger);
+ rb.PushIpcInterface<ISystemAppletProxy>(nvflinger, msg_queue);
LOG_DEBUG(Service_AM, "called");
}
void AppletAE::OpenLibraryAppletProxy(Kernel::HLERequestContext& ctx) {
IPC::ResponseBuilder rb{ctx, 2, 0, 1};
rb.Push(RESULT_SUCCESS);
- rb.PushIpcInterface<ILibraryAppletProxy>(nvflinger);
+ rb.PushIpcInterface<ILibraryAppletProxy>(nvflinger, msg_queue);
LOG_DEBUG(Service_AM, "called");
}
void AppletAE::OpenLibraryAppletProxyOld(Kernel::HLERequestContext& ctx) {
IPC::ResponseBuilder rb{ctx, 2, 0, 1};
rb.Push(RESULT_SUCCESS);
- rb.PushIpcInterface<ILibraryAppletProxy>(nvflinger);
+ rb.PushIpcInterface<ILibraryAppletProxy>(nvflinger, msg_queue);
LOG_DEBUG(Service_AM, "called");
}
-AppletAE::AppletAE(std::shared_ptr<NVFlinger::NVFlinger> nvflinger)
- : ServiceFramework("appletAE"), nvflinger(std::move(nvflinger)) {
+AppletAE::AppletAE(std::shared_ptr<NVFlinger::NVFlinger> nvflinger,
+ std::shared_ptr<AppletMessageQueue> msg_queue)
+ : ServiceFramework("appletAE"), nvflinger(std::move(nvflinger)),
+ msg_queue(std::move(msg_queue)) {
// clang-format off
static const FunctionInfo functions[] = {
{100, &AppletAE::OpenSystemAppletProxy, "OpenSystemAppletProxy"},
@@ -228,4 +236,8 @@ AppletAE::AppletAE(std::shared_ptr<NVFlinger::NVFlinger> nvflinger)
AppletAE::~AppletAE() = default;
+const std::shared_ptr<AppletMessageQueue>& AppletAE::GetMessageQueue() const {
+ return msg_queue;
+}
+
} // namespace Service::AM
diff --git a/src/core/hle/service/am/applet_ae.h b/src/core/hle/service/am/applet_ae.h
index 1ed77baa4..902db2665 100644
--- a/src/core/hle/service/am/applet_ae.h
+++ b/src/core/hle/service/am/applet_ae.h
@@ -17,15 +17,19 @@ namespace AM {
class AppletAE final : public ServiceFramework<AppletAE> {
public:
- explicit AppletAE(std::shared_ptr<NVFlinger::NVFlinger> nvflinger);
+ explicit AppletAE(std::shared_ptr<NVFlinger::NVFlinger> nvflinger,
+ std::shared_ptr<AppletMessageQueue> msg_queue);
~AppletAE() override;
+ const std::shared_ptr<AppletMessageQueue>& GetMessageQueue() const;
+
private:
void OpenSystemAppletProxy(Kernel::HLERequestContext& ctx);
void OpenLibraryAppletProxy(Kernel::HLERequestContext& ctx);
void OpenLibraryAppletProxyOld(Kernel::HLERequestContext& ctx);
std::shared_ptr<NVFlinger::NVFlinger> nvflinger;
+ std::shared_ptr<AppletMessageQueue> msg_queue;
};
} // namespace AM
diff --git a/src/core/hle/service/am/applet_oe.cpp b/src/core/hle/service/am/applet_oe.cpp
index 60717afd9..20c8d5fff 100644
--- a/src/core/hle/service/am/applet_oe.cpp
+++ b/src/core/hle/service/am/applet_oe.cpp
@@ -12,8 +12,10 @@ namespace Service::AM {
class IApplicationProxy final : public ServiceFramework<IApplicationProxy> {
public:
- explicit IApplicationProxy(std::shared_ptr<NVFlinger::NVFlinger> nvflinger)
- : ServiceFramework("IApplicationProxy"), nvflinger(std::move(nvflinger)) {
+ explicit IApplicationProxy(std::shared_ptr<NVFlinger::NVFlinger> nvflinger,
+ std::shared_ptr<AppletMessageQueue> msg_queue)
+ : ServiceFramework("IApplicationProxy"), nvflinger(std::move(nvflinger)),
+ msg_queue(std::move(msg_queue)) {
// clang-format off
static const FunctionInfo functions[] = {
{0, &IApplicationProxy::GetCommonStateGetter, "GetCommonStateGetter"},
@@ -70,7 +72,7 @@ private:
void GetCommonStateGetter(Kernel::HLERequestContext& ctx) {
IPC::ResponseBuilder rb{ctx, 2, 0, 1};
rb.Push(RESULT_SUCCESS);
- rb.PushIpcInterface<ICommonStateGetter>();
+ rb.PushIpcInterface<ICommonStateGetter>(msg_queue);
LOG_DEBUG(Service_AM, "called");
}
@@ -89,17 +91,20 @@ private:
}
std::shared_ptr<NVFlinger::NVFlinger> nvflinger;
+ std::shared_ptr<AppletMessageQueue> msg_queue;
};
void AppletOE::OpenApplicationProxy(Kernel::HLERequestContext& ctx) {
IPC::ResponseBuilder rb{ctx, 2, 0, 1};
rb.Push(RESULT_SUCCESS);
- rb.PushIpcInterface<IApplicationProxy>(nvflinger);
+ rb.PushIpcInterface<IApplicationProxy>(nvflinger, msg_queue);
LOG_DEBUG(Service_AM, "called");
}
-AppletOE::AppletOE(std::shared_ptr<NVFlinger::NVFlinger> nvflinger)
- : ServiceFramework("appletOE"), nvflinger(std::move(nvflinger)) {
+AppletOE::AppletOE(std::shared_ptr<NVFlinger::NVFlinger> nvflinger,
+ std::shared_ptr<AppletMessageQueue> msg_queue)
+ : ServiceFramework("appletOE"), nvflinger(std::move(nvflinger)),
+ msg_queue(std::move(msg_queue)) {
static const FunctionInfo functions[] = {
{0, &AppletOE::OpenApplicationProxy, "OpenApplicationProxy"},
};
@@ -108,4 +113,8 @@ AppletOE::AppletOE(std::shared_ptr<NVFlinger::NVFlinger> nvflinger)
AppletOE::~AppletOE() = default;
+const std::shared_ptr<AppletMessageQueue>& AppletOE::GetMessageQueue() const {
+ return msg_queue;
+}
+
} // namespace Service::AM
diff --git a/src/core/hle/service/am/applet_oe.h b/src/core/hle/service/am/applet_oe.h
index 60cfdfd9d..bbd0108ef 100644
--- a/src/core/hle/service/am/applet_oe.h
+++ b/src/core/hle/service/am/applet_oe.h
@@ -17,13 +17,17 @@ namespace AM {
class AppletOE final : public ServiceFramework<AppletOE> {
public:
- explicit AppletOE(std::shared_ptr<NVFlinger::NVFlinger> nvflinger);
+ explicit AppletOE(std::shared_ptr<NVFlinger::NVFlinger> nvflinger,
+ std::shared_ptr<AppletMessageQueue> msg_queue);
~AppletOE() override;
+ const std::shared_ptr<AppletMessageQueue>& GetMessageQueue() const;
+
private:
void OpenApplicationProxy(Kernel::HLERequestContext& ctx);
std::shared_ptr<NVFlinger::NVFlinger> nvflinger;
+ std::shared_ptr<AppletMessageQueue> msg_queue;
};
} // namespace AM
diff --git a/src/core/hle/service/am/applets/applets.cpp b/src/core/hle/service/am/applets/applets.cpp
new file mode 100644
index 000000000..becbadd06
--- /dev/null
+++ b/src/core/hle/service/am/applets/applets.cpp
@@ -0,0 +1,113 @@
+// Copyright 2018 yuzu emulator team
+// Licensed under GPLv2 or any later version
+// Refer to the license.txt file included.
+
+#include <cstring>
+#include "common/assert.h"
+#include "core/core.h"
+#include "core/hle/kernel/event.h"
+#include "core/hle/kernel/server_port.h"
+#include "core/hle/service/am/am.h"
+#include "core/hle/service/am/applets/applets.h"
+
+namespace Service::AM::Applets {
+
+AppletDataBroker::AppletDataBroker() {
+ auto& kernel = Core::System::GetInstance().Kernel();
+ state_changed_event = Kernel::Event::Create(kernel, Kernel::ResetType::OneShot,
+ "ILibraryAppletAccessor:StateChangedEvent");
+ pop_out_data_event = Kernel::Event::Create(kernel, Kernel::ResetType::OneShot,
+ "ILibraryAppletAccessor:PopDataOutEvent");
+ pop_interactive_out_data_event = Kernel::Event::Create(
+ kernel, Kernel::ResetType::OneShot, "ILibraryAppletAccessor:PopInteractiveDataOutEvent");
+}
+
+AppletDataBroker::~AppletDataBroker() = default;
+
+std::unique_ptr<IStorage> AppletDataBroker::PopNormalDataToGame() {
+ if (out_channel.empty())
+ return nullptr;
+
+ auto out = std::move(out_channel.front());
+ out_channel.pop();
+ return out;
+}
+
+std::unique_ptr<IStorage> AppletDataBroker::PopNormalDataToApplet() {
+ if (in_channel.empty())
+ return nullptr;
+
+ auto out = std::move(in_channel.front());
+ in_channel.pop();
+ return out;
+}
+
+std::unique_ptr<IStorage> AppletDataBroker::PopInteractiveDataToGame() {
+ if (out_interactive_channel.empty())
+ return nullptr;
+
+ auto out = std::move(out_interactive_channel.front());
+ out_interactive_channel.pop();
+ return out;
+}
+
+std::unique_ptr<IStorage> AppletDataBroker::PopInteractiveDataToApplet() {
+ if (in_interactive_channel.empty())
+ return nullptr;
+
+ auto out = std::move(in_interactive_channel.front());
+ in_interactive_channel.pop();
+ return out;
+}
+
+void AppletDataBroker::PushNormalDataFromGame(IStorage storage) {
+ in_channel.push(std::make_unique<IStorage>(storage));
+}
+
+void AppletDataBroker::PushNormalDataFromApplet(IStorage storage) {
+ out_channel.push(std::make_unique<IStorage>(storage));
+ pop_out_data_event->Signal();
+}
+
+void AppletDataBroker::PushInteractiveDataFromGame(IStorage storage) {
+ in_interactive_channel.push(std::make_unique<IStorage>(storage));
+}
+
+void AppletDataBroker::PushInteractiveDataFromApplet(IStorage storage) {
+ out_interactive_channel.push(std::make_unique<IStorage>(storage));
+ pop_interactive_out_data_event->Signal();
+}
+
+void AppletDataBroker::SignalStateChanged() const {
+ state_changed_event->Signal();
+}
+
+Kernel::SharedPtr<Kernel::Event> AppletDataBroker::GetNormalDataEvent() const {
+ return pop_out_data_event;
+}
+
+Kernel::SharedPtr<Kernel::Event> AppletDataBroker::GetInteractiveDataEvent() const {
+ return pop_interactive_out_data_event;
+}
+
+Kernel::SharedPtr<Kernel::Event> AppletDataBroker::GetStateChangedEvent() const {
+ return state_changed_event;
+}
+
+Applet::Applet() = default;
+
+Applet::~Applet() = default;
+
+void Applet::Initialize() {
+ const auto common = broker.PopNormalDataToApplet();
+ ASSERT(common != nullptr);
+
+ const auto common_data = common->GetData();
+
+ ASSERT(common_data.size() >= sizeof(CommonArguments));
+ std::memcpy(&common_args, common_data.data(), sizeof(CommonArguments));
+
+ initialized = true;
+}
+
+} // namespace Service::AM::Applets
diff --git a/src/core/hle/service/am/applets/applets.h b/src/core/hle/service/am/applets/applets.h
new file mode 100644
index 000000000..f65ea119c
--- /dev/null
+++ b/src/core/hle/service/am/applets/applets.h
@@ -0,0 +1,112 @@
+// Copyright 2018 yuzu emulator team
+// Licensed under GPLv2 or any later version
+// Refer to the license.txt file included.
+
+#pragma once
+
+#include <memory>
+#include <queue>
+#include "common/swap.h"
+#include "core/hle/kernel/kernel.h"
+
+union ResultCode;
+
+namespace Kernel {
+class Event;
+}
+
+namespace Service::AM {
+
+class IStorage;
+
+namespace Applets {
+
+class AppletDataBroker final {
+public:
+ AppletDataBroker();
+ ~AppletDataBroker();
+
+ std::unique_ptr<IStorage> PopNormalDataToGame();
+ std::unique_ptr<IStorage> PopNormalDataToApplet();
+
+ std::unique_ptr<IStorage> PopInteractiveDataToGame();
+ std::unique_ptr<IStorage> PopInteractiveDataToApplet();
+
+ void PushNormalDataFromGame(IStorage storage);
+ void PushNormalDataFromApplet(IStorage storage);
+
+ void PushInteractiveDataFromGame(IStorage storage);
+ void PushInteractiveDataFromApplet(IStorage storage);
+
+ void SignalStateChanged() const;
+
+ Kernel::SharedPtr<Kernel::Event> GetNormalDataEvent() const;
+ Kernel::SharedPtr<Kernel::Event> GetInteractiveDataEvent() const;
+ Kernel::SharedPtr<Kernel::Event> GetStateChangedEvent() const;
+
+private:
+ // Queues are named from applet's perspective
+
+ // PopNormalDataToApplet and PushNormalDataFromGame
+ std::queue<std::unique_ptr<IStorage>> in_channel;
+
+ // PopNormalDataToGame and PushNormalDataFromApplet
+ std::queue<std::unique_ptr<IStorage>> out_channel;
+
+ // PopInteractiveDataToApplet and PushInteractiveDataFromGame
+ std::queue<std::unique_ptr<IStorage>> in_interactive_channel;
+
+ // PopInteractiveDataToGame and PushInteractiveDataFromApplet
+ std::queue<std::unique_ptr<IStorage>> out_interactive_channel;
+
+ Kernel::SharedPtr<Kernel::Event> state_changed_event;
+
+ // Signaled on PushNormalDataFromApplet
+ Kernel::SharedPtr<Kernel::Event> pop_out_data_event;
+
+ // Signaled on PushInteractiveDataFromApplet
+ Kernel::SharedPtr<Kernel::Event> pop_interactive_out_data_event;
+};
+
+class Applet {
+public:
+ Applet();
+ virtual ~Applet();
+
+ virtual void Initialize();
+
+ virtual bool TransactionComplete() const = 0;
+ virtual ResultCode GetStatus() const = 0;
+ virtual void ExecuteInteractive() = 0;
+ virtual void Execute() = 0;
+
+ bool IsInitialized() const {
+ return initialized;
+ }
+
+ AppletDataBroker& GetBroker() {
+ return broker;
+ }
+
+ const AppletDataBroker& GetBroker() const {
+ return broker;
+ }
+
+protected:
+ struct CommonArguments {
+ u32_le arguments_version;
+ u32_le size;
+ u32_le library_version;
+ u32_le theme_color;
+ u8 play_startup_sound;
+ u64_le system_tick;
+ };
+ static_assert(sizeof(CommonArguments) == 0x20, "CommonArguments has incorrect size.");
+
+ CommonArguments common_args{};
+ AppletDataBroker broker;
+ bool initialized = false;
+};
+
+} // namespace Applets
+} // namespace Service::AM
diff --git a/src/core/hle/service/am/applets/software_keyboard.cpp b/src/core/hle/service/am/applets/software_keyboard.cpp
new file mode 100644
index 000000000..981bdec51
--- /dev/null
+++ b/src/core/hle/service/am/applets/software_keyboard.cpp
@@ -0,0 +1,161 @@
+// Copyright 2018 yuzu emulator team
+// Licensed under GPLv2 or any later version
+// Refer to the license.txt file included.
+
+#include <cstring>
+#include "common/assert.h"
+#include "common/string_util.h"
+#include "core/core.h"
+#include "core/frontend/applets/software_keyboard.h"
+#include "core/hle/service/am/am.h"
+#include "core/hle/service/am/applets/software_keyboard.h"
+
+namespace Service::AM::Applets {
+
+constexpr std::size_t SWKBD_OUTPUT_BUFFER_SIZE = 0x7D8;
+constexpr std::size_t SWKBD_OUTPUT_INTERACTIVE_BUFFER_SIZE = 0x7D4;
+constexpr std::size_t DEFAULT_MAX_LENGTH = 500;
+constexpr bool INTERACTIVE_STATUS_OK = false;
+
+static Core::Frontend::SoftwareKeyboardParameters ConvertToFrontendParameters(
+ KeyboardConfig config, std::u16string initial_text) {
+ Core::Frontend::SoftwareKeyboardParameters params{};
+
+ params.submit_text = Common::UTF16StringFromFixedZeroTerminatedBuffer(
+ config.submit_text.data(), config.submit_text.size());
+ params.header_text = Common::UTF16StringFromFixedZeroTerminatedBuffer(
+ config.header_text.data(), config.header_text.size());
+ params.sub_text = Common::UTF16StringFromFixedZeroTerminatedBuffer(config.sub_text.data(),
+ config.sub_text.size());
+ params.guide_text = Common::UTF16StringFromFixedZeroTerminatedBuffer(config.guide_text.data(),
+ config.guide_text.size());
+ params.initial_text = initial_text;
+ params.max_length = config.length_limit == 0 ? DEFAULT_MAX_LENGTH : config.length_limit;
+ params.password = static_cast<bool>(config.is_password);
+ params.cursor_at_beginning = static_cast<bool>(config.initial_cursor_position);
+ params.value = static_cast<u8>(config.keyset_disable_bitmask);
+
+ return params;
+}
+
+SoftwareKeyboard::SoftwareKeyboard() = default;
+
+SoftwareKeyboard::~SoftwareKeyboard() = default;
+
+void SoftwareKeyboard::Initialize() {
+ complete = false;
+ initial_text.clear();
+ final_data.clear();
+
+ Applet::Initialize();
+
+ const auto keyboard_config_storage = broker.PopNormalDataToApplet();
+ ASSERT(keyboard_config_storage != nullptr);
+ const auto& keyboard_config = keyboard_config_storage->GetData();
+
+ ASSERT(keyboard_config.size() >= sizeof(KeyboardConfig));
+ std::memcpy(&config, keyboard_config.data(), sizeof(KeyboardConfig));
+
+ const auto work_buffer_storage = broker.PopNormalDataToApplet();
+ ASSERT(work_buffer_storage != nullptr);
+ const auto& work_buffer = work_buffer_storage->GetData();
+
+ if (config.initial_string_size == 0)
+ return;
+
+ std::vector<char16_t> string(config.initial_string_size);
+ std::memcpy(string.data(), work_buffer.data() + config.initial_string_offset,
+ string.size() * 2);
+ initial_text = Common::UTF16StringFromFixedZeroTerminatedBuffer(string.data(), string.size());
+}
+
+bool SoftwareKeyboard::TransactionComplete() const {
+ return complete;
+}
+
+ResultCode SoftwareKeyboard::GetStatus() const {
+ return RESULT_SUCCESS;
+}
+
+void SoftwareKeyboard::ExecuteInteractive() {
+ if (complete)
+ return;
+
+ const auto storage = broker.PopInteractiveDataToApplet();
+ ASSERT(storage != nullptr);
+ const auto data = storage->GetData();
+ const auto status = static_cast<bool>(data[0]);
+
+ if (status == INTERACTIVE_STATUS_OK) {
+ complete = true;
+ } else {
+ const auto& frontend{Core::System::GetInstance().GetSoftwareKeyboard()};
+
+ std::array<char16_t, SWKBD_OUTPUT_INTERACTIVE_BUFFER_SIZE / 2 - 2> string;
+ std::memcpy(string.data(), data.data() + 4, string.size() * 2);
+ frontend.SendTextCheckDialog(
+ Common::UTF16StringFromFixedZeroTerminatedBuffer(string.data(), string.size()),
+ [this] { broker.SignalStateChanged(); });
+ }
+}
+
+void SoftwareKeyboard::Execute() {
+ if (complete) {
+ broker.PushNormalDataFromApplet(IStorage{final_data});
+ return;
+ }
+
+ const auto& frontend{Core::System::GetInstance().GetSoftwareKeyboard()};
+
+ const auto parameters = ConvertToFrontendParameters(config, initial_text);
+
+ frontend.RequestText([this](std::optional<std::u16string> text) { WriteText(text); },
+ parameters);
+}
+
+void SoftwareKeyboard::WriteText(std::optional<std::u16string> text) {
+ std::vector<u8> output_main(SWKBD_OUTPUT_BUFFER_SIZE);
+
+ if (text.has_value()) {
+ std::vector<u8> output_sub(SWKBD_OUTPUT_BUFFER_SIZE);
+
+ if (config.utf_8) {
+ const u64 size = text->size() + 8;
+ const auto new_text = Common::UTF16ToUTF8(*text);
+
+ std::memcpy(output_sub.data(), &size, sizeof(u64));
+ std::memcpy(output_sub.data() + 8, new_text.data(),
+ std::min(new_text.size(), SWKBD_OUTPUT_BUFFER_SIZE - 8));
+
+ output_main[0] = INTERACTIVE_STATUS_OK;
+ std::memcpy(output_main.data() + 4, new_text.data(),
+ std::min(new_text.size(), SWKBD_OUTPUT_BUFFER_SIZE - 4));
+ } else {
+ const u64 size = text->size() * 2 + 8;
+ std::memcpy(output_sub.data(), &size, sizeof(u64));
+ std::memcpy(output_sub.data() + 8, text->data(),
+ std::min(text->size() * 2, SWKBD_OUTPUT_BUFFER_SIZE - 8));
+
+ output_main[0] = INTERACTIVE_STATUS_OK;
+ std::memcpy(output_main.data() + 4, text->data(),
+ std::min(text->size() * 2, SWKBD_OUTPUT_BUFFER_SIZE - 4));
+ }
+
+ complete = !config.text_check;
+ final_data = output_main;
+
+ if (complete) {
+ broker.PushNormalDataFromApplet(IStorage{output_main});
+ } else {
+ broker.PushInteractiveDataFromApplet(IStorage{output_sub});
+ }
+
+ broker.SignalStateChanged();
+ } else {
+ output_main[0] = 1;
+ complete = true;
+ broker.PushNormalDataFromApplet(IStorage{output_main});
+ broker.SignalStateChanged();
+ }
+}
+} // namespace Service::AM::Applets
diff --git a/src/core/hle/service/am/applets/software_keyboard.h b/src/core/hle/service/am/applets/software_keyboard.h
new file mode 100644
index 000000000..efd5753a1
--- /dev/null
+++ b/src/core/hle/service/am/applets/software_keyboard.h
@@ -0,0 +1,74 @@
+// Copyright 2018 yuzu emulator team
+// Licensed under GPLv2 or any later version
+// Refer to the license.txt file included.
+
+#pragma once
+
+#include <array>
+#include <string>
+#include <vector>
+
+#include "common/common_funcs.h"
+#include "common/swap.h"
+#include "core/hle/service/am/am.h"
+#include "core/hle/service/am/applets/applets.h"
+
+namespace Service::AM::Applets {
+
+enum class KeysetDisable : u32 {
+ Space = 0x02,
+ Address = 0x04,
+ Percent = 0x08,
+ Slashes = 0x10,
+ Numbers = 0x40,
+ DownloadCode = 0x80,
+};
+
+struct KeyboardConfig {
+ INSERT_PADDING_BYTES(4);
+ std::array<char16_t, 9> submit_text;
+ u16_le left_symbol_key;
+ u16_le right_symbol_key;
+ INSERT_PADDING_BYTES(1);
+ KeysetDisable keyset_disable_bitmask;
+ u32_le initial_cursor_position;
+ std::array<char16_t, 65> header_text;
+ std::array<char16_t, 129> sub_text;
+ std::array<char16_t, 257> guide_text;
+ u32_le length_limit;
+ INSERT_PADDING_BYTES(4);
+ u32_le is_password;
+ INSERT_PADDING_BYTES(5);
+ bool utf_8;
+ bool draw_background;
+ u32_le initial_string_offset;
+ u32_le initial_string_size;
+ u32_le user_dictionary_offset;
+ u32_le user_dictionary_size;
+ bool text_check;
+ u64_le text_check_callback;
+};
+static_assert(sizeof(KeyboardConfig) == 0x3E0, "KeyboardConfig has incorrect size.");
+
+class SoftwareKeyboard final : public Applet {
+public:
+ SoftwareKeyboard();
+ ~SoftwareKeyboard() override;
+
+ void Initialize() override;
+
+ bool TransactionComplete() const override;
+ ResultCode GetStatus() const override;
+ void ExecuteInteractive() override;
+ void Execute() override;
+
+ void WriteText(std::optional<std::u16string> text);
+
+private:
+ KeyboardConfig config;
+ std::u16string initial_text;
+ bool complete = false;
+ std::vector<u8> final_data;
+};
+
+} // namespace Service::AM::Applets
diff --git a/src/core/hle/service/am/applets/stub_applet.cpp b/src/core/hle/service/am/applets/stub_applet.cpp
new file mode 100644
index 000000000..ed166b87d
--- /dev/null
+++ b/src/core/hle/service/am/applets/stub_applet.cpp
@@ -0,0 +1,70 @@
+// Copyright 2018 yuzu emulator team
+// Licensed under GPLv2 or any later version
+// Refer to the license.txt file included.
+
+#include <string>
+
+#include "common/hex_util.h"
+#include "common/logging/log.h"
+#include "core/hle/result.h"
+#include "core/hle/service/am/am.h"
+#include "core/hle/service/am/applets/stub_applet.h"
+
+namespace Service::AM::Applets {
+
+static void LogCurrentStorage(AppletDataBroker& broker, std::string prefix) {
+ std::unique_ptr<IStorage> storage = broker.PopNormalDataToApplet();
+ for (; storage != nullptr; storage = broker.PopNormalDataToApplet()) {
+ const auto data = storage->GetData();
+ LOG_INFO(Service_AM,
+ "called (STUBBED), during {} recieved normal data with size={:08X}, data={}",
+ prefix, data.size(), Common::HexVectorToString(data));
+ }
+
+ storage = broker.PopInteractiveDataToApplet();
+ for (; storage != nullptr; storage = broker.PopInteractiveDataToApplet()) {
+ const auto data = storage->GetData();
+ LOG_INFO(Service_AM,
+ "called (STUBBED), during {} recieved interactive data with size={:08X}, data={}",
+ prefix, data.size(), Common::HexVectorToString(data));
+ }
+}
+
+StubApplet::StubApplet() = default;
+
+StubApplet::~StubApplet() = default;
+
+void StubApplet::Initialize() {
+ LOG_WARNING(Service_AM, "called (STUBBED)");
+ Applet::Initialize();
+ LogCurrentStorage(broker, "Initialize");
+}
+
+bool StubApplet::TransactionComplete() const {
+ LOG_WARNING(Service_AM, "called (STUBBED)");
+ return true;
+}
+
+ResultCode StubApplet::GetStatus() const {
+ LOG_WARNING(Service_AM, "called (STUBBED)");
+ return RESULT_SUCCESS;
+}
+
+void StubApplet::ExecuteInteractive() {
+ LOG_WARNING(Service_AM, "called (STUBBED)");
+ LogCurrentStorage(broker, "ExecuteInteractive");
+
+ broker.PushNormalDataFromApplet(IStorage{std::vector<u8>(0x1000)});
+ broker.PushInteractiveDataFromApplet(IStorage{std::vector<u8>(0x1000)});
+ broker.SignalStateChanged();
+}
+
+void StubApplet::Execute() {
+ LOG_WARNING(Service_AM, "called (STUBBED)");
+ LogCurrentStorage(broker, "Execute");
+
+ broker.PushNormalDataFromApplet(IStorage{std::vector<u8>(0x1000)});
+ broker.PushInteractiveDataFromApplet(IStorage{std::vector<u8>(0x1000)});
+ broker.SignalStateChanged();
+}
+} // namespace Service::AM::Applets
diff --git a/src/core/hle/service/am/applets/stub_applet.h b/src/core/hle/service/am/applets/stub_applet.h
new file mode 100644
index 000000000..7d8dc968d
--- /dev/null
+++ b/src/core/hle/service/am/applets/stub_applet.h
@@ -0,0 +1,24 @@
+// Copyright 2018 yuzu emulator team
+// Licensed under GPLv2 or any later version
+// Refer to the license.txt file included.
+
+#pragma once
+
+#include "core/hle/service/am/applets/applets.h"
+
+namespace Service::AM::Applets {
+
+class StubApplet final : public Applet {
+public:
+ StubApplet();
+ ~StubApplet() override;
+
+ void Initialize() override;
+
+ bool TransactionComplete() const override;
+ ResultCode GetStatus() const override;
+ void ExecuteInteractive() override;
+ void Execute() override;
+};
+
+} // namespace Service::AM::Applets
diff --git a/src/core/hle/service/audio/audout_u.cpp b/src/core/hle/service/audio/audout_u.cpp
index ff1edefbb..23e1f1165 100644
--- a/src/core/hle/service/audio/audout_u.cpp
+++ b/src/core/hle/service/audio/audout_u.cpp
@@ -44,8 +44,10 @@ enum class AudioState : u32 {
class IAudioOut final : public ServiceFramework<IAudioOut> {
public:
- IAudioOut(AudoutParams audio_params, AudioCore::AudioOut& audio_core)
- : ServiceFramework("IAudioOut"), audio_core(audio_core), audio_params(audio_params) {
+ IAudioOut(AudoutParams audio_params, AudioCore::AudioOut& audio_core, std::string&& device_name,
+ std::string&& unique_name)
+ : ServiceFramework("IAudioOut"), audio_core(audio_core), audio_params(audio_params),
+ device_name(std::move(device_name)) {
static const FunctionInfo functions[] = {
{0, &IAudioOut::GetAudioOutState, "GetAudioOutState"},
@@ -69,7 +71,7 @@ public:
Kernel::Event::Create(kernel, Kernel::ResetType::Sticky, "IAudioOutBufferReleased");
stream = audio_core.OpenStream(audio_params.sample_rate, audio_params.channel_count,
- "IAudioOut", [=]() { buffer_event->Signal(); });
+ std::move(unique_name), [=]() { buffer_event->Signal(); });
}
private:
@@ -177,6 +179,7 @@ private:
AudioCore::AudioOut& audio_core;
AudioCore::StreamPtr stream;
+ std::string device_name;
AudoutParams audio_params{};
@@ -199,7 +202,15 @@ void AudOutU::ListAudioOutsImpl(Kernel::HLERequestContext& ctx) {
void AudOutU::OpenAudioOutImpl(Kernel::HLERequestContext& ctx) {
LOG_DEBUG(Service_Audio, "called");
- ctx.WriteBuffer(DefaultDevice);
+ const auto device_name_data{ctx.ReadBuffer()};
+ std::string device_name;
+ if (device_name_data[0] != '\0') {
+ device_name.assign(device_name_data.begin(), device_name_data.end());
+ } else {
+ device_name.assign(DefaultDevice.begin(), DefaultDevice.end());
+ }
+ ctx.WriteBuffer(device_name);
+
IPC::RequestParser rp{ctx};
auto params{rp.PopRaw<AudoutParams>()};
if (params.channel_count <= 2) {
@@ -212,10 +223,9 @@ void AudOutU::OpenAudioOutImpl(Kernel::HLERequestContext& ctx) {
params.sample_rate = DefaultSampleRate;
}
- // TODO(bunnei): Support more than one IAudioOut interface. When we add this, ListAudioOutsImpl
- // will likely need to be updated as well.
- ASSERT_MSG(!audio_out_interface, "Unimplemented");
- audio_out_interface = std::make_shared<IAudioOut>(params, *audio_core);
+ std::string unique_name{fmt::format("{}-{}", device_name, audio_out_interfaces.size())};
+ auto audio_out_interface = std::make_shared<IAudioOut>(
+ params, *audio_core, std::move(device_name), std::move(unique_name));
IPC::ResponseBuilder rb{ctx, 6, 0, 1};
rb.Push(RESULT_SUCCESS);
@@ -224,6 +234,8 @@ void AudOutU::OpenAudioOutImpl(Kernel::HLERequestContext& ctx) {
rb.Push<u32>(static_cast<u32>(AudioCore::Codec::PcmFormat::Int16));
rb.Push<u32>(static_cast<u32>(AudioState::Stopped));
rb.PushIpcInterface<Audio::IAudioOut>(audio_out_interface);
+
+ audio_out_interfaces.push_back(std::move(audio_out_interface));
}
AudOutU::AudOutU() : ServiceFramework("audout:u") {
diff --git a/src/core/hle/service/audio/audout_u.h b/src/core/hle/service/audio/audout_u.h
index dcaf64708..aed4c43b2 100644
--- a/src/core/hle/service/audio/audout_u.h
+++ b/src/core/hle/service/audio/audout_u.h
@@ -4,6 +4,7 @@
#pragma once
+#include <vector>
#include "core/hle/service/service.h"
namespace AudioCore {
@@ -24,7 +25,7 @@ public:
~AudOutU() override;
private:
- std::shared_ptr<IAudioOut> audio_out_interface;
+ std::vector<std::shared_ptr<IAudioOut>> audio_out_interfaces;
std::unique_ptr<AudioCore::AudioOut> audio_core;
void ListAudioOutsImpl(Kernel::HLERequestContext& ctx);
diff --git a/src/core/hle/service/audio/audren_u.cpp b/src/core/hle/service/audio/audren_u.cpp
index fac6785a5..d3ea57ea7 100644
--- a/src/core/hle/service/audio/audren_u.cpp
+++ b/src/core/hle/service/audio/audren_u.cpp
@@ -28,13 +28,13 @@ public:
{1, &IAudioRenderer::GetSampleCount, "GetSampleCount"},
{2, &IAudioRenderer::GetMixBufferCount, "GetMixBufferCount"},
{3, &IAudioRenderer::GetState, "GetState"},
- {4, &IAudioRenderer::RequestUpdate, "RequestUpdate"},
+ {4, &IAudioRenderer::RequestUpdateImpl, "RequestUpdate"},
{5, &IAudioRenderer::Start, "Start"},
{6, &IAudioRenderer::Stop, "Stop"},
{7, &IAudioRenderer::QuerySystemEvent, "QuerySystemEvent"},
- {8, nullptr, "SetRenderingTimeLimit"},
- {9, nullptr, "GetRenderingTimeLimit"},
- {10, nullptr, "RequestUpdateAuto"},
+ {8, &IAudioRenderer::SetRenderingTimeLimit, "SetRenderingTimeLimit"},
+ {9, &IAudioRenderer::GetRenderingTimeLimit, "GetRenderingTimeLimit"},
+ {10, &IAudioRenderer::RequestUpdateImpl, "RequestUpdateAuto"},
{11, nullptr, "ExecuteAudioRendererRendering"},
};
// clang-format on
@@ -79,7 +79,7 @@ private:
LOG_DEBUG(Service_Audio, "called");
}
- void RequestUpdate(Kernel::HLERequestContext& ctx) {
+ void RequestUpdateImpl(Kernel::HLERequestContext& ctx) {
ctx.WriteBuffer(renderer->UpdateAudioRenderer(ctx.ReadBuffer()));
IPC::ResponseBuilder rb{ctx, 2};
rb.Push(RESULT_SUCCESS);
@@ -110,8 +110,29 @@ private:
LOG_WARNING(Service_Audio, "(STUBBED) called");
}
+ void SetRenderingTimeLimit(Kernel::HLERequestContext& ctx) {
+ IPC::RequestParser rp{ctx};
+ rendering_time_limit_percent = rp.Pop<u32>();
+ ASSERT(rendering_time_limit_percent >= 0 && rendering_time_limit_percent <= 100);
+
+ IPC::ResponseBuilder rb{ctx, 2};
+ rb.Push(RESULT_SUCCESS);
+
+ LOG_DEBUG(Service_Audio, "called. rendering_time_limit_percent={}",
+ rendering_time_limit_percent);
+ }
+
+ void GetRenderingTimeLimit(Kernel::HLERequestContext& ctx) {
+ LOG_DEBUG(Service_Audio, "called");
+
+ IPC::ResponseBuilder rb{ctx, 3};
+ rb.Push(RESULT_SUCCESS);
+ rb.Push(rendering_time_limit_percent);
+ }
+
Kernel::SharedPtr<Kernel::Event> system_event;
std::unique_ptr<AudioCore::AudioRenderer> renderer;
+ u32 rendering_time_limit_percent = 100;
};
class IAudioDevice final : public ServiceFramework<IAudioDevice> {
diff --git a/src/core/hle/service/audio/hwopus.cpp b/src/core/hle/service/audio/hwopus.cpp
index 783c39503..763e619a4 100644
--- a/src/core/hle/service/audio/hwopus.cpp
+++ b/src/core/hle/service/audio/hwopus.cpp
@@ -77,8 +77,8 @@ private:
IPC::ResponseBuilder rb{ctx, 6};
rb.Push(RESULT_SUCCESS);
rb.Push<u32>(consumed);
- rb.Push<u64>(performance);
rb.Push<u32>(sample_count);
+ rb.Push<u64>(performance);
ctx.WriteBuffer(samples.data(), samples.size() * sizeof(s16));
}
diff --git a/src/core/hle/service/btdrv/btdrv.cpp b/src/core/hle/service/btdrv/btdrv.cpp
index d0a15cc4c..f3bde6d0d 100644
--- a/src/core/hle/service/btdrv/btdrv.cpp
+++ b/src/core/hle/service/btdrv/btdrv.cpp
@@ -2,12 +2,49 @@
// Licensed under GPLv2 or any later version
// Refer to the license.txt file included.
+#include "common/logging/log.h"
+#include "core/hle/ipc_helpers.h"
+#include "core/hle/kernel/event.h"
+#include "core/hle/kernel/hle_ipc.h"
#include "core/hle/service/btdrv/btdrv.h"
#include "core/hle/service/service.h"
#include "core/hle/service/sm/sm.h"
namespace Service::BtDrv {
+class Bt final : public ServiceFramework<Bt> {
+public:
+ explicit Bt() : ServiceFramework{"bt"} {
+ // clang-format off
+ static const FunctionInfo functions[] = {
+ {0, nullptr, "Unknown0"},
+ {1, nullptr, "Unknown1"},
+ {2, nullptr, "Unknown2"},
+ {3, nullptr, "Unknown3"},
+ {4, nullptr, "Unknown4"},
+ {5, nullptr, "Unknown5"},
+ {6, nullptr, "Unknown6"},
+ {7, nullptr, "Unknown7"},
+ {8, nullptr, "Unknown8"},
+ {9, &Bt::RegisterEvent, "RegisterEvent"},
+ };
+ // clang-format on
+ RegisterHandlers(functions);
+ }
+
+private:
+ void RegisterEvent(Kernel::HLERequestContext& ctx) {
+ auto& kernel = Core::System::GetInstance().Kernel();
+ register_event =
+ Kernel::Event::Create(kernel, Kernel::ResetType::OneShot, "BT:RegisterEvent");
+ IPC::ResponseBuilder rb{ctx, 2, 1};
+ rb.Push(RESULT_SUCCESS);
+ rb.PushCopyObjects(register_event);
+ LOG_WARNING(Service_BTM, "(STUBBED) called");
+ }
+ Kernel::SharedPtr<Kernel::Event> register_event;
+};
+
class BtDrv final : public ServiceFramework<BtDrv> {
public:
explicit BtDrv() : ServiceFramework{"btdrv"} {
@@ -67,6 +104,7 @@ public:
void InstallInterfaces(SM::ServiceManager& sm) {
std::make_shared<BtDrv>()->InstallAsService(sm);
+ std::make_shared<Bt>()->InstallAsService(sm);
}
} // namespace Service::BtDrv
diff --git a/src/core/hle/service/btm/btm.cpp b/src/core/hle/service/btm/btm.cpp
index b949bfabd..a02f6b53a 100644
--- a/src/core/hle/service/btm/btm.cpp
+++ b/src/core/hle/service/btm/btm.cpp
@@ -6,13 +6,118 @@
#include "common/logging/log.h"
#include "core/hle/ipc_helpers.h"
+#include "core/hle/kernel/event.h"
#include "core/hle/kernel/hle_ipc.h"
#include "core/hle/service/btm/btm.h"
#include "core/hle/service/service.h"
-#include "core/hle/service/sm/sm.h"
namespace Service::BTM {
+class IBtmUserCore final : public ServiceFramework<IBtmUserCore> {
+public:
+ explicit IBtmUserCore() : ServiceFramework{"IBtmUserCore"} {
+ // clang-format off
+ static const FunctionInfo functions[] = {
+ {0, &IBtmUserCore::GetScanEvent, "GetScanEvent"},
+ {1, nullptr, "Unknown1"},
+ {2, nullptr, "Unknown2"},
+ {3, nullptr, "Unknown3"},
+ {4, nullptr, "Unknown4"},
+ {5, nullptr, "Unknown5"},
+ {6, nullptr, "Unknown6"},
+ {7, nullptr, "Unknown7"},
+ {8, nullptr, "Unknown8"},
+ {9, nullptr, "Unknown9"},
+ {10, nullptr, "Unknown10"},
+ {17, &IBtmUserCore::GetConnectionEvent, "GetConnectionEvent"},
+ {18, nullptr, "Unknown18"},
+ {19, nullptr, "Unknown19"},
+ {20, nullptr, "Unknown20"},
+ {21, nullptr, "Unknown21"},
+ {22, nullptr, "Unknown22"},
+ {23, nullptr, "Unknown23"},
+ {24, nullptr, "Unknown24"},
+ {25, nullptr, "Unknown25"},
+ {26, &IBtmUserCore::GetDiscoveryEvent, "AcquireBleServiceDiscoveryEventImpl"},
+ {27, nullptr, "Unknown27"},
+ {28, nullptr, "Unknown28"},
+ {29, nullptr, "Unknown29"},
+ {30, nullptr, "Unknown30"},
+ {31, nullptr, "Unknown31"},
+ {32, nullptr, "Unknown32"},
+ {33, &IBtmUserCore::GetConfigEvent, "GetConfigEvent"},
+ {34, nullptr, "Unknown34"},
+ {35, nullptr, "Unknown35"},
+ {36, nullptr, "Unknown36"},
+ {37, nullptr, "Unknown37"},
+ };
+ // clang-format on
+ RegisterHandlers(functions);
+ }
+
+private:
+ void GetScanEvent(Kernel::HLERequestContext& ctx) {
+ auto& kernel = Core::System::GetInstance().Kernel();
+ scan_event =
+ Kernel::Event::Create(kernel, Kernel::ResetType::OneShot, "IBtmUserCore:ScanEvent");
+ IPC::ResponseBuilder rb{ctx, 2, 1};
+ rb.Push(RESULT_SUCCESS);
+ rb.PushCopyObjects(scan_event);
+ LOG_WARNING(Service_BTM, "(STUBBED) called");
+ }
+ void GetConnectionEvent(Kernel::HLERequestContext& ctx) {
+ auto& kernel = Core::System::GetInstance().Kernel();
+ connection_event = Kernel::Event::Create(kernel, Kernel::ResetType::OneShot,
+ "IBtmUserCore:ConnectionEvent");
+ IPC::ResponseBuilder rb{ctx, 2, 1};
+ rb.Push(RESULT_SUCCESS);
+ rb.PushCopyObjects(connection_event);
+ LOG_WARNING(Service_BTM, "(STUBBED) called");
+ }
+ void GetDiscoveryEvent(Kernel::HLERequestContext& ctx) {
+ auto& kernel = Core::System::GetInstance().Kernel();
+ service_discovery =
+ Kernel::Event::Create(kernel, Kernel::ResetType::OneShot, "IBtmUserCore:Discovery");
+ IPC::ResponseBuilder rb{ctx, 2, 1};
+ rb.Push(RESULT_SUCCESS);
+ rb.PushCopyObjects(service_discovery);
+ LOG_WARNING(Service_BTM, "(STUBBED) called");
+ }
+ void GetConfigEvent(Kernel::HLERequestContext& ctx) {
+ auto& kernel = Core::System::GetInstance().Kernel();
+ config_event =
+ Kernel::Event::Create(kernel, Kernel::ResetType::OneShot, "IBtmUserCore:ConfigEvent");
+ IPC::ResponseBuilder rb{ctx, 2, 1};
+ rb.Push(RESULT_SUCCESS);
+ rb.PushCopyObjects(config_event);
+ LOG_WARNING(Service_BTM, "(STUBBED) called");
+ }
+ Kernel::SharedPtr<Kernel::Event> scan_event;
+ Kernel::SharedPtr<Kernel::Event> connection_event;
+ Kernel::SharedPtr<Kernel::Event> service_discovery;
+ Kernel::SharedPtr<Kernel::Event> config_event;
+};
+
+class BTM_USR final : public ServiceFramework<BTM_USR> {
+public:
+ explicit BTM_USR() : ServiceFramework{"btm:u"} {
+ // clang-format off
+ static const FunctionInfo functions[] = {
+ {0, &BTM_USR::GetCoreImpl, "GetCoreImpl"},
+ };
+ // clang-format on
+ RegisterHandlers(functions);
+ }
+
+private:
+ void GetCoreImpl(Kernel::HLERequestContext& ctx) {
+ IPC::ResponseBuilder rb{ctx, 2, 0, 1};
+ rb.Push(RESULT_SUCCESS);
+ rb.PushIpcInterface<IBtmUserCore>();
+ LOG_DEBUG(Service_BTM, "called");
+ }
+};
+
class BTM final : public ServiceFramework<BTM> {
public:
explicit BTM() : ServiceFramework{"btm"} {
@@ -116,6 +221,7 @@ void InstallInterfaces(SM::ServiceManager& sm) {
std::make_shared<BTM>()->InstallAsService(sm);
std::make_shared<BTM_DBG>()->InstallAsService(sm);
std::make_shared<BTM_SYS>()->InstallAsService(sm);
+ std::make_shared<BTM_USR>()->InstallAsService(sm);
}
} // namespace Service::BTM
diff --git a/src/core/hle/service/filesystem/filesystem.cpp b/src/core/hle/service/filesystem/filesystem.cpp
index e32a7c48e..2aa77f68d 100644
--- a/src/core/hle/service/filesystem/filesystem.cpp
+++ b/src/core/hle/service/filesystem/filesystem.cpp
@@ -303,25 +303,46 @@ ResultVal<FileSys::VirtualDir> OpenSaveData(FileSys::SaveDataSpaceId space,
static_cast<u8>(space), save_struct.DebugInfo());
if (save_data_factory == nullptr) {
- return ResultCode(ErrorModule::FS, FileSys::ErrCodes::TitleNotFound);
+ return FileSys::ERROR_ENTITY_NOT_FOUND;
}
return save_data_factory->Open(space, save_struct);
}
+ResultVal<FileSys::VirtualDir> OpenSaveDataSpace(FileSys::SaveDataSpaceId space) {
+ LOG_TRACE(Service_FS, "Opening Save Data Space for space_id={:01X}", static_cast<u8>(space));
+
+ if (save_data_factory == nullptr) {
+ return FileSys::ERROR_ENTITY_NOT_FOUND;
+ }
+
+ return MakeResult(save_data_factory->GetSaveDataSpaceDirectory(space));
+}
+
ResultVal<FileSys::VirtualDir> OpenSDMC() {
LOG_TRACE(Service_FS, "Opening SDMC");
if (sdmc_factory == nullptr) {
- return ResultCode(ErrorModule::FS, FileSys::ErrCodes::SdCardNotFound);
+ return FileSys::ERROR_SD_CARD_NOT_FOUND;
}
return sdmc_factory->Open();
}
-std::unique_ptr<FileSys::RegisteredCacheUnion> GetUnionContents() {
- return std::make_unique<FileSys::RegisteredCacheUnion>(std::vector<FileSys::RegisteredCache*>{
- GetSystemNANDContents(), GetUserNANDContents(), GetSDMCContents()});
+std::shared_ptr<FileSys::RegisteredCacheUnion> registered_cache_union;
+
+std::shared_ptr<FileSys::RegisteredCacheUnion> GetUnionContents() {
+ if (registered_cache_union == nullptr) {
+ registered_cache_union =
+ std::make_shared<FileSys::RegisteredCacheUnion>(std::vector<FileSys::RegisteredCache*>{
+ GetSystemNANDContents(), GetUserNANDContents(), GetSDMCContents()});
+ }
+
+ return registered_cache_union;
+}
+
+void ClearUnionContents() {
+ registered_cache_union = nullptr;
}
FileSys::RegisteredCache* GetSystemNANDContents() {
@@ -360,11 +381,21 @@ FileSys::VirtualDir GetModificationLoadRoot(u64 title_id) {
return bis_factory->GetModificationLoadRoot(title_id);
}
+FileSys::VirtualDir GetModificationDumpRoot(u64 title_id) {
+ LOG_TRACE(Service_FS, "Opening mod dump root for tid={:016X}", title_id);
+
+ if (bis_factory == nullptr)
+ return nullptr;
+
+ return bis_factory->GetModificationDumpRoot(title_id);
+}
+
void CreateFactories(FileSys::VfsFilesystem& vfs, bool overwrite) {
if (overwrite) {
bis_factory = nullptr;
save_data_factory = nullptr;
sdmc_factory = nullptr;
+ ClearUnionContents();
}
auto nand_directory = vfs.OpenDirectory(FileUtil::GetUserPath(FileUtil::UserPath::NANDDir),
@@ -373,13 +404,21 @@ void CreateFactories(FileSys::VfsFilesystem& vfs, bool overwrite) {
FileSys::Mode::ReadWrite);
auto load_directory = vfs.OpenDirectory(FileUtil::GetUserPath(FileUtil::UserPath::LoadDir),
FileSys::Mode::ReadWrite);
+ auto dump_directory = vfs.OpenDirectory(FileUtil::GetUserPath(FileUtil::UserPath::DumpDir),
+ FileSys::Mode::ReadWrite);
- if (bis_factory == nullptr)
- bis_factory = std::make_unique<FileSys::BISFactory>(nand_directory, load_directory);
- if (save_data_factory == nullptr)
+ if (bis_factory == nullptr) {
+ bis_factory =
+ std::make_unique<FileSys::BISFactory>(nand_directory, load_directory, dump_directory);
+ }
+
+ if (save_data_factory == nullptr) {
save_data_factory = std::make_unique<FileSys::SaveDataFactory>(std::move(nand_directory));
- if (sdmc_factory == nullptr)
+ }
+
+ if (sdmc_factory == nullptr) {
sdmc_factory = std::make_unique<FileSys::SDMCFactory>(std::move(sd_directory));
+ }
}
void InstallInterfaces(SM::ServiceManager& service_manager, FileSys::VfsFilesystem& vfs) {
diff --git a/src/core/hle/service/filesystem/filesystem.h b/src/core/hle/service/filesystem/filesystem.h
index 6ca5c5636..0a6cb6635 100644
--- a/src/core/hle/service/filesystem/filesystem.h
+++ b/src/core/hle/service/filesystem/filesystem.h
@@ -45,15 +45,18 @@ ResultVal<FileSys::VirtualFile> OpenRomFS(u64 title_id, FileSys::StorageId stora
FileSys::ContentRecordType type);
ResultVal<FileSys::VirtualDir> OpenSaveData(FileSys::SaveDataSpaceId space,
FileSys::SaveDataDescriptor save_struct);
+ResultVal<FileSys::VirtualDir> OpenSaveDataSpace(FileSys::SaveDataSpaceId space);
ResultVal<FileSys::VirtualDir> OpenSDMC();
-std::unique_ptr<FileSys::RegisteredCacheUnion> GetUnionContents();
+std::shared_ptr<FileSys::RegisteredCacheUnion> GetUnionContents();
+void ClearUnionContents();
FileSys::RegisteredCache* GetSystemNANDContents();
FileSys::RegisteredCache* GetUserNANDContents();
FileSys::RegisteredCache* GetSDMCContents();
FileSys::VirtualDir GetModificationLoadRoot(u64 title_id);
+FileSys::VirtualDir GetModificationDumpRoot(u64 title_id);
// Creates the SaveData, SDMC, and BIS Factories. Should be called once and before any function
// above is called.
diff --git a/src/core/hle/service/filesystem/fsp_srv.cpp b/src/core/hle/service/filesystem/fsp_srv.cpp
index c1c83a11d..038dc80b1 100644
--- a/src/core/hle/service/filesystem/fsp_srv.cpp
+++ b/src/core/hle/service/filesystem/fsp_srv.cpp
@@ -11,6 +11,7 @@
#include "common/assert.h"
#include "common/common_types.h"
+#include "common/hex_util.h"
#include "common/logging/log.h"
#include "common/string_util.h"
#include "core/file_sys/directory.h"
@@ -62,12 +63,12 @@ private:
// Error checking
if (length < 0) {
IPC::ResponseBuilder rb{ctx, 2};
- rb.Push(ResultCode(ErrorModule::FS, ErrorDescription::InvalidLength));
+ rb.Push(FileSys::ERROR_INVALID_SIZE);
return;
}
if (offset < 0) {
IPC::ResponseBuilder rb{ctx, 2};
- rb.Push(ResultCode(ErrorModule::FS, ErrorDescription::InvalidOffset));
+ rb.Push(FileSys::ERROR_INVALID_OFFSET);
return;
}
@@ -107,12 +108,12 @@ private:
// Error checking
if (length < 0) {
IPC::ResponseBuilder rb{ctx, 2};
- rb.Push(ResultCode(ErrorModule::FS, ErrorDescription::InvalidLength));
+ rb.Push(FileSys::ERROR_INVALID_SIZE);
return;
}
if (offset < 0) {
IPC::ResponseBuilder rb{ctx, 2};
- rb.Push(ResultCode(ErrorModule::FS, ErrorDescription::InvalidOffset));
+ rb.Push(FileSys::ERROR_INVALID_OFFSET);
return;
}
@@ -138,12 +139,12 @@ private:
// Error checking
if (length < 0) {
IPC::ResponseBuilder rb{ctx, 2};
- rb.Push(ResultCode(ErrorModule::FS, ErrorDescription::InvalidLength));
+ rb.Push(FileSys::ERROR_INVALID_SIZE);
return;
}
if (offset < 0) {
IPC::ResponseBuilder rb{ctx, 2};
- rb.Push(ResultCode(ErrorModule::FS, ErrorDescription::InvalidOffset));
+ rb.Push(FileSys::ERROR_INVALID_OFFSET);
return;
}
@@ -451,7 +452,147 @@ private:
VfsDirectoryServiceWrapper backend;
};
+class ISaveDataInfoReader final : public ServiceFramework<ISaveDataInfoReader> {
+public:
+ explicit ISaveDataInfoReader(FileSys::SaveDataSpaceId space)
+ : ServiceFramework("ISaveDataInfoReader") {
+ static const FunctionInfo functions[] = {
+ {0, &ISaveDataInfoReader::ReadSaveDataInfo, "ReadSaveDataInfo"},
+ };
+ RegisterHandlers(functions);
+
+ FindAllSaves(space);
+ }
+
+ void ReadSaveDataInfo(Kernel::HLERequestContext& ctx) {
+ // Calculate how many entries we can fit in the output buffer
+ const u64 count_entries = ctx.GetWriteBufferSize() / sizeof(SaveDataInfo);
+
+ // Cap at total number of entries.
+ const u64 actual_entries = std::min(count_entries, info.size() - next_entry_index);
+
+ // Determine data start and end
+ const auto* begin = reinterpret_cast<u8*>(info.data() + next_entry_index);
+ const auto* end = reinterpret_cast<u8*>(info.data() + next_entry_index + actual_entries);
+ const auto range_size = static_cast<std::size_t>(std::distance(begin, end));
+
+ next_entry_index += actual_entries;
+
+ // Write the data to memory
+ ctx.WriteBuffer(begin, range_size);
+
+ IPC::ResponseBuilder rb{ctx, 3};
+ rb.Push(RESULT_SUCCESS);
+ rb.Push<u32>(static_cast<u32>(actual_entries));
+ }
+
+private:
+ static u64 stoull_be(std::string_view str) {
+ if (str.size() != 16)
+ return 0;
+
+ const auto bytes = Common::HexStringToArray<0x8>(str);
+ u64 out{};
+ std::memcpy(&out, bytes.data(), sizeof(u64));
+
+ return Common::swap64(out);
+ }
+
+ void FindAllSaves(FileSys::SaveDataSpaceId space) {
+ const auto save_root = OpenSaveDataSpace(space);
+ ASSERT(save_root.Succeeded());
+
+ for (const auto& type : (*save_root)->GetSubdirectories()) {
+ if (type->GetName() == "save") {
+ for (const auto& save_id : type->GetSubdirectories()) {
+ for (const auto& user_id : save_id->GetSubdirectories()) {
+ const auto save_id_numeric = stoull_be(save_id->GetName());
+ auto user_id_numeric = Common::HexStringToArray<0x10>(user_id->GetName());
+ std::reverse(user_id_numeric.begin(), user_id_numeric.end());
+
+ if (save_id_numeric != 0) {
+ // System Save Data
+ info.emplace_back(SaveDataInfo{
+ 0,
+ space,
+ FileSys::SaveDataType::SystemSaveData,
+ {},
+ user_id_numeric,
+ save_id_numeric,
+ 0,
+ user_id->GetSize(),
+ {},
+ });
+
+ continue;
+ }
+
+ for (const auto& title_id : user_id->GetSubdirectories()) {
+ const auto device =
+ std::all_of(user_id_numeric.begin(), user_id_numeric.end(),
+ [](u8 val) { return val == 0; });
+ info.emplace_back(SaveDataInfo{
+ 0,
+ space,
+ device ? FileSys::SaveDataType::DeviceSaveData
+ : FileSys::SaveDataType::SaveData,
+ {},
+ user_id_numeric,
+ save_id_numeric,
+ stoull_be(title_id->GetName()),
+ title_id->GetSize(),
+ {},
+ });
+ }
+ }
+ }
+ } else if (space == FileSys::SaveDataSpaceId::TemporaryStorage) {
+ // Temporary Storage
+ for (const auto& user_id : type->GetSubdirectories()) {
+ for (const auto& title_id : user_id->GetSubdirectories()) {
+ if (!title_id->GetFiles().empty() ||
+ !title_id->GetSubdirectories().empty()) {
+ auto user_id_numeric =
+ Common::HexStringToArray<0x10>(user_id->GetName());
+ std::reverse(user_id_numeric.begin(), user_id_numeric.end());
+
+ info.emplace_back(SaveDataInfo{
+ 0,
+ space,
+ FileSys::SaveDataType::TemporaryStorage,
+ {},
+ user_id_numeric,
+ stoull_be(type->GetName()),
+ stoull_be(title_id->GetName()),
+ title_id->GetSize(),
+ {},
+ });
+ }
+ }
+ }
+ }
+ }
+ }
+
+ struct SaveDataInfo {
+ u64_le save_id_unknown;
+ FileSys::SaveDataSpaceId space;
+ FileSys::SaveDataType type;
+ INSERT_PADDING_BYTES(0x6);
+ std::array<u8, 0x10> user_id;
+ u64_le save_id;
+ u64_le title_id;
+ u64_le save_image_size;
+ INSERT_PADDING_BYTES(0x28);
+ };
+ static_assert(sizeof(SaveDataInfo) == 0x60, "SaveDataInfo has incorrect size.");
+
+ std::vector<SaveDataInfo> info;
+ u64 next_entry_index = 0;
+};
+
FSP_SRV::FSP_SRV() : ServiceFramework("fsp-srv") {
+ // clang-format off
static const FunctionInfo functions[] = {
{0, nullptr, "MountContent"},
{1, &FSP_SRV::Initialize, "Initialize"},
@@ -485,7 +626,7 @@ FSP_SRV::FSP_SRV() : ServiceFramework("fsp-srv") {
{58, nullptr, "ReadSaveDataFileSystemExtraData"},
{59, nullptr, "WriteSaveDataFileSystemExtraData"},
{60, nullptr, "OpenSaveDataInfoReader"},
- {61, nullptr, "OpenSaveDataInfoReaderBySaveDataSpaceId"},
+ {61, &FSP_SRV::OpenSaveDataInfoReaderBySaveDataSpaceId, "OpenSaveDataInfoReaderBySaveDataSpaceId"},
{62, nullptr, "OpenCacheStorageList"},
{64, nullptr, "OpenSaveDataInternalStorageFileSystem"},
{65, nullptr, "UpdateSaveDataMacForDebug"},
@@ -544,6 +685,7 @@ FSP_SRV::FSP_SRV() : ServiceFramework("fsp-srv") {
{1009, nullptr, "GetAndClearMemoryReportInfo"},
{1100, nullptr, "OverrideSaveDataTransferTokenSignVerificationKey"},
};
+ // clang-format on
RegisterHandlers(functions);
}
@@ -602,7 +744,7 @@ void FSP_SRV::MountSaveData(Kernel::HLERequestContext& ctx) {
if (dir.Failed()) {
IPC::ResponseBuilder rb{ctx, 2, 0, 0};
- rb.Push(ResultCode(ErrorModule::FS, FileSys::ErrCodes::TitleNotFound));
+ rb.Push(FileSys::ERROR_ENTITY_NOT_FOUND);
return;
}
@@ -618,6 +760,15 @@ void FSP_SRV::OpenReadOnlySaveDataFileSystem(Kernel::HLERequestContext& ctx) {
MountSaveData(ctx);
}
+void FSP_SRV::OpenSaveDataInfoReaderBySaveDataSpaceId(Kernel::HLERequestContext& ctx) {
+ IPC::RequestParser rp{ctx};
+ const auto space = rp.PopRaw<FileSys::SaveDataSpaceId>();
+
+ IPC::ResponseBuilder rb{ctx, 2, 0, 1};
+ rb.Push(RESULT_SUCCESS);
+ rb.PushIpcInterface<ISaveDataInfoReader>(std::make_shared<ISaveDataInfoReader>(space));
+}
+
void FSP_SRV::GetGlobalAccessLogMode(Kernel::HLERequestContext& ctx) {
LOG_WARNING(Service_FS, "(STUBBED) called");
@@ -685,7 +836,7 @@ void FSP_SRV::OpenRomStorage(Kernel::HLERequestContext& ctx) {
static_cast<u8>(storage_id), title_id);
IPC::ResponseBuilder rb{ctx, 2};
- rb.Push(ResultCode(ErrorModule::FS, FileSys::ErrCodes::TitleNotFound));
+ rb.Push(FileSys::ERROR_ENTITY_NOT_FOUND);
}
} // namespace Service::FileSystem
diff --git a/src/core/hle/service/filesystem/fsp_srv.h b/src/core/hle/service/filesystem/fsp_srv.h
index 4aa0358cb..e7abec0a3 100644
--- a/src/core/hle/service/filesystem/fsp_srv.h
+++ b/src/core/hle/service/filesystem/fsp_srv.h
@@ -25,6 +25,7 @@ private:
void CreateSaveData(Kernel::HLERequestContext& ctx);
void MountSaveData(Kernel::HLERequestContext& ctx);
void OpenReadOnlySaveDataFileSystem(Kernel::HLERequestContext& ctx);
+ void OpenSaveDataInfoReaderBySaveDataSpaceId(Kernel::HLERequestContext& ctx);
void GetGlobalAccessLogMode(Kernel::HLERequestContext& ctx);
void OpenDataStorageByCurrentProcess(Kernel::HLERequestContext& ctx);
void OpenDataStorageByDataId(Kernel::HLERequestContext& ctx);
diff --git a/src/core/hle/service/hid/controllers/debug_pad.cpp b/src/core/hle/service/hid/controllers/debug_pad.cpp
index 3d100763f..c22357d8c 100644
--- a/src/core/hle/service/hid/controllers/debug_pad.cpp
+++ b/src/core/hle/service/hid/controllers/debug_pad.cpp
@@ -6,9 +6,14 @@
#include "common/common_types.h"
#include "core/core_timing.h"
#include "core/hle/service/hid/controllers/debug_pad.h"
+#include "core/settings.h"
namespace Service::HID {
+constexpr s32 HID_JOYSTICK_MAX = 0x7fff;
+constexpr s32 HID_JOYSTICK_MIN = -0x7fff;
+enum class JoystickId : std::size_t { Joystick_Left, Joystick_Right };
+
Controller_DebugPad::Controller_DebugPad() = default;
Controller_DebugPad::~Controller_DebugPad() = default;
@@ -33,10 +38,44 @@ void Controller_DebugPad::OnUpdate(u8* data, std::size_t size) {
cur_entry.sampling_number = last_entry.sampling_number + 1;
cur_entry.sampling_number2 = cur_entry.sampling_number;
- // TODO(ogniK): Update debug pad states
+ cur_entry.attribute.connected.Assign(1);
+ auto& pad = cur_entry.pad_state;
+
+ using namespace Settings::NativeButton;
+ pad.a.Assign(buttons[A - BUTTON_HID_BEGIN]->GetStatus());
+ pad.b.Assign(buttons[B - BUTTON_HID_BEGIN]->GetStatus());
+ pad.x.Assign(buttons[X - BUTTON_HID_BEGIN]->GetStatus());
+ pad.y.Assign(buttons[Y - BUTTON_HID_BEGIN]->GetStatus());
+ pad.l.Assign(buttons[L - BUTTON_HID_BEGIN]->GetStatus());
+ pad.r.Assign(buttons[R - BUTTON_HID_BEGIN]->GetStatus());
+ pad.zl.Assign(buttons[ZL - BUTTON_HID_BEGIN]->GetStatus());
+ pad.zr.Assign(buttons[ZR - BUTTON_HID_BEGIN]->GetStatus());
+ pad.plus.Assign(buttons[Plus - BUTTON_HID_BEGIN]->GetStatus());
+ pad.minus.Assign(buttons[Minus - BUTTON_HID_BEGIN]->GetStatus());
+ pad.d_left.Assign(buttons[DLeft - BUTTON_HID_BEGIN]->GetStatus());
+ pad.d_up.Assign(buttons[DUp - BUTTON_HID_BEGIN]->GetStatus());
+ pad.d_right.Assign(buttons[DRight - BUTTON_HID_BEGIN]->GetStatus());
+ pad.d_down.Assign(buttons[DDown - BUTTON_HID_BEGIN]->GetStatus());
+
+ const auto [stick_l_x_f, stick_l_y_f] =
+ analogs[static_cast<std::size_t>(JoystickId::Joystick_Left)]->GetStatus();
+ const auto [stick_r_x_f, stick_r_y_f] =
+ analogs[static_cast<std::size_t>(JoystickId::Joystick_Right)]->GetStatus();
+ cur_entry.l_stick.x = static_cast<s32>(stick_l_x_f * HID_JOYSTICK_MAX);
+ cur_entry.l_stick.y = static_cast<s32>(stick_l_y_f * HID_JOYSTICK_MAX);
+ cur_entry.r_stick.x = static_cast<s32>(stick_r_x_f * HID_JOYSTICK_MAX);
+ cur_entry.r_stick.y = static_cast<s32>(stick_r_y_f * HID_JOYSTICK_MAX);
std::memcpy(data, &shared_memory, sizeof(SharedMemory));
}
-void Controller_DebugPad::OnLoadInputDevices() {}
+void Controller_DebugPad::OnLoadInputDevices() {
+ std::transform(Settings::values.debug_pad_buttons.begin(),
+ Settings::values.debug_pad_buttons.begin() +
+ Settings::NativeButton::NUM_BUTTONS_HID,
+ buttons.begin(), Input::CreateDevice<Input::ButtonDevice>);
+ std::transform(Settings::values.debug_pad_analogs.begin(),
+ Settings::values.debug_pad_analogs.end(), analogs.begin(),
+ Input::CreateDevice<Input::AnalogDevice>);
+}
} // namespace Service::HID
diff --git a/src/core/hle/service/hid/controllers/debug_pad.h b/src/core/hle/service/hid/controllers/debug_pad.h
index 62b4f2682..68b734248 100644
--- a/src/core/hle/service/hid/controllers/debug_pad.h
+++ b/src/core/hle/service/hid/controllers/debug_pad.h
@@ -5,10 +5,13 @@
#pragma once
#include <array>
+#include "common/bit_field.h"
#include "common/common_funcs.h"
#include "common/common_types.h"
#include "common/swap.h"
+#include "core/frontend/input.h"
#include "core/hle/service/hid/controllers/controller_base.h"
+#include "core/settings.h"
namespace Service::HID {
class Controller_DebugPad final : public ControllerBase {
@@ -35,11 +38,40 @@ private:
};
static_assert(sizeof(AnalogStick) == 0x8);
+ struct PadState {
+ union {
+ u32_le raw{};
+ BitField<0, 1, u32_le> a;
+ BitField<1, 1, u32_le> b;
+ BitField<2, 1, u32_le> x;
+ BitField<3, 1, u32_le> y;
+ BitField<4, 1, u32_le> l;
+ BitField<5, 1, u32_le> r;
+ BitField<6, 1, u32_le> zl;
+ BitField<7, 1, u32_le> zr;
+ BitField<8, 1, u32_le> plus;
+ BitField<9, 1, u32_le> minus;
+ BitField<10, 1, u32_le> d_left;
+ BitField<11, 1, u32_le> d_up;
+ BitField<12, 1, u32_le> d_right;
+ BitField<13, 1, u32_le> d_down;
+ };
+ };
+ static_assert(sizeof(PadState) == 0x4, "PadState is an invalid size");
+
+ struct Attributes {
+ union {
+ u32_le raw{};
+ BitField<0, 1, u32_le> connected;
+ };
+ };
+ static_assert(sizeof(Attributes) == 0x4, "Attributes is an invalid size");
+
struct PadStates {
s64_le sampling_number;
s64_le sampling_number2;
- u32_le attribute;
- u32_le button_state;
+ Attributes attribute;
+ PadState pad_state;
AnalogStick r_stick;
AnalogStick l_stick;
};
@@ -52,5 +84,10 @@ private:
};
static_assert(sizeof(SharedMemory) == 0x400, "SharedMemory is an invalid size");
SharedMemory shared_memory{};
+
+ std::array<std::unique_ptr<Input::ButtonDevice>, Settings::NativeButton::NUM_BUTTONS_HID>
+ buttons;
+ std::array<std::unique_ptr<Input::AnalogDevice>, Settings::NativeAnalog::NUM_STICKS_HID>
+ analogs;
};
} // namespace Service::HID
diff --git a/src/core/hle/service/hid/controllers/keyboard.cpp b/src/core/hle/service/hid/controllers/keyboard.cpp
index ccfbce9ac..ca75adc2b 100644
--- a/src/core/hle/service/hid/controllers/keyboard.cpp
+++ b/src/core/hle/service/hid/controllers/keyboard.cpp
@@ -6,9 +6,11 @@
#include "common/common_types.h"
#include "core/core_timing.h"
#include "core/hle/service/hid/controllers/keyboard.h"
+#include "core/settings.h"
namespace Service::HID {
constexpr std::size_t SHARED_MEMORY_OFFSET = 0x3800;
+constexpr u8 KEYS_PER_BYTE = 8;
Controller_Keyboard::Controller_Keyboard() = default;
Controller_Keyboard::~Controller_Keyboard() = default;
@@ -34,10 +36,24 @@ void Controller_Keyboard::OnUpdate(u8* data, std::size_t size) {
cur_entry.sampling_number = last_entry.sampling_number + 1;
cur_entry.sampling_number2 = cur_entry.sampling_number;
- // TODO(ogniK): Update keyboard states
+
+ for (std::size_t i = 0; i < keyboard_keys.size(); ++i) {
+ for (std::size_t k = 0; k < KEYS_PER_BYTE; ++k) {
+ cur_entry.key[i / KEYS_PER_BYTE] |= (keyboard_keys[i]->GetStatus() << k);
+ }
+ }
+
+ for (std::size_t i = 0; i < keyboard_mods.size(); ++i) {
+ cur_entry.modifier |= (keyboard_mods[i]->GetStatus() << i);
+ }
std::memcpy(data + SHARED_MEMORY_OFFSET, &shared_memory, sizeof(SharedMemory));
}
-void Controller_Keyboard::OnLoadInputDevices() {}
+void Controller_Keyboard::OnLoadInputDevices() {
+ std::transform(Settings::values.keyboard_keys.begin(), Settings::values.keyboard_keys.end(),
+ keyboard_keys.begin(), Input::CreateDevice<Input::ButtonDevice>);
+ std::transform(Settings::values.keyboard_mods.begin(), Settings::values.keyboard_mods.end(),
+ keyboard_mods.begin(), Input::CreateDevice<Input::ButtonDevice>);
+}
} // namespace Service::HID
diff --git a/src/core/hle/service/hid/controllers/keyboard.h b/src/core/hle/service/hid/controllers/keyboard.h
index 493e68fce..f52775456 100644
--- a/src/core/hle/service/hid/controllers/keyboard.h
+++ b/src/core/hle/service/hid/controllers/keyboard.h
@@ -8,7 +8,9 @@
#include "common/common_funcs.h"
#include "common/common_types.h"
#include "common/swap.h"
+#include "core/frontend/input.h"
#include "core/hle/service/hid/controllers/controller_base.h"
+#include "core/settings.h"
namespace Service::HID {
class Controller_Keyboard final : public ControllerBase {
@@ -46,5 +48,10 @@ private:
};
static_assert(sizeof(SharedMemory) == 0x400, "SharedMemory is an invalid size");
SharedMemory shared_memory{};
+
+ std::array<std::unique_ptr<Input::ButtonDevice>, Settings::NativeKeyboard::NumKeyboardKeys>
+ keyboard_keys;
+ std::array<std::unique_ptr<Input::ButtonDevice>, Settings::NativeKeyboard::NumKeyboardMods>
+ keyboard_mods;
};
} // namespace Service::HID
diff --git a/src/core/hle/service/hid/controllers/mouse.cpp b/src/core/hle/service/hid/controllers/mouse.cpp
index 4e246a57d..63391dbe9 100644
--- a/src/core/hle/service/hid/controllers/mouse.cpp
+++ b/src/core/hle/service/hid/controllers/mouse.cpp
@@ -5,6 +5,7 @@
#include <cstring>
#include "common/common_types.h"
#include "core/core_timing.h"
+#include "core/frontend/emu_window.h"
#include "core/hle/service/hid/controllers/mouse.h"
namespace Service::HID {
@@ -14,7 +15,6 @@ Controller_Mouse::Controller_Mouse() = default;
Controller_Mouse::~Controller_Mouse() = default;
void Controller_Mouse::OnInit() {}
-
void Controller_Mouse::OnRelease() {}
void Controller_Mouse::OnUpdate(u8* data, std::size_t size) {
@@ -34,10 +34,29 @@ void Controller_Mouse::OnUpdate(u8* data, std::size_t size) {
cur_entry.sampling_number = last_entry.sampling_number + 1;
cur_entry.sampling_number2 = cur_entry.sampling_number;
- // TODO(ogniK): Update mouse states
+
+ if (Settings::values.mouse_enabled) {
+ const auto [px, py, sx, sy] = mouse_device->GetStatus();
+ const auto x = static_cast<s32>(px * Layout::ScreenUndocked::Width);
+ const auto y = static_cast<s32>(py * Layout::ScreenUndocked::Height);
+ cur_entry.x = x;
+ cur_entry.y = y;
+ cur_entry.delta_x = x - last_entry.x;
+ cur_entry.delta_y = y - last_entry.y;
+ cur_entry.mouse_wheel_x = sx;
+ cur_entry.mouse_wheel_y = sy;
+
+ for (std::size_t i = 0; i < mouse_button_devices.size(); ++i) {
+ cur_entry.button |= (mouse_button_devices[i]->GetStatus() << i);
+ }
+ }
std::memcpy(data + SHARED_MEMORY_OFFSET, &shared_memory, sizeof(SharedMemory));
}
-void Controller_Mouse::OnLoadInputDevices() {}
+void Controller_Mouse::OnLoadInputDevices() {
+ mouse_device = Input::CreateDevice<Input::MouseDevice>(Settings::values.mouse_device);
+ std::transform(Settings::values.mouse_buttons.begin(), Settings::values.mouse_buttons.end(),
+ mouse_button_devices.begin(), Input::CreateDevice<Input::ButtonDevice>);
+}
} // namespace Service::HID
diff --git a/src/core/hle/service/hid/controllers/mouse.h b/src/core/hle/service/hid/controllers/mouse.h
index 543b0b71f..70b654d07 100644
--- a/src/core/hle/service/hid/controllers/mouse.h
+++ b/src/core/hle/service/hid/controllers/mouse.h
@@ -7,7 +7,9 @@
#include <array>
#include "common/common_types.h"
#include "common/swap.h"
+#include "core/frontend/input.h"
#include "core/hle/service/hid/controllers/controller_base.h"
+#include "core/settings.h"
namespace Service::HID {
class Controller_Mouse final : public ControllerBase {
@@ -35,7 +37,8 @@ private:
s32_le y;
s32_le delta_x;
s32_le delta_y;
- s32_le mouse_wheel;
+ s32_le mouse_wheel_x;
+ s32_le mouse_wheel_y;
s32_le button;
s32_le attribute;
};
@@ -46,5 +49,9 @@ private:
std::array<MouseState, 17> mouse_states;
};
SharedMemory shared_memory{};
+
+ std::unique_ptr<Input::MouseDevice> mouse_device;
+ std::array<std::unique_ptr<Input::ButtonDevice>, Settings::NativeMouseButton::NumMouseButtons>
+ mouse_button_devices;
};
} // namespace Service::HID
diff --git a/src/core/hle/service/hid/controllers/npad.cpp b/src/core/hle/service/hid/controllers/npad.cpp
index 4b4d1324f..46604887c 100644
--- a/src/core/hle/service/hid/controllers/npad.cpp
+++ b/src/core/hle/service/hid/controllers/npad.cpp
@@ -17,22 +17,13 @@
#include "core/settings.h"
namespace Service::HID {
-
-constexpr u32 JOYCON_BODY_NEON_RED = 0xFF3C28;
-constexpr u32 JOYCON_BUTTONS_NEON_RED = 0x1E0A0A;
-constexpr u32 JOYCON_BODY_NEON_BLUE = 0x0AB9E6;
-constexpr u32 JOYCON_BUTTONS_NEON_BLUE = 0x001E1E;
constexpr s32 HID_JOYSTICK_MAX = 0x7fff;
constexpr s32 HID_JOYSTICK_MIN = -0x7fff;
constexpr std::size_t NPAD_OFFSET = 0x9A00;
constexpr u32 BATTERY_FULL = 2;
-constexpr u32 NPAD_HANDHELD = 32;
-constexpr u32 NPAD_UNKNOWN = 16; // TODO(ogniK): What is this?
constexpr u32 MAX_NPAD_ID = 7;
-constexpr Controller_NPad::NPadControllerType PREFERRED_CONTROLLER =
- Controller_NPad::NPadControllerType::JoyDual;
constexpr std::array<u32, 10> npad_id_list{
- 0, 1, 2, 3, 4, 5, 6, 7, 32, 16,
+ 0, 1, 2, 3, 4, 5, 6, 7, NPAD_HANDHELD, NPAD_UNKNOWN,
};
enum class JoystickId : std::size_t {
@@ -40,6 +31,66 @@ enum class JoystickId : std::size_t {
Joystick_Right,
};
+static Controller_NPad::NPadControllerType MapSettingsTypeToNPad(Settings::ControllerType type) {
+ switch (type) {
+ case Settings::ControllerType::ProController:
+ return Controller_NPad::NPadControllerType::ProController;
+ case Settings::ControllerType::DualJoycon:
+ return Controller_NPad::NPadControllerType::JoyDual;
+ case Settings::ControllerType::LeftJoycon:
+ return Controller_NPad::NPadControllerType::JoyLeft;
+ case Settings::ControllerType::RightJoycon:
+ return Controller_NPad::NPadControllerType::JoyRight;
+ default:
+ UNREACHABLE();
+ return Controller_NPad::NPadControllerType::JoyDual;
+ }
+}
+
+std::size_t Controller_NPad::NPadIdToIndex(u32 npad_id) {
+ switch (npad_id) {
+ case 0:
+ case 1:
+ case 2:
+ case 3:
+ case 4:
+ case 5:
+ case 6:
+ case 7:
+ return npad_id;
+ case 8:
+ case NPAD_HANDHELD:
+ return 8;
+ case 9:
+ case NPAD_UNKNOWN:
+ return 9;
+ default:
+ UNIMPLEMENTED_MSG("Unknown npad id {}", npad_id);
+ return 0;
+ }
+}
+
+u32 Controller_NPad::IndexToNPad(std::size_t index) {
+ switch (index) {
+ case 0:
+ case 1:
+ case 2:
+ case 3:
+ case 4:
+ case 5:
+ case 6:
+ case 7:
+ return static_cast<u32>(index);
+ case 8:
+ return NPAD_HANDHELD;
+ case 9:
+ return NPAD_UNKNOWN;
+ default:
+ UNIMPLEMENTED_MSG("Unknown npad index {}", index);
+ return 0;
+ };
+}
+
Controller_NPad::Controller_NPad() = default;
Controller_NPad::~Controller_NPad() = default;
@@ -56,22 +107,32 @@ void Controller_NPad::InitNewlyAddedControler(std::size_t controller_idx) {
controller.joy_styles.handheld.Assign(1);
controller.device_type.handheld.Assign(1);
controller.pad_assignment = NPadAssignments::Dual;
+ controller.properties.is_vertical.Assign(1);
+ controller.properties.use_plus.Assign(1);
+ controller.properties.use_minus.Assign(1);
break;
case NPadControllerType::JoyDual:
controller.joy_styles.joycon_dual.Assign(1);
controller.device_type.joycon_left.Assign(1);
controller.device_type.joycon_right.Assign(1);
+ controller.properties.is_vertical.Assign(1);
+ controller.properties.use_plus.Assign(1);
+ controller.properties.use_minus.Assign(1);
controller.pad_assignment = NPadAssignments::Dual;
break;
case NPadControllerType::JoyLeft:
controller.joy_styles.joycon_left.Assign(1);
controller.device_type.joycon_left.Assign(1);
- controller.pad_assignment = NPadAssignments::Dual;
+ controller.properties.is_horizontal.Assign(1);
+ controller.properties.use_minus.Assign(1);
+ controller.pad_assignment = NPadAssignments::Single;
break;
case NPadControllerType::JoyRight:
controller.joy_styles.joycon_right.Assign(1);
controller.device_type.joycon_right.Assign(1);
- controller.pad_assignment = NPadAssignments::Dual;
+ controller.properties.is_horizontal.Assign(1);
+ controller.properties.use_plus.Assign(1);
+ controller.pad_assignment = NPadAssignments::Single;
break;
case NPadControllerType::Pokeball:
controller.joy_styles.pokeball.Assign(1);
@@ -81,6 +142,9 @@ void Controller_NPad::InitNewlyAddedControler(std::size_t controller_idx) {
case NPadControllerType::ProController:
controller.joy_styles.pro_controller.Assign(1);
controller.device_type.pro_controller.Assign(1);
+ controller.properties.is_vertical.Assign(1);
+ controller.properties.use_plus.Assign(1);
+ controller.properties.use_minus.Assign(1);
controller.pad_assignment = NPadAssignments::Single;
break;
}
@@ -90,14 +154,12 @@ void Controller_NPad::InitNewlyAddedControler(std::size_t controller_idx) {
controller.single_color.button_color = 0;
controller.dual_color_error = ColorReadError::ReadOk;
- controller.left_color.body_color = JOYCON_BODY_NEON_BLUE;
- controller.left_color.button_color = JOYCON_BUTTONS_NEON_BLUE;
- controller.right_color.body_color = JOYCON_BODY_NEON_RED;
- controller.right_color.button_color = JOYCON_BUTTONS_NEON_RED;
-
- controller.properties.is_vertical.Assign(1); // TODO(ogniK): Swap joycons orientations
- controller.properties.use_plus.Assign(1);
- controller.properties.use_minus.Assign(1);
+ controller.left_color.body_color = Settings::values.players[controller_idx].body_color_left;
+ controller.left_color.button_color = Settings::values.players[controller_idx].button_color_left;
+ controller.right_color.body_color = Settings::values.players[controller_idx].body_color_right;
+ controller.right_color.button_color =
+ Settings::values.players[controller_idx].button_color_right;
+
controller.battery_level[0] = BATTERY_FULL;
controller.battery_level[1] = BATTERY_FULL;
controller.battery_level[2] = BATTERY_FULL;
@@ -121,26 +183,109 @@ void Controller_NPad::OnInit() {
style.pro_controller.Assign(1);
style.pokeball.Assign(1);
}
+
+ std::transform(
+ Settings::values.players.begin(), Settings::values.players.end(),
+ connected_controllers.begin(), [](const Settings::PlayerInput& player) {
+ return ControllerHolder{MapSettingsTypeToNPad(player.type), player.connected};
+ });
+
+ std::stable_partition(connected_controllers.begin(), connected_controllers.begin() + 8,
+ [](const ControllerHolder& holder) { return holder.is_connected; });
+
+ // Account for handheld
+ if (connected_controllers[8].is_connected)
+ connected_controllers[8].type = NPadControllerType::Handheld;
+
+ supported_npad_id_types.resize(npad_id_list.size());
+ std::memcpy(supported_npad_id_types.data(), npad_id_list.data(),
+ npad_id_list.size() * sizeof(u32));
+
+ // Add a default dual joycon controller if none are present.
if (std::none_of(connected_controllers.begin(), connected_controllers.end(),
[](const ControllerHolder& controller) { return controller.is_connected; })) {
supported_npad_id_types.resize(npad_id_list.size());
std::memcpy(supported_npad_id_types.data(), npad_id_list.data(),
npad_id_list.size() * sizeof(u32));
- AddNewController(PREFERRED_CONTROLLER);
+ AddNewController(NPadControllerType::JoyDual);
+ }
+
+ for (std::size_t i = 0; i < connected_controllers.size(); ++i) {
+ const auto& controller = connected_controllers[i];
+ if (controller.is_connected) {
+ AddNewControllerAt(controller.type, IndexToNPad(i));
+ }
}
}
void Controller_NPad::OnLoadInputDevices() {
- std::transform(Settings::values.buttons.begin() + Settings::NativeButton::BUTTON_HID_BEGIN,
- Settings::values.buttons.begin() + Settings::NativeButton::BUTTON_HID_END,
- buttons.begin(), Input::CreateDevice<Input::ButtonDevice>);
- std::transform(Settings::values.analogs.begin() + Settings::NativeAnalog::STICK_HID_BEGIN,
- Settings::values.analogs.begin() + Settings::NativeAnalog::STICK_HID_END,
- sticks.begin(), Input::CreateDevice<Input::AnalogDevice>);
+ const auto& players = Settings::values.players;
+ for (std::size_t i = 0; i < players.size(); ++i) {
+ std::transform(players[i].buttons.begin() + Settings::NativeButton::BUTTON_HID_BEGIN,
+ players[i].buttons.begin() + Settings::NativeButton::BUTTON_HID_END,
+ buttons[i].begin(), Input::CreateDevice<Input::ButtonDevice>);
+ std::transform(players[i].analogs.begin() + Settings::NativeAnalog::STICK_HID_BEGIN,
+ players[i].analogs.begin() + Settings::NativeAnalog::STICK_HID_END,
+ sticks[i].begin(), Input::CreateDevice<Input::AnalogDevice>);
+ }
}
void Controller_NPad::OnRelease() {}
+void Controller_NPad::RequestPadStateUpdate(u32 npad_id) {
+ const auto controller_idx = NPadIdToIndex(npad_id);
+ const auto controller_type = connected_controllers[controller_idx].type;
+ if (!connected_controllers[controller_idx].is_connected) {
+ return;
+ }
+ auto& pad_state = npad_pad_states[controller_idx].pad_states;
+ auto& lstick_entry = npad_pad_states[controller_idx].l_stick;
+ auto& rstick_entry = npad_pad_states[controller_idx].r_stick;
+ const auto& button_state = buttons[controller_idx];
+ const auto& analog_state = sticks[controller_idx];
+
+ using namespace Settings::NativeButton;
+ pad_state.a.Assign(button_state[A - BUTTON_HID_BEGIN]->GetStatus());
+ pad_state.b.Assign(button_state[B - BUTTON_HID_BEGIN]->GetStatus());
+ pad_state.x.Assign(button_state[X - BUTTON_HID_BEGIN]->GetStatus());
+ pad_state.y.Assign(button_state[Y - BUTTON_HID_BEGIN]->GetStatus());
+ pad_state.l_stick.Assign(button_state[LStick - BUTTON_HID_BEGIN]->GetStatus());
+ pad_state.r_stick.Assign(button_state[RStick - BUTTON_HID_BEGIN]->GetStatus());
+ pad_state.l.Assign(button_state[L - BUTTON_HID_BEGIN]->GetStatus());
+ pad_state.r.Assign(button_state[R - BUTTON_HID_BEGIN]->GetStatus());
+ pad_state.zl.Assign(button_state[ZL - BUTTON_HID_BEGIN]->GetStatus());
+ pad_state.zr.Assign(button_state[ZR - BUTTON_HID_BEGIN]->GetStatus());
+ pad_state.plus.Assign(button_state[Plus - BUTTON_HID_BEGIN]->GetStatus());
+ pad_state.minus.Assign(button_state[Minus - BUTTON_HID_BEGIN]->GetStatus());
+
+ pad_state.d_left.Assign(button_state[DLeft - BUTTON_HID_BEGIN]->GetStatus());
+ pad_state.d_up.Assign(button_state[DUp - BUTTON_HID_BEGIN]->GetStatus());
+ pad_state.d_right.Assign(button_state[DRight - BUTTON_HID_BEGIN]->GetStatus());
+ pad_state.d_down.Assign(button_state[DDown - BUTTON_HID_BEGIN]->GetStatus());
+
+ pad_state.l_stick_left.Assign(button_state[LStick_Left - BUTTON_HID_BEGIN]->GetStatus());
+ pad_state.l_stick_up.Assign(button_state[LStick_Up - BUTTON_HID_BEGIN]->GetStatus());
+ pad_state.l_stick_right.Assign(button_state[LStick_Right - BUTTON_HID_BEGIN]->GetStatus());
+ pad_state.l_stick_down.Assign(button_state[LStick_Down - BUTTON_HID_BEGIN]->GetStatus());
+
+ pad_state.r_stick_left.Assign(button_state[RStick_Left - BUTTON_HID_BEGIN]->GetStatus());
+ pad_state.r_stick_up.Assign(button_state[RStick_Up - BUTTON_HID_BEGIN]->GetStatus());
+ pad_state.r_stick_right.Assign(button_state[RStick_Right - BUTTON_HID_BEGIN]->GetStatus());
+ pad_state.r_stick_down.Assign(button_state[RStick_Down - BUTTON_HID_BEGIN]->GetStatus());
+
+ pad_state.left_sl.Assign(button_state[SL - BUTTON_HID_BEGIN]->GetStatus());
+ pad_state.left_sr.Assign(button_state[SR - BUTTON_HID_BEGIN]->GetStatus());
+
+ const auto [stick_l_x_f, stick_l_y_f] =
+ analog_state[static_cast<std::size_t>(JoystickId::Joystick_Left)]->GetStatus();
+ const auto [stick_r_x_f, stick_r_y_f] =
+ analog_state[static_cast<std::size_t>(JoystickId::Joystick_Right)]->GetStatus();
+ lstick_entry.x = static_cast<s32>(stick_l_x_f * HID_JOYSTICK_MAX);
+ lstick_entry.y = static_cast<s32>(stick_l_y_f * HID_JOYSTICK_MAX);
+ rstick_entry.x = static_cast<s32>(stick_r_x_f * HID_JOYSTICK_MAX);
+ rstick_entry.y = static_cast<s32>(stick_r_y_f * HID_JOYSTICK_MAX);
+}
+
void Controller_NPad::OnUpdate(u8* data, std::size_t data_len) {
if (!IsControllerActivated())
return;
@@ -176,97 +321,9 @@ void Controller_NPad::OnUpdate(u8* data, std::size_t data_len) {
if (controller_type == NPadControllerType::None || !connected_controllers[i].is_connected) {
continue;
}
-
- // Pad states
- ControllerPadState pad_state{};
- using namespace Settings::NativeButton;
- pad_state.a.Assign(buttons[A - BUTTON_HID_BEGIN]->GetStatus());
- pad_state.b.Assign(buttons[B - BUTTON_HID_BEGIN]->GetStatus());
- pad_state.x.Assign(buttons[X - BUTTON_HID_BEGIN]->GetStatus());
- pad_state.y.Assign(buttons[Y - BUTTON_HID_BEGIN]->GetStatus());
- pad_state.l_stick.Assign(buttons[LStick - BUTTON_HID_BEGIN]->GetStatus());
- pad_state.r_stick.Assign(buttons[RStick - BUTTON_HID_BEGIN]->GetStatus());
- pad_state.l.Assign(buttons[L - BUTTON_HID_BEGIN]->GetStatus());
- pad_state.r.Assign(buttons[R - BUTTON_HID_BEGIN]->GetStatus());
- pad_state.zl.Assign(buttons[ZL - BUTTON_HID_BEGIN]->GetStatus());
- pad_state.zr.Assign(buttons[ZR - BUTTON_HID_BEGIN]->GetStatus());
- pad_state.plus.Assign(buttons[Plus - BUTTON_HID_BEGIN]->GetStatus());
- pad_state.minus.Assign(buttons[Minus - BUTTON_HID_BEGIN]->GetStatus());
-
- pad_state.d_left.Assign(buttons[DLeft - BUTTON_HID_BEGIN]->GetStatus());
- pad_state.d_up.Assign(buttons[DUp - BUTTON_HID_BEGIN]->GetStatus());
- pad_state.d_right.Assign(buttons[DRight - BUTTON_HID_BEGIN]->GetStatus());
- pad_state.d_down.Assign(buttons[DDown - BUTTON_HID_BEGIN]->GetStatus());
-
- pad_state.l_stick_left.Assign(buttons[LStick_Left - BUTTON_HID_BEGIN]->GetStatus());
- pad_state.l_stick_up.Assign(buttons[LStick_Up - BUTTON_HID_BEGIN]->GetStatus());
- pad_state.l_stick_right.Assign(buttons[LStick_Right - BUTTON_HID_BEGIN]->GetStatus());
- pad_state.l_stick_down.Assign(buttons[LStick_Down - BUTTON_HID_BEGIN]->GetStatus());
-
- pad_state.r_stick_left.Assign(buttons[RStick_Left - BUTTON_HID_BEGIN]->GetStatus());
- pad_state.r_stick_up.Assign(buttons[RStick_Up - BUTTON_HID_BEGIN]->GetStatus());
- pad_state.r_stick_right.Assign(buttons[RStick_Right - BUTTON_HID_BEGIN]->GetStatus());
- pad_state.r_stick_down.Assign(buttons[RStick_Down - BUTTON_HID_BEGIN]->GetStatus());
-
- pad_state.sl.Assign(buttons[SL - BUTTON_HID_BEGIN]->GetStatus());
- pad_state.sr.Assign(buttons[SR - BUTTON_HID_BEGIN]->GetStatus());
-
- AnalogPosition lstick_entry{};
- AnalogPosition rstick_entry{};
-
- const auto [stick_l_x_f, stick_l_y_f] =
- sticks[static_cast<std::size_t>(JoystickId::Joystick_Left)]->GetStatus();
- const auto [stick_r_x_f, stick_r_y_f] =
- sticks[static_cast<std::size_t>(JoystickId::Joystick_Right)]->GetStatus();
- lstick_entry.x = static_cast<s32>(stick_l_x_f * HID_JOYSTICK_MAX);
- lstick_entry.y = static_cast<s32>(stick_l_y_f * HID_JOYSTICK_MAX);
- rstick_entry.x = static_cast<s32>(stick_r_x_f * HID_JOYSTICK_MAX);
- rstick_entry.y = static_cast<s32>(stick_r_y_f * HID_JOYSTICK_MAX);
-
- if (controller_type == NPadControllerType::JoyLeft ||
- controller_type == NPadControllerType::JoyRight) {
- if (npad.properties.is_horizontal) {
- ControllerPadState state{};
- AnalogPosition temp_lstick_entry{};
- AnalogPosition temp_rstick_entry{};
- if (controller_type == NPadControllerType::JoyLeft) {
- state.d_down.Assign(pad_state.d_left.Value());
- state.d_left.Assign(pad_state.d_up.Value());
- state.d_right.Assign(pad_state.d_down.Value());
- state.d_up.Assign(pad_state.d_right.Value());
- state.l.Assign(pad_state.l.Value() | pad_state.sl.Value());
- state.r.Assign(pad_state.r.Value() | pad_state.sr.Value());
-
- state.zl.Assign(pad_state.zl.Value());
- state.plus.Assign(pad_state.minus.Value());
-
- temp_lstick_entry = lstick_entry;
- temp_rstick_entry = rstick_entry;
- std::swap(temp_lstick_entry.x, temp_lstick_entry.y);
- std::swap(temp_rstick_entry.x, temp_rstick_entry.y);
- temp_lstick_entry.y *= -1;
- } else if (controller_type == NPadControllerType::JoyRight) {
- state.x.Assign(pad_state.a.Value());
- state.a.Assign(pad_state.b.Value());
- state.b.Assign(pad_state.y.Value());
- state.y.Assign(pad_state.b.Value());
-
- state.l.Assign(pad_state.l.Value() | pad_state.sl.Value());
- state.r.Assign(pad_state.r.Value() | pad_state.sr.Value());
- state.zr.Assign(pad_state.zr.Value());
- state.plus.Assign(pad_state.plus.Value());
-
- temp_lstick_entry = lstick_entry;
- temp_rstick_entry = rstick_entry;
- std::swap(temp_lstick_entry.x, temp_lstick_entry.y);
- std::swap(temp_rstick_entry.x, temp_rstick_entry.y);
- temp_rstick_entry.x *= -1;
- }
- pad_state.raw = state.raw;
- lstick_entry = temp_lstick_entry;
- rstick_entry = temp_rstick_entry;
- }
- }
+ const u32 npad_index = static_cast<u32>(i);
+ RequestPadStateUpdate(npad_index);
+ auto& pad_state = npad_pad_states[npad_index];
auto& main_controller =
npad.main_controller_states.npad[npad.main_controller_states.common.last_entry_index];
@@ -281,20 +338,64 @@ void Controller_NPad::OnUpdate(u8* data, std::size_t data_len) {
auto& libnx_entry = npad.libnx.npad[npad.libnx.common.last_entry_index];
if (hold_type == NpadHoldType::Horizontal) {
- // TODO(ogniK): Remap buttons for different orientations
+ ControllerPadState state{};
+ AnalogPosition temp_lstick_entry{};
+ AnalogPosition temp_rstick_entry{};
+ if (controller_type == NPadControllerType::JoyLeft) {
+ state.d_down.Assign(pad_state.pad_states.d_left.Value());
+ state.d_left.Assign(pad_state.pad_states.d_up.Value());
+ state.d_right.Assign(pad_state.pad_states.d_down.Value());
+ state.d_up.Assign(pad_state.pad_states.d_right.Value());
+ state.l.Assign(pad_state.pad_states.l.Value() |
+ pad_state.pad_states.left_sl.Value());
+ state.r.Assign(pad_state.pad_states.r.Value() |
+ pad_state.pad_states.left_sr.Value());
+
+ state.zl.Assign(pad_state.pad_states.zl.Value());
+ state.plus.Assign(pad_state.pad_states.minus.Value());
+
+ temp_lstick_entry = pad_state.l_stick;
+ temp_rstick_entry = pad_state.r_stick;
+ std::swap(temp_lstick_entry.x, temp_lstick_entry.y);
+ std::swap(temp_rstick_entry.x, temp_rstick_entry.y);
+ temp_lstick_entry.y *= -1;
+ } else if (controller_type == NPadControllerType::JoyRight) {
+ state.x.Assign(pad_state.pad_states.a.Value());
+ state.a.Assign(pad_state.pad_states.b.Value());
+ state.b.Assign(pad_state.pad_states.y.Value());
+ state.y.Assign(pad_state.pad_states.b.Value());
+
+ state.l.Assign(pad_state.pad_states.l.Value() |
+ pad_state.pad_states.right_sl.Value());
+ state.r.Assign(pad_state.pad_states.r.Value() |
+ pad_state.pad_states.right_sr.Value());
+ state.zr.Assign(pad_state.pad_states.zr.Value());
+ state.plus.Assign(pad_state.pad_states.plus.Value());
+
+ temp_lstick_entry = pad_state.l_stick;
+ temp_rstick_entry = pad_state.r_stick;
+ std::swap(temp_lstick_entry.x, temp_lstick_entry.y);
+ std::swap(temp_rstick_entry.x, temp_rstick_entry.y);
+ temp_rstick_entry.x *= -1;
+ }
+ pad_state.pad_states.raw = state.raw;
+ pad_state.l_stick = temp_lstick_entry;
+ pad_state.r_stick = temp_rstick_entry;
}
+
libnx_entry.connection_status.raw = 0;
switch (controller_type) {
case NPadControllerType::Handheld:
handheld_entry.connection_status.raw = 0;
- handheld_entry.connection_status.IsConnected.Assign(1);
- if (!Settings::values.use_docked_mode) {
- handheld_entry.connection_status.IsWired.Assign(1);
- }
- handheld_entry.pad_states.raw = pad_state.raw;
- handheld_entry.l_stick = lstick_entry;
- handheld_entry.r_stick = rstick_entry;
+ handheld_entry.connection_status.IsWired.Assign(1);
+ handheld_entry.connection_status.IsLeftJoyConnected.Assign(1);
+ handheld_entry.connection_status.IsRightJoyConnected.Assign(1);
+ handheld_entry.connection_status.IsLeftJoyWired.Assign(1);
+ handheld_entry.connection_status.IsRightJoyWired.Assign(1);
+ handheld_entry.pad.pad_states.raw = pad_state.pad_states.raw;
+ handheld_entry.pad.l_stick = pad_state.l_stick;
+ handheld_entry.pad.r_stick = pad_state.r_stick;
break;
case NPadControllerType::JoyDual:
dual_entry.connection_status.raw = 0;
@@ -307,24 +408,25 @@ void Controller_NPad::OnUpdate(u8* data, std::size_t data_len) {
libnx_entry.connection_status.IsRightJoyConnected.Assign(1);
libnx_entry.connection_status.IsConnected.Assign(1);
- dual_entry.pad_states.raw = pad_state.raw;
- dual_entry.l_stick = lstick_entry;
- dual_entry.r_stick = rstick_entry;
+ dual_entry.pad.pad_states.raw = pad_state.pad_states.raw;
+ dual_entry.pad.l_stick = pad_state.l_stick;
+ dual_entry.pad.r_stick = pad_state.r_stick;
+ break;
case NPadControllerType::JoyLeft:
left_entry.connection_status.raw = 0;
left_entry.connection_status.IsConnected.Assign(1);
- left_entry.pad_states.raw = pad_state.raw;
- left_entry.l_stick = lstick_entry;
- left_entry.r_stick = rstick_entry;
+ left_entry.pad.pad_states.raw = pad_state.pad_states.raw;
+ left_entry.pad.l_stick = pad_state.l_stick;
+ left_entry.pad.r_stick = pad_state.r_stick;
break;
case NPadControllerType::JoyRight:
right_entry.connection_status.raw = 0;
right_entry.connection_status.IsConnected.Assign(1);
- right_entry.pad_states.raw = pad_state.raw;
- right_entry.l_stick = lstick_entry;
- right_entry.r_stick = rstick_entry;
+ right_entry.pad.pad_states.raw = pad_state.pad_states.raw;
+ right_entry.pad.l_stick = pad_state.l_stick;
+ right_entry.pad.r_stick = pad_state.r_stick;
break;
case NPadControllerType::Pokeball:
pokeball_entry.connection_status.raw = 0;
@@ -332,30 +434,30 @@ void Controller_NPad::OnUpdate(u8* data, std::size_t data_len) {
pokeball_entry.connection_status.IsConnected.Assign(1);
pokeball_entry.connection_status.IsWired.Assign(1);
- pokeball_entry.pad_states.raw = pad_state.raw;
- pokeball_entry.l_stick = lstick_entry;
- pokeball_entry.r_stick = rstick_entry;
+ pokeball_entry.pad.pad_states.raw = pad_state.pad_states.raw;
+ pokeball_entry.pad.l_stick = pad_state.l_stick;
+ pokeball_entry.pad.r_stick = pad_state.r_stick;
break;
case NPadControllerType::ProController:
main_controller.connection_status.raw = 0;
main_controller.connection_status.IsConnected.Assign(1);
main_controller.connection_status.IsWired.Assign(1);
- main_controller.pad_states.raw = pad_state.raw;
- main_controller.l_stick = lstick_entry;
- main_controller.r_stick = rstick_entry;
+ main_controller.pad.pad_states.raw = pad_state.pad_states.raw;
+ main_controller.pad.l_stick = pad_state.l_stick;
+ main_controller.pad.r_stick = pad_state.r_stick;
break;
}
// LibNX exclusively uses this section, so we always update it since LibNX doesn't activate
// any controllers.
- libnx_entry.pad_states.raw = pad_state.raw;
- libnx_entry.l_stick = lstick_entry;
- libnx_entry.r_stick = rstick_entry;
+ libnx_entry.pad.pad_states.raw = pad_state.pad_states.raw;
+ libnx_entry.pad.l_stick = pad_state.l_stick;
+ libnx_entry.pad.r_stick = pad_state.r_stick;
}
std::memcpy(data + NPAD_OFFSET, shared_memory_entries.data(),
shared_memory_entries.size() * sizeof(NPadEntry));
-} // namespace Service::HID
+}
void Controller_NPad::SetSupportedStyleSet(NPadType style_set) {
style.raw = style_set.raw;
@@ -370,14 +472,29 @@ void Controller_NPad::SetSupportedNPadIdTypes(u8* data, std::size_t length) {
supported_npad_id_types.clear();
supported_npad_id_types.resize(length / sizeof(u32));
std::memcpy(supported_npad_id_types.data(), data, length);
+ bool had_controller_update = false;
for (std::size_t i = 0; i < connected_controllers.size(); i++) {
auto& controller = connected_controllers[i];
if (!controller.is_connected) {
continue;
}
- if (!IsControllerSupported(PREFERRED_CONTROLLER)) {
- controller.type = DecideBestController(PREFERRED_CONTROLLER);
- InitNewlyAddedControler(i);
+ const auto requested_controller =
+ i <= MAX_NPAD_ID ? MapSettingsTypeToNPad(Settings::values.players[i].type)
+ : NPadControllerType::Handheld;
+ if (!IsControllerSupported(requested_controller)) {
+ const auto is_handheld = requested_controller == NPadControllerType::Handheld;
+ if (is_handheld) {
+ controller.type = NPadControllerType::None;
+ controller.is_connected = false;
+ AddNewController(requested_controller);
+ } else {
+ controller.type = requested_controller;
+ InitNewlyAddedControler(i);
+ }
+ had_controller_update = true;
+ }
+ if (had_controller_update) {
+ styleset_changed_event->Signal();
}
}
}
@@ -392,8 +509,10 @@ std::size_t Controller_NPad::GetSupportedNPadIdTypesSize() const {
}
void Controller_NPad::SetHoldType(NpadHoldType joy_hold_type) {
+ styleset_changed_event->Signal();
hold_type = joy_hold_type;
}
+
Controller_NPad::NpadHoldType Controller_NPad::GetHoldType() const {
return hold_type;
}
@@ -409,15 +528,7 @@ void Controller_NPad::VibrateController(const std::vector<u32>& controller_ids,
return;
}
for (std::size_t i = 0; i < controller_ids.size(); i++) {
- std::size_t controller_pos = i;
- // Handheld controller conversion
- if (controller_pos == NPAD_HANDHELD) {
- controller_pos = 8;
- }
- // Unknown controller conversion
- if (controller_pos == NPAD_UNKNOWN) {
- controller_pos = 9;
- }
+ std::size_t controller_pos = NPadIdToIndex(static_cast<u32>(i));
if (connected_controllers[controller_pos].is_connected) {
// TODO(ogniK): Vibrate the physical controller
}
@@ -427,13 +538,18 @@ void Controller_NPad::VibrateController(const std::vector<u32>& controller_ids,
}
Kernel::SharedPtr<Kernel::Event> Controller_NPad::GetStyleSetChangedEvent() const {
+ // TODO(ogniK): Figure out the best time to signal this event. This event seems that it should
+ // be signalled at least once, and signaled after a new controller is connected?
+ styleset_changed_event->Signal();
return styleset_changed_event;
}
Controller_NPad::Vibration Controller_NPad::GetLastVibration() const {
return last_processed_vibration;
}
+
void Controller_NPad::AddNewController(NPadControllerType controller) {
+ controller = DecideBestController(controller);
if (controller == NPadControllerType::Handheld) {
connected_controllers[8] = {controller, true};
InitNewlyAddedControler(8);
@@ -451,16 +567,54 @@ void Controller_NPad::AddNewController(NPadControllerType controller) {
InitNewlyAddedControler(controller_id);
}
-void Controller_NPad::ConnectNPad(u32 npad_id) {
- if (npad_id >= connected_controllers.size())
+void Controller_NPad::AddNewControllerAt(NPadControllerType controller, u32 npad_id) {
+ controller = DecideBestController(controller);
+ if (controller == NPadControllerType::Handheld) {
+ connected_controllers[NPadIdToIndex(NPAD_HANDHELD)] = {controller, true};
+ InitNewlyAddedControler(NPadIdToIndex(NPAD_HANDHELD));
return;
- connected_controllers[npad_id].is_connected = true;
+ }
+
+ connected_controllers[npad_id] = {controller, true};
+ InitNewlyAddedControler(npad_id);
+}
+
+void Controller_NPad::ConnectNPad(u32 npad_id) {
+ connected_controllers[NPadIdToIndex(npad_id)].is_connected = true;
}
void Controller_NPad::DisconnectNPad(u32 npad_id) {
- if (npad_id >= connected_controllers.size())
- return;
- connected_controllers[npad_id].is_connected = false;
+ connected_controllers[NPadIdToIndex(npad_id)].is_connected = false;
+}
+
+bool Controller_NPad::IsControllerSupported(NPadControllerType controller) {
+ if (controller == NPadControllerType::Handheld) {
+ // Handheld is not even a supported type, lets stop here
+ if (std::find(supported_npad_id_types.begin(), supported_npad_id_types.end(),
+ NPAD_HANDHELD) == supported_npad_id_types.end()) {
+ return false;
+ }
+ // Handheld should not be supported in docked mode
+ if (Settings::values.use_docked_mode) {
+ return false;
+ }
+ }
+ switch (controller) {
+ case NPadControllerType::ProController:
+ return style.pro_controller;
+ case NPadControllerType::Handheld:
+ return style.handheld;
+ case NPadControllerType::JoyDual:
+ return style.joycon_dual;
+ case NPadControllerType::JoyLeft:
+ return style.joycon_left;
+ case NPadControllerType::JoyRight:
+ return style.joycon_right;
+ case NPadControllerType::Pokeball:
+ return style.pokeball;
+ default:
+ return false;
+ }
}
Controller_NPad::LedPattern Controller_NPad::GetLedPattern(u32 npad_id) {
@@ -494,6 +648,36 @@ void Controller_NPad::SetVibrationEnabled(bool can_vibrate) {
can_controllers_vibrate = can_vibrate;
}
+void Controller_NPad::ClearAllConnectedControllers() {
+ for (auto& controller : connected_controllers) {
+ if (controller.is_connected && controller.type != NPadControllerType::None) {
+ controller.type = NPadControllerType::None;
+ controller.is_connected = false;
+ }
+ }
+}
+void Controller_NPad::DisconnectAllConnectedControllers() {
+ std::for_each(connected_controllers.begin(), connected_controllers.end(),
+ [](ControllerHolder& controller) { controller.is_connected = false; });
+}
+
+void Controller_NPad::ConnectAllDisconnectedControllers() {
+ std::for_each(connected_controllers.begin(), connected_controllers.end(),
+ [](ControllerHolder& controller) {
+ if (controller.type != NPadControllerType::None && !controller.is_connected) {
+ controller.is_connected = false;
+ }
+ });
+}
+
+void Controller_NPad::ClearAllControllers() {
+ std::for_each(connected_controllers.begin(), connected_controllers.end(),
+ [](ControllerHolder& controller) {
+ controller.type = NPadControllerType::None;
+ controller.is_connected = false;
+ });
+}
+
bool Controller_NPad::IsControllerSupported(NPadControllerType controller) const {
const bool support_handheld =
std::find(supported_npad_id_types.begin(), supported_npad_id_types.end(), NPAD_HANDHELD) !=
diff --git a/src/core/hle/service/hid/controllers/npad.h b/src/core/hle/service/hid/controllers/npad.h
index ac86985ff..ea8057b80 100644
--- a/src/core/hle/service/hid/controllers/npad.h
+++ b/src/core/hle/service/hid/controllers/npad.h
@@ -5,13 +5,18 @@
#pragma once
#include <array>
+#include "common/bit_field.h"
#include "common/common_types.h"
#include "core/frontend/input.h"
+#include "core/hle/kernel/event.h"
#include "core/hle/service/hid/controllers/controller_base.h"
#include "core/settings.h"
namespace Service::HID {
+constexpr u32 NPAD_HANDHELD = 32;
+constexpr u32 NPAD_UNKNOWN = 16; // TODO(ogniK): What is this?
+
class Controller_NPad final : public ControllerBase {
public:
Controller_NPad();
@@ -107,11 +112,19 @@ public:
Vibration GetLastVibration() const;
void AddNewController(NPadControllerType controller);
+ void AddNewControllerAt(NPadControllerType controller, u32 npad_id);
void ConnectNPad(u32 npad_id);
void DisconnectNPad(u32 npad_id);
LedPattern GetLedPattern(u32 npad_id);
void SetVibrationEnabled(bool can_vibrate);
+ void ClearAllConnectedControllers();
+ void DisconnectAllConnectedControllers();
+ void ConnectAllDisconnectedControllers();
+ void ClearAllControllers();
+
+ static std::size_t NPadIdToIndex(u32 npad_id);
+ static u32 IndexToNPad(std::size_t index);
private:
struct CommonHeader {
@@ -164,8 +177,11 @@ private:
BitField<23, 1, u64_le> r_stick_down;
// Not always active?
- BitField<24, 1, u64_le> sl;
- BitField<25, 1, u64_le> sr;
+ BitField<24, 1, u64_le> left_sl;
+ BitField<25, 1, u64_le> left_sr;
+
+ BitField<26, 1, u64_le> right_sl;
+ BitField<27, 1, u64_le> right_sr;
};
};
static_assert(sizeof(ControllerPadState) == 8, "ControllerPadState is an invalid size");
@@ -189,12 +205,17 @@ private:
};
static_assert(sizeof(ConnectionState) == 4, "ConnectionState is an invalid size");
- struct GenericStates {
- s64_le timestamp;
- s64_le timestamp2;
+ struct ControllerPad {
ControllerPadState pad_states;
AnalogPosition l_stick;
AnalogPosition r_stick;
+ };
+ static_assert(sizeof(ControllerPad) == 0x18, "ControllerPad is an invalid size");
+
+ struct GenericStates {
+ s64_le timestamp;
+ s64_le timestamp2;
+ ControllerPad pad;
ConnectionState connection_status;
};
static_assert(sizeof(GenericStates) == 0x30, "NPadGenericStates is an invalid size");
@@ -266,15 +287,20 @@ private:
static_assert(sizeof(NPadEntry) == 0x5000, "NPadEntry is an invalid size");
struct ControllerHolder {
- Controller_NPad::NPadControllerType type;
+ NPadControllerType type;
bool is_connected;
};
NPadType style{};
std::array<NPadEntry, 10> shared_memory_entries{};
- std::array<std::unique_ptr<Input::ButtonDevice>, Settings::NativeButton::NUM_BUTTONS_HID>
+ std::array<
+ std::array<std::unique_ptr<Input::ButtonDevice>, Settings::NativeButton::NUM_BUTTONS_HID>,
+ 10>
buttons;
- std::array<std::unique_ptr<Input::AnalogDevice>, Settings::NativeAnalog::NUM_STICKS_HID> sticks;
+ std::array<
+ std::array<std::unique_ptr<Input::AnalogDevice>, Settings::NativeAnalog::NUM_STICKS_HID>,
+ 10>
+ sticks;
std::vector<u32> supported_npad_id_types{};
NpadHoldType hold_type{NpadHoldType::Vertical};
Kernel::SharedPtr<Kernel::Event> styleset_changed_event;
@@ -285,5 +311,8 @@ private:
void InitNewlyAddedControler(std::size_t controller_idx);
bool IsControllerSupported(NPadControllerType controller) const;
NPadControllerType DecideBestController(NPadControllerType priority) const;
+ void RequestPadStateUpdate(u32 npad_id);
+ std::array<ControllerPad, 10> npad_pad_states{};
+ bool IsControllerSupported(NPadControllerType controller);
};
} // namespace Service::HID
diff --git a/src/core/hle/service/hid/controllers/touchscreen.cpp b/src/core/hle/service/hid/controllers/touchscreen.cpp
index 43efef803..f666b1bd8 100644
--- a/src/core/hle/service/hid/controllers/touchscreen.cpp
+++ b/src/core/hle/service/hid/controllers/touchscreen.cpp
@@ -41,16 +41,17 @@ void Controller_Touchscreen::OnUpdate(u8* data, std::size_t size) {
const auto [x, y, pressed] = touch_device->GetStatus();
auto& touch_entry = cur_entry.states[0];
- if (pressed) {
+ touch_entry.attribute.raw = 0;
+ if (pressed && Settings::values.touchscreen.enabled) {
touch_entry.x = static_cast<u16>(x * Layout::ScreenUndocked::Width);
touch_entry.y = static_cast<u16>(y * Layout::ScreenUndocked::Height);
- touch_entry.diameter_x = 15;
- touch_entry.diameter_y = 15;
- touch_entry.rotation_angle = 0;
+ touch_entry.diameter_x = Settings::values.touchscreen.diameter_x;
+ touch_entry.diameter_y = Settings::values.touchscreen.diameter_y;
+ touch_entry.rotation_angle = Settings::values.touchscreen.rotation_angle;
const u64 tick = CoreTiming::GetTicks();
touch_entry.delta_time = tick - last_touch;
last_touch = tick;
- touch_entry.finger = 0;
+ touch_entry.finger = Settings::values.touchscreen.finger;
cur_entry.entry_count = 1;
} else {
cur_entry.entry_count = 0;
@@ -60,6 +61,6 @@ void Controller_Touchscreen::OnUpdate(u8* data, std::size_t size) {
}
void Controller_Touchscreen::OnLoadInputDevices() {
- touch_device = Input::CreateDevice<Input::TouchDevice>(Settings::values.touch_device);
+ touch_device = Input::CreateDevice<Input::TouchDevice>(Settings::values.touchscreen.device);
}
} // namespace Service::HID
diff --git a/src/core/hle/service/hid/controllers/touchscreen.h b/src/core/hle/service/hid/controllers/touchscreen.h
index e5db6e6ba..94cd0eba9 100644
--- a/src/core/hle/service/hid/controllers/touchscreen.h
+++ b/src/core/hle/service/hid/controllers/touchscreen.h
@@ -4,6 +4,7 @@
#pragma once
+#include "common/bit_field.h"
#include "common/common_funcs.h"
#include "common/common_types.h"
#include "common/swap.h"
@@ -29,9 +30,18 @@ public:
void OnLoadInputDevices() override;
private:
+ struct Attributes {
+ union {
+ u32 raw{};
+ BitField<0, 1, u32_le> start_touch;
+ BitField<1, 1, u32_le> end_touch;
+ };
+ };
+ static_assert(sizeof(Attributes) == 0x4, "Attributes is an invalid size");
+
struct TouchState {
u64_le delta_time;
- u32_le attribute;
+ Attributes attribute;
u32_le finger;
u32_le x;
u32_le y;
diff --git a/src/core/hle/service/hid/hid.cpp b/src/core/hle/service/hid/hid.cpp
index a9aa9ec78..7c0dac5dc 100644
--- a/src/core/hle/service/hid/hid.cpp
+++ b/src/core/hle/service/hid/hid.cpp
@@ -34,8 +34,8 @@
namespace Service::HID {
// Updating period for each HID device.
-// TODO(shinyquagsire23): These need better values.
-constexpr u64 pad_update_ticks = CoreTiming::BASE_CLOCK_RATE / 100;
+// TODO(ogniK): Find actual polling rate of hid
+constexpr u64 pad_update_ticks = CoreTiming::BASE_CLOCK_RATE / 66;
constexpr u64 accelerometer_update_ticks = CoreTiming::BASE_CLOCK_RATE / 100;
constexpr u64 gyroscope_update_ticks = CoreTiming::BASE_CLOCK_RATE / 100;
constexpr std::size_t SHARED_MEMORY_SIZE = 0x40000;
@@ -96,6 +96,8 @@ public:
// TODO(shinyquagsire23): Other update callbacks? (accel, gyro?)
CoreTiming::ScheduleEvent(pad_update_ticks, pad_update_event);
+
+ ReloadInputDevices();
}
void ActivateController(HidController controller) {
@@ -284,10 +286,10 @@ public:
{519, nullptr, "GetPalmaOperationResult"},
{520, nullptr, "ReadPalmaPlayLog"},
{521, nullptr, "ResetPalmaPlayLog"},
- {522, nullptr, "SetIsPalmaAllConnectable"},
+ {522, &Hid::SetIsPalmaAllConnectable, "SetIsPalmaAllConnectable"},
{523, nullptr, "SetIsPalmaPairedConnectable"},
{524, nullptr, "PairPalma"},
- {525, nullptr, "SetPalmaBoostMode"},
+ {525, &Hid::SetPalmaBoostMode, "SetPalmaBoostMode"},
{1000, nullptr, "SetNpadCommunicationMode"},
{1001, nullptr, "GetNpadCommunicationMode"},
};
@@ -594,6 +596,18 @@ private:
rb.Push(RESULT_SUCCESS);
LOG_WARNING(Service_HID, "(STUBBED) called");
}
+
+ void SetIsPalmaAllConnectable(Kernel::HLERequestContext& ctx) {
+ IPC::ResponseBuilder rb{ctx, 2};
+ rb.Push(RESULT_SUCCESS);
+ LOG_WARNING(Service_HID, "(STUBBED) called");
+ }
+
+ void SetPalmaBoostMode(Kernel::HLERequestContext& ctx) {
+ IPC::ResponseBuilder rb{ctx, 2};
+ rb.Push(RESULT_SUCCESS);
+ LOG_WARNING(Service_HID, "(STUBBED) called");
+ }
};
class HidDbg final : public ServiceFramework<HidDbg> {
diff --git a/src/core/hle/service/ldr/ldr.cpp b/src/core/hle/service/ldr/ldr.cpp
index d607d985e..7a9d0d0dd 100644
--- a/src/core/hle/service/ldr/ldr.cpp
+++ b/src/core/hle/service/ldr/ldr.cpp
@@ -4,7 +4,10 @@
#include <memory>
#include <fmt/format.h>
+#include <mbedtls/sha256.h>
+#include "common/alignment.h"
+#include "common/hex_util.h"
#include "core/hle/ipc_helpers.h"
#include "core/hle/kernel/process.h"
#include "core/hle/service/ldr/ldr.h"
@@ -13,6 +16,21 @@
namespace Service::LDR {
+constexpr ResultCode ERROR_INVALID_MEMORY_STATE{ErrorModule::Loader, 51};
+constexpr ResultCode ERROR_INVALID_NRO{ErrorModule::Loader, 52};
+constexpr ResultCode ERROR_INVALID_NRR{ErrorModule::Loader, 53};
+constexpr ResultCode ERROR_MISSING_NRR_HASH{ErrorModule::Loader, 54};
+constexpr ResultCode ERROR_MAXIMUM_NRO{ErrorModule::Loader, 55};
+constexpr ResultCode ERROR_MAXIMUM_NRR{ErrorModule::Loader, 56};
+constexpr ResultCode ERROR_ALREADY_LOADED{ErrorModule::Loader, 57};
+constexpr ResultCode ERROR_INVALID_ALIGNMENT{ErrorModule::Loader, 81};
+constexpr ResultCode ERROR_INVALID_SIZE{ErrorModule::Loader, 82};
+constexpr ResultCode ERROR_INVALID_NRO_ADDRESS{ErrorModule::Loader, 84};
+constexpr ResultCode ERROR_INVALID_NRR_ADDRESS{ErrorModule::Loader, 85};
+constexpr ResultCode ERROR_NOT_INITIALIZED{ErrorModule::Loader, 87};
+
+constexpr u64 MAXIMUM_LOADED_RO = 0x40;
+
class DebugMonitor final : public ServiceFramework<DebugMonitor> {
public:
explicit DebugMonitor() : ServiceFramework{"ldr:dmnt"} {
@@ -64,9 +82,9 @@ public:
// clang-format off
static const FunctionInfo functions[] = {
{0, &RelocatableObject::LoadNro, "LoadNro"},
- {1, nullptr, "UnloadNro"},
+ {1, &RelocatableObject::UnloadNro, "UnloadNro"},
{2, &RelocatableObject::LoadNrr, "LoadNrr"},
- {3, nullptr, "UnloadNrr"},
+ {3, &RelocatableObject::UnloadNrr, "UnloadNrr"},
{4, &RelocatableObject::Initialize, "Initialize"},
};
// clang-format on
@@ -75,9 +93,123 @@ public:
}
void LoadNrr(Kernel::HLERequestContext& ctx) {
+ IPC::RequestParser rp{ctx};
+ rp.Skip(2, false);
+ const VAddr nrr_addr{rp.Pop<VAddr>()};
+ const u64 nrr_size{rp.Pop<u64>()};
+
+ if (!initialized) {
+ LOG_ERROR(Service_LDR, "LDR:RO not initialized before use!");
+ IPC::ResponseBuilder rb{ctx, 2};
+ rb.Push(ERROR_NOT_INITIALIZED);
+ return;
+ }
+
+ if (nrr.size() >= MAXIMUM_LOADED_RO) {
+ LOG_ERROR(Service_LDR, "Loading new NRR would exceed the maximum number of loaded NRRs "
+ "(0x40)! Failing...");
+ IPC::ResponseBuilder rb{ctx, 2};
+ rb.Push(ERROR_MAXIMUM_NRR);
+ return;
+ }
+
+ // NRR Address does not fall on 0x1000 byte boundary
+ if (!Common::Is4KBAligned(nrr_addr)) {
+ LOG_ERROR(Service_LDR, "NRR Address has invalid alignment (actual {:016X})!", nrr_addr);
+ IPC::ResponseBuilder rb{ctx, 2};
+ rb.Push(ERROR_INVALID_ALIGNMENT);
+ return;
+ }
+
+ // NRR Size is zero or causes overflow
+ if (nrr_addr + nrr_size <= nrr_addr || nrr_size == 0 || !Common::Is4KBAligned(nrr_size)) {
+ LOG_ERROR(Service_LDR, "NRR Size is invalid! (nrr_address={:016X}, nrr_size={:016X})",
+ nrr_addr, nrr_size);
+ IPC::ResponseBuilder rb{ctx, 2};
+ rb.Push(ERROR_INVALID_SIZE);
+ return;
+ }
+ // Read NRR data from memory
+ std::vector<u8> nrr_data(nrr_size);
+ Memory::ReadBlock(nrr_addr, nrr_data.data(), nrr_size);
+ NRRHeader header;
+ std::memcpy(&header, nrr_data.data(), sizeof(NRRHeader));
+
+ if (header.magic != Common::MakeMagic('N', 'R', 'R', '0')) {
+ LOG_ERROR(Service_LDR, "NRR did not have magic 'NRR0' (actual {:08X})!", header.magic);
+ IPC::ResponseBuilder rb{ctx, 2};
+ rb.Push(ERROR_INVALID_NRR);
+ return;
+ }
+
+ if (header.size != nrr_size) {
+ LOG_ERROR(Service_LDR,
+ "NRR header reported size did not match LoadNrr parameter size! "
+ "(header_size={:016X}, loadnrr_size={:016X})",
+ header.size, nrr_size);
+ IPC::ResponseBuilder rb{ctx, 2};
+ rb.Push(ERROR_INVALID_SIZE);
+ return;
+ }
+
+ if (Core::CurrentProcess()->GetTitleID() != header.title_id) {
+ LOG_ERROR(Service_LDR,
+ "Attempting to load NRR with title ID other than current process. (actual "
+ "{:016X})!",
+ header.title_id);
+ IPC::ResponseBuilder rb{ctx, 2};
+ rb.Push(ERROR_INVALID_NRR);
+ return;
+ }
+
+ std::vector<SHA256Hash> hashes;
+
+ // Copy all hashes in the NRR (specified by hash count/hash offset) into vector.
+ for (std::size_t i = header.hash_offset;
+ i < (header.hash_offset + (header.hash_count * sizeof(SHA256Hash))); i += 8) {
+ SHA256Hash hash;
+ std::memcpy(hash.data(), nrr_data.data() + i, sizeof(SHA256Hash));
+ hashes.emplace_back(hash);
+ }
+
+ nrr.insert_or_assign(nrr_addr, std::move(hashes));
+
+ IPC::ResponseBuilder rb{ctx, 2};
+ rb.Push(RESULT_SUCCESS);
+ }
+
+ void UnloadNrr(Kernel::HLERequestContext& ctx) {
+ if (!initialized) {
+ LOG_ERROR(Service_LDR, "LDR:RO not initialized before use!");
+ IPC::ResponseBuilder rb{ctx, 2};
+ rb.Push(ERROR_NOT_INITIALIZED);
+ return;
+ }
+
+ IPC::RequestParser rp{ctx};
+ rp.Skip(2, false);
+ const auto nrr_addr{rp.Pop<VAddr>()};
+
+ if (!Common::Is4KBAligned(nrr_addr)) {
+ LOG_ERROR(Service_LDR, "NRR Address has invalid alignment (actual {:016X})!", nrr_addr);
+ IPC::ResponseBuilder rb{ctx, 2};
+ rb.Push(ERROR_INVALID_ALIGNMENT);
+ return;
+ }
+
+ const auto iter = nrr.find(nrr_addr);
+ if (iter == nrr.end()) {
+ LOG_ERROR(Service_LDR,
+ "Attempting to unload NRR which has not been loaded! (addr={:016X})",
+ nrr_addr);
+ IPC::ResponseBuilder rb{ctx, 2};
+ rb.Push(ERROR_INVALID_NRR_ADDRESS);
+ return;
+ }
+
+ nrr.erase(iter);
IPC::ResponseBuilder rb{ctx, 2};
rb.Push(RESULT_SUCCESS);
- LOG_WARNING(Service_LDR, "(STUBBED) called");
}
void LoadNro(Kernel::HLERequestContext& ctx) {
@@ -88,33 +220,253 @@ public:
const VAddr bss_addr{rp.Pop<VAddr>()};
const u64 bss_size{rp.Pop<u64>()};
+ if (!initialized) {
+ LOG_ERROR(Service_LDR, "LDR:RO not initialized before use!");
+ IPC::ResponseBuilder rb{ctx, 2};
+ rb.Push(ERROR_NOT_INITIALIZED);
+ return;
+ }
+
+ if (nro.size() >= MAXIMUM_LOADED_RO) {
+ LOG_ERROR(Service_LDR, "Loading new NRO would exceed the maximum number of loaded NROs "
+ "(0x40)! Failing...");
+ IPC::ResponseBuilder rb{ctx, 2};
+ rb.Push(ERROR_MAXIMUM_NRO);
+ return;
+ }
+
+ // NRO Address does not fall on 0x1000 byte boundary
+ if (!Common::Is4KBAligned(nro_addr)) {
+ LOG_ERROR(Service_LDR, "NRO Address has invalid alignment (actual {:016X})!", nro_addr);
+ IPC::ResponseBuilder rb{ctx, 2};
+ rb.Push(ERROR_INVALID_ALIGNMENT);
+ return;
+ }
+
+ // NRO Size or BSS Size is zero or causes overflow
+ const auto nro_size_valid =
+ nro_size != 0 && nro_addr + nro_size > nro_addr && Common::Is4KBAligned(nro_size);
+ const auto bss_size_valid =
+ nro_size + bss_size >= nro_size && (bss_size == 0 || bss_addr + bss_size > bss_addr);
+
+ if (!nro_size_valid || !bss_size_valid) {
+ LOG_ERROR(Service_LDR,
+ "NRO Size or BSS Size is invalid! (nro_address={:016X}, nro_size={:016X}, "
+ "bss_address={:016X}, bss_size={:016X})",
+ nro_addr, nro_size, bss_addr, bss_size);
+ IPC::ResponseBuilder rb{ctx, 2};
+ rb.Push(ERROR_INVALID_SIZE);
+ return;
+ }
+
// Read NRO data from memory
std::vector<u8> nro_data(nro_size);
Memory::ReadBlock(nro_addr, nro_data.data(), nro_size);
+ SHA256Hash hash{};
+ mbedtls_sha256(nro_data.data(), nro_data.size(), hash.data(), 0);
+
+ // NRO Hash is already loaded
+ if (std::any_of(nro.begin(), nro.end(), [&hash](const std::pair<VAddr, NROInfo>& info) {
+ return info.second.hash == hash;
+ })) {
+ LOG_ERROR(Service_LDR, "NRO is already loaded!");
+ IPC::ResponseBuilder rb{ctx, 2};
+ rb.Push(ERROR_ALREADY_LOADED);
+ return;
+ }
+
+ // NRO Hash is not in any loaded NRR
+ if (!IsValidNROHash(hash)) {
+ LOG_ERROR(Service_LDR,
+ "NRO hash is not present in any currently loaded NRRs (hash={})!",
+ Common::HexArrayToString(hash));
+ IPC::ResponseBuilder rb{ctx, 2};
+ rb.Push(ERROR_MISSING_NRR_HASH);
+ return;
+ }
+
+ NROHeader header;
+ std::memcpy(&header, nro_data.data(), sizeof(NROHeader));
+
+ if (!IsValidNRO(header, nro_size, bss_size)) {
+ LOG_ERROR(Service_LDR, "NRO was invalid!");
+ IPC::ResponseBuilder rb{ctx, 2};
+ rb.Push(ERROR_INVALID_NRO);
+ return;
+ }
+
// Load NRO as new executable module
- const VAddr addr{*Core::CurrentProcess()->VMManager().FindFreeRegion(nro_size + bss_size)};
- Loader::AppLoader_NRO::LoadNro(nro_data, fmt::format("nro-{:08x}", addr), addr);
+ auto* process = Core::CurrentProcess();
+ auto& vm_manager = process->VMManager();
+ auto map_address = vm_manager.FindFreeRegion(nro_size + bss_size);
+
+ if (!map_address.Succeeded() ||
+ *map_address + nro_size + bss_size > vm_manager.GetAddressSpaceEndAddress()) {
+
+ LOG_ERROR(Service_LDR,
+ "General error while allocation memory or no available memory to allocate!");
+ IPC::ResponseBuilder rb{ctx, 2};
+ rb.Push(ERROR_INVALID_MEMORY_STATE);
+ return;
+ }
+
+ ASSERT(process->MirrorMemory(*map_address, nro_addr, nro_size,
+ Kernel::MemoryState::ModuleCodeStatic) == RESULT_SUCCESS);
+ ASSERT(process->UnmapMemory(nro_addr, 0, nro_size) == RESULT_SUCCESS);
- // TODO(bunnei): This is an incomplete implementation. It was tested with Super Mario Party.
- // It is currently missing:
- // - Signature checks with LoadNRR
- // - Checking if a module has already been loaded
- // - Using/validating BSS, etc. params (these are used from NRO header instead)
- // - Error checking
- // - ...Probably other things
+ if (bss_size > 0) {
+ ASSERT(process->MirrorMemory(*map_address + nro_size, bss_addr, bss_size,
+ Kernel::MemoryState::ModuleCodeStatic) == RESULT_SUCCESS);
+ ASSERT(process->UnmapMemory(bss_addr, 0, bss_size) == RESULT_SUCCESS);
+ }
+
+ vm_manager.ReprotectRange(*map_address, header.text_size,
+ Kernel::VMAPermission::ReadExecute);
+ vm_manager.ReprotectRange(*map_address + header.ro_offset, header.ro_size,
+ Kernel::VMAPermission::Read);
+ vm_manager.ReprotectRange(*map_address + header.rw_offset, header.rw_size,
+ Kernel::VMAPermission::ReadWrite);
+
+ Core::System::GetInstance().ArmInterface(0).ClearInstructionCache();
+ Core::System::GetInstance().ArmInterface(1).ClearInstructionCache();
+ Core::System::GetInstance().ArmInterface(2).ClearInstructionCache();
+ Core::System::GetInstance().ArmInterface(3).ClearInstructionCache();
+
+ nro.insert_or_assign(*map_address, NROInfo{hash, nro_size + bss_size});
IPC::ResponseBuilder rb{ctx, 4};
rb.Push(RESULT_SUCCESS);
- rb.Push(addr);
- LOG_WARNING(Service_LDR, "(STUBBED) called");
+ rb.Push(*map_address);
+ }
+
+ void UnloadNro(Kernel::HLERequestContext& ctx) {
+ IPC::RequestParser rp{ctx};
+ rp.Skip(2, false);
+ const VAddr mapped_addr{rp.PopRaw<VAddr>()};
+ const VAddr heap_addr{rp.PopRaw<VAddr>()};
+
+ if (!initialized) {
+ LOG_ERROR(Service_LDR, "LDR:RO not initialized before use!");
+ IPC::ResponseBuilder rb{ctx, 2};
+ rb.Push(ERROR_NOT_INITIALIZED);
+ return;
+ }
+
+ if (!Common::Is4KBAligned(mapped_addr) || !Common::Is4KBAligned(heap_addr)) {
+ LOG_ERROR(Service_LDR,
+ "NRO/BSS Address has invalid alignment (actual nro_addr={:016X}, "
+ "bss_addr={:016X})!",
+ mapped_addr, heap_addr);
+ IPC::ResponseBuilder rb{ctx, 2};
+ rb.Push(ERROR_INVALID_ALIGNMENT);
+ return;
+ }
+
+ const auto iter = nro.find(mapped_addr);
+ if (iter == nro.end()) {
+ LOG_ERROR(Service_LDR,
+ "The NRO attempting to unmap was not mapped or has an invalid address "
+ "(actual {:016X})!",
+ mapped_addr);
+ IPC::ResponseBuilder rb{ctx, 2};
+ rb.Push(ERROR_INVALID_NRO_ADDRESS);
+ return;
+ }
+
+ auto* process = Core::CurrentProcess();
+ auto& vm_manager = process->VMManager();
+ const auto& nro_size = iter->second.size;
+
+ ASSERT(process->MirrorMemory(heap_addr, mapped_addr, nro_size,
+ Kernel::MemoryState::ModuleCodeStatic) == RESULT_SUCCESS);
+ ASSERT(process->UnmapMemory(mapped_addr, 0, nro_size) == RESULT_SUCCESS);
+
+ Core::System::GetInstance().ArmInterface(0).ClearInstructionCache();
+ Core::System::GetInstance().ArmInterface(1).ClearInstructionCache();
+ Core::System::GetInstance().ArmInterface(2).ClearInstructionCache();
+ Core::System::GetInstance().ArmInterface(3).ClearInstructionCache();
+
+ nro.erase(iter);
+ IPC::ResponseBuilder rb{ctx, 2};
+ rb.Push(RESULT_SUCCESS);
}
void Initialize(Kernel::HLERequestContext& ctx) {
+ initialized = true;
+
IPC::ResponseBuilder rb{ctx, 2};
rb.Push(RESULT_SUCCESS);
LOG_WARNING(Service_LDR, "(STUBBED) called");
}
+
+private:
+ using SHA256Hash = std::array<u8, 0x20>;
+
+ struct NROHeader {
+ u32_le entrypoint_insn;
+ u32_le mod_offset;
+ INSERT_PADDING_WORDS(2);
+ u32_le magic;
+ INSERT_PADDING_WORDS(1);
+ u32_le nro_size;
+ INSERT_PADDING_WORDS(1);
+ u32_le text_offset;
+ u32_le text_size;
+ u32_le ro_offset;
+ u32_le ro_size;
+ u32_le rw_offset;
+ u32_le rw_size;
+ u32_le bss_size;
+ INSERT_PADDING_WORDS(1);
+ std::array<u8, 0x20> build_id;
+ INSERT_PADDING_BYTES(0x20);
+ };
+ static_assert(sizeof(NROHeader) == 0x80, "NROHeader has invalid size.");
+
+ struct NRRHeader {
+ u32_le magic;
+ INSERT_PADDING_BYTES(0x1C);
+ u64_le title_id_mask;
+ u64_le title_id_pattern;
+ std::array<u8, 0x100> modulus;
+ std::array<u8, 0x100> signature_1;
+ std::array<u8, 0x100> signature_2;
+ u64_le title_id;
+ u32_le size;
+ INSERT_PADDING_BYTES(4);
+ u32_le hash_offset;
+ u32_le hash_count;
+ INSERT_PADDING_BYTES(8);
+ };
+ static_assert(sizeof(NRRHeader) == 0x350, "NRRHeader has incorrect size.");
+
+ struct NROInfo {
+ SHA256Hash hash;
+ u64 size;
+ };
+
+ bool initialized = false;
+
+ std::map<VAddr, NROInfo> nro;
+ std::map<VAddr, std::vector<SHA256Hash>> nrr;
+
+ bool IsValidNROHash(const SHA256Hash& hash) {
+ return std::any_of(
+ nrr.begin(), nrr.end(), [&hash](const std::pair<VAddr, std::vector<SHA256Hash>>& p) {
+ return std::find(p.second.begin(), p.second.end(), hash) != p.second.end();
+ });
+ }
+
+ static bool IsValidNRO(const NROHeader& header, u64 nro_size, u64 bss_size) {
+ return header.magic == Common::MakeMagic('N', 'R', 'O', '0') &&
+ header.nro_size == nro_size && header.bss_size == bss_size &&
+ header.ro_offset == header.text_offset + header.text_size &&
+ header.rw_offset == header.ro_offset + header.ro_size &&
+ nro_size == header.rw_offset + header.rw_size &&
+ Common::Is4KBAligned(header.text_size) && Common::Is4KBAligned(header.ro_size) &&
+ Common::Is4KBAligned(header.rw_size);
+ }
};
void InstallInterfaces(SM::ServiceManager& sm) {
diff --git a/src/core/hle/service/lm/lm.cpp b/src/core/hle/service/lm/lm.cpp
index c89157a4d..4e5fdb16e 100644
--- a/src/core/hle/service/lm/lm.cpp
+++ b/src/core/hle/service/lm/lm.cpp
@@ -18,7 +18,7 @@ public:
ILogger() : ServiceFramework("ILogger") {
static const FunctionInfo functions[] = {
{0x00000000, &ILogger::Initialize, "Initialize"},
- {0x00000001, nullptr, "SetDestination"},
+ {0x00000001, &ILogger::SetDestination, "SetDestination"},
};
RegisterHandlers(functions);
}
@@ -178,6 +178,17 @@ private:
}
}
+ // This service function is intended to be used as a way to
+ // redirect logging output to different destinations, however,
+ // given we always want to see the logging output, it's sufficient
+ // to do nothing and return success here.
+ void SetDestination(Kernel::HLERequestContext& ctx) {
+ LOG_DEBUG(Service_LM, "called");
+
+ IPC::ResponseBuilder rb{ctx, 2};
+ rb.Push(RESULT_SUCCESS);
+ }
+
std::ostringstream log_stream;
};
diff --git a/src/core/hle/service/nfp/nfp.cpp b/src/core/hle/service/nfp/nfp.cpp
index c1af878fe..1d6e7756f 100644
--- a/src/core/hle/service/nfp/nfp.cpp
+++ b/src/core/hle/service/nfp/nfp.cpp
@@ -212,7 +212,7 @@ private:
IPC::ResponseBuilder rb{ctx, 2};
auto amiibo = nfp_interface.GetAmiiboBuffer();
TagInfo tag_info{};
- std::memcpy(tag_info.uuid.data(), amiibo.uuid.data(), sizeof(tag_info.uuid.size()));
+ tag_info.uuid = amiibo.uuid;
tag_info.uuid_length = static_cast<u8>(tag_info.uuid.size());
tag_info.protocol = 1; // TODO(ogniK): Figure out actual values
diff --git a/src/core/hle/service/ns/ns.cpp b/src/core/hle/service/ns/ns.cpp
index 07c1381fe..1d2978f24 100644
--- a/src/core/hle/service/ns/ns.cpp
+++ b/src/core/hle/service/ns/ns.cpp
@@ -2,6 +2,9 @@
// Licensed under GPLv2 or any later version
// Refer to the license.txt file included.
+#include "common/logging/log.h"
+#include "core/file_sys/control_metadata.h"
+#include "core/file_sys/patch_manager.h"
#include "core/hle/ipc_helpers.h"
#include "core/hle/kernel/hle_ipc.h"
#include "core/hle/service/ns/ns.h"
@@ -118,7 +121,7 @@ public:
{305, nullptr, "TerminateSystemApplet"},
{306, nullptr, "LaunchOverlayApplet"},
{307, nullptr, "TerminateOverlayApplet"},
- {400, nullptr, "GetApplicationControlData"},
+ {400, &IApplicationManagerInterface::GetApplicationControlData, "GetApplicationControlData"},
{401, nullptr, "InvalidateAllApplicationControlCache"},
{402, nullptr, "RequestDownloadApplicationControlData"},
{403, nullptr, "GetMaxApplicationControlCacheCount"},
@@ -243,6 +246,65 @@ public:
RegisterHandlers(functions);
}
+
+ void GetApplicationControlData(Kernel::HLERequestContext& ctx) {
+ IPC::RequestParser rp{ctx};
+ const auto flag = rp.PopRaw<u64>();
+ LOG_DEBUG(Service_NS, "called with flag={:016X}", flag);
+
+ const auto title_id = rp.PopRaw<u64>();
+
+ const auto size = ctx.GetWriteBufferSize();
+
+ const FileSys::PatchManager pm{title_id};
+ const auto control = pm.GetControlMetadata();
+
+ std::vector<u8> out;
+
+ if (control.first != nullptr) {
+ if (size < 0x4000) {
+ LOG_ERROR(Service_NS,
+ "output buffer is too small! (actual={:016X}, expected_min=0x4000)",
+ size);
+ IPC::ResponseBuilder rb{ctx, 2};
+ // TODO(DarkLordZach): Find a better error code for this.
+ rb.Push(ResultCode(-1));
+ return;
+ }
+
+ out.resize(0x4000);
+ const auto bytes = control.first->GetRawBytes();
+ std::memcpy(out.data(), bytes.data(), bytes.size());
+ } else {
+ LOG_WARNING(Service_NS, "missing NACP data for title_id={:016X}, defaulting to zeros.",
+ title_id);
+ out.resize(std::min<u64>(0x4000, size));
+ }
+
+ if (control.second != nullptr) {
+ if (size < 0x4000 + control.second->GetSize()) {
+ LOG_ERROR(Service_NS,
+ "output buffer is too small! (actual={:016X}, expected_min={:016X})",
+ size, 0x4000 + control.second->GetSize());
+ IPC::ResponseBuilder rb{ctx, 2};
+ // TODO(DarkLordZach): Find a better error code for this.
+ rb.Push(ResultCode(-1));
+ return;
+ }
+
+ out.resize(0x4000 + control.second->GetSize());
+ control.second->Read(out.data() + 0x4000, control.second->GetSize());
+ } else {
+ LOG_WARNING(Service_NS, "missing icon data for title_id={:016X}, defaulting to zeros.",
+ title_id);
+ }
+
+ ctx.WriteBuffer(out);
+
+ IPC::ResponseBuilder rb{ctx, 3};
+ rb.Push(RESULT_SUCCESS);
+ rb.Push<u32>(static_cast<u32>(out.size()));
+ }
};
class IApplicationVersionInterface final : public ServiceFramework<IApplicationVersionInterface> {
diff --git a/src/core/hle/service/ns/pl_u.cpp b/src/core/hle/service/ns/pl_u.cpp
index 44accecb7..1066bf505 100644
--- a/src/core/hle/service/ns/pl_u.cpp
+++ b/src/core/hle/service/ns/pl_u.cpp
@@ -351,6 +351,14 @@ void PL_U::GetSharedFontInOrderOfPriority(Kernel::HLERequestContext& ctx) {
font_sizes.push_back(region.size);
}
+ // Resize buffers if game requests smaller size output.
+ font_codes.resize(
+ std::min<std::size_t>(font_codes.size(), ctx.GetWriteBufferSize(0) / sizeof(u32)));
+ font_offsets.resize(
+ std::min<std::size_t>(font_offsets.size(), ctx.GetWriteBufferSize(1) / sizeof(u32)));
+ font_sizes.resize(
+ std::min<std::size_t>(font_sizes.size(), ctx.GetWriteBufferSize(2) / sizeof(u32)));
+
ctx.WriteBuffer(font_codes, 0);
ctx.WriteBuffer(font_offsets, 1);
ctx.WriteBuffer(font_sizes, 2);
diff --git a/src/core/hle/service/nvdrv/devices/nvhost_ctrl_gpu.cpp b/src/core/hle/service/nvdrv/devices/nvhost_ctrl_gpu.cpp
index 7a88ae029..792d26e52 100644
--- a/src/core/hle/service/nvdrv/devices/nvhost_ctrl_gpu.cpp
+++ b/src/core/hle/service/nvdrv/devices/nvhost_ctrl_gpu.cpp
@@ -5,6 +5,8 @@
#include <cstring>
#include "common/assert.h"
#include "common/logging/log.h"
+#include "core/core_timing.h"
+#include "core/core_timing_util.h"
#include "core/hle/service/nvdrv/devices/nvhost_ctrl_gpu.h"
namespace Service::Nvidia::Devices {
@@ -33,6 +35,8 @@ u32 nvhost_ctrl_gpu::ioctl(Ioctl command, const std::vector<u8>& input, std::vec
return ZBCQueryTable(input, output);
case IoctlCommand::IocFlushL2:
return FlushL2(input, output);
+ case IoctlCommand::IocGetGpuTime:
+ return GetGpuTime(input, output);
}
UNIMPLEMENTED_MSG("Unimplemented ioctl");
return 0;
@@ -169,4 +173,13 @@ u32 nvhost_ctrl_gpu::FlushL2(const std::vector<u8>& input, std::vector<u8>& outp
return 0;
}
+u32 nvhost_ctrl_gpu::GetGpuTime(const std::vector<u8>& input, std::vector<u8>& output) {
+ LOG_DEBUG(Service_NVDRV, "called");
+ IoctlGetGpuTime params{};
+ std::memcpy(&params, input.data(), input.size());
+ params.gpu_time = CoreTiming::cyclesToNs(CoreTiming::GetTicks());
+ std::memcpy(output.data(), &params, output.size());
+ return 0;
+}
+
} // namespace Service::Nvidia::Devices
diff --git a/src/core/hle/service/nvdrv/devices/nvhost_ctrl_gpu.h b/src/core/hle/service/nvdrv/devices/nvhost_ctrl_gpu.h
index 3bbf028ad..240435eea 100644
--- a/src/core/hle/service/nvdrv/devices/nvhost_ctrl_gpu.h
+++ b/src/core/hle/service/nvdrv/devices/nvhost_ctrl_gpu.h
@@ -156,6 +156,11 @@ private:
};
static_assert(sizeof(IoctlFlushL2) == 8, "IoctlFlushL2 is incorrect size");
+ struct IoctlGetGpuTime {
+ u64_le gpu_time;
+ };
+ static_assert(sizeof(IoctlGetGpuTime) == 8, "IoctlGetGpuTime is incorrect size");
+
u32 GetCharacteristics(const std::vector<u8>& input, std::vector<u8>& output);
u32 GetTPCMasks(const std::vector<u8>& input, std::vector<u8>& output);
u32 GetActiveSlotMask(const std::vector<u8>& input, std::vector<u8>& output);
@@ -164,6 +169,7 @@ private:
u32 ZBCSetTable(const std::vector<u8>& input, std::vector<u8>& output);
u32 ZBCQueryTable(const std::vector<u8>& input, std::vector<u8>& output);
u32 FlushL2(const std::vector<u8>& input, std::vector<u8>& output);
+ u32 GetGpuTime(const std::vector<u8>& input, std::vector<u8>& output);
};
} // namespace Service::Nvidia::Devices
diff --git a/src/core/hle/service/nvflinger/buffer_queue.h b/src/core/hle/service/nvflinger/buffer_queue.h
index 2fe81a560..8cff5eb71 100644
--- a/src/core/hle/service/nvflinger/buffer_queue.h
+++ b/src/core/hle/service/nvflinger/buffer_queue.h
@@ -58,9 +58,9 @@ public:
/// Rotate source image 90 degrees clockwise
Rotate90 = 0x04,
/// Rotate source image 180 degrees
- Roate180 = 0x03,
+ Rotate180 = 0x03,
/// Rotate source image 270 degrees clockwise
- Roate270 = 0x07,
+ Rotate270 = 0x07,
};
struct Buffer {
diff --git a/src/core/hle/service/service.cpp b/src/core/hle/service/service.cpp
index a4cf45267..1ec340466 100644
--- a/src/core/hle/service/service.cpp
+++ b/src/core/hle/service/service.cpp
@@ -80,8 +80,8 @@ namespace Service {
* Creates a function string for logging, complete with the name (or header code, depending
* on what's passed in) the port name, and all the cmd_buff arguments.
*/
-static std::string MakeFunctionString(const char* name, const char* port_name,
- const u32* cmd_buff) {
+[[maybe_unused]] static std::string MakeFunctionString(const char* name, const char* port_name,
+ const u32* cmd_buff) {
// Number of params == bits 0-5 + bits 6-11
int num_params = (cmd_buff[0] & 0x3F) + ((cmd_buff[0] >> 6) & 0x3F);
diff --git a/src/core/hle/service/spl/module.cpp b/src/core/hle/service/spl/module.cpp
index 44a6717d0..b2de2a818 100644
--- a/src/core/hle/service/spl/module.cpp
+++ b/src/core/hle/service/spl/module.cpp
@@ -3,18 +3,23 @@
// Refer to the license.txt file included.
#include <algorithm>
+#include <chrono>
#include <cstdlib>
+#include <ctime>
+#include <functional>
#include <vector>
#include "common/logging/log.h"
#include "core/hle/ipc_helpers.h"
#include "core/hle/service/spl/csrng.h"
#include "core/hle/service/spl/module.h"
#include "core/hle/service/spl/spl.h"
+#include "core/settings.h"
namespace Service::SPL {
Module::Interface::Interface(std::shared_ptr<Module> module, const char* name)
- : ServiceFramework(name), module(std::move(module)) {}
+ : ServiceFramework(name), module(std::move(module)),
+ rng(Settings::values.rng_seed.value_or(std::time(nullptr))) {}
Module::Interface::~Interface() = default;
@@ -23,8 +28,9 @@ void Module::Interface::GetRandomBytes(Kernel::HLERequestContext& ctx) {
std::size_t size = ctx.GetWriteBufferSize();
+ std::uniform_int_distribution<u16> distribution(0, std::numeric_limits<u8>::max());
std::vector<u8> data(size);
- std::generate(data.begin(), data.end(), std::rand);
+ std::generate(data.begin(), data.end(), [&] { return static_cast<u8>(distribution(rng)); });
ctx.WriteBuffer(data);
diff --git a/src/core/hle/service/spl/module.h b/src/core/hle/service/spl/module.h
index 48fda6099..afa1f0295 100644
--- a/src/core/hle/service/spl/module.h
+++ b/src/core/hle/service/spl/module.h
@@ -4,6 +4,7 @@
#pragma once
+#include <random>
#include "core/hle/service/service.h"
namespace Service::SPL {
@@ -19,6 +20,9 @@ public:
protected:
std::shared_ptr<Module> module;
+
+ private:
+ std::mt19937 rng;
};
};
diff --git a/src/core/hle/service/time/interface.cpp b/src/core/hle/service/time/interface.cpp
index 18a5d71d5..b3a196f65 100644
--- a/src/core/hle/service/time/interface.cpp
+++ b/src/core/hle/service/time/interface.cpp
@@ -21,9 +21,10 @@ Time::Time(std::shared_ptr<Module> time, const char* name)
{102, nullptr, "GetStandardUserSystemClockInitialYear"},
{200, nullptr, "IsStandardNetworkSystemClockAccuracySufficient"},
{300, nullptr, "CalculateMonotonicSystemClockBaseTimePoint"},
- {400, nullptr, "GetClockSnapshot"},
+ {400, &Time::GetClockSnapshot, "GetClockSnapshot"},
{401, nullptr, "GetClockSnapshotFromSystemClockContext"},
- {500, nullptr, "CalculateStandardUserSystemClockDifferenceByUser"},
+ {500, &Time::CalculateStandardUserSystemClockDifferenceByUser,
+ "CalculateStandardUserSystemClockDifferenceByUser"},
{501, nullptr, "CalculateSpanBetween"},
};
RegisterHandlers(functions);
diff --git a/src/core/hle/service/time/time.cpp b/src/core/hle/service/time/time.cpp
index 28fd8debc..e561a0c52 100644
--- a/src/core/hle/service/time/time.cpp
+++ b/src/core/hle/service/time/time.cpp
@@ -15,6 +15,44 @@
namespace Service::Time {
+static void PosixToCalendar(u64 posix_time, CalendarTime& calendar_time,
+ CalendarAdditionalInfo& additional_info,
+ [[maybe_unused]] const TimeZoneRule& /*rule*/) {
+ const std::time_t time(posix_time);
+ const std::tm* tm = std::localtime(&time);
+ if (tm == nullptr) {
+ calendar_time = {};
+ additional_info = {};
+ return;
+ }
+ calendar_time.year = tm->tm_year + 1900;
+ calendar_time.month = tm->tm_mon + 1;
+ calendar_time.day = tm->tm_mday;
+ calendar_time.hour = tm->tm_hour;
+ calendar_time.minute = tm->tm_min;
+ calendar_time.second = tm->tm_sec;
+
+ additional_info.day_of_week = tm->tm_wday;
+ additional_info.day_of_year = tm->tm_yday;
+ std::memcpy(additional_info.name.data(), "UTC", sizeof("UTC"));
+ additional_info.utc_offset = 0;
+}
+
+static u64 CalendarToPosix(const CalendarTime& calendar_time,
+ [[maybe_unused]] const TimeZoneRule& /*rule*/) {
+ std::tm time{};
+ time.tm_year = calendar_time.year - 1900;
+ time.tm_mon = calendar_time.month - 1;
+ time.tm_mday = calendar_time.day;
+
+ time.tm_hour = calendar_time.hour;
+ time.tm_min = calendar_time.minute;
+ time.tm_sec = calendar_time.second;
+
+ std::time_t epoch_time = std::mktime(&time);
+ return static_cast<u64>(epoch_time);
+}
+
class ISystemClock final : public ServiceFramework<ISystemClock> {
public:
ISystemClock() : ServiceFramework("ISystemClock") {
@@ -80,8 +118,8 @@ public:
{5, nullptr, "GetTimeZoneRuleVersion"},
{100, &ITimeZoneService::ToCalendarTime, "ToCalendarTime"},
{101, &ITimeZoneService::ToCalendarTimeWithMyRule, "ToCalendarTimeWithMyRule"},
- {201, nullptr, "ToPosixTime"},
- {202, nullptr, "ToPosixTimeWithMyRule"},
+ {201, &ITimeZoneService::ToPosixTime, "ToPosixTime"},
+ {202, &ITimeZoneService::ToPosixTimeWithMyRule, "ToPosixTimeWithMyRule"},
};
RegisterHandlers(functions);
}
@@ -151,24 +189,29 @@ private:
rb.PushRaw(additional_info);
}
- void PosixToCalendar(u64 posix_time, CalendarTime& calendar_time,
- CalendarAdditionalInfo& additional_info, const TimeZoneRule& /*rule*/) {
- std::time_t t(posix_time);
- std::tm* tm = std::localtime(&t);
- if (!tm) {
- return;
- }
- calendar_time.year = tm->tm_year + 1900;
- calendar_time.month = tm->tm_mon + 1;
- calendar_time.day = tm->tm_mday;
- calendar_time.hour = tm->tm_hour;
- calendar_time.minute = tm->tm_min;
- calendar_time.second = tm->tm_sec;
-
- additional_info.day_of_week = tm->tm_wday;
- additional_info.day_of_year = tm->tm_yday;
- std::memcpy(additional_info.name.data(), "UTC", sizeof("UTC"));
- additional_info.utc_offset = 0;
+ void ToPosixTime(Kernel::HLERequestContext& ctx) {
+ // TODO(ogniK): Figure out how to handle multiple times
+ LOG_WARNING(Service_Time, "(STUBBED) called");
+ IPC::RequestParser rp{ctx};
+ auto calendar_time = rp.PopRaw<CalendarTime>();
+ auto posix_time = CalendarToPosix(calendar_time, {});
+
+ IPC::ResponseBuilder rb{ctx, 3};
+ rb.Push(RESULT_SUCCESS);
+ rb.PushRaw<u32>(1); // Amount of times we're returning
+ ctx.WriteBuffer(&posix_time, sizeof(u64));
+ }
+
+ void ToPosixTimeWithMyRule(Kernel::HLERequestContext& ctx) {
+ LOG_WARNING(Service_Time, "(STUBBED) called");
+ IPC::RequestParser rp{ctx};
+ auto calendar_time = rp.PopRaw<CalendarTime>();
+ auto posix_time = CalendarToPosix(calendar_time, {});
+
+ IPC::ResponseBuilder rb{ctx, 3};
+ rb.Push(RESULT_SUCCESS);
+ rb.PushRaw<u32>(1); // Amount of times we're returning
+ ctx.WriteBuffer(&posix_time, sizeof(u64));
}
};
@@ -207,6 +250,70 @@ void Module::Interface::GetStandardLocalSystemClock(Kernel::HLERequestContext& c
LOG_DEBUG(Service_Time, "called");
}
+void Module::Interface::GetClockSnapshot(Kernel::HLERequestContext& ctx) {
+ LOG_DEBUG(Service_Time, "called");
+
+ IPC::RequestParser rp{ctx};
+ auto unknown_u8 = rp.PopRaw<u8>();
+
+ ClockSnapshot clock_snapshot{};
+
+ const s64 time_since_epoch{std::chrono::duration_cast<std::chrono::seconds>(
+ std::chrono::system_clock::now().time_since_epoch())
+ .count()};
+ CalendarTime calendar_time{};
+ const std::time_t time(time_since_epoch);
+ const std::tm* tm = std::localtime(&time);
+ if (tm == nullptr) {
+ IPC::ResponseBuilder rb{ctx, 2};
+ rb.Push(ResultCode(-1)); // TODO(ogniK): Find appropriate error code
+ return;
+ }
+ SteadyClockTimePoint steady_clock_time_point{CoreTiming::cyclesToMs(CoreTiming::GetTicks()) /
+ 1000};
+
+ LocationName location_name{"UTC"};
+ calendar_time.year = tm->tm_year + 1900;
+ calendar_time.month = tm->tm_mon + 1;
+ calendar_time.day = tm->tm_mday;
+ calendar_time.hour = tm->tm_hour;
+ calendar_time.minute = tm->tm_min;
+ calendar_time.second = tm->tm_sec;
+ clock_snapshot.system_posix_time = time_since_epoch;
+ clock_snapshot.network_posix_time = time_since_epoch;
+ clock_snapshot.system_calendar_time = calendar_time;
+ clock_snapshot.network_calendar_time = calendar_time;
+
+ CalendarAdditionalInfo additional_info{};
+ PosixToCalendar(time_since_epoch, calendar_time, additional_info, {});
+
+ clock_snapshot.system_calendar_info = additional_info;
+ clock_snapshot.network_calendar_info = additional_info;
+
+ clock_snapshot.steady_clock_timepoint = steady_clock_time_point;
+ clock_snapshot.location_name = location_name;
+ clock_snapshot.clock_auto_adjustment_enabled = 1;
+ clock_snapshot.ipc_u8 = unknown_u8;
+ IPC::ResponseBuilder rb{ctx, 2};
+ rb.Push(RESULT_SUCCESS);
+ ctx.WriteBuffer(&clock_snapshot, sizeof(ClockSnapshot));
+}
+
+void Module::Interface::CalculateStandardUserSystemClockDifferenceByUser(
+ Kernel::HLERequestContext& ctx) {
+ LOG_DEBUG(Service_Time, "called");
+
+ IPC::RequestParser rp{ctx};
+ const auto snapshot_a = rp.PopRaw<ClockSnapshot>();
+ const auto snapshot_b = rp.PopRaw<ClockSnapshot>();
+ const u64 difference =
+ snapshot_b.user_clock_context.offset - snapshot_a.user_clock_context.offset;
+
+ IPC::ResponseBuilder rb{ctx, 4};
+ rb.Push(RESULT_SUCCESS);
+ rb.PushRaw<u64>(difference);
+}
+
Module::Interface::Interface(std::shared_ptr<Module> time, const char* name)
: ServiceFramework(name), time(std::move(time)) {}
diff --git a/src/core/hle/service/time/time.h b/src/core/hle/service/time/time.h
index 5659ecad3..ea43fbea7 100644
--- a/src/core/hle/service/time/time.h
+++ b/src/core/hle/service/time/time.h
@@ -5,6 +5,7 @@
#pragma once
#include <array>
+#include "common/common_funcs.h"
#include "core/hle/service/service.h"
namespace Service::Time {
@@ -53,6 +54,23 @@ struct SystemClockContext {
static_assert(sizeof(SystemClockContext) == 0x20,
"SystemClockContext structure has incorrect size");
+struct ClockSnapshot {
+ SystemClockContext user_clock_context;
+ SystemClockContext network_clock_context;
+ s64_le system_posix_time;
+ s64_le network_posix_time;
+ CalendarTime system_calendar_time;
+ CalendarTime network_calendar_time;
+ CalendarAdditionalInfo system_calendar_info;
+ CalendarAdditionalInfo network_calendar_info;
+ SteadyClockTimePoint steady_clock_timepoint;
+ LocationName location_name;
+ u8 clock_auto_adjustment_enabled;
+ u8 ipc_u8;
+ INSERT_PADDING_BYTES(2);
+};
+static_assert(sizeof(ClockSnapshot) == 0xd0, "ClockSnapshot is an invalid size");
+
class Module final {
public:
class Interface : public ServiceFramework<Interface> {
@@ -65,6 +83,8 @@ public:
void GetStandardSteadyClock(Kernel::HLERequestContext& ctx);
void GetTimeZoneService(Kernel::HLERequestContext& ctx);
void GetStandardLocalSystemClock(Kernel::HLERequestContext& ctx);
+ void GetClockSnapshot(Kernel::HLERequestContext& ctx);
+ void CalculateStandardUserSystemClockDifferenceByUser(Kernel::HLERequestContext& ctx);
protected:
std::shared_ptr<Module> time;
diff --git a/src/core/hle/service/vi/vi.cpp b/src/core/hle/service/vi/vi.cpp
index d764b2406..a72416084 100644
--- a/src/core/hle/service/vi/vi.cpp
+++ b/src/core/hle/service/vi/vi.cpp
@@ -237,6 +237,22 @@ private:
Data data{};
};
+/// Represents a parcel containing one int '0' as its data
+/// Used by DetachBuffer and Disconnect
+class IGBPEmptyResponseParcel : public Parcel {
+protected:
+ void SerializeData() override {
+ Write(data);
+ }
+
+private:
+ struct Data {
+ u32_le unk_0;
+ };
+
+ Data data{};
+};
+
class IGBPSetPreallocatedBufferRequestParcel : public Parcel {
public:
explicit IGBPSetPreallocatedBufferRequestParcel(std::vector<u8> buffer)
@@ -494,7 +510,11 @@ private:
if (transaction == TransactionId::Connect) {
IGBPConnectRequestParcel request{ctx.ReadBuffer()};
- IGBPConnectResponseParcel response{1280, 720};
+ IGBPConnectResponseParcel response{
+ static_cast<u32>(static_cast<u32>(DisplayResolution::UndockedWidth) *
+ Settings::values.resolution_factor),
+ static_cast<u32>(static_cast<u32>(DisplayResolution::UndockedHeight) *
+ Settings::values.resolution_factor)};
ctx.WriteBuffer(response.Serialize());
} else if (transaction == TransactionId::SetPreallocatedBuffer) {
IGBPSetPreallocatedBufferRequestParcel request{ctx.ReadBuffer()};
@@ -554,6 +574,12 @@ private:
ctx.WriteBuffer(response.Serialize());
} else if (transaction == TransactionId::CancelBuffer) {
LOG_CRITICAL(Service_VI, "(STUBBED) called, transaction=CancelBuffer");
+ } else if (transaction == TransactionId::Disconnect ||
+ transaction == TransactionId::DetachBuffer) {
+ const auto buffer = ctx.ReadBuffer();
+
+ IGBPEmptyResponseParcel response{};
+ ctx.WriteBuffer(response.Serialize());
} else {
ASSERT_MSG(false, "Unimplemented");
}
@@ -670,11 +696,15 @@ private:
rb.Push(RESULT_SUCCESS);
if (Settings::values.use_docked_mode) {
- rb.Push(static_cast<u32>(Service::VI::DisplayResolution::DockedWidth));
- rb.Push(static_cast<u32>(Service::VI::DisplayResolution::DockedHeight));
+ rb.Push(static_cast<u32>(Service::VI::DisplayResolution::DockedWidth) *
+ static_cast<u32>(Settings::values.resolution_factor));
+ rb.Push(static_cast<u32>(Service::VI::DisplayResolution::DockedHeight) *
+ static_cast<u32>(Settings::values.resolution_factor));
} else {
- rb.Push(static_cast<u32>(Service::VI::DisplayResolution::UndockedWidth));
- rb.Push(static_cast<u32>(Service::VI::DisplayResolution::UndockedHeight));
+ rb.Push(static_cast<u32>(Service::VI::DisplayResolution::UndockedWidth) *
+ static_cast<u32>(Settings::values.resolution_factor));
+ rb.Push(static_cast<u32>(Service::VI::DisplayResolution::UndockedHeight) *
+ static_cast<u32>(Settings::values.resolution_factor));
}
rb.PushRaw<float>(60.0f);
@@ -879,11 +909,15 @@ private:
rb.Push(RESULT_SUCCESS);
if (Settings::values.use_docked_mode) {
- rb.Push(static_cast<u64>(DisplayResolution::DockedWidth));
- rb.Push(static_cast<u64>(DisplayResolution::DockedHeight));
+ rb.Push(static_cast<u64>(DisplayResolution::DockedWidth) *
+ static_cast<u32>(Settings::values.resolution_factor));
+ rb.Push(static_cast<u64>(DisplayResolution::DockedHeight) *
+ static_cast<u32>(Settings::values.resolution_factor));
} else {
- rb.Push(static_cast<u64>(DisplayResolution::UndockedWidth));
- rb.Push(static_cast<u64>(DisplayResolution::UndockedHeight));
+ rb.Push(static_cast<u64>(DisplayResolution::UndockedWidth) *
+ static_cast<u32>(Settings::values.resolution_factor));
+ rb.Push(static_cast<u64>(DisplayResolution::UndockedHeight) *
+ static_cast<u32>(Settings::values.resolution_factor));
}
}
@@ -900,6 +934,8 @@ private:
void ListDisplays(Kernel::HLERequestContext& ctx) {
IPC::RequestParser rp{ctx};
DisplayInfo display_info;
+ display_info.width *= static_cast<u64>(Settings::values.resolution_factor);
+ display_info.height *= static_cast<u64>(Settings::values.resolution_factor);
ctx.WriteBuffer(&display_info, sizeof(DisplayInfo));
IPC::ResponseBuilder rb{ctx, 4};
rb.Push(RESULT_SUCCESS);
diff --git a/src/core/loader/nro.cpp b/src/core/loader/nro.cpp
index bc8e402a8..fbbd6b0de 100644
--- a/src/core/loader/nro.cpp
+++ b/src/core/loader/nro.cpp
@@ -12,10 +12,12 @@
#include "common/swap.h"
#include "core/core.h"
#include "core/file_sys/control_metadata.h"
+#include "core/file_sys/romfs_factory.h"
#include "core/file_sys/vfs_offset.h"
#include "core/gdbstub/gdbstub.h"
#include "core/hle/kernel/process.h"
#include "core/hle/kernel/vm_manager.h"
+#include "core/hle/service/filesystem/filesystem.h"
#include "core/loader/nro.h"
#include "core/loader/nso.h"
#include "core/memory.h"
@@ -168,17 +170,20 @@ static constexpr u32 PageAlignSize(u32 size) {
arg_data.size());
}
- // Read MOD header
- ModHeader mod_header{};
// Default .bss to NRO header bss size if MOD0 section doesn't exist
u32 bss_size{PageAlignSize(nro_header.bss_size)};
+
+ // Read MOD header
+ ModHeader mod_header{};
std::memcpy(&mod_header, program_image.data() + nro_header.module_header_offset,
sizeof(ModHeader));
+
const bool has_mod_header{mod_header.magic == Common::MakeMagic('M', 'O', 'D', '0')};
if (has_mod_header) {
// Resize program image to include .bss section and page align each section
bss_size = PageAlignSize(mod_header.bss_end_offset - mod_header.bss_start_offset);
}
+
codeset.DataSegment().size += bss_size;
program_image.resize(static_cast<u32>(program_image.size()) + bss_size);
@@ -208,6 +213,9 @@ ResultStatus AppLoader_NRO::Load(Kernel::Process& process) {
return ResultStatus::ErrorLoadingNRO;
}
+ if (romfs != nullptr)
+ Service::FileSystem::RegisterRomFS(std::make_unique<FileSys::RomFSFactory>(*this));
+
process.Run(base_address, Kernel::THREADPRIO_DEFAULT, Memory::DEFAULT_STACK_SIZE);
is_loaded = true;
diff --git a/src/core/loader/nso.cpp b/src/core/loader/nso.cpp
index 68efca5c0..aaf006309 100644
--- a/src/core/loader/nso.cpp
+++ b/src/core/loader/nso.cpp
@@ -154,7 +154,7 @@ std::optional<VAddr> AppLoader_NSO::LoadModule(const FileSys::VfsFile& file, VAd
program_image.resize(image_size);
// Apply patches if necessary
- if (pm && pm->HasNSOPatch(nso_header.build_id)) {
+ if (pm && (pm->HasNSOPatch(nso_header.build_id) || Settings::values.dump_nso)) {
std::vector<u8> pi_header(program_image.size() + 0x100);
std::memcpy(pi_header.data(), &nso_header, sizeof(NsoHeader));
std::memcpy(pi_header.data() + 0x100, program_image.data(), program_image.size());
diff --git a/src/core/settings.cpp b/src/core/settings.cpp
index 0da159559..26fcd3405 100644
--- a/src/core/settings.cpp
+++ b/src/core/settings.cpp
@@ -10,6 +10,56 @@
namespace Settings {
+namespace NativeButton {
+const std::array<const char*, NumButtons> mapping = {{
+ "button_a",
+ "button_b",
+ "button_x",
+ "button_y",
+ "button_lstick",
+ "button_rstick",
+ "button_l",
+ "button_r",
+ "button_zl",
+ "button_zr",
+ "button_plus",
+ "button_minus",
+ "button_dleft",
+ "button_dup",
+ "button_dright",
+ "button_ddown",
+ "button_lstick_left",
+ "button_lstick_up",
+ "button_lstick_right",
+ "button_lstick_down",
+ "button_rstick_left",
+ "button_rstick_up",
+ "button_rstick_right",
+ "button_rstick_down",
+ "button_sl",
+ "button_sr",
+ "button_home",
+ "button_screenshot",
+}};
+}
+
+namespace NativeAnalog {
+const std::array<const char*, NumAnalogs> mapping = {{
+ "lstick",
+ "rstick",
+}};
+}
+
+namespace NativeMouseButton {
+const std::array<const char*, NumMouseButtons> mapping = {{
+ "left",
+ "right",
+ "middle",
+ "forward",
+ "back",
+}};
+}
+
Values values = {};
void Apply() {
diff --git a/src/core/settings.h b/src/core/settings.h
index b5aeff29b..a0c5fd447 100644
--- a/src/core/settings.h
+++ b/src/core/settings.h
@@ -6,6 +6,7 @@
#include <array>
#include <atomic>
+#include <optional>
#include <string>
#include "common/common_types.h"
@@ -59,36 +60,7 @@ constexpr int BUTTON_NS_END = NumButtons;
constexpr int NUM_BUTTONS_HID = BUTTON_HID_END - BUTTON_HID_BEGIN;
constexpr int NUM_BUTTONS_NS = BUTTON_NS_END - BUTTON_NS_BEGIN;
-static const std::array<const char*, NumButtons> mapping = {{
- "button_a",
- "button_b",
- "button_x",
- "button_y",
- "button_lstick",
- "button_rstick",
- "button_l",
- "button_r",
- "button_zl",
- "button_zr",
- "button_plus",
- "button_minus",
- "button_dleft",
- "button_dup",
- "button_dright",
- "button_ddown",
- "button_lstick_left",
- "button_lstick_up",
- "button_lstick_right",
- "button_lstick_down",
- "button_rstick_left",
- "button_rstick_up",
- "button_rstick_right",
- "button_rstick_down",
- "button_sl",
- "button_sr",
- "button_home",
- "button_screenshot",
-}};
+extern const std::array<const char*, NumButtons> mapping;
} // namespace NativeButton
@@ -104,24 +76,298 @@ constexpr int STICK_HID_BEGIN = LStick;
constexpr int STICK_HID_END = NumAnalogs;
constexpr int NUM_STICKS_HID = NumAnalogs;
-static const std::array<const char*, NumAnalogs> mapping = {{
- "lstick",
- "rstick",
-}};
+extern const std::array<const char*, NumAnalogs> mapping;
} // namespace NativeAnalog
+namespace NativeMouseButton {
+enum Values {
+ Left,
+ Right,
+ Middle,
+ Forward,
+ Back,
+
+ NumMouseButtons,
+};
+
+constexpr int MOUSE_HID_BEGIN = Left;
+constexpr int MOUSE_HID_END = NumMouseButtons;
+constexpr int NUM_MOUSE_HID = NumMouseButtons;
+
+extern const std::array<const char*, NumMouseButtons> mapping;
+} // namespace NativeMouseButton
+
+namespace NativeKeyboard {
+enum Keys {
+ None,
+ Error,
+
+ A = 4,
+ B,
+ C,
+ D,
+ E,
+ F,
+ G,
+ H,
+ I,
+ J,
+ K,
+ L,
+ M,
+ N,
+ O,
+ P,
+ Q,
+ R,
+ S,
+ T,
+ U,
+ V,
+ W,
+ X,
+ Y,
+ Z,
+ N1,
+ N2,
+ N3,
+ N4,
+ N5,
+ N6,
+ N7,
+ N8,
+ N9,
+ N0,
+ Enter,
+ Escape,
+ Backspace,
+ Tab,
+ Space,
+ Minus,
+ Equal,
+ LeftBrace,
+ RightBrace,
+ Backslash,
+ Tilde,
+ Semicolon,
+ Apostrophe,
+ Grave,
+ Comma,
+ Dot,
+ Slash,
+ CapsLockKey,
+
+ F1,
+ F2,
+ F3,
+ F4,
+ F5,
+ F6,
+ F7,
+ F8,
+ F9,
+ F10,
+ F11,
+ F12,
+
+ SystemRequest,
+ ScrollLockKey,
+ Pause,
+ Insert,
+ Home,
+ PageUp,
+ Delete,
+ End,
+ PageDown,
+ Right,
+ Left,
+ Down,
+ Up,
+
+ NumLockKey,
+ KPSlash,
+ KPAsterisk,
+ KPMinus,
+ KPPlus,
+ KPEnter,
+ KP1,
+ KP2,
+ KP3,
+ KP4,
+ KP5,
+ KP6,
+ KP7,
+ KP8,
+ KP9,
+ KP0,
+ KPDot,
+
+ Key102,
+ Compose,
+ Power,
+ KPEqual,
+
+ F13,
+ F14,
+ F15,
+ F16,
+ F17,
+ F18,
+ F19,
+ F20,
+ F21,
+ F22,
+ F23,
+ F24,
+
+ Open,
+ Help,
+ Properties,
+ Front,
+ Stop,
+ Repeat,
+ Undo,
+ Cut,
+ Copy,
+ Paste,
+ Find,
+ Mute,
+ VolumeUp,
+ VolumeDown,
+ CapsLockActive,
+ NumLockActive,
+ ScrollLockActive,
+ KPComma,
+
+ KPLeftParenthesis,
+ KPRightParenthesis,
+
+ LeftControlKey = 0xE0,
+ LeftShiftKey,
+ LeftAltKey,
+ LeftMetaKey,
+ RightControlKey,
+ RightShiftKey,
+ RightAltKey,
+ RightMetaKey,
+
+ MediaPlayPause,
+ MediaStopCD,
+ MediaPrevious,
+ MediaNext,
+ MediaEject,
+ MediaVolumeUp,
+ MediaVolumeDown,
+ MediaMute,
+ MediaWebsite,
+ MediaBack,
+ MediaForward,
+ MediaStop,
+ MediaFind,
+ MediaScrollUp,
+ MediaScrollDown,
+ MediaEdit,
+ MediaSleep,
+ MediaCoffee,
+ MediaRefresh,
+ MediaCalculator,
+
+ NumKeyboardKeys,
+};
+
+static_assert(NumKeyboardKeys == 0xFC, "Incorrect number of keyboard keys.");
+
+enum Modifiers {
+ LeftControl,
+ LeftShift,
+ LeftAlt,
+ LeftMeta,
+ RightControl,
+ RightShift,
+ RightAlt,
+ RightMeta,
+ CapsLock,
+ ScrollLock,
+ NumLock,
+
+ NumKeyboardMods,
+};
+
+constexpr int KEYBOARD_KEYS_HID_BEGIN = None;
+constexpr int KEYBOARD_KEYS_HID_END = NumKeyboardKeys;
+constexpr int NUM_KEYBOARD_KEYS_HID = NumKeyboardKeys;
+
+constexpr int KEYBOARD_MODS_HID_BEGIN = LeftControl;
+constexpr int KEYBOARD_MODS_HID_END = NumKeyboardMods;
+constexpr int NUM_KEYBOARD_MODS_HID = NumKeyboardMods;
+
+} // namespace NativeKeyboard
+
+using ButtonsRaw = std::array<std::string, NativeButton::NumButtons>;
+using AnalogsRaw = std::array<std::string, NativeAnalog::NumAnalogs>;
+using MouseButtonsRaw = std::array<std::string, NativeMouseButton::NumMouseButtons>;
+using KeyboardKeysRaw = std::array<std::string, NativeKeyboard::NumKeyboardKeys>;
+using KeyboardModsRaw = std::array<std::string, NativeKeyboard::NumKeyboardMods>;
+
+constexpr u32 JOYCON_BODY_NEON_RED = 0xFF3C28;
+constexpr u32 JOYCON_BUTTONS_NEON_RED = 0x1E0A0A;
+constexpr u32 JOYCON_BODY_NEON_BLUE = 0x0AB9E6;
+constexpr u32 JOYCON_BUTTONS_NEON_BLUE = 0x001E1E;
+
+enum class ControllerType {
+ ProController,
+ DualJoycon,
+ RightJoycon,
+ LeftJoycon,
+};
+
+struct PlayerInput {
+ bool connected;
+ ControllerType type;
+ ButtonsRaw buttons;
+ AnalogsRaw analogs;
+
+ u32 body_color_right;
+ u32 button_color_right;
+ u32 body_color_left;
+ u32 button_color_left;
+};
+
+struct TouchscreenInput {
+ bool enabled;
+ std::string device;
+
+ u32 finger;
+ u32 diameter_x;
+ u32 diameter_y;
+ u32 rotation_angle;
+};
+
struct Values {
// System
bool use_docked_mode;
bool enable_nfc;
- int current_user;
- int language_index;
+ std::optional<u32> rng_seed;
+ s32 current_user;
+ s32 language_index;
// Controls
- std::array<std::string, NativeButton::NumButtons> buttons;
- std::array<std::string, NativeAnalog::NumAnalogs> analogs;
+ std::array<PlayerInput, 10> players;
+
+ bool mouse_enabled;
+ std::string mouse_device;
+ MouseButtonsRaw mouse_buttons;
+
+ bool keyboard_enabled;
+ KeyboardKeysRaw keyboard_keys;
+ KeyboardModsRaw keyboard_mods;
+
+ bool debug_pad_enabled;
+ ButtonsRaw debug_pad_buttons;
+ AnalogsRaw debug_pad_analogs;
+
std::string motion_device;
- std::string touch_device;
+ TouchscreenInput touchscreen;
std::atomic_bool is_device_reload_pending{true};
// Core
@@ -157,6 +403,8 @@ struct Values {
bool use_gdbstub;
u16 gdbstub_port;
std::string program_args;
+ bool dump_exefs;
+ bool dump_nso;
// WebService
bool enable_telemetry;
diff --git a/src/video_core/CMakeLists.txt b/src/video_core/CMakeLists.txt
index ddb1a1d69..a780215c1 100644
--- a/src/video_core/CMakeLists.txt
+++ b/src/video_core/CMakeLists.txt
@@ -21,6 +21,7 @@ add_library(video_core STATIC
macro_interpreter.h
memory_manager.cpp
memory_manager.h
+ rasterizer_cache.cpp
rasterizer_cache.h
rasterizer_interface.h
renderer_base.cpp
@@ -33,6 +34,7 @@ add_library(video_core STATIC
renderer_opengl/gl_rasterizer.h
renderer_opengl/gl_rasterizer_cache.cpp
renderer_opengl/gl_rasterizer_cache.h
+ renderer_opengl/gl_resource_manager.cpp
renderer_opengl/gl_resource_manager.h
renderer_opengl/gl_shader_cache.cpp
renderer_opengl/gl_shader_cache.h
diff --git a/src/video_core/engines/maxwell_3d.cpp b/src/video_core/engines/maxwell_3d.cpp
index d79c50919..2bc534be3 100644
--- a/src/video_core/engines/maxwell_3d.cpp
+++ b/src/video_core/engines/maxwell_3d.cpp
@@ -34,8 +34,49 @@ void Maxwell3D::InitializeRegisterDefaults() {
// Depth range near/far is not always set, but is expected to be the default 0.0f, 1.0f. This is
// needed for ARMS.
for (std::size_t viewport{}; viewport < Regs::NumViewports; ++viewport) {
- regs.viewport[viewport].depth_range_near = 0.0f;
- regs.viewport[viewport].depth_range_far = 1.0f;
+ regs.viewports[viewport].depth_range_near = 0.0f;
+ regs.viewports[viewport].depth_range_far = 1.0f;
+ }
+ // Doom and Bomberman seems to use the uninitialized registers and just enable blend
+ // so initialize blend registers with sane values
+ regs.blend.equation_rgb = Regs::Blend::Equation::Add;
+ regs.blend.factor_source_rgb = Regs::Blend::Factor::One;
+ regs.blend.factor_dest_rgb = Regs::Blend::Factor::Zero;
+ regs.blend.equation_a = Regs::Blend::Equation::Add;
+ regs.blend.factor_source_a = Regs::Blend::Factor::One;
+ regs.blend.factor_dest_a = Regs::Blend::Factor::Zero;
+ for (std::size_t blend_index = 0; blend_index < Regs::NumRenderTargets; blend_index++) {
+ regs.independent_blend[blend_index].equation_rgb = Regs::Blend::Equation::Add;
+ regs.independent_blend[blend_index].factor_source_rgb = Regs::Blend::Factor::One;
+ regs.independent_blend[blend_index].factor_dest_rgb = Regs::Blend::Factor::Zero;
+ regs.independent_blend[blend_index].equation_a = Regs::Blend::Equation::Add;
+ regs.independent_blend[blend_index].factor_source_a = Regs::Blend::Factor::One;
+ regs.independent_blend[blend_index].factor_dest_a = Regs::Blend::Factor::Zero;
+ }
+ regs.stencil_front_op_fail = Regs::StencilOp::Keep;
+ regs.stencil_front_op_zfail = Regs::StencilOp::Keep;
+ regs.stencil_front_op_zpass = Regs::StencilOp::Keep;
+ regs.stencil_front_func_func = Regs::ComparisonOp::Always;
+ regs.stencil_front_func_mask = 0xFFFFFFFF;
+ regs.stencil_front_mask = 0xFFFFFFFF;
+ regs.stencil_two_side_enable = 1;
+ regs.stencil_back_op_fail = Regs::StencilOp::Keep;
+ regs.stencil_back_op_zfail = Regs::StencilOp::Keep;
+ regs.stencil_back_op_zpass = Regs::StencilOp::Keep;
+ regs.stencil_back_func_func = Regs::ComparisonOp::Always;
+ regs.stencil_back_func_mask = 0xFFFFFFFF;
+ regs.stencil_back_mask = 0xFFFFFFFF;
+ // TODO(Rodrigo): Most games do not set a point size. I think this is a case of a
+ // register carrying a default value. Assume it's OpenGL's default (1).
+ regs.point_size = 1.0f;
+
+ // TODO(bunnei): Some games do not initialize the color masks (e.g. Sonic Mania). Assuming a
+ // default of enabled fixes rendering here.
+ for (std::size_t color_mask = 0; color_mask < Regs::NumRenderTargets; color_mask++) {
+ regs.color_mask[color_mask].R.Assign(1);
+ regs.color_mask[color_mask].G.Assign(1);
+ regs.color_mask[color_mask].B.Assign(1);
+ regs.color_mask[color_mask].A.Assign(1);
}
}
@@ -92,7 +133,13 @@ void Maxwell3D::WriteReg(u32 method, u32 value, u32 remaining_params) {
debug_context->OnEvent(Tegra::DebugContext::Event::MaxwellCommandLoaded, nullptr);
}
- regs.reg_array[method] = value;
+ if (regs.reg_array[method] != value) {
+ regs.reg_array[method] = value;
+ if (method >= MAXWELL3D_REG_INDEX(vertex_attrib_format) &&
+ method < MAXWELL3D_REG_INDEX(vertex_attrib_format) + regs.vertex_attrib_format.size()) {
+ dirty_flags.vertex_attrib_format = true;
+ }
+ }
switch (method) {
case MAXWELL3D_REG_INDEX(macros.data): {
diff --git a/src/video_core/engines/maxwell_3d.h b/src/video_core/engines/maxwell_3d.h
index 50873813e..4f137e693 100644
--- a/src/video_core/engines/maxwell_3d.h
+++ b/src/video_core/engines/maxwell_3d.h
@@ -345,6 +345,14 @@ public:
Invert = 6,
IncrWrap = 7,
DecrWrap = 8,
+ KeepOGL = 0x1E00,
+ ZeroOGL = 0,
+ ReplaceOGL = 0x1E01,
+ IncrOGL = 0x1E02,
+ DecrOGL = 0x1E03,
+ InvertOGL = 0x150A,
+ IncrWrapOGL = 0x8507,
+ DecrWrapOGL = 0x8508,
};
enum class MemoryLayout : u32 {
@@ -381,6 +389,13 @@ public:
ReverseSubtract = 3,
Min = 4,
Max = 5,
+
+ // These values are used by Nouveau and some games.
+ AddGL = 0x8006,
+ SubtractGL = 0x8007,
+ ReverseSubtractGL = 0x8008,
+ MinGL = 0x800a,
+ MaxGL = 0x800b
};
enum class Factor : u32 {
@@ -462,6 +477,77 @@ public:
}
};
+ struct ColorMask {
+ union {
+ u32 raw;
+ BitField<0, 4, u32> R;
+ BitField<4, 4, u32> G;
+ BitField<8, 4, u32> B;
+ BitField<12, 4, u32> A;
+ };
+ };
+
+ struct ViewportTransform {
+ f32 scale_x;
+ f32 scale_y;
+ f32 scale_z;
+ f32 translate_x;
+ f32 translate_y;
+ f32 translate_z;
+ INSERT_PADDING_WORDS(2);
+
+ MathUtil::Rectangle<s32> GetRect() const {
+ return {
+ GetX(), // left
+ GetY() + GetHeight(), // top
+ GetX() + GetWidth(), // right
+ GetY() // bottom
+ };
+ };
+
+ s32 GetX() const {
+ return static_cast<s32>(std::max(0.0f, translate_x - std::fabs(scale_x)));
+ }
+
+ s32 GetY() const {
+ return static_cast<s32>(std::max(0.0f, translate_y - std::fabs(scale_y)));
+ }
+
+ s32 GetWidth() const {
+ return static_cast<s32>(translate_x + std::fabs(scale_x)) - GetX();
+ }
+
+ s32 GetHeight() const {
+ return static_cast<s32>(translate_y + std::fabs(scale_y)) - GetY();
+ }
+ };
+
+ struct ScissorTest {
+ u32 enable;
+ union {
+ BitField<0, 16, u32> min_x;
+ BitField<16, 16, u32> max_x;
+ };
+ union {
+ BitField<0, 16, u32> min_y;
+ BitField<16, 16, u32> max_y;
+ };
+ u32 fill;
+ };
+
+ struct ViewPort {
+ union {
+ BitField<0, 16, u32> x;
+ BitField<16, 16, u32> width;
+ };
+ union {
+ BitField<0, 16, u32> y;
+ BitField<16, 16, u32> height;
+ };
+ float depth_range_near;
+ float depth_range_far;
+ };
+
bool IsShaderConfigEnabled(std::size_t index) const {
// The VertexB is always enabled.
if (index == static_cast<std::size_t>(Regs::ShaderProgram::VertexB)) {
@@ -487,55 +573,11 @@ public:
INSERT_PADDING_WORDS(0x2E);
- RenderTargetConfig rt[NumRenderTargets];
+ std::array<RenderTargetConfig, NumRenderTargets> rt;
- struct {
- f32 scale_x;
- f32 scale_y;
- f32 scale_z;
- f32 translate_x;
- f32 translate_y;
- f32 translate_z;
- INSERT_PADDING_WORDS(2);
-
- MathUtil::Rectangle<s32> GetRect() const {
- return {
- GetX(), // left
- GetY() + GetHeight(), // top
- GetX() + GetWidth(), // right
- GetY() // bottom
- };
- };
+ std::array<ViewportTransform, NumViewports> viewport_transform;
- s32 GetX() const {
- return static_cast<s32>(std::max(0.0f, translate_x - std::fabs(scale_x)));
- }
-
- s32 GetY() const {
- return static_cast<s32>(std::max(0.0f, translate_y - std::fabs(scale_y)));
- }
-
- s32 GetWidth() const {
- return static_cast<s32>(translate_x + std::fabs(scale_x)) - GetX();
- }
-
- s32 GetHeight() const {
- return static_cast<s32>(translate_y + std::fabs(scale_y)) - GetY();
- }
- } viewport_transform[NumViewports];
-
- struct {
- union {
- BitField<0, 16, u32> x;
- BitField<16, 16, u32> width;
- };
- union {
- BitField<0, 16, u32> y;
- BitField<16, 16, u32> height;
- };
- float depth_range_near;
- float depth_range_far;
- } viewport[NumViewports];
+ std::array<ViewPort, NumViewports> viewports;
INSERT_PADDING_WORDS(0x1D);
@@ -553,25 +595,19 @@ public:
INSERT_PADDING_WORDS(0x17);
- struct {
- u32 enable;
- union {
- BitField<0, 16, u32> min_x;
- BitField<16, 16, u32> max_x;
- };
- union {
- BitField<0, 16, u32> min_y;
- BitField<16, 16, u32> max_y;
- };
- } scissor_test;
+ std::array<ScissorTest, NumViewports> scissor_test;
- INSERT_PADDING_WORDS(0x52);
+ INSERT_PADDING_WORDS(0x15);
s32 stencil_back_func_ref;
u32 stencil_back_mask;
u32 stencil_back_func_mask;
- INSERT_PADDING_WORDS(0x13);
+ INSERT_PADDING_WORDS(0xC);
+
+ u32 color_mask_common;
+
+ INSERT_PADDING_WORDS(0x6);
u32 rt_separate_frag_data;
@@ -595,7 +631,16 @@ public:
}
} zeta;
- INSERT_PADDING_WORDS(0x5B);
+ INSERT_PADDING_WORDS(0x41);
+
+ union {
+ BitField<0, 4, u32> stencil;
+ BitField<4, 4, u32> unknown;
+ BitField<8, 4, u32> scissor;
+ BitField<12, 4, u32> viewport;
+ } clear_flags;
+
+ INSERT_PADDING_WORDS(0x19);
std::array<VertexAttribute, NumVertexAttributes> vertex_attrib_format;
@@ -646,8 +691,14 @@ public:
ComparisonOp depth_test_func;
float alpha_test_ref;
ComparisonOp alpha_test_func;
-
- INSERT_PADDING_WORDS(0x9);
+ u32 draw_tfb_stride;
+ struct {
+ float r;
+ float g;
+ float b;
+ float a;
+ } blend_color;
+ INSERT_PADDING_WORDS(0x4);
struct {
u32 separate_alpha;
@@ -672,7 +723,9 @@ public:
u32 stencil_front_func_mask;
u32 stencil_front_mask;
- INSERT_PADDING_WORDS(0x3);
+ INSERT_PADDING_WORDS(0x2);
+
+ u32 frag_color_clamp;
union {
BitField<4, 1, u32> triangle_rast_flip;
@@ -690,7 +743,12 @@ public:
u32 zeta_enable;
- INSERT_PADDING_WORDS(0x8);
+ union {
+ BitField<0, 1, u32> alpha_to_coverage;
+ BitField<4, 1, u32> alpha_to_one;
+ } multisample_control;
+
+ INSERT_PADDING_WORDS(0x7);
struct {
u32 tsc_address_high;
@@ -841,8 +899,9 @@ public:
BitField<6, 4, u32> RT;
BitField<10, 11, u32> layer;
} clear_buffers;
-
- INSERT_PADDING_WORDS(0x4B);
+ INSERT_PADDING_WORDS(0xB);
+ std::array<ColorMask, NumRenderTargets> color_mask;
+ INSERT_PADDING_WORDS(0x38);
struct {
u32 query_address_high;
@@ -983,6 +1042,12 @@ public:
State state{};
MemoryManager& memory_manager;
+ struct DirtyFlags {
+ bool vertex_attrib_format = true;
+ };
+
+ DirtyFlags dirty_flags;
+
/// Reads a register value located at the input method address
u32 GetRegisterValue(u32 method) const;
@@ -1065,8 +1130,8 @@ private:
ASSERT_REG_POSITION(macros, 0x45);
ASSERT_REG_POSITION(tfb_enabled, 0x1D1);
ASSERT_REG_POSITION(rt, 0x200);
-ASSERT_REG_POSITION(viewport_transform[0], 0x280);
-ASSERT_REG_POSITION(viewport, 0x300);
+ASSERT_REG_POSITION(viewport_transform, 0x280);
+ASSERT_REG_POSITION(viewports, 0x300);
ASSERT_REG_POSITION(vertex_buffer, 0x35D);
ASSERT_REG_POSITION(clear_color[0], 0x360);
ASSERT_REG_POSITION(clear_depth, 0x364);
@@ -1075,8 +1140,10 @@ ASSERT_REG_POSITION(scissor_test, 0x380);
ASSERT_REG_POSITION(stencil_back_func_ref, 0x3D5);
ASSERT_REG_POSITION(stencil_back_mask, 0x3D6);
ASSERT_REG_POSITION(stencil_back_func_mask, 0x3D7);
+ASSERT_REG_POSITION(color_mask_common, 0x3E4);
ASSERT_REG_POSITION(rt_separate_frag_data, 0x3EB);
ASSERT_REG_POSITION(zeta, 0x3F8);
+ASSERT_REG_POSITION(clear_flags, 0x43E);
ASSERT_REG_POSITION(vertex_attrib_format, 0x458);
ASSERT_REG_POSITION(rt_control, 0x487);
ASSERT_REG_POSITION(zeta_width, 0x48a);
@@ -1087,6 +1154,10 @@ ASSERT_REG_POSITION(depth_write_enabled, 0x4BA);
ASSERT_REG_POSITION(alpha_test_enabled, 0x4BB);
ASSERT_REG_POSITION(d3d_cull_mode, 0x4C2);
ASSERT_REG_POSITION(depth_test_func, 0x4C3);
+ASSERT_REG_POSITION(alpha_test_ref, 0x4C4);
+ASSERT_REG_POSITION(alpha_test_func, 0x4C5);
+ASSERT_REG_POSITION(draw_tfb_stride, 0x4C6);
+ASSERT_REG_POSITION(blend_color, 0x4C7);
ASSERT_REG_POSITION(blend, 0x4CF);
ASSERT_REG_POSITION(stencil_enable, 0x4E0);
ASSERT_REG_POSITION(stencil_front_op_fail, 0x4E1);
@@ -1096,10 +1167,12 @@ ASSERT_REG_POSITION(stencil_front_func_func, 0x4E4);
ASSERT_REG_POSITION(stencil_front_func_ref, 0x4E5);
ASSERT_REG_POSITION(stencil_front_func_mask, 0x4E6);
ASSERT_REG_POSITION(stencil_front_mask, 0x4E7);
+ASSERT_REG_POSITION(frag_color_clamp, 0x4EA);
ASSERT_REG_POSITION(screen_y_control, 0x4EB);
ASSERT_REG_POSITION(vb_element_base, 0x50D);
ASSERT_REG_POSITION(point_size, 0x546);
ASSERT_REG_POSITION(zeta_enable, 0x54E);
+ASSERT_REG_POSITION(multisample_control, 0x54F);
ASSERT_REG_POSITION(tsc, 0x557);
ASSERT_REG_POSITION(tic, 0x55D);
ASSERT_REG_POSITION(stencil_two_side_enable, 0x565);
@@ -1117,6 +1190,7 @@ ASSERT_REG_POSITION(instanced_arrays, 0x620);
ASSERT_REG_POSITION(cull, 0x646);
ASSERT_REG_POSITION(logic_op, 0x671);
ASSERT_REG_POSITION(clear_buffers, 0x674);
+ASSERT_REG_POSITION(color_mask, 0x680);
ASSERT_REG_POSITION(query, 0x6C0);
ASSERT_REG_POSITION(vertex_array[0], 0x700);
ASSERT_REG_POSITION(independent_blend, 0x780);
diff --git a/src/video_core/engines/shader_bytecode.h b/src/video_core/engines/shader_bytecode.h
index 83a6fd875..7e8449bc4 100644
--- a/src/video_core/engines/shader_bytecode.h
+++ b/src/video_core/engines/shader_bytecode.h
@@ -153,6 +153,7 @@ enum class PredCondition : u64 {
NotEqual = 5,
GreaterEqual = 6,
LessThanWithNan = 9,
+ LessEqualWithNan = 11,
GreaterThanWithNan = 12,
NotEqualWithNan = 13,
GreaterEqualWithNan = 14,
@@ -261,7 +262,7 @@ enum class FlowCondition : u64 {
Fcsm_Tr = 0x1C, // TODO(bunnei): What is this used for?
};
-enum class ControlCode : u64 {
+enum class ConditionCode : u64 {
F = 0,
LT = 1,
EQ = 2,
@@ -569,7 +570,6 @@ union Instruction {
BitField<39, 2, u64> tab5cb8_2;
BitField<41, 3, u64> tab5c68_1;
BitField<44, 2, u64> tab5c68_0;
- BitField<47, 1, u64> cc;
BitField<48, 1, u64> negate_b;
} fmul;
@@ -831,7 +831,7 @@ union Instruction {
union {
BitField<0, 3, u64> pred0;
BitField<3, 3, u64> pred3;
- BitField<8, 5, ControlCode> cc; // flag in cc
+ BitField<8, 5, ConditionCode> cc; // flag in cc
BitField<39, 3, u64> pred39;
BitField<42, 1, u64> neg_pred39;
BitField<45, 4, PredOperation> op; // op with pred39
@@ -1235,7 +1235,7 @@ union Instruction {
BitField<60, 1, u64> is_b_gpr;
BitField<59, 1, u64> is_c_gpr;
BitField<20, 24, s64> smem_imm;
- BitField<0, 5, ControlCode> flow_control_code;
+ BitField<0, 5, ConditionCode> flow_condition_code;
Attribute attribute;
Sampler sampler;
diff --git a/src/video_core/gpu.cpp b/src/video_core/gpu.cpp
index 83c7e5b0b..51b3904f6 100644
--- a/src/video_core/gpu.cpp
+++ b/src/video_core/gpu.cpp
@@ -17,6 +17,8 @@ u32 FramebufferConfig::BytesPerPixel(PixelFormat format) {
switch (format) {
case PixelFormat::ABGR8:
return 4;
+ default:
+ return 4;
}
UNREACHABLE();
diff --git a/src/video_core/macro_interpreter.cpp b/src/video_core/macro_interpreter.cpp
index 335a8d407..2b0dea5cd 100644
--- a/src/video_core/macro_interpreter.cpp
+++ b/src/video_core/macro_interpreter.cpp
@@ -35,6 +35,7 @@ void MacroInterpreter::Reset() {
// The next parameter index starts at 1, because $r1 already has the value of the first
// parameter.
next_parameter_index = 1;
+ carry_flag = false;
}
bool MacroInterpreter::Step(u32 offset, bool is_delay_slot) {
@@ -135,14 +136,28 @@ MacroInterpreter::Opcode MacroInterpreter::GetOpcode(u32 offset) const {
return {macro_memory[offset + pc / sizeof(u32)]};
}
-u32 MacroInterpreter::GetALUResult(ALUOperation operation, u32 src_a, u32 src_b) const {
+u32 MacroInterpreter::GetALUResult(ALUOperation operation, u32 src_a, u32 src_b) {
switch (operation) {
- case ALUOperation::Add:
- return src_a + src_b;
- // TODO(Subv): Implement AddWithCarry
- case ALUOperation::Subtract:
- return src_a - src_b;
- // TODO(Subv): Implement SubtractWithBorrow
+ case ALUOperation::Add: {
+ const u64 result{static_cast<u64>(src_a) + src_b};
+ carry_flag = result > 0xffffffff;
+ return static_cast<u32>(result);
+ }
+ case ALUOperation::AddWithCarry: {
+ const u64 result{static_cast<u64>(src_a) + src_b + (carry_flag ? 1ULL : 0ULL)};
+ carry_flag = result > 0xffffffff;
+ return static_cast<u32>(result);
+ }
+ case ALUOperation::Subtract: {
+ const u64 result{static_cast<u64>(src_a) - src_b};
+ carry_flag = result < 0x100000000;
+ return static_cast<u32>(result);
+ }
+ case ALUOperation::SubtractWithBorrow: {
+ const u64 result{static_cast<u64>(src_a) - src_b - (carry_flag ? 0ULL : 1ULL)};
+ carry_flag = result < 0x100000000;
+ return static_cast<u32>(result);
+ }
case ALUOperation::Xor:
return src_a ^ src_b;
case ALUOperation::Or:
diff --git a/src/video_core/macro_interpreter.h b/src/video_core/macro_interpreter.h
index 62d1ce289..cde360288 100644
--- a/src/video_core/macro_interpreter.h
+++ b/src/video_core/macro_interpreter.h
@@ -117,7 +117,7 @@ private:
bool Step(u32 offset, bool is_delay_slot);
/// Calculates the result of an ALU operation. src_a OP src_b;
- u32 GetALUResult(ALUOperation operation, u32 src_a, u32 src_b) const;
+ u32 GetALUResult(ALUOperation operation, u32 src_a, u32 src_b);
/// Performs the result operation on the input result and stores it in the specified register
/// (if necessary).
@@ -165,5 +165,7 @@ private:
std::vector<u32> parameters;
/// Index of the next parameter that will be fetched by the 'parm' instruction.
u32 next_parameter_index = 0;
+
+ bool carry_flag{};
};
} // namespace Tegra
diff --git a/src/video_core/memory_manager.cpp b/src/video_core/memory_manager.cpp
index 90a8e825d..77a20bb84 100644
--- a/src/video_core/memory_manager.cpp
+++ b/src/video_core/memory_manager.cpp
@@ -4,18 +4,21 @@
#include "common/alignment.h"
#include "common/assert.h"
+#include "common/logging/log.h"
#include "video_core/memory_manager.h"
namespace Tegra {
GPUVAddr MemoryManager::AllocateSpace(u64 size, u64 align) {
- std::optional<GPUVAddr> gpu_addr = FindFreeBlock(size, align);
- ASSERT(gpu_addr);
+ const std::optional<GPUVAddr> gpu_addr{FindFreeBlock(0, size, align, PageStatus::Unmapped)};
- for (u64 offset = 0; offset < size; offset += PAGE_SIZE) {
- VAddr& slot = PageSlot(*gpu_addr + offset);
+ ASSERT_MSG(gpu_addr, "unable to find available GPU memory");
+
+ for (u64 offset{}; offset < size; offset += PAGE_SIZE) {
+ VAddr& slot{PageSlot(*gpu_addr + offset)};
ASSERT(slot == static_cast<u64>(PageStatus::Unmapped));
+
slot = static_cast<u64>(PageStatus::Allocated);
}
@@ -23,10 +26,11 @@ GPUVAddr MemoryManager::AllocateSpace(u64 size, u64 align) {
}
GPUVAddr MemoryManager::AllocateSpace(GPUVAddr gpu_addr, u64 size, u64 align) {
- for (u64 offset = 0; offset < size; offset += PAGE_SIZE) {
- VAddr& slot = PageSlot(gpu_addr + offset);
+ for (u64 offset{}; offset < size; offset += PAGE_SIZE) {
+ VAddr& slot{PageSlot(gpu_addr + offset)};
ASSERT(slot == static_cast<u64>(PageStatus::Unmapped));
+
slot = static_cast<u64>(PageStatus::Allocated);
}
@@ -34,17 +38,19 @@ GPUVAddr MemoryManager::AllocateSpace(GPUVAddr gpu_addr, u64 size, u64 align) {
}
GPUVAddr MemoryManager::MapBufferEx(VAddr cpu_addr, u64 size) {
- std::optional<GPUVAddr> gpu_addr = FindFreeBlock(size, PAGE_SIZE);
- ASSERT(gpu_addr);
+ const std::optional<GPUVAddr> gpu_addr{FindFreeBlock(0, size, PAGE_SIZE, PageStatus::Unmapped)};
+
+ ASSERT_MSG(gpu_addr, "unable to find available GPU memory");
- for (u64 offset = 0; offset < size; offset += PAGE_SIZE) {
- VAddr& slot = PageSlot(*gpu_addr + offset);
+ for (u64 offset{}; offset < size; offset += PAGE_SIZE) {
+ VAddr& slot{PageSlot(*gpu_addr + offset)};
ASSERT(slot == static_cast<u64>(PageStatus::Unmapped));
+
slot = cpu_addr + offset;
}
- MappedRegion region{cpu_addr, *gpu_addr, size};
+ const MappedRegion region{cpu_addr, *gpu_addr, size};
mapped_regions.push_back(region);
return *gpu_addr;
@@ -53,14 +59,31 @@ GPUVAddr MemoryManager::MapBufferEx(VAddr cpu_addr, u64 size) {
GPUVAddr MemoryManager::MapBufferEx(VAddr cpu_addr, GPUVAddr gpu_addr, u64 size) {
ASSERT((gpu_addr & PAGE_MASK) == 0);
- for (u64 offset = 0; offset < size; offset += PAGE_SIZE) {
- VAddr& slot = PageSlot(gpu_addr + offset);
+ if (PageSlot(gpu_addr) != static_cast<u64>(PageStatus::Allocated)) {
+ // Page has been already mapped. In this case, we must find a new area of memory to use that
+ // is different than the specified one. Super Mario Odyssey hits this scenario when changing
+ // areas, but we do not want to overwrite the old pages.
+ // TODO(bunnei): We need to write a hardware test to confirm this behavior.
+
+ LOG_ERROR(HW_GPU, "attempting to map addr 0x{:016X}, which is not available!", gpu_addr);
+
+ const std::optional<GPUVAddr> new_gpu_addr{
+ FindFreeBlock(gpu_addr, size, PAGE_SIZE, PageStatus::Allocated)};
+
+ ASSERT_MSG(new_gpu_addr, "unable to find available GPU memory");
+
+ gpu_addr = *new_gpu_addr;
+ }
+
+ for (u64 offset{}; offset < size; offset += PAGE_SIZE) {
+ VAddr& slot{PageSlot(gpu_addr + offset)};
ASSERT(slot == static_cast<u64>(PageStatus::Allocated));
+
slot = cpu_addr + offset;
}
- MappedRegion region{cpu_addr, gpu_addr, size};
+ const MappedRegion region{cpu_addr, gpu_addr, size};
mapped_regions.push_back(region);
return gpu_addr;
@@ -69,11 +92,12 @@ GPUVAddr MemoryManager::MapBufferEx(VAddr cpu_addr, GPUVAddr gpu_addr, u64 size)
GPUVAddr MemoryManager::UnmapBuffer(GPUVAddr gpu_addr, u64 size) {
ASSERT((gpu_addr & PAGE_MASK) == 0);
- for (u64 offset = 0; offset < size; offset += PAGE_SIZE) {
- VAddr& slot = PageSlot(gpu_addr + offset);
+ for (u64 offset{}; offset < size; offset += PAGE_SIZE) {
+ VAddr& slot{PageSlot(gpu_addr + offset)};
ASSERT(slot != static_cast<u64>(PageStatus::Allocated) &&
slot != static_cast<u64>(PageStatus::Unmapped));
+
slot = static_cast<u64>(PageStatus::Unmapped);
}
@@ -97,13 +121,14 @@ GPUVAddr MemoryManager::GetRegionEnd(GPUVAddr region_start) const {
return {};
}
-std::optional<GPUVAddr> MemoryManager::FindFreeBlock(u64 size, u64 align) {
- GPUVAddr gpu_addr = 0;
- u64 free_space = 0;
+std::optional<GPUVAddr> MemoryManager::FindFreeBlock(GPUVAddr region_start, u64 size, u64 align,
+ PageStatus status) {
+ GPUVAddr gpu_addr{region_start};
+ u64 free_space{};
align = (align + PAGE_MASK) & ~PAGE_MASK;
while (gpu_addr + free_space < MAX_ADDRESS) {
- if (!IsPageMapped(gpu_addr + free_space)) {
+ if (PageSlot(gpu_addr + free_space) == static_cast<u64>(status)) {
free_space += PAGE_SIZE;
if (free_space >= size) {
return gpu_addr;
@@ -119,7 +144,7 @@ std::optional<GPUVAddr> MemoryManager::FindFreeBlock(u64 size, u64 align) {
}
std::optional<VAddr> MemoryManager::GpuToCpuAddress(GPUVAddr gpu_addr) {
- VAddr base_addr = PageSlot(gpu_addr);
+ const VAddr base_addr{PageSlot(gpu_addr)};
if (base_addr == static_cast<u64>(PageStatus::Allocated) ||
base_addr == static_cast<u64>(PageStatus::Unmapped)) {
@@ -133,19 +158,15 @@ std::vector<GPUVAddr> MemoryManager::CpuToGpuAddress(VAddr cpu_addr) const {
std::vector<GPUVAddr> results;
for (const auto& region : mapped_regions) {
if (cpu_addr >= region.cpu_addr && cpu_addr < (region.cpu_addr + region.size)) {
- u64 offset = cpu_addr - region.cpu_addr;
+ const u64 offset{cpu_addr - region.cpu_addr};
results.push_back(region.gpu_addr + offset);
}
}
return results;
}
-bool MemoryManager::IsPageMapped(GPUVAddr gpu_addr) {
- return PageSlot(gpu_addr) != static_cast<u64>(PageStatus::Unmapped);
-}
-
VAddr& MemoryManager::PageSlot(GPUVAddr gpu_addr) {
- auto& block = page_table[(gpu_addr >> (PAGE_BITS + PAGE_TABLE_BITS)) & PAGE_TABLE_MASK];
+ auto& block{page_table[(gpu_addr >> (PAGE_BITS + PAGE_TABLE_BITS)) & PAGE_TABLE_MASK]};
if (!block) {
block = std::make_unique<PageBlock>();
block->fill(static_cast<VAddr>(PageStatus::Unmapped));
diff --git a/src/video_core/memory_manager.h b/src/video_core/memory_manager.h
index b1255fd56..4eb338aa2 100644
--- a/src/video_core/memory_manager.h
+++ b/src/video_core/memory_manager.h
@@ -34,15 +34,15 @@ public:
static constexpr u64 PAGE_MASK = PAGE_SIZE - 1;
private:
- std::optional<GPUVAddr> FindFreeBlock(u64 size, u64 align = 1);
- bool IsPageMapped(GPUVAddr gpu_addr);
- VAddr& PageSlot(GPUVAddr gpu_addr);
-
enum class PageStatus : u64 {
Unmapped = 0xFFFFFFFFFFFFFFFFULL,
Allocated = 0xFFFFFFFFFFFFFFFEULL,
};
+ std::optional<GPUVAddr> FindFreeBlock(GPUVAddr region_start, u64 size, u64 align,
+ PageStatus status);
+ VAddr& PageSlot(GPUVAddr gpu_addr);
+
static constexpr u64 MAX_ADDRESS{0x10000000000ULL};
static constexpr u64 PAGE_TABLE_BITS{10};
static constexpr u64 PAGE_TABLE_SIZE{1 << PAGE_TABLE_BITS};
diff --git a/src/video_core/rasterizer_cache.cpp b/src/video_core/rasterizer_cache.cpp
new file mode 100644
index 000000000..093b2cdf4
--- /dev/null
+++ b/src/video_core/rasterizer_cache.cpp
@@ -0,0 +1,7 @@
+// Copyright 2018 yuzu Emulator Project
+// Licensed under GPLv2 or any later version
+// Refer to the license.txt file included.
+
+#include "video_core/rasterizer_cache.h"
+
+RasterizerCacheObject::~RasterizerCacheObject() = default;
diff --git a/src/video_core/rasterizer_cache.h b/src/video_core/rasterizer_cache.h
index 0a3b3951e..bcf0c15a4 100644
--- a/src/video_core/rasterizer_cache.h
+++ b/src/video_core/rasterizer_cache.h
@@ -5,18 +5,19 @@
#pragma once
#include <set>
+#include <unordered_map>
#include <boost/icl/interval_map.hpp>
#include <boost/range/iterator_range_core.hpp>
#include "common/common_types.h"
-#include "core/core.h"
#include "core/settings.h"
#include "video_core/rasterizer_interface.h"
-#include "video_core/renderer_base.h"
class RasterizerCacheObject {
public:
+ virtual ~RasterizerCacheObject();
+
/// Gets the address of the shader in guest memory, required for cache management
virtual VAddr GetAddr() const = 0;
@@ -64,6 +65,8 @@ class RasterizerCache : NonCopyable {
friend class RasterizerCacheObject;
public:
+ explicit RasterizerCache(VideoCore::RasterizerInterface& rasterizer) : rasterizer{rasterizer} {}
+
/// Write any cached resources overlapping the specified region back to memory
void FlushRegion(Tegra::GPUVAddr addr, size_t size) {
const auto& objects{GetSortedObjectsFromRegion(addr, size)};
@@ -86,45 +89,39 @@ public:
/// Invalidates everything in the cache
void InvalidateAll() {
- while (object_cache.begin() != object_cache.end()) {
- Unregister(*object_cache.begin()->second.begin());
+ while (interval_cache.begin() != interval_cache.end()) {
+ Unregister(*interval_cache.begin()->second.begin());
}
}
protected:
/// Tries to get an object from the cache with the specified address
T TryGet(VAddr addr) const {
- const ObjectInterval interval{addr};
- for (auto& pair : boost::make_iterator_range(object_cache.equal_range(interval))) {
- for (auto& cached_object : pair.second) {
- if (cached_object->GetAddr() == addr) {
- return cached_object;
- }
- }
- }
+ const auto iter = map_cache.find(addr);
+ if (iter != map_cache.end())
+ return iter->second;
return nullptr;
}
/// Register an object into the cache
void Register(const T& object) {
object->SetIsRegistered(true);
- object_cache.add({GetInterval(object), ObjectSet{object}});
- auto& rasterizer = Core::System::GetInstance().Renderer().Rasterizer();
+ interval_cache.add({GetInterval(object), ObjectSet{object}});
+ map_cache.insert({object->GetAddr(), object});
rasterizer.UpdatePagesCachedCount(object->GetAddr(), object->GetSizeInBytes(), 1);
}
/// Unregisters an object from the cache
void Unregister(const T& object) {
object->SetIsRegistered(false);
- auto& rasterizer = Core::System::GetInstance().Renderer().Rasterizer();
rasterizer.UpdatePagesCachedCount(object->GetAddr(), object->GetSizeInBytes(), -1);
-
// Only flush if use_accurate_gpu_emulation is enabled, as it incurs a performance hit
if (Settings::values.use_accurate_gpu_emulation) {
FlushObject(object);
}
- object_cache.subtract({GetInterval(object), ObjectSet{object}});
+ interval_cache.subtract({GetInterval(object), ObjectSet{object}});
+ map_cache.erase(object->GetAddr());
}
/// Returns a ticks counter used for tracking when cached objects were last modified
@@ -141,7 +138,7 @@ private:
std::vector<T> objects;
const ObjectInterval interval{addr, addr + size};
- for (auto& pair : boost::make_iterator_range(object_cache.equal_range(interval))) {
+ for (auto& pair : boost::make_iterator_range(interval_cache.equal_range(interval))) {
for (auto& cached_object : pair.second) {
if (!cached_object) {
continue;
@@ -167,14 +164,17 @@ private:
}
using ObjectSet = std::set<T>;
- using ObjectCache = boost::icl::interval_map<VAddr, ObjectSet>;
- using ObjectInterval = typename ObjectCache::interval_type;
+ using ObjectCache = std::unordered_map<VAddr, T>;
+ using IntervalCache = boost::icl::interval_map<VAddr, ObjectSet>;
+ using ObjectInterval = typename IntervalCache::interval_type;
static auto GetInterval(const T& object) {
return ObjectInterval::right_open(object->GetAddr(),
object->GetAddr() + object->GetSizeInBytes());
}
- ObjectCache object_cache; ///< Cache of objects
- u64 modified_ticks{}; ///< Counter of cache state ticks, used for in-order flushing
+ ObjectCache map_cache;
+ IntervalCache interval_cache; ///< Cache of objects
+ u64 modified_ticks{}; ///< Counter of cache state ticks, used for in-order flushing
+ VideoCore::RasterizerInterface& rasterizer;
};
diff --git a/src/video_core/renderer_base.cpp b/src/video_core/renderer_base.cpp
index 0df3725c2..1482cdb40 100644
--- a/src/video_core/renderer_base.cpp
+++ b/src/video_core/renderer_base.cpp
@@ -5,7 +5,6 @@
#include "core/frontend/emu_window.h"
#include "core/settings.h"
#include "video_core/renderer_base.h"
-#include "video_core/renderer_opengl/gl_rasterizer.h"
namespace VideoCore {
diff --git a/src/video_core/renderer_opengl/gl_buffer_cache.cpp b/src/video_core/renderer_opengl/gl_buffer_cache.cpp
index 41a54b3e7..075192c3f 100644
--- a/src/video_core/renderer_opengl/gl_buffer_cache.cpp
+++ b/src/video_core/renderer_opengl/gl_buffer_cache.cpp
@@ -9,10 +9,12 @@
#include "core/core.h"
#include "core/memory.h"
#include "video_core/renderer_opengl/gl_buffer_cache.h"
+#include "video_core/renderer_opengl/gl_rasterizer.h"
namespace OpenGL {
-OGLBufferCache::OGLBufferCache(std::size_t size) : stream_buffer(GL_ARRAY_BUFFER, size) {}
+OGLBufferCache::OGLBufferCache(RasterizerOpenGL& rasterizer, std::size_t size)
+ : RasterizerCache{rasterizer}, stream_buffer(GL_ARRAY_BUFFER, size) {}
GLintptr OGLBufferCache::UploadMemory(Tegra::GPUVAddr gpu_addr, std::size_t size,
std::size_t alignment, bool cache) {
diff --git a/src/video_core/renderer_opengl/gl_buffer_cache.h b/src/video_core/renderer_opengl/gl_buffer_cache.h
index be29dc8be..91fca3f6c 100644
--- a/src/video_core/renderer_opengl/gl_buffer_cache.h
+++ b/src/video_core/renderer_opengl/gl_buffer_cache.h
@@ -15,6 +15,8 @@
namespace OpenGL {
+class RasterizerOpenGL;
+
struct CachedBufferEntry final : public RasterizerCacheObject {
VAddr GetAddr() const override {
return addr;
@@ -35,7 +37,7 @@ struct CachedBufferEntry final : public RasterizerCacheObject {
class OGLBufferCache final : public RasterizerCache<std::shared_ptr<CachedBufferEntry>> {
public:
- explicit OGLBufferCache(std::size_t size);
+ explicit OGLBufferCache(RasterizerOpenGL& rasterizer, std::size_t size);
/// Uploads data from a guest GPU address. Returns host's buffer offset where it's been
/// allocated.
diff --git a/src/video_core/renderer_opengl/gl_primitive_assembler.cpp b/src/video_core/renderer_opengl/gl_primitive_assembler.cpp
index 741f14bc3..d9ed08437 100644
--- a/src/video_core/renderer_opengl/gl_primitive_assembler.cpp
+++ b/src/video_core/renderer_opengl/gl_primitive_assembler.cpp
@@ -6,6 +6,7 @@
#include <array>
#include "common/assert.h"
#include "common/common_types.h"
+#include "core/core.h"
#include "core/memory.h"
#include "video_core/renderer_opengl/gl_buffer_cache.h"
#include "video_core/renderer_opengl/gl_primitive_assembler.h"
diff --git a/src/video_core/renderer_opengl/gl_rasterizer.cpp b/src/video_core/renderer_opengl/gl_rasterizer.cpp
index a0527fe57..630a58e49 100644
--- a/src/video_core/renderer_opengl/gl_rasterizer.cpp
+++ b/src/video_core/renderer_opengl/gl_rasterizer.cpp
@@ -33,7 +33,8 @@ using Maxwell = Tegra::Engines::Maxwell3D::Regs;
using PixelFormat = VideoCore::Surface::PixelFormat;
using SurfaceType = VideoCore::Surface::SurfaceType;
-MICROPROFILE_DEFINE(OpenGL_VAO, "OpenGL", "Vertex Array Setup", MP_RGB(128, 128, 192));
+MICROPROFILE_DEFINE(OpenGL_VAO, "OpenGL", "Vertex Format Setup", MP_RGB(128, 128, 192));
+MICROPROFILE_DEFINE(OpenGL_VB, "OpenGL", "Vertex Buffer Setup", MP_RGB(128, 128, 192));
MICROPROFILE_DEFINE(OpenGL_Shader, "OpenGL", "Shader Setup", MP_RGB(128, 128, 192));
MICROPROFILE_DEFINE(OpenGL_UBO, "OpenGL", "Const Buffer Setup", MP_RGB(128, 128, 192));
MICROPROFILE_DEFINE(OpenGL_Index, "OpenGL", "Index Buffer Setup", MP_RGB(128, 128, 192));
@@ -79,7 +80,8 @@ struct DrawParameters {
};
RasterizerOpenGL::RasterizerOpenGL(Core::Frontend::EmuWindow& window, ScreenInfo& info)
- : emu_window{window}, screen_info{info}, buffer_cache(STREAM_BUFFER_SIZE) {
+ : res_cache{*this}, shader_cache{*this}, emu_window{window}, screen_info{info},
+ buffer_cache(*this, STREAM_BUFFER_SIZE) {
// Create sampler objects
for (std::size_t i = 0; i < texture_samplers.size(); ++i) {
texture_samplers[i].Create();
@@ -96,17 +98,10 @@ RasterizerOpenGL::RasterizerOpenGL(Core::Frontend::EmuWindow& window, ScreenInfo
has_ARB_direct_state_access = true;
} else if (extension == "GL_ARB_multi_bind") {
has_ARB_multi_bind = true;
- } else if (extension == "GL_ARB_separate_shader_objects") {
- has_ARB_separate_shader_objects = true;
- } else if (extension == "GL_ARB_vertex_attrib_binding") {
- has_ARB_vertex_attrib_binding = true;
}
}
- ASSERT_MSG(has_ARB_separate_shader_objects, "has_ARB_separate_shader_objects is unsupported");
OpenGLState::ApplyDefaultState();
- // Clipping plane 0 is always enabled for PICA fixed clip plane z <= 0
- state.clip_distance[0] = true;
// Create render framebuffer
framebuffer.Create();
@@ -122,18 +117,23 @@ RasterizerOpenGL::RasterizerOpenGL(Core::Frontend::EmuWindow& window, ScreenInfo
RasterizerOpenGL::~RasterizerOpenGL() {}
-void RasterizerOpenGL::SetupVertexArrays() {
- MICROPROFILE_SCOPE(OpenGL_VAO);
- const auto& gpu = Core::System::GetInstance().GPU().Maxwell3D();
+void RasterizerOpenGL::SetupVertexFormat() {
+ auto& gpu = Core::System::GetInstance().GPU().Maxwell3D();
const auto& regs = gpu.regs;
+ if (!gpu.dirty_flags.vertex_attrib_format)
+ return;
+ gpu.dirty_flags.vertex_attrib_format = false;
+
+ MICROPROFILE_SCOPE(OpenGL_VAO);
+
auto [iter, is_cache_miss] = vertex_array_cache.try_emplace(regs.vertex_attrib_format);
auto& VAO = iter->second;
if (is_cache_miss) {
VAO.Create();
state.draw.vertex_array = VAO.handle;
- state.Apply();
+ state.ApplyVertexBufferState();
// The index buffer binding is stored within the VAO. Stupid OpenGL, but easy to work
// around.
@@ -175,8 +175,13 @@ void RasterizerOpenGL::SetupVertexArrays() {
}
}
state.draw.vertex_array = VAO.handle;
- state.draw.vertex_buffer = buffer_cache.GetHandle();
- state.Apply();
+ state.ApplyVertexBufferState();
+}
+
+void RasterizerOpenGL::SetupVertexBuffer() {
+ MICROPROFILE_SCOPE(OpenGL_VB);
+ const auto& gpu = Core::System::GetInstance().GPU().Maxwell3D();
+ const auto& regs = gpu.regs;
// Upload all guest vertex arrays sequentially to our buffer
for (u32 index = 0; index < Maxwell::NumVertexArrays; ++index) {
@@ -203,6 +208,9 @@ void RasterizerOpenGL::SetupVertexArrays() {
glVertexBindingDivisor(index, 0);
}
}
+
+ // Implicit set by glBindVertexBuffer. Stupid glstate handling...
+ state.draw.vertex_buffer = buffer_cache.GetHandle();
}
DrawParameters RasterizerOpenGL::SetupDraw() {
@@ -327,8 +335,6 @@ void RasterizerOpenGL::SetupShaders(GLenum primitive_mode) {
index++;
}
}
-
- state.Apply();
}
std::size_t RasterizerOpenGL::CalculateVertexArraysSize() const {
@@ -397,8 +403,8 @@ void RasterizerOpenGL::UpdatePagesCachedCount(VAddr addr, u64 size, int delta) {
cached_pages.add({pages_interval, delta});
}
-void RasterizerOpenGL::ConfigureFramebuffers(bool using_color_fb, bool using_depth_fb,
- bool preserve_contents,
+void RasterizerOpenGL::ConfigureFramebuffers(OpenGLState& current_state, bool using_color_fb,
+ bool using_depth_fb, bool preserve_contents,
std::optional<std::size_t> single_color_target) {
MICROPROFILE_SCOPE(OpenGL_Framebuffer);
const auto& regs = Core::System::GetInstance().GPU().Maxwell3D().regs;
@@ -414,9 +420,9 @@ void RasterizerOpenGL::ConfigureFramebuffers(bool using_color_fb, bool using_dep
ASSERT_MSG(regs.rt_separate_frag_data == 0, "Unimplemented");
// Bind the framebuffer surfaces
- state.draw.draw_framebuffer = framebuffer.handle;
- state.Apply();
- state.framebuffer_srgb.enabled = regs.framebuffer_srgb != 0;
+ current_state.draw.draw_framebuffer = framebuffer.handle;
+ current_state.ApplyFramebufferState();
+ current_state.framebuffer_srgb.enabled = regs.framebuffer_srgb != 0;
if (using_color_fb) {
if (single_color_target) {
@@ -494,10 +500,7 @@ void RasterizerOpenGL::ConfigureFramebuffers(bool using_color_fb, bool using_dep
glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_TEXTURE_2D, 0,
0);
}
-
- SyncViewport();
-
- state.Apply();
+ SyncViewport(current_state);
}
void RasterizerOpenGL::Clear() {
@@ -510,22 +513,23 @@ void RasterizerOpenGL::Clear() {
bool use_stencil{};
OpenGLState clear_state;
- clear_state.draw.draw_framebuffer = framebuffer.handle;
- clear_state.color_mask.red_enabled = regs.clear_buffers.R ? GL_TRUE : GL_FALSE;
- clear_state.color_mask.green_enabled = regs.clear_buffers.G ? GL_TRUE : GL_FALSE;
- clear_state.color_mask.blue_enabled = regs.clear_buffers.B ? GL_TRUE : GL_FALSE;
- clear_state.color_mask.alpha_enabled = regs.clear_buffers.A ? GL_TRUE : GL_FALSE;
-
if (regs.clear_buffers.R || regs.clear_buffers.G || regs.clear_buffers.B ||
regs.clear_buffers.A) {
use_color = true;
}
+ if (use_color) {
+ clear_state.color_mask[0].red_enabled = regs.clear_buffers.R ? GL_TRUE : GL_FALSE;
+ clear_state.color_mask[0].green_enabled = regs.clear_buffers.G ? GL_TRUE : GL_FALSE;
+ clear_state.color_mask[0].blue_enabled = regs.clear_buffers.B ? GL_TRUE : GL_FALSE;
+ clear_state.color_mask[0].alpha_enabled = regs.clear_buffers.A ? GL_TRUE : GL_FALSE;
+ }
if (regs.clear_buffers.Z) {
ASSERT_MSG(regs.zeta_enable != 0, "Tried to clear Z but buffer is not enabled!");
use_depth = true;
// Always enable the depth write when clearing the depth buffer. The depth write mask is
- // ignored when clearing the buffer in the Switch, but OpenGL obeys it so we set it to true.
+ // ignored when clearing the buffer in the Switch, but OpenGL obeys it so we set it to
+ // true.
clear_state.depth.test_enabled = true;
clear_state.depth.test_func = GL_ALWAYS;
}
@@ -533,6 +537,30 @@ void RasterizerOpenGL::Clear() {
ASSERT_MSG(regs.zeta_enable != 0, "Tried to clear stencil but buffer is not enabled!");
use_stencil = true;
clear_state.stencil.test_enabled = true;
+ if (regs.clear_flags.stencil) {
+ // Stencil affects the clear so fill it with the used masks
+ clear_state.stencil.front.test_func = GL_ALWAYS;
+ clear_state.stencil.front.test_mask = regs.stencil_front_func_mask;
+ clear_state.stencil.front.action_stencil_fail = GL_KEEP;
+ clear_state.stencil.front.action_depth_fail = GL_KEEP;
+ clear_state.stencil.front.action_depth_pass = GL_KEEP;
+ clear_state.stencil.front.write_mask = regs.stencil_front_mask;
+ if (regs.stencil_two_side_enable) {
+ clear_state.stencil.back.test_func = GL_ALWAYS;
+ clear_state.stencil.back.test_mask = regs.stencil_back_func_mask;
+ clear_state.stencil.back.action_stencil_fail = GL_KEEP;
+ clear_state.stencil.back.action_depth_fail = GL_KEEP;
+ clear_state.stencil.back.action_depth_pass = GL_KEEP;
+ clear_state.stencil.back.write_mask = regs.stencil_back_mask;
+ } else {
+ clear_state.stencil.back.test_func = GL_ALWAYS;
+ clear_state.stencil.back.test_mask = 0xFFFFFFFF;
+ clear_state.stencil.back.write_mask = 0xFFFFFFFF;
+ clear_state.stencil.back.action_stencil_fail = GL_KEEP;
+ clear_state.stencil.back.action_depth_fail = GL_KEEP;
+ clear_state.stencil.back.action_depth_pass = GL_KEEP;
+ }
+ }
}
if (!use_color && !use_depth && !use_stencil) {
@@ -542,11 +570,16 @@ void RasterizerOpenGL::Clear() {
ScopeAcquireGLContext acquire_context{emu_window};
- ConfigureFramebuffers(use_color, use_depth || use_stencil, false,
+ ConfigureFramebuffers(clear_state, use_color, use_depth || use_stencil, false,
regs.clear_buffers.RT.Value());
- // Copy the sRGB setting to the clear state to avoid problem with
- // specific driver implementations
- clear_state.framebuffer_srgb.enabled = state.framebuffer_srgb.enabled;
+ if (regs.clear_flags.scissor) {
+ SyncScissorTest(clear_state);
+ }
+
+ if (regs.clear_flags.viewport) {
+ clear_state.EmulateViewportWithScissor();
+ }
+
clear_state.Apply();
if (use_color) {
@@ -572,16 +605,17 @@ void RasterizerOpenGL::DrawArrays() {
ScopeAcquireGLContext acquire_context{emu_window};
- ConfigureFramebuffers();
-
+ ConfigureFramebuffers(state);
+ SyncColorMask();
+ SyncFragmentColorClampState();
+ SyncMultiSampleState();
SyncDepthTestState();
SyncStencilTestState();
SyncBlendState();
SyncLogicOpState();
SyncCullMode();
SyncPrimitiveRestart();
- SyncDepthRange();
- SyncScissorTest();
+ SyncScissorTest(state);
// Alpha Testing is synced on shaders.
SyncTransformFeedback();
SyncPointState();
@@ -594,7 +628,7 @@ void RasterizerOpenGL::DrawArrays() {
const bool is_indexed = accelerate_draw == AccelDraw::Indexed;
state.draw.vertex_buffer = buffer_cache.GetHandle();
- state.Apply();
+ state.ApplyVertexBufferState();
std::size_t buffer_size = CalculateVertexArraysSize();
@@ -621,7 +655,8 @@ void RasterizerOpenGL::DrawArrays() {
buffer_cache.Map(buffer_size);
- SetupVertexArrays();
+ SetupVertexFormat();
+ SetupVertexBuffer();
DrawParameters params = SetupDraw();
SetupShaders(params.primitive_mode);
@@ -634,7 +669,7 @@ void RasterizerOpenGL::DrawArrays() {
params.DispatchDraw();
// Disable scissor test
- state.scissor.enabled = false;
+ state.viewports[0].scissor.enabled = false;
accelerate_draw = AccelDraw::Disabled;
@@ -727,7 +762,6 @@ void RasterizerOpenGL::SamplerInfo::Create() {
void RasterizerOpenGL::SamplerInfo::SyncWithConfig(const Tegra::Texture::TSCEntry& config) {
const GLuint s = sampler.handle;
-
if (mag_filter != config.mag_filter) {
mag_filter = config.mag_filter;
glSamplerParameteri(
@@ -769,15 +803,51 @@ void RasterizerOpenGL::SamplerInfo::SyncWithConfig(const Tegra::Texture::TSCEntr
MaxwellToGL::DepthCompareFunc(depth_compare_func));
}
- if (wrap_u == Tegra::Texture::WrapMode::Border || wrap_v == Tegra::Texture::WrapMode::Border ||
- wrap_p == Tegra::Texture::WrapMode::Border) {
- const GLvec4 new_border_color = {{config.border_color_r, config.border_color_g,
- config.border_color_b, config.border_color_a}};
- if (border_color != new_border_color) {
- border_color = new_border_color;
- glSamplerParameterfv(s, GL_TEXTURE_BORDER_COLOR, border_color.data());
+ GLvec4 new_border_color;
+ if (config.srgb_conversion) {
+ new_border_color[0] = config.srgb_border_color_r / 255.0f;
+ new_border_color[1] = config.srgb_border_color_g / 255.0f;
+ new_border_color[2] = config.srgb_border_color_g / 255.0f;
+ } else {
+ new_border_color[0] = config.border_color_r;
+ new_border_color[1] = config.border_color_g;
+ new_border_color[2] = config.border_color_b;
+ }
+ new_border_color[3] = config.border_color_a;
+
+ if (border_color != new_border_color) {
+ border_color = new_border_color;
+ glSamplerParameterfv(s, GL_TEXTURE_BORDER_COLOR, border_color.data());
+ }
+
+ const float anisotropic_max = static_cast<float>(1 << config.max_anisotropy.Value());
+ if (anisotropic_max != max_anisotropic) {
+ max_anisotropic = anisotropic_max;
+ if (GLAD_GL_ARB_texture_filter_anisotropic) {
+ glSamplerParameterf(s, GL_TEXTURE_MAX_ANISOTROPY, max_anisotropic);
+ } else if (GLAD_GL_EXT_texture_filter_anisotropic) {
+ glSamplerParameterf(s, GL_TEXTURE_MAX_ANISOTROPY_EXT, max_anisotropic);
}
}
+ const float lod_min = static_cast<float>(config.min_lod_clamp.Value()) / 256.0f;
+ if (lod_min != min_lod) {
+ min_lod = lod_min;
+ glSamplerParameterf(s, GL_TEXTURE_MIN_LOD, min_lod);
+ }
+
+ const float lod_max = static_cast<float>(config.max_lod_clamp.Value()) / 256.0f;
+ if (lod_max != max_lod) {
+ max_lod = lod_max;
+ glSamplerParameterf(s, GL_TEXTURE_MAX_LOD, max_lod);
+ }
+ const u32 bias = config.mip_lod_bias.Value();
+ // Sign extend the 13-bit value.
+ constexpr u32 mask = 1U << (13 - 1);
+ const float bias_lod = static_cast<s32>((bias ^ mask) - mask) / 256.f;
+ if (lod_bias != bias_lod) {
+ lod_bias = bias_lod;
+ glSamplerParameterf(s, GL_TEXTURE_LOD_BIAS, lod_bias);
+ }
}
u32 RasterizerOpenGL::SetupConstBuffers(Maxwell::ShaderStage stage, Shader& shader,
@@ -897,14 +967,18 @@ u32 RasterizerOpenGL::SetupTextures(Maxwell::ShaderStage stage, Shader& shader,
return current_unit + static_cast<u32>(entries.size());
}
-void RasterizerOpenGL::SyncViewport() {
+void RasterizerOpenGL::SyncViewport(OpenGLState& current_state) {
const auto& regs = Core::System::GetInstance().GPU().Maxwell3D().regs;
- const MathUtil::Rectangle<s32> viewport_rect{regs.viewport_transform[0].GetRect()};
-
- state.viewport.x = viewport_rect.left;
- state.viewport.y = viewport_rect.bottom;
- state.viewport.width = static_cast<GLsizei>(viewport_rect.GetWidth());
- state.viewport.height = static_cast<GLsizei>(viewport_rect.GetHeight());
+ for (std::size_t i = 0; i < Tegra::Engines::Maxwell3D::Regs::NumViewports; i++) {
+ const MathUtil::Rectangle<s32> viewport_rect{regs.viewport_transform[i].GetRect()};
+ auto& viewport = current_state.viewports[i];
+ viewport.x = viewport_rect.left;
+ viewport.y = viewport_rect.bottom;
+ viewport.width = viewport_rect.GetWidth();
+ viewport.height = viewport_rect.GetHeight();
+ viewport.depth_range_far = regs.viewports[i].depth_range_far;
+ viewport.depth_range_near = regs.viewports[i].depth_range_near;
+ }
}
void RasterizerOpenGL::SyncClipEnabled() {
@@ -946,13 +1020,6 @@ void RasterizerOpenGL::SyncPrimitiveRestart() {
state.primitive_restart.index = regs.primitive_restart.index;
}
-void RasterizerOpenGL::SyncDepthRange() {
- const auto& regs = Core::System::GetInstance().GPU().Maxwell3D().regs;
-
- state.depth.depth_range_near = regs.viewport->depth_range_near;
- state.depth.depth_range_far = regs.viewport->depth_range_far;
-}
-
void RasterizerOpenGL::SyncDepthTestState() {
const auto& regs = Core::System::GetInstance().GPU().Maxwell3D().regs;
@@ -973,9 +1040,6 @@ void RasterizerOpenGL::SyncStencilTestState() {
return;
}
- // TODO(bunnei): Verify behavior when this is not set
- ASSERT(regs.stencil_two_side_enable);
-
state.stencil.front.test_func = MaxwellToGL::ComparisonOp(regs.stencil_front_func_func);
state.stencil.front.test_ref = regs.stencil_front_func_ref;
state.stencil.front.test_mask = regs.stencil_front_func_mask;
@@ -983,42 +1047,95 @@ void RasterizerOpenGL::SyncStencilTestState() {
state.stencil.front.action_depth_fail = MaxwellToGL::StencilOp(regs.stencil_front_op_zfail);
state.stencil.front.action_depth_pass = MaxwellToGL::StencilOp(regs.stencil_front_op_zpass);
state.stencil.front.write_mask = regs.stencil_front_mask;
+ if (regs.stencil_two_side_enable) {
+ state.stencil.back.test_func = MaxwellToGL::ComparisonOp(regs.stencil_back_func_func);
+ state.stencil.back.test_ref = regs.stencil_back_func_ref;
+ state.stencil.back.test_mask = regs.stencil_back_func_mask;
+ state.stencil.back.action_stencil_fail = MaxwellToGL::StencilOp(regs.stencil_back_op_fail);
+ state.stencil.back.action_depth_fail = MaxwellToGL::StencilOp(regs.stencil_back_op_zfail);
+ state.stencil.back.action_depth_pass = MaxwellToGL::StencilOp(regs.stencil_back_op_zpass);
+ state.stencil.back.write_mask = regs.stencil_back_mask;
+ } else {
+ state.stencil.back.test_func = GL_ALWAYS;
+ state.stencil.back.test_ref = 0;
+ state.stencil.back.test_mask = 0xFFFFFFFF;
+ state.stencil.back.write_mask = 0xFFFFFFFF;
+ state.stencil.back.action_stencil_fail = GL_KEEP;
+ state.stencil.back.action_depth_fail = GL_KEEP;
+ state.stencil.back.action_depth_pass = GL_KEEP;
+ }
+}
- state.stencil.back.test_func = MaxwellToGL::ComparisonOp(regs.stencil_back_func_func);
- state.stencil.back.test_ref = regs.stencil_back_func_ref;
- state.stencil.back.test_mask = regs.stencil_back_func_mask;
- state.stencil.back.action_stencil_fail = MaxwellToGL::StencilOp(regs.stencil_back_op_fail);
- state.stencil.back.action_depth_fail = MaxwellToGL::StencilOp(regs.stencil_back_op_zfail);
- state.stencil.back.action_depth_pass = MaxwellToGL::StencilOp(regs.stencil_back_op_zpass);
- state.stencil.back.write_mask = regs.stencil_back_mask;
+void RasterizerOpenGL::SyncColorMask() {
+ const auto& regs = Core::System::GetInstance().GPU().Maxwell3D().regs;
+ const std::size_t count =
+ regs.independent_blend_enable ? Tegra::Engines::Maxwell3D::Regs::NumRenderTargets : 1;
+ for (std::size_t i = 0; i < count; i++) {
+ const auto& source = regs.color_mask[regs.color_mask_common ? 0 : i];
+ auto& dest = state.color_mask[i];
+ dest.red_enabled = (source.R == 0) ? GL_FALSE : GL_TRUE;
+ dest.green_enabled = (source.G == 0) ? GL_FALSE : GL_TRUE;
+ dest.blue_enabled = (source.B == 0) ? GL_FALSE : GL_TRUE;
+ dest.alpha_enabled = (source.A == 0) ? GL_FALSE : GL_TRUE;
+ }
}
-void RasterizerOpenGL::SyncBlendState() {
+void RasterizerOpenGL::SyncMultiSampleState() {
const auto& regs = Core::System::GetInstance().GPU().Maxwell3D().regs;
+ state.multisample_control.alpha_to_coverage = regs.multisample_control.alpha_to_coverage != 0;
+ state.multisample_control.alpha_to_one = regs.multisample_control.alpha_to_one != 0;
+}
- // TODO(Subv): Support more than just render target 0.
- state.blend.enabled = regs.blend.enable[0] != 0;
+void RasterizerOpenGL::SyncFragmentColorClampState() {
+ const auto& regs = Core::System::GetInstance().GPU().Maxwell3D().regs;
+ state.fragment_color_clamp.enabled = regs.frag_color_clamp != 0;
+}
- if (!state.blend.enabled)
- return;
+void RasterizerOpenGL::SyncBlendState() {
+ const auto& regs = Core::System::GetInstance().GPU().Maxwell3D().regs;
- ASSERT_MSG(regs.logic_op.enable == 0,
- "Blending and logic op can't be enabled at the same time.");
+ state.blend_color.red = regs.blend_color.r;
+ state.blend_color.green = regs.blend_color.g;
+ state.blend_color.blue = regs.blend_color.b;
+ state.blend_color.alpha = regs.blend_color.a;
+
+ state.independant_blend.enabled = regs.independent_blend_enable;
+ if (!state.independant_blend.enabled) {
+ auto& blend = state.blend[0];
+ const auto& src = regs.blend;
+ blend.enabled = src.enable[0] != 0;
+ if (blend.enabled) {
+ blend.rgb_equation = MaxwellToGL::BlendEquation(src.equation_rgb);
+ blend.src_rgb_func = MaxwellToGL::BlendFunc(src.factor_source_rgb);
+ blend.dst_rgb_func = MaxwellToGL::BlendFunc(src.factor_dest_rgb);
+ blend.a_equation = MaxwellToGL::BlendEquation(src.equation_a);
+ blend.src_a_func = MaxwellToGL::BlendFunc(src.factor_source_a);
+ blend.dst_a_func = MaxwellToGL::BlendFunc(src.factor_dest_a);
+ }
+ for (std::size_t i = 1; i < Tegra::Engines::Maxwell3D::Regs::NumRenderTargets; i++) {
+ state.blend[i].enabled = false;
+ }
+ return;
+ }
- ASSERT_MSG(regs.independent_blend_enable == 1, "Only independent blending is implemented");
- ASSERT_MSG(!regs.independent_blend[0].separate_alpha, "Unimplemented");
- state.blend.rgb_equation = MaxwellToGL::BlendEquation(regs.independent_blend[0].equation_rgb);
- state.blend.src_rgb_func = MaxwellToGL::BlendFunc(regs.independent_blend[0].factor_source_rgb);
- state.blend.dst_rgb_func = MaxwellToGL::BlendFunc(regs.independent_blend[0].factor_dest_rgb);
- state.blend.a_equation = MaxwellToGL::BlendEquation(regs.independent_blend[0].equation_a);
- state.blend.src_a_func = MaxwellToGL::BlendFunc(regs.independent_blend[0].factor_source_a);
- state.blend.dst_a_func = MaxwellToGL::BlendFunc(regs.independent_blend[0].factor_dest_a);
+ for (std::size_t i = 0; i < Tegra::Engines::Maxwell3D::Regs::NumRenderTargets; i++) {
+ auto& blend = state.blend[i];
+ const auto& src = regs.independent_blend[i];
+ blend.enabled = regs.blend.enable[i] != 0;
+ if (!blend.enabled)
+ continue;
+ blend.rgb_equation = MaxwellToGL::BlendEquation(src.equation_rgb);
+ blend.src_rgb_func = MaxwellToGL::BlendFunc(src.factor_source_rgb);
+ blend.dst_rgb_func = MaxwellToGL::BlendFunc(src.factor_dest_rgb);
+ blend.a_equation = MaxwellToGL::BlendEquation(src.equation_a);
+ blend.src_a_func = MaxwellToGL::BlendFunc(src.factor_source_a);
+ blend.dst_a_func = MaxwellToGL::BlendFunc(src.factor_dest_a);
+ }
}
void RasterizerOpenGL::SyncLogicOpState() {
const auto& regs = Core::System::GetInstance().GPU().Maxwell3D().regs;
- // TODO(Subv): Support more than just render target 0.
state.logic_op.enabled = regs.logic_op.enable != 0;
if (!state.logic_op.enabled)
@@ -1030,19 +1147,21 @@ void RasterizerOpenGL::SyncLogicOpState() {
state.logic_op.operation = MaxwellToGL::LogicOp(regs.logic_op.operation);
}
-void RasterizerOpenGL::SyncScissorTest() {
+void RasterizerOpenGL::SyncScissorTest(OpenGLState& current_state) {
const auto& regs = Core::System::GetInstance().GPU().Maxwell3D().regs;
-
- state.scissor.enabled = (regs.scissor_test.enable != 0);
- // TODO(Blinkhawk): Figure if the hardware supports scissor testing per viewport and how it's
- // implemented.
- if (regs.scissor_test.enable != 0) {
- const u32 width = regs.scissor_test.max_x - regs.scissor_test.min_x;
- const u32 height = regs.scissor_test.max_y - regs.scissor_test.min_y;
- state.scissor.x = regs.scissor_test.min_x;
- state.scissor.y = regs.scissor_test.min_y;
- state.scissor.width = width;
- state.scissor.height = height;
+ for (std::size_t i = 0; i < Tegra::Engines::Maxwell3D::Regs::NumViewports; i++) {
+ const auto& src = regs.scissor_test[i];
+ auto& dst = current_state.viewports[i].scissor;
+ dst.enabled = (src.enable != 0);
+ if (dst.enabled == 0) {
+ return;
+ }
+ const u32 width = src.max_x - src.min_x;
+ const u32 height = src.max_y - src.min_y;
+ dst.x = src.min_x;
+ dst.y = src.min_y;
+ dst.width = width;
+ dst.height = height;
}
}
@@ -1057,20 +1176,15 @@ void RasterizerOpenGL::SyncTransformFeedback() {
void RasterizerOpenGL::SyncPointState() {
const auto& regs = Core::System::GetInstance().GPU().Maxwell3D().regs;
-
- // TODO(Rodrigo): Most games do not set a point size. I think this is a case of a
- // register carrying a default value. For now, if the point size is zero, assume it's
- // OpenGL's default (1).
- state.point.size = regs.point_size == 0 ? 1 : regs.point_size;
+ state.point.size = regs.point_size;
}
void RasterizerOpenGL::CheckAlphaTests() {
const auto& regs = Core::System::GetInstance().GPU().Maxwell3D().regs;
if (regs.alpha_test_enabled != 0 && regs.rt_control.count > 1) {
- LOG_CRITICAL(
- Render_OpenGL,
- "Alpha Testing is enabled with Multiple Render Targets, this behavior is undefined.");
+ LOG_CRITICAL(Render_OpenGL, "Alpha Testing is enabled with Multiple Render Targets, "
+ "this behavior is undefined.");
UNREACHABLE();
}
}
diff --git a/src/video_core/renderer_opengl/gl_rasterizer.h b/src/video_core/renderer_opengl/gl_rasterizer.h
index 47097c569..f4354289c 100644
--- a/src/video_core/renderer_opengl/gl_rasterizer.h
+++ b/src/video_core/renderer_opengl/gl_rasterizer.h
@@ -88,18 +88,23 @@ private:
/// SamplerInfo struct.
void Create();
/// Syncs the sampler object with the config, updating any necessary state.
- void SyncWithConfig(const Tegra::Texture::TSCEntry& config);
+ void SyncWithConfig(const Tegra::Texture::TSCEntry& info);
private:
- Tegra::Texture::TextureFilter mag_filter;
- Tegra::Texture::TextureFilter min_filter;
- Tegra::Texture::TextureMipmapFilter mip_filter;
- Tegra::Texture::WrapMode wrap_u;
- Tegra::Texture::WrapMode wrap_v;
- Tegra::Texture::WrapMode wrap_p;
- bool uses_depth_compare;
- Tegra::Texture::DepthCompareFunc depth_compare_func;
- GLvec4 border_color;
+ Tegra::Texture::TextureFilter mag_filter = Tegra::Texture::TextureFilter::Nearest;
+ Tegra::Texture::TextureFilter min_filter = Tegra::Texture::TextureFilter::Nearest;
+ Tegra::Texture::TextureMipmapFilter mip_filter = Tegra::Texture::TextureMipmapFilter::None;
+ Tegra::Texture::WrapMode wrap_u = Tegra::Texture::WrapMode::ClampToEdge;
+ Tegra::Texture::WrapMode wrap_v = Tegra::Texture::WrapMode::ClampToEdge;
+ Tegra::Texture::WrapMode wrap_p = Tegra::Texture::WrapMode::ClampToEdge;
+ bool uses_depth_compare = false;
+ Tegra::Texture::DepthCompareFunc depth_compare_func =
+ Tegra::Texture::DepthCompareFunc::Always;
+ GLvec4 border_color = {};
+ float min_lod = 0.0f;
+ float max_lod = 16.0f;
+ float lod_bias = 0.0f;
+ float max_anisotropic = 1.0f;
};
/**
@@ -109,8 +114,8 @@ private:
* @param preserve_contents If true, tries to preserve data from a previously used framebuffer.
* @param single_color_target Specifies if a single color buffer target should be used.
*/
- void ConfigureFramebuffers(bool use_color_fb = true, bool using_depth_fb = true,
- bool preserve_contents = true,
+ void ConfigureFramebuffers(OpenGLState& current_state, bool use_color_fb = true,
+ bool using_depth_fb = true, bool preserve_contents = true,
std::optional<std::size_t> single_color_target = {});
/*
@@ -133,8 +138,8 @@ private:
u32 SetupTextures(Tegra::Engines::Maxwell3D::Regs::ShaderStage stage, Shader& shader,
GLenum primitive_mode, u32 current_unit);
- /// Syncs the viewport to match the guest state
- void SyncViewport();
+ /// Syncs the viewport and depth range to match the guest state
+ void SyncViewport(OpenGLState& current_state);
/// Syncs the clip enabled status to match the guest state
void SyncClipEnabled();
@@ -148,9 +153,6 @@ private:
/// Syncs the primitve restart to match the guest state
void SyncPrimitiveRestart();
- /// Syncs the depth range to match the guest state
- void SyncDepthRange();
-
/// Syncs the depth test state to match the guest state
void SyncDepthTestState();
@@ -163,8 +165,14 @@ private:
/// Syncs the LogicOp state to match the guest state
void SyncLogicOpState();
+ /// Syncs the the color clamp state
+ void SyncFragmentColorClampState();
+
+ /// Syncs the alpha coverage and alpha to one
+ void SyncMultiSampleState();
+
/// Syncs the scissor test state to match the guest state
- void SyncScissorTest();
+ void SyncScissorTest(OpenGLState& current_state);
/// Syncs the transform feedback state to match the guest state
void SyncTransformFeedback();
@@ -172,13 +180,14 @@ private:
/// Syncs the point state to match the guest state
void SyncPointState();
+ /// Syncs Color Mask
+ void SyncColorMask();
+
/// Check asserts for alpha testing.
void CheckAlphaTests();
bool has_ARB_direct_state_access = false;
bool has_ARB_multi_bind = false;
- bool has_ARB_separate_shader_objects = false;
- bool has_ARB_vertex_attrib_binding = false;
OpenGLState state;
@@ -207,7 +216,8 @@ private:
std::size_t CalculateIndexBufferSize() const;
- void SetupVertexArrays();
+ void SetupVertexFormat();
+ void SetupVertexBuffer();
DrawParameters SetupDraw();
diff --git a/src/video_core/renderer_opengl/gl_rasterizer_cache.cpp b/src/video_core/renderer_opengl/gl_rasterizer_cache.cpp
index f194a7687..4f434fc31 100644
--- a/src/video_core/renderer_opengl/gl_rasterizer_cache.cpp
+++ b/src/video_core/renderer_opengl/gl_rasterizer_cache.cpp
@@ -15,7 +15,9 @@
#include "core/memory.h"
#include "core/settings.h"
#include "video_core/engines/maxwell_3d.h"
+#include "video_core/renderer_opengl/gl_rasterizer.h"
#include "video_core/renderer_opengl/gl_rasterizer_cache.h"
+#include "video_core/renderer_opengl/gl_state.h"
#include "video_core/renderer_opengl/utils.h"
#include "video_core/surface.h"
#include "video_core/textures/astc.h"
@@ -58,16 +60,14 @@ void SurfaceParams::InitCacheParameters(Tegra::GPUVAddr gpu_addr_) {
std::size_t SurfaceParams::InnerMipmapMemorySize(u32 mip_level, bool force_gl, bool layer_only,
bool uncompressed) const {
- const u32 compression_factor{GetCompressionFactor(pixel_format)};
+ const u32 tile_x{GetDefaultBlockWidth(pixel_format)};
+ const u32 tile_y{GetDefaultBlockHeight(pixel_format)};
const u32 bytes_per_pixel{GetBytesPerPixel(pixel_format)};
u32 m_depth = (layer_only ? 1U : depth);
u32 m_width = MipWidth(mip_level);
u32 m_height = MipHeight(mip_level);
- m_width = uncompressed ? m_width
- : std::max(1U, (m_width + compression_factor - 1) / compression_factor);
- m_height = uncompressed
- ? m_height
- : std::max(1U, (m_height + compression_factor - 1) / compression_factor);
+ m_width = uncompressed ? m_width : std::max(1U, (m_width + tile_x - 1) / tile_x);
+ m_height = uncompressed ? m_height : std::max(1U, (m_height + tile_y - 1) / tile_y);
m_depth = std::max(1U, m_depth >> mip_level);
u32 m_block_height = MipBlockHeight(mip_level);
u32 m_block_depth = MipBlockDepth(mip_level);
@@ -128,6 +128,13 @@ std::size_t SurfaceParams::InnerMemorySize(bool force_gl, bool layer_only,
params.target = SurfaceTarget::Texture2D;
}
break;
+ case SurfaceTarget::TextureCubeArray:
+ params.depth = config.tic.Depth() * 6;
+ if (!entry.IsArray()) {
+ ASSERT(params.depth == 6);
+ params.target = SurfaceTarget::TextureCubemap;
+ }
+ break;
default:
LOG_CRITICAL(HW_GPU, "Unknown depth for target={}", static_cast<u32>(params.target));
UNREACHABLE();
@@ -258,11 +265,11 @@ static constexpr std::array<FormatTuple, VideoCore::Surface::MaxPixelFormat> tex
{GL_COMPRESSED_RG_RGTC2, GL_RG, GL_UNSIGNED_INT_8_8_8_8, ComponentType::UNorm,
true}, // DXN2UNORM
{GL_COMPRESSED_SIGNED_RG_RGTC2, GL_RG, GL_INT, ComponentType::SNorm, true}, // DXN2SNORM
- {GL_COMPRESSED_RGBA_BPTC_UNORM_ARB, GL_RGBA, GL_UNSIGNED_INT_8_8_8_8, ComponentType::UNorm,
+ {GL_COMPRESSED_RGBA_BPTC_UNORM, GL_RGBA, GL_UNSIGNED_INT_8_8_8_8, ComponentType::UNorm,
true}, // BC7U
- {GL_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_ARB, GL_RGB, GL_UNSIGNED_INT_8_8_8_8,
- ComponentType::Float, true}, // BC6H_UF16
- {GL_COMPRESSED_RGB_BPTC_SIGNED_FLOAT_ARB, GL_RGB, GL_UNSIGNED_INT_8_8_8_8, ComponentType::Float,
+ {GL_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT, GL_RGB, GL_UNSIGNED_INT_8_8_8_8, ComponentType::Float,
+ true}, // BC6H_UF16
+ {GL_COMPRESSED_RGB_BPTC_SIGNED_FLOAT, GL_RGB, GL_UNSIGNED_INT_8_8_8_8, ComponentType::Float,
true}, // BC6H_SF16
{GL_RGBA8, GL_RGBA, GL_UNSIGNED_BYTE, ComponentType::UNorm, false}, // ASTC_2D_4X4
{GL_RG8, GL_RG, GL_UNSIGNED_BYTE, ComponentType::UNorm, false}, // G8R8U
@@ -299,12 +306,16 @@ static constexpr std::array<FormatTuple, VideoCore::Surface::MaxPixelFormat> tex
true}, // DXT23_SRGB
{GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT, GL_RGBA, GL_UNSIGNED_INT_8_8_8_8, ComponentType::UNorm,
true}, // DXT45_SRGB
- {GL_COMPRESSED_SRGB_ALPHA_BPTC_UNORM_ARB, GL_RGBA, GL_UNSIGNED_INT_8_8_8_8,
- ComponentType::UNorm, true}, // BC7U_SRGB
+ {GL_COMPRESSED_SRGB_ALPHA_BPTC_UNORM, GL_RGBA, GL_UNSIGNED_INT_8_8_8_8, ComponentType::UNorm,
+ true}, // BC7U_SRGB
{GL_SRGB8_ALPHA8, GL_RGBA, GL_UNSIGNED_BYTE, ComponentType::UNorm, false}, // ASTC_2D_4X4_SRGB
{GL_SRGB8_ALPHA8, GL_RGBA, GL_UNSIGNED_BYTE, ComponentType::UNorm, false}, // ASTC_2D_8X8_SRGB
{GL_SRGB8_ALPHA8, GL_RGBA, GL_UNSIGNED_BYTE, ComponentType::UNorm, false}, // ASTC_2D_8X5_SRGB
{GL_SRGB8_ALPHA8, GL_RGBA, GL_UNSIGNED_BYTE, ComponentType::UNorm, false}, // ASTC_2D_5X4_SRGB
+ {GL_RGBA8, GL_RGBA, GL_UNSIGNED_BYTE, ComponentType::UNorm, false}, // ASTC_2D_5X5
+ {GL_SRGB8_ALPHA8, GL_RGBA, GL_UNSIGNED_BYTE, ComponentType::UNorm, false}, // ASTC_2D_5X5_SRGB
+ {GL_RGBA8, GL_RGBA, GL_UNSIGNED_BYTE, ComponentType::UNorm, false}, // ASTC_2D_10X8
+ {GL_SRGB8_ALPHA8, GL_RGBA, GL_UNSIGNED_BYTE, ComponentType::UNorm, false}, // ASTC_2D_10X8_SRGB
// Depth formats
{GL_DEPTH_COMPONENT32F, GL_DEPTH_COMPONENT, GL_FLOAT, ComponentType::Float, false}, // Z32F
@@ -334,6 +345,8 @@ static GLenum SurfaceTargetToGL(SurfaceTarget target) {
return GL_TEXTURE_2D_ARRAY;
case SurfaceTarget::TextureCubemap:
return GL_TEXTURE_CUBE_MAP;
+ case SurfaceTarget::TextureCubeArray:
+ return GL_TEXTURE_CUBE_MAP_ARRAY;
}
LOG_CRITICAL(Render_OpenGL, "Unimplemented texture target={}", static_cast<u32>(target));
UNREACHABLE();
@@ -364,15 +377,15 @@ void MortonCopy(u32 stride, u32 block_height, u32 height, u32 block_depth, u32 d
// With the BCn formats (DXT and DXN), each 4x4 tile is swizzled instead of just individual
// pixel values.
- const u32 tile_size{IsFormatBCn(format) ? 4U : 1U};
+ const u32 tile_size_x{GetDefaultBlockWidth(format)};
+ const u32 tile_size_y{GetDefaultBlockHeight(format)};
if (morton_to_gl) {
- const std::vector<u8> data = Tegra::Texture::UnswizzleTexture(
- addr, tile_size, bytes_per_pixel, stride, height, depth, block_height, block_depth);
- const std::size_t size_to_copy{std::min(gl_buffer_size, data.size())};
- memcpy(gl_buffer, data.data(), size_to_copy);
+ Tegra::Texture::UnswizzleTexture(gl_buffer, addr, tile_size_x, tile_size_y, bytes_per_pixel,
+ stride, height, depth, block_height, block_depth);
} else {
- Tegra::Texture::CopySwizzledData(stride / tile_size, height / tile_size, depth,
+ Tegra::Texture::CopySwizzledData((stride + tile_size_x - 1) / tile_size_x,
+ (height + tile_size_y - 1) / tile_size_y, depth,
bytes_per_pixel, bytes_per_pixel, Memory::GetPointer(addr),
gl_buffer, false, block_height, block_depth);
}
@@ -440,6 +453,10 @@ static constexpr GLConversionArray morton_to_gl_fns = {
MortonCopy<true, PixelFormat::ASTC_2D_8X8_SRGB>,
MortonCopy<true, PixelFormat::ASTC_2D_8X5_SRGB>,
MortonCopy<true, PixelFormat::ASTC_2D_5X4_SRGB>,
+ MortonCopy<true, PixelFormat::ASTC_2D_5X5>,
+ MortonCopy<true, PixelFormat::ASTC_2D_5X5_SRGB>,
+ MortonCopy<true, PixelFormat::ASTC_2D_10X8>,
+ MortonCopy<true, PixelFormat::ASTC_2D_10X8_SRGB>,
MortonCopy<true, PixelFormat::Z32F>,
MortonCopy<true, PixelFormat::Z16>,
MortonCopy<true, PixelFormat::Z24S8>,
@@ -508,6 +525,10 @@ static constexpr GLConversionArray gl_to_morton_fns = {
nullptr,
nullptr,
nullptr,
+ nullptr,
+ nullptr,
+ nullptr,
+ nullptr,
MortonCopy<false, PixelFormat::Z32F>,
MortonCopy<false, PixelFormat::Z16>,
MortonCopy<false, PixelFormat::Z24S8>,
@@ -526,8 +547,8 @@ void SwizzleFunc(const GLConversionArray& functions, const SurfaceParams& params
if (params.is_layered) {
u64 offset = params.GetMipmapLevelOffset(mip_level);
u64 offset_gl = 0;
- u64 layer_size = params.LayerMemorySize();
- u64 gl_size = params.LayerSizeGL(mip_level);
+ const u64 layer_size = params.LayerMemorySize();
+ const u64 gl_size = params.LayerSizeGL(mip_level);
for (u32 i = 0; i < params.depth; i++) {
functions[static_cast<std::size_t>(params.pixel_format)](
params.MipWidth(mip_level), params.MipBlockHeight(mip_level),
@@ -537,7 +558,7 @@ void SwizzleFunc(const GLConversionArray& functions, const SurfaceParams& params
offset_gl += gl_size;
}
} else {
- u64 offset = params.GetMipmapLevelOffset(mip_level);
+ const u64 offset = params.GetMipmapLevelOffset(mip_level);
functions[static_cast<std::size_t>(params.pixel_format)](
params.MipWidth(mip_level), params.MipBlockHeight(mip_level),
params.MipHeight(mip_level), params.MipBlockDepth(mip_level), depth, gl_buffer.data(),
@@ -545,9 +566,11 @@ void SwizzleFunc(const GLConversionArray& functions, const SurfaceParams& params
}
}
+MICROPROFILE_DEFINE(OpenGL_BlitSurface, "OpenGL", "BlitSurface", MP_RGB(128, 192, 64));
static bool BlitSurface(const Surface& src_surface, const Surface& dst_surface,
GLuint read_fb_handle, GLuint draw_fb_handle, GLenum src_attachment = 0,
GLenum dst_attachment = 0, std::size_t cubemap_face = 0) {
+ MICROPROFILE_SCOPE(OpenGL_BlitSurface);
const auto& src_params{src_surface->GetSurfaceParams()};
const auto& dst_params{dst_surface->GetSurfaceParams()};
@@ -560,7 +583,7 @@ static bool BlitSurface(const Surface& src_surface, const Surface& dst_surface,
state.draw.draw_framebuffer = draw_fb_handle;
// Set sRGB enabled if the destination surfaces need it
state.framebuffer_srgb.enabled = dst_params.srgb_conversion;
- state.Apply();
+ state.ApplyFramebufferState();
u32 buffers{};
@@ -687,21 +710,23 @@ static void FastCopySurface(const Surface& src_surface, const Surface& dst_surfa
0, 0, width, height, 1);
}
+MICROPROFILE_DEFINE(OpenGL_CopySurface, "OpenGL", "CopySurface", MP_RGB(128, 192, 64));
static void CopySurface(const Surface& src_surface, const Surface& dst_surface,
- GLuint copy_pbo_handle, GLenum src_attachment = 0,
- GLenum dst_attachment = 0, std::size_t cubemap_face = 0) {
+ const GLuint copy_pbo_handle, const GLenum src_attachment = 0,
+ const GLenum dst_attachment = 0, const std::size_t cubemap_face = 0) {
+ MICROPROFILE_SCOPE(OpenGL_CopySurface);
ASSERT_MSG(dst_attachment == 0, "Unimplemented");
const auto& src_params{src_surface->GetSurfaceParams()};
const auto& dst_params{dst_surface->GetSurfaceParams()};
- auto source_format = GetFormatTuple(src_params.pixel_format, src_params.component_type);
- auto dest_format = GetFormatTuple(dst_params.pixel_format, dst_params.component_type);
+ const auto source_format = GetFormatTuple(src_params.pixel_format, src_params.component_type);
+ const auto dest_format = GetFormatTuple(dst_params.pixel_format, dst_params.component_type);
- std::size_t buffer_size = std::max(src_params.size_in_bytes, dst_params.size_in_bytes);
+ const std::size_t buffer_size = std::max(src_params.size_in_bytes, dst_params.size_in_bytes);
glBindBuffer(GL_PIXEL_PACK_BUFFER, copy_pbo_handle);
- glBufferData(GL_PIXEL_PACK_BUFFER, buffer_size, nullptr, GL_STREAM_DRAW_ARB);
+ glBufferData(GL_PIXEL_PACK_BUFFER, buffer_size, nullptr, GL_STREAM_DRAW);
if (source_format.compressed) {
glGetCompressedTextureImage(src_surface->Texture().handle, src_attachment,
static_cast<GLsizei>(src_params.size_in_bytes), nullptr);
@@ -722,13 +747,10 @@ static void CopySurface(const Surface& src_surface, const Surface& dst_surface,
LOG_DEBUG(HW_GPU, "Trying to upload extra texture data from the CPU during "
"reinterpretation but the texture is tiled.");
}
- std::size_t remaining_size = dst_params.size_in_bytes - src_params.size_in_bytes;
- std::vector<u8> data(remaining_size);
- std::memcpy(data.data(), Memory::GetPointer(dst_params.addr + src_params.size_in_bytes),
- data.size());
+ const std::size_t remaining_size = dst_params.size_in_bytes - src_params.size_in_bytes;
glBufferSubData(GL_PIXEL_PACK_BUFFER, src_params.size_in_bytes, remaining_size,
- data.data());
+ Memory::GetPointer(dst_params.addr + src_params.size_in_bytes));
}
glBindBuffer(GL_PIXEL_PACK_BUFFER, 0);
@@ -754,6 +776,7 @@ static void CopySurface(const Surface& src_surface, const Surface& dst_surface,
break;
case SurfaceTarget::Texture3D:
case SurfaceTarget::Texture2DArray:
+ case SurfaceTarget::TextureCubeArray:
glTextureSubImage3D(dst_surface->Texture().handle, 0, 0, 0, 0, width, height,
static_cast<GLsizei>(dst_params.depth), dest_format.format,
dest_format.type, nullptr);
@@ -806,6 +829,7 @@ CachedSurface::CachedSurface(const SurfaceParams& params)
break;
case SurfaceTarget::Texture3D:
case SurfaceTarget::Texture2DArray:
+ case SurfaceTarget::TextureCubeArray:
glTexStorage3D(SurfaceTargetToGL(params.target), params.max_mip_level,
format_tuple.internal_format, rect.GetWidth(), rect.GetHeight(),
params.depth);
@@ -897,21 +921,26 @@ static void ConvertG8R8ToR8G8(std::vector<u8>& data, u32 width, u32 height) {
* typical desktop GPUs.
*/
static void ConvertFormatAsNeeded_LoadGLBuffer(std::vector<u8>& data, PixelFormat pixel_format,
- u32 width, u32 height) {
+ u32 width, u32 height, u32 depth) {
switch (pixel_format) {
case PixelFormat::ASTC_2D_4X4:
case PixelFormat::ASTC_2D_8X8:
case PixelFormat::ASTC_2D_8X5:
case PixelFormat::ASTC_2D_5X4:
+ case PixelFormat::ASTC_2D_5X5:
case PixelFormat::ASTC_2D_4X4_SRGB:
case PixelFormat::ASTC_2D_8X8_SRGB:
case PixelFormat::ASTC_2D_8X5_SRGB:
- case PixelFormat::ASTC_2D_5X4_SRGB: {
+ case PixelFormat::ASTC_2D_5X4_SRGB:
+ case PixelFormat::ASTC_2D_5X5_SRGB:
+ case PixelFormat::ASTC_2D_10X8:
+ case PixelFormat::ASTC_2D_10X8_SRGB: {
// Convert ASTC pixel formats to RGBA8, as most desktop GPUs do not support ASTC.
u32 block_width{};
u32 block_height{};
std::tie(block_width, block_height) = GetASTCBlockSize(pixel_format);
- data = Tegra::Texture::ASTC::Decompress(data, width, height, block_width, block_height);
+ data =
+ Tegra::Texture::ASTC::Decompress(data, width, height, depth, block_width, block_height);
break;
}
case PixelFormat::S8Z24:
@@ -940,7 +969,11 @@ static void ConvertFormatAsNeeded_FlushGLBuffer(std::vector<u8>& data, PixelForm
case PixelFormat::ASTC_2D_4X4:
case PixelFormat::ASTC_2D_8X8:
case PixelFormat::ASTC_2D_4X4_SRGB:
- case PixelFormat::ASTC_2D_8X8_SRGB: {
+ case PixelFormat::ASTC_2D_8X8_SRGB:
+ case PixelFormat::ASTC_2D_5X5:
+ case PixelFormat::ASTC_2D_5X5_SRGB:
+ case PixelFormat::ASTC_2D_10X8:
+ case PixelFormat::ASTC_2D_10X8_SRGB: {
LOG_CRITICAL(HW_GPU, "Conversion of format {} after texture flushing is not implemented",
static_cast<u32>(pixel_format));
UNREACHABLE();
@@ -953,7 +986,7 @@ static void ConvertFormatAsNeeded_FlushGLBuffer(std::vector<u8>& data, PixelForm
}
}
-MICROPROFILE_DEFINE(OpenGL_SurfaceLoad, "OpenGL", "Surface Load", MP_RGB(128, 64, 192));
+MICROPROFILE_DEFINE(OpenGL_SurfaceLoad, "OpenGL", "Surface Load", MP_RGB(128, 192, 64));
void CachedSurface::LoadGLBuffer() {
MICROPROFILE_SCOPE(OpenGL_SurfaceLoad);
gl_buffer.resize(params.max_mip_level);
@@ -971,7 +1004,7 @@ void CachedSurface::LoadGLBuffer() {
}
for (u32 i = 0; i < params.max_mip_level; i++)
ConvertFormatAsNeeded_LoadGLBuffer(gl_buffer[i], params.pixel_format, params.MipWidth(i),
- params.MipHeight(i));
+ params.MipHeight(i), params.MipDepth(i));
}
MICROPROFILE_DEFINE(OpenGL_SurfaceFlush, "OpenGL", "Surface Flush", MP_RGB(128, 192, 64));
@@ -1055,6 +1088,7 @@ void CachedSurface::UploadGLMipmapTexture(u32 mip_map, GLuint read_fb_handle,
&gl_buffer[mip_map][buffer_offset]);
break;
case SurfaceTarget::Texture2DArray:
+ case SurfaceTarget::TextureCubeArray:
glCompressedTexImage3D(SurfaceTargetToGL(params.target), mip_map, tuple.internal_format,
static_cast<GLsizei>(params.MipWidth(mip_map)),
static_cast<GLsizei>(params.MipHeight(mip_map)),
@@ -1104,6 +1138,7 @@ void CachedSurface::UploadGLMipmapTexture(u32 mip_map, GLuint read_fb_handle,
tuple.format, tuple.type, &gl_buffer[mip_map][buffer_offset]);
break;
case SurfaceTarget::Texture2DArray:
+ case SurfaceTarget::TextureCubeArray:
glTexSubImage3D(SurfaceTargetToGL(params.target), mip_map, x0, y0, 0,
static_cast<GLsizei>(rect.GetWidth()),
static_cast<GLsizei>(rect.GetHeight()), params.depth, tuple.format,
@@ -1133,7 +1168,7 @@ void CachedSurface::UploadGLMipmapTexture(u32 mip_map, GLuint read_fb_handle,
glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
}
-MICROPROFILE_DEFINE(OpenGL_TextureUL, "OpenGL", "Texture Upload", MP_RGB(128, 64, 192));
+MICROPROFILE_DEFINE(OpenGL_TextureUL, "OpenGL", "Texture Upload", MP_RGB(128, 192, 64));
void CachedSurface::UploadGLTexture(GLuint read_fb_handle, GLuint draw_fb_handle) {
if (params.type == SurfaceType::Fill)
return;
@@ -1144,7 +1179,8 @@ void CachedSurface::UploadGLTexture(GLuint read_fb_handle, GLuint draw_fb_handle
UploadGLMipmapTexture(i, read_fb_handle, draw_fb_handle);
}
-RasterizerCacheOpenGL::RasterizerCacheOpenGL() {
+RasterizerCacheOpenGL::RasterizerCacheOpenGL(RasterizerOpenGL& rasterizer)
+ : RasterizerCache{rasterizer} {
read_framebuffer.Create();
draw_framebuffer.Create();
copy_pbo.Create();
@@ -1239,6 +1275,31 @@ Surface RasterizerCacheOpenGL::GetUncachedSurface(const SurfaceParams& params) {
return surface;
}
+void RasterizerCacheOpenGL::FastLayeredCopySurface(const Surface& src_surface,
+ const Surface& dst_surface) {
+ const auto& init_params{src_surface->GetSurfaceParams()};
+ const auto& dst_params{dst_surface->GetSurfaceParams()};
+ VAddr address = init_params.addr;
+ const std::size_t layer_size = dst_params.LayerMemorySize();
+ for (u32 layer = 0; layer < dst_params.depth; layer++) {
+ for (u32 mipmap = 0; mipmap < dst_params.max_mip_level; mipmap++) {
+ const VAddr sub_address = address + dst_params.GetMipmapLevelOffset(mipmap);
+ const Surface& copy = TryGet(sub_address);
+ if (!copy)
+ continue;
+ const auto& src_params{copy->GetSurfaceParams()};
+ const u32 width{std::min(src_params.width, dst_params.MipWidth(mipmap))};
+ const u32 height{std::min(src_params.height, dst_params.MipHeight(mipmap))};
+
+ glCopyImageSubData(copy->Texture().handle, SurfaceTargetToGL(src_params.target), 0, 0,
+ 0, 0, dst_surface->Texture().handle,
+ SurfaceTargetToGL(dst_params.target), mipmap, 0, 0, layer, width,
+ height, 1);
+ }
+ address += layer_size;
+ }
+}
+
void RasterizerCacheOpenGL::FermiCopySurface(
const Tegra::Engines::Fermi2D::Regs::Surface& src_config,
const Tegra::Engines::Fermi2D::Regs::Surface& dst_config) {
@@ -1304,10 +1365,14 @@ Surface RasterizerCacheOpenGL::RecreateSurface(const Surface& old_surface,
CopySurface(old_surface, new_surface, copy_pbo.handle);
}
break;
- case SurfaceTarget::TextureCubemap:
case SurfaceTarget::Texture3D:
AccurateCopySurface(old_surface, new_surface);
break;
+ case SurfaceTarget::TextureCubemap:
+ case SurfaceTarget::Texture2DArray:
+ case SurfaceTarget::TextureCubeArray:
+ FastLayeredCopySurface(old_surface, new_surface);
+ break;
default:
LOG_CRITICAL(Render_OpenGL, "Unimplemented surface target={}",
static_cast<u32>(new_params.target));
diff --git a/src/video_core/renderer_opengl/gl_rasterizer_cache.h b/src/video_core/renderer_opengl/gl_rasterizer_cache.h
index f255f4419..9ac79c5a4 100644
--- a/src/video_core/renderer_opengl/gl_rasterizer_cache.h
+++ b/src/video_core/renderer_opengl/gl_rasterizer_cache.h
@@ -49,6 +49,8 @@ struct SurfaceParams {
return "Texture2DArray";
case SurfaceTarget::TextureCubemap:
return "TextureCubemap";
+ case SurfaceTarget::TextureCubeArray:
+ return "TextureCubeArray";
default:
LOG_CRITICAL(HW_GPU, "Unimplemented surface_target={}", static_cast<u32>(target));
UNREACHABLE();
@@ -139,7 +141,7 @@ struct SurfaceParams {
}
u32 MipDepth(u32 mip_level) const {
- return std::max(1U, depth >> mip_level);
+ return is_layered ? depth : std::max(1U, depth >> mip_level);
}
// Auto block resizing algorithm from:
@@ -262,6 +264,8 @@ struct hash<SurfaceReserveKey> {
namespace OpenGL {
+class RasterizerOpenGL;
+
class CachedSurface final : public RasterizerCacheObject {
public:
CachedSurface(const SurfaceParams& params);
@@ -309,7 +313,7 @@ private:
class RasterizerCacheOpenGL final : public RasterizerCache<Surface> {
public:
- RasterizerCacheOpenGL();
+ explicit RasterizerCacheOpenGL(RasterizerOpenGL& rasterizer);
/// Get a surface based on the texture configuration
Surface GetTextureSurface(const Tegra::Texture::FullTextureInfo& config,
@@ -346,6 +350,7 @@ private:
/// Performs a slow but accurate surface copy, flushing to RAM and reinterpreting the data
void AccurateCopySurface(const Surface& src_surface, const Surface& dst_surface);
+ void FastLayeredCopySurface(const Surface& src_surface, const Surface& dst_surface);
/// The surface reserve is a "backup" cache, this is where we put unique surfaces that have
/// previously been used. This is to prevent surfaces from being constantly created and
diff --git a/src/video_core/renderer_opengl/gl_resource_manager.cpp b/src/video_core/renderer_opengl/gl_resource_manager.cpp
new file mode 100644
index 000000000..c17d5ac00
--- /dev/null
+++ b/src/video_core/renderer_opengl/gl_resource_manager.cpp
@@ -0,0 +1,186 @@
+// Copyright 2015 Citra Emulator Project
+// Licensed under GPLv2 or any later version
+// Refer to the license.txt file included.
+
+#include <utility>
+#include <glad/glad.h>
+#include "common/common_types.h"
+#include "common/microprofile.h"
+#include "video_core/renderer_opengl/gl_resource_manager.h"
+#include "video_core/renderer_opengl/gl_shader_util.h"
+#include "video_core/renderer_opengl/gl_state.h"
+
+MICROPROFILE_DEFINE(OpenGL_ResourceCreation, "OpenGL", "Resource Creation", MP_RGB(128, 128, 192));
+MICROPROFILE_DEFINE(OpenGL_ResourceDeletion, "OpenGL", "Resource Deletion", MP_RGB(128, 128, 192));
+
+namespace OpenGL {
+
+void OGLTexture::Create() {
+ if (handle != 0)
+ return;
+
+ MICROPROFILE_SCOPE(OpenGL_ResourceCreation);
+ glGenTextures(1, &handle);
+}
+
+void OGLTexture::Release() {
+ if (handle == 0)
+ return;
+
+ MICROPROFILE_SCOPE(OpenGL_ResourceDeletion);
+ glDeleteTextures(1, &handle);
+ OpenGLState::GetCurState().UnbindTexture(handle).Apply();
+ handle = 0;
+}
+
+void OGLSampler::Create() {
+ if (handle != 0)
+ return;
+
+ MICROPROFILE_SCOPE(OpenGL_ResourceCreation);
+ glGenSamplers(1, &handle);
+}
+
+void OGLSampler::Release() {
+ if (handle == 0)
+ return;
+
+ MICROPROFILE_SCOPE(OpenGL_ResourceDeletion);
+ glDeleteSamplers(1, &handle);
+ OpenGLState::GetCurState().ResetSampler(handle).Apply();
+ handle = 0;
+}
+
+void OGLShader::Create(const char* source, GLenum type) {
+ if (handle != 0)
+ return;
+ if (source == nullptr)
+ return;
+
+ MICROPROFILE_SCOPE(OpenGL_ResourceCreation);
+ handle = GLShader::LoadShader(source, type);
+}
+
+void OGLShader::Release() {
+ if (handle == 0)
+ return;
+
+ MICROPROFILE_SCOPE(OpenGL_ResourceDeletion);
+ glDeleteShader(handle);
+ handle = 0;
+}
+
+void OGLProgram::CreateFromSource(const char* vert_shader, const char* geo_shader,
+ const char* frag_shader, bool separable_program) {
+ OGLShader vert, geo, frag;
+ if (vert_shader)
+ vert.Create(vert_shader, GL_VERTEX_SHADER);
+ if (geo_shader)
+ geo.Create(geo_shader, GL_GEOMETRY_SHADER);
+ if (frag_shader)
+ frag.Create(frag_shader, GL_FRAGMENT_SHADER);
+
+ MICROPROFILE_SCOPE(OpenGL_ResourceCreation);
+ Create(separable_program, vert.handle, geo.handle, frag.handle);
+}
+
+void OGLProgram::Release() {
+ if (handle == 0)
+ return;
+
+ MICROPROFILE_SCOPE(OpenGL_ResourceDeletion);
+ glDeleteProgram(handle);
+ OpenGLState::GetCurState().ResetProgram(handle).Apply();
+ handle = 0;
+}
+
+void OGLPipeline::Create() {
+ if (handle != 0)
+ return;
+
+ MICROPROFILE_SCOPE(OpenGL_ResourceCreation);
+ glGenProgramPipelines(1, &handle);
+}
+
+void OGLPipeline::Release() {
+ if (handle == 0)
+ return;
+
+ MICROPROFILE_SCOPE(OpenGL_ResourceDeletion);
+ glDeleteProgramPipelines(1, &handle);
+ OpenGLState::GetCurState().ResetPipeline(handle).Apply();
+ handle = 0;
+}
+
+void OGLBuffer::Create() {
+ if (handle != 0)
+ return;
+
+ MICROPROFILE_SCOPE(OpenGL_ResourceCreation);
+ glGenBuffers(1, &handle);
+}
+
+void OGLBuffer::Release() {
+ if (handle == 0)
+ return;
+
+ MICROPROFILE_SCOPE(OpenGL_ResourceDeletion);
+ glDeleteBuffers(1, &handle);
+ OpenGLState::GetCurState().ResetBuffer(handle).Apply();
+ handle = 0;
+}
+
+void OGLSync::Create() {
+ if (handle != 0)
+ return;
+
+ // Don't profile here, this one is expected to happen ingame.
+ handle = glFenceSync(GL_SYNC_GPU_COMMANDS_COMPLETE, 0);
+}
+
+void OGLSync::Release() {
+ if (handle == 0)
+ return;
+
+ // Don't profile here, this one is expected to happen ingame.
+ glDeleteSync(handle);
+ handle = 0;
+}
+
+void OGLVertexArray::Create() {
+ if (handle != 0)
+ return;
+
+ MICROPROFILE_SCOPE(OpenGL_ResourceCreation);
+ glGenVertexArrays(1, &handle);
+}
+
+void OGLVertexArray::Release() {
+ if (handle == 0)
+ return;
+
+ MICROPROFILE_SCOPE(OpenGL_ResourceDeletion);
+ glDeleteVertexArrays(1, &handle);
+ OpenGLState::GetCurState().ResetVertexArray(handle).Apply();
+ handle = 0;
+}
+
+void OGLFramebuffer::Create() {
+ if (handle != 0)
+ return;
+
+ MICROPROFILE_SCOPE(OpenGL_ResourceCreation);
+ glGenFramebuffers(1, &handle);
+}
+
+void OGLFramebuffer::Release() {
+ if (handle == 0)
+ return;
+
+ MICROPROFILE_SCOPE(OpenGL_ResourceDeletion);
+ glDeleteFramebuffers(1, &handle);
+ OpenGLState::GetCurState().ResetFramebuffer(handle).Apply();
+ handle = 0;
+}
+
+} // namespace OpenGL
diff --git a/src/video_core/renderer_opengl/gl_resource_manager.h b/src/video_core/renderer_opengl/gl_resource_manager.h
index 3bc1b83b5..e33f1e973 100644
--- a/src/video_core/renderer_opengl/gl_resource_manager.h
+++ b/src/video_core/renderer_opengl/gl_resource_manager.h
@@ -8,7 +8,6 @@
#include <glad/glad.h>
#include "common/common_types.h"
#include "video_core/renderer_opengl/gl_shader_util.h"
-#include "video_core/renderer_opengl/gl_state.h"
namespace OpenGL {
@@ -29,20 +28,10 @@ public:
}
/// Creates a new internal OpenGL resource and stores the handle
- void Create() {
- if (handle != 0)
- return;
- glGenTextures(1, &handle);
- }
+ void Create();
/// Deletes the internal OpenGL resource
- void Release() {
- if (handle == 0)
- return;
- glDeleteTextures(1, &handle);
- OpenGLState::GetCurState().UnbindTexture(handle).Apply();
- handle = 0;
- }
+ void Release();
GLuint handle = 0;
};
@@ -64,20 +53,10 @@ public:
}
/// Creates a new internal OpenGL resource and stores the handle
- void Create() {
- if (handle != 0)
- return;
- glGenSamplers(1, &handle);
- }
+ void Create();
/// Deletes the internal OpenGL resource
- void Release() {
- if (handle == 0)
- return;
- glDeleteSamplers(1, &handle);
- OpenGLState::GetCurState().ResetSampler(handle).Apply();
- handle = 0;
- }
+ void Release();
GLuint handle = 0;
};
@@ -98,20 +77,9 @@ public:
return *this;
}
- void Create(const char* source, GLenum type) {
- if (handle != 0)
- return;
- if (source == nullptr)
- return;
- handle = GLShader::LoadShader(source, type);
- }
+ void Create(const char* source, GLenum type);
- void Release() {
- if (handle == 0)
- return;
- glDeleteShader(handle);
- handle = 0;
- }
+ void Release();
GLuint handle = 0;
};
@@ -141,25 +109,10 @@ public:
/// Creates a new internal OpenGL resource and stores the handle
void CreateFromSource(const char* vert_shader, const char* geo_shader, const char* frag_shader,
- bool separable_program = false) {
- OGLShader vert, geo, frag;
- if (vert_shader)
- vert.Create(vert_shader, GL_VERTEX_SHADER);
- if (geo_shader)
- geo.Create(geo_shader, GL_GEOMETRY_SHADER);
- if (frag_shader)
- frag.Create(frag_shader, GL_FRAGMENT_SHADER);
- Create(separable_program, vert.handle, geo.handle, frag.handle);
- }
+ bool separable_program = false);
/// Deletes the internal OpenGL resource
- void Release() {
- if (handle == 0)
- return;
- glDeleteProgram(handle);
- OpenGLState::GetCurState().ResetProgram(handle).Apply();
- handle = 0;
- }
+ void Release();
GLuint handle = 0;
};
@@ -178,20 +131,10 @@ public:
}
/// Creates a new internal OpenGL resource and stores the handle
- void Create() {
- if (handle != 0)
- return;
- glGenProgramPipelines(1, &handle);
- }
+ void Create();
/// Deletes the internal OpenGL resource
- void Release() {
- if (handle == 0)
- return;
- glDeleteProgramPipelines(1, &handle);
- OpenGLState::GetCurState().ResetPipeline(handle).Apply();
- handle = 0;
- }
+ void Release();
GLuint handle = 0;
};
@@ -213,20 +156,10 @@ public:
}
/// Creates a new internal OpenGL resource and stores the handle
- void Create() {
- if (handle != 0)
- return;
- glGenBuffers(1, &handle);
- }
+ void Create();
/// Deletes the internal OpenGL resource
- void Release() {
- if (handle == 0)
- return;
- glDeleteBuffers(1, &handle);
- OpenGLState::GetCurState().ResetBuffer(handle).Apply();
- handle = 0;
- }
+ void Release();
GLuint handle = 0;
};
@@ -247,19 +180,10 @@ public:
}
/// Creates a new internal OpenGL resource and stores the handle
- void Create() {
- if (handle != 0)
- return;
- handle = glFenceSync(GL_SYNC_GPU_COMMANDS_COMPLETE, 0);
- }
+ void Create();
/// Deletes the internal OpenGL resource
- void Release() {
- if (handle == 0)
- return;
- glDeleteSync(handle);
- handle = 0;
- }
+ void Release();
GLsync handle = 0;
};
@@ -281,20 +205,10 @@ public:
}
/// Creates a new internal OpenGL resource and stores the handle
- void Create() {
- if (handle != 0)
- return;
- glGenVertexArrays(1, &handle);
- }
+ void Create();
/// Deletes the internal OpenGL resource
- void Release() {
- if (handle == 0)
- return;
- glDeleteVertexArrays(1, &handle);
- OpenGLState::GetCurState().ResetVertexArray(handle).Apply();
- handle = 0;
- }
+ void Release();
GLuint handle = 0;
};
@@ -316,20 +230,10 @@ public:
}
/// Creates a new internal OpenGL resource and stores the handle
- void Create() {
- if (handle != 0)
- return;
- glGenFramebuffers(1, &handle);
- }
+ void Create();
/// Deletes the internal OpenGL resource
- void Release() {
- if (handle == 0)
- return;
- glDeleteFramebuffers(1, &handle);
- OpenGLState::GetCurState().ResetFramebuffer(handle).Apply();
- handle = 0;
- }
+ void Release();
GLuint handle = 0;
};
diff --git a/src/video_core/renderer_opengl/gl_shader_cache.cpp b/src/video_core/renderer_opengl/gl_shader_cache.cpp
index 9522fd344..038b25c75 100644
--- a/src/video_core/renderer_opengl/gl_shader_cache.cpp
+++ b/src/video_core/renderer_opengl/gl_shader_cache.cpp
@@ -6,10 +6,10 @@
#include "core/core.h"
#include "core/memory.h"
#include "video_core/engines/maxwell_3d.h"
+#include "video_core/renderer_opengl/gl_rasterizer.h"
#include "video_core/renderer_opengl/gl_shader_cache.h"
#include "video_core/renderer_opengl/gl_shader_manager.h"
#include "video_core/renderer_opengl/utils.h"
-#include "video_core/utils.h"
namespace OpenGL {
@@ -84,6 +84,7 @@ CachedShader::CachedShader(VAddr addr, Maxwell::ShaderProgram program_type)
}
entries = program_result.second;
+ shader_length = entries.shader_length;
if (program_type != Maxwell::ShaderProgram::Geometry) {
OGLShader shader;
@@ -121,12 +122,16 @@ GLint CachedShader::GetUniformLocation(const GLShader::SamplerEntry& sampler) {
}
GLuint CachedShader::LazyGeometryProgram(OGLProgram& target_program,
- const std::string& glsl_topology,
+ const std::string& glsl_topology, u32 max_vertices,
const std::string& debug_name) {
if (target_program.handle != 0) {
return target_program.handle;
}
- const std::string source{geometry_programs.code + "layout (" + glsl_topology + ") in;\n"};
+ std::string source = "#version 430 core\n";
+ source += "layout (" + glsl_topology + ") in;\n";
+ source += "#define MAX_VERTEX_INPUT " + std::to_string(max_vertices) + '\n';
+ source += geometry_programs.code;
+
OGLShader shader;
shader.Create(source.c_str(), GL_GEOMETRY_SHADER);
target_program.Create(true, shader.handle);
@@ -135,6 +140,8 @@ GLuint CachedShader::LazyGeometryProgram(OGLProgram& target_program,
return target_program.handle;
};
+ShaderCacheOpenGL::ShaderCacheOpenGL(RasterizerOpenGL& rasterizer) : RasterizerCache{rasterizer} {}
+
Shader ShaderCacheOpenGL::GetStageProgram(Maxwell::ShaderProgram program) {
const VAddr program_addr{GetShaderAddress(program)};
diff --git a/src/video_core/renderer_opengl/gl_shader_cache.h b/src/video_core/renderer_opengl/gl_shader_cache.h
index a210f1731..08f470de3 100644
--- a/src/video_core/renderer_opengl/gl_shader_cache.h
+++ b/src/video_core/renderer_opengl/gl_shader_cache.h
@@ -16,6 +16,8 @@
namespace OpenGL {
class CachedShader;
+class RasterizerOpenGL;
+
using Shader = std::shared_ptr<CachedShader>;
using Maxwell = Tegra::Engines::Maxwell3D::Regs;
@@ -28,7 +30,7 @@ public:
}
std::size_t GetSizeInBytes() const override {
- return GLShader::MAX_PROGRAM_CODE_LENGTH * sizeof(u64);
+ return shader_length;
}
// We do not have to flush this cache as things in it are never modified by us.
@@ -46,22 +48,23 @@ public:
}
switch (primitive_mode) {
case GL_POINTS:
- return LazyGeometryProgram(geometry_programs.points, "points", "ShaderPoints");
+ return LazyGeometryProgram(geometry_programs.points, "points", 1, "ShaderPoints");
case GL_LINES:
case GL_LINE_STRIP:
- return LazyGeometryProgram(geometry_programs.lines, "lines", "ShaderLines");
+ return LazyGeometryProgram(geometry_programs.lines, "lines", 2, "ShaderLines");
case GL_LINES_ADJACENCY:
case GL_LINE_STRIP_ADJACENCY:
- return LazyGeometryProgram(geometry_programs.lines_adjacency, "lines_adjacency",
+ return LazyGeometryProgram(geometry_programs.lines_adjacency, "lines_adjacency", 4,
"ShaderLinesAdjacency");
case GL_TRIANGLES:
case GL_TRIANGLE_STRIP:
case GL_TRIANGLE_FAN:
- return LazyGeometryProgram(geometry_programs.triangles, "triangles", "ShaderTriangles");
+ return LazyGeometryProgram(geometry_programs.triangles, "triangles", 3,
+ "ShaderTriangles");
case GL_TRIANGLES_ADJACENCY:
case GL_TRIANGLE_STRIP_ADJACENCY:
return LazyGeometryProgram(geometry_programs.triangles_adjacency, "triangles_adjacency",
- "ShaderLines");
+ 6, "ShaderTrianglesAdjacency");
default:
UNREACHABLE_MSG("Unknown primitive mode.");
}
@@ -76,9 +79,10 @@ public:
private:
/// Generates a geometry shader or returns one that already exists.
GLuint LazyGeometryProgram(OGLProgram& target_program, const std::string& glsl_topology,
- const std::string& debug_name);
+ u32 max_vertices, const std::string& debug_name);
VAddr addr;
+ std::size_t shader_length;
Maxwell::ShaderProgram program_type;
GLShader::ShaderSetup setup;
GLShader::ShaderEntries entries;
@@ -104,6 +108,8 @@ private:
class ShaderCacheOpenGL final : public RasterizerCache<Shader> {
public:
+ explicit ShaderCacheOpenGL(RasterizerOpenGL& rasterizer);
+
/// Gets the current specified shader stage program
Shader GetStageProgram(Maxwell::ShaderProgram program);
};
diff --git a/src/video_core/renderer_opengl/gl_shader_decompiler.cpp b/src/video_core/renderer_opengl/gl_shader_decompiler.cpp
index 09b003c59..97b9028c5 100644
--- a/src/video_core/renderer_opengl/gl_shader_decompiler.cpp
+++ b/src/video_core/renderer_opengl/gl_shader_decompiler.cpp
@@ -34,6 +34,17 @@ constexpr u32 PROGRAM_HEADER_SIZE = sizeof(Tegra::Shader::Header);
constexpr u32 MAX_GEOMETRY_BUFFERS = 6;
constexpr u32 MAX_ATTRIBUTES = 0x100; // Size in vec4s, this value is untested
+static const char* INTERNAL_FLAG_NAMES[] = {"zero_flag", "sign_flag", "carry_flag",
+ "overflow_flag"};
+
+enum class InternalFlag : u64 {
+ ZeroFlag = 0,
+ SignFlag = 1,
+ CarryFlag = 2,
+ OverflowFlag = 3,
+ Amount
+};
+
class DecompileFail : public std::runtime_error {
public:
using std::runtime_error::runtime_error;
@@ -49,8 +60,7 @@ static std::string GetTopologyName(Tegra::Shader::OutputTopology topology) {
case Tegra::Shader::OutputTopology::TriangleStrip:
return "triangle_strip";
default:
- LOG_CRITICAL(Render_OpenGL, "Unknown output topology {}", static_cast<u32>(topology));
- UNREACHABLE();
+ UNIMPLEMENTED_MSG("Unknown output topology: {}", static_cast<u32>(topology));
return "points";
}
}
@@ -85,7 +95,8 @@ struct Subroutine {
class ControlFlowAnalyzer {
public:
ControlFlowAnalyzer(const ProgramCode& program_code, u32 main_offset, const std::string& suffix)
- : program_code(program_code) {
+ : program_code(program_code), shader_coverage_begin(main_offset),
+ shader_coverage_end(main_offset + 1) {
// Recursively finds all subroutines.
const Subroutine& program_main = AddSubroutine(main_offset, PROGRAM_END, suffix);
@@ -97,10 +108,16 @@ public:
return std::move(subroutines);
}
+ std::size_t GetShaderLength() const {
+ return shader_coverage_end * sizeof(u64);
+ }
+
private:
const ProgramCode& program_code;
std::set<Subroutine> subroutines;
std::map<std::pair<u32, u32>, ExitMethod> exit_method_map;
+ u32 shader_coverage_begin;
+ u32 shader_coverage_end;
/// Adds and analyzes a new subroutine if it is not added yet.
const Subroutine& AddSubroutine(u32 begin, u32 end, const std::string& suffix) {
@@ -142,6 +159,9 @@ private:
return exit_method;
for (u32 offset = begin; offset != end && offset != PROGRAM_END; ++offset) {
+ shader_coverage_begin = std::min(shader_coverage_begin, offset);
+ shader_coverage_end = std::max(shader_coverage_end, offset + 1);
+
const Instruction instr = {program_code[offset]};
if (const auto opcode = OpCode::Decode(instr)) {
switch (opcode->get().GetId()) {
@@ -167,8 +187,8 @@ private:
case OpCode::Id::SSY:
case OpCode::Id::PBK: {
// The SSY and PBK use a similar encoding as the BRA instruction.
- ASSERT_MSG(instr.bra.constant_buffer == 0,
- "Constant buffer branching is not supported");
+ UNIMPLEMENTED_IF_MSG(instr.bra.constant_buffer != 0,
+ "Constant buffer branching is not supported");
const u32 target = offset + instr.bra.GetBranchTarget();
labels.insert(target);
// Continue scanning for an exit method.
@@ -258,14 +278,6 @@ private:
const std::string& suffix;
};
-enum class InternalFlag : u64 {
- ZeroFlag = 0,
- CarryFlag = 1,
- OverflowFlag = 2,
- NaNFlag = 3,
- Amount
-};
-
/**
* Used to manage shader registers that are emulated with GLSL. This class keeps track of the state
* of all registers (e.g. whether they are currently being used as Floats or Integers), and
@@ -299,8 +311,7 @@ public:
// Default - do nothing
return value;
default:
- LOG_CRITICAL(HW_GPU, "Unimplemented conversion size {}", static_cast<u32>(size));
- UNREACHABLE();
+ UNIMPLEMENTED_MSG("Unimplemented conversion size: {}", static_cast<u32>(size));
}
}
@@ -363,7 +374,7 @@ public:
u64 value_num_components, bool is_saturated = false,
u64 dest_elem = 0, Register::Size size = Register::Size::Word,
bool sets_cc = false) {
- ASSERT_MSG(!is_saturated, "Unimplemented");
+ UNIMPLEMENTED_IF(is_saturated);
const std::string func{is_signed ? "intBitsToFloat" : "uintBitsToFloat"};
@@ -373,7 +384,7 @@ public:
if (sets_cc) {
const std::string zero_condition = "( " + ConvertIntegerSize(value, size) + " == 0 )";
SetInternalFlag(InternalFlag::ZeroFlag, zero_condition);
- LOG_WARNING(HW_GPU, "Control Codes Imcomplete.");
+ LOG_WARNING(HW_GPU, "Condition codes implementation is incomplete.");
}
}
@@ -392,7 +403,7 @@ public:
Tegra::Shader::HalfMerge merge, u64 dest_num_components,
u64 value_num_components, bool is_saturated = false,
u64 dest_elem = 0) {
- ASSERT_MSG(!is_saturated, "Unimplemented");
+ UNIMPLEMENTED_IF(is_saturated);
const std::string result = [&]() {
switch (merge) {
@@ -456,24 +467,25 @@ public:
shader.AddLine("lmem[" + index + "] = " + func + '(' + value + ");");
}
- std::string GetControlCode(const Tegra::Shader::ControlCode cc) const {
+ std::string GetConditionCode(const Tegra::Shader::ConditionCode cc) const {
switch (cc) {
- case Tegra::Shader::ControlCode::NEU:
+ case Tegra::Shader::ConditionCode::NEU:
return "!(" + GetInternalFlag(InternalFlag::ZeroFlag) + ')';
default:
- LOG_CRITICAL(HW_GPU, "Unimplemented Control Code {}", static_cast<u32>(cc));
- UNREACHABLE();
+ UNIMPLEMENTED_MSG("Unimplemented condition code: {}", static_cast<u32>(cc));
return "false";
}
}
- std::string GetInternalFlag(const InternalFlag ii) const {
- const u32 code = static_cast<u32>(ii);
- return "internalFlag_" + std::to_string(code) + suffix;
+ std::string GetInternalFlag(const InternalFlag flag) const {
+ const auto index = static_cast<u32>(flag);
+ ASSERT(index < static_cast<u32>(InternalFlag::Amount));
+
+ return std::string(INTERNAL_FLAG_NAMES[index]) + '_' + suffix;
}
- void SetInternalFlag(const InternalFlag ii, const std::string& value) const {
- shader.AddLine(GetInternalFlag(ii) + " = " + value + ';');
+ void SetInternalFlag(const InternalFlag flag, const std::string& value) const {
+ shader.AddLine(GetInternalFlag(flag) + " = " + value + ';');
}
/**
@@ -494,10 +506,10 @@ public:
// instruction for now.
if (stage == Maxwell3D::Regs::ShaderStage::Geometry) {
// TODO(Rodrigo): nouveau sets some attributes after setting emitting a geometry
- // shader. These instructions use a dirty register as buffer index. To avoid some
- // drivers from complaining for the out of boundary writes, guard them.
- const std::string buf_index{"min(" + GetRegisterAsInteger(buf_reg) + ", " +
- std::to_string(MAX_GEOMETRY_BUFFERS - 1) + ')'};
+ // shader. These instructions use a dirty register as buffer index, to avoid some
+ // drivers from complaining about out of boundary writes, guard them.
+ const std::string buf_index{"((" + GetRegisterAsInteger(buf_reg) + ") % " +
+ std::to_string(MAX_GEOMETRY_BUFFERS) + ')'};
shader.AddLine("amem[" + buf_index + "][" +
std::to_string(static_cast<u32>(attribute)) + ']' +
GetSwizzle(elem) + " = " + src + ';');
@@ -624,8 +636,8 @@ private:
/// Generates declarations for internal flags.
void GenerateInternalFlags() {
- for (u32 ii = 0; ii < static_cast<u64>(InternalFlag::Amount); ii++) {
- const InternalFlag code = static_cast<InternalFlag>(ii);
+ for (u32 flag = 0; flag < static_cast<u32>(InternalFlag::Amount); flag++) {
+ const InternalFlag code = static_cast<InternalFlag>(flag);
declarations.AddLine("bool " + GetInternalFlag(code) + " = false;");
}
declarations.AddNewLine();
@@ -761,8 +773,7 @@ private:
u64 dest_num_components, u64 value_num_components, u64 dest_elem,
bool precise) {
if (reg == Register::ZeroIndex) {
- LOG_CRITICAL(HW_GPU, "Cannot set Register::ZeroIndex");
- UNREACHABLE();
+ // Setting RZ is a nop in hardware.
return;
}
@@ -811,7 +822,11 @@ private:
std::optional<Register> vertex = {}) {
auto GeometryPass = [&](const std::string& name) {
if (stage == Maxwell3D::Regs::ShaderStage::Geometry && vertex) {
- return "gs_" + name + '[' + GetRegisterAsInteger(*vertex, 0, false) + ']';
+ // TODO(Rodrigo): Guard geometry inputs against out of bound reads. Some games set
+ // an 0x80000000 index for those and the shader fails to build. Find out why this
+ // happens and what's its intent.
+ return "gs_" + name + '[' + GetRegisterAsInteger(*vertex, 0, false) +
+ " % MAX_VERTEX_INPUT]";
}
return name;
};
@@ -843,16 +858,13 @@ private:
if (declr_input_attribute.count(attribute) == 0) {
declr_input_attribute[attribute] = input_mode;
} else {
- if (declr_input_attribute[attribute] != input_mode) {
- LOG_CRITICAL(HW_GPU, "Same Input multiple input modes");
- UNREACHABLE();
- }
+ UNIMPLEMENTED_IF_MSG(declr_input_attribute[attribute] != input_mode,
+ "Multiple input modes for the same attribute");
}
return GeometryPass("input_attribute_" + std::to_string(index));
}
- LOG_CRITICAL(HW_GPU, "Unhandled input attribute: {}", static_cast<u32>(attribute));
- UNREACHABLE();
+ UNIMPLEMENTED_MSG("Unhandled input attribute: {}", static_cast<u32>(attribute));
}
return "vec4(0, 0, 0, 0)";
@@ -878,24 +890,20 @@ private:
break;
}
default: {
- LOG_CRITICAL(HW_GPU, "Unhandled Ipa InterpMode: {}", static_cast<u32>(interp_mode));
- UNREACHABLE();
+ UNIMPLEMENTED_MSG("Unhandled IPA interp mode: {}", static_cast<u32>(interp_mode));
}
}
switch (sample_mode) {
- case Tegra::Shader::IpaSampleMode::Centroid: {
- // Note not implemented, it can be implemented with the "centroid " keyword in glsl;
- LOG_CRITICAL(HW_GPU, "Ipa Sampler Mode: centroid, not implemented");
- UNREACHABLE();
+ case Tegra::Shader::IpaSampleMode::Centroid:
+ // It can be implemented with the "centroid " keyword in glsl
+ UNIMPLEMENTED_MSG("Unimplemented IPA sampler mode centroid");
break;
- }
- case Tegra::Shader::IpaSampleMode::Default: {
+ case Tegra::Shader::IpaSampleMode::Default:
// Default, n/a
break;
- }
default: {
- LOG_CRITICAL(HW_GPU, "Unhandled Ipa SampleMode: {}", static_cast<u32>(sample_mode));
- UNREACHABLE();
+ UNIMPLEMENTED_MSG("Unimplemented IPA sampler mode: {}", static_cast<u32>(sample_mode));
+ break;
}
}
return out;
@@ -916,8 +924,7 @@ private:
return "output_attribute_" + std::to_string(index);
}
- LOG_CRITICAL(HW_GPU, "Unhandled output attribute: {}", index);
- UNREACHABLE();
+ UNIMPLEMENTED_MSG("Unhandled output attribute={}", index);
return {};
}
}
@@ -947,9 +954,10 @@ private:
class GLSLGenerator {
public:
GLSLGenerator(const std::set<Subroutine>& subroutines, const ProgramCode& program_code,
- u32 main_offset, Maxwell3D::Regs::ShaderStage stage, const std::string& suffix)
+ u32 main_offset, Maxwell3D::Regs::ShaderStage stage, const std::string& suffix,
+ std::size_t shader_length)
: subroutines(subroutines), program_code(program_code), main_offset(main_offset),
- stage(stage), suffix(suffix) {
+ stage(stage), suffix(suffix), shader_length(shader_length) {
std::memcpy(&header, program_code.data(), sizeof(Tegra::Shader::Header));
local_memory_size = header.GetLocalMemorySize();
regs.SetLocalMemory(local_memory_size);
@@ -962,7 +970,7 @@ public:
/// Returns entries in the shader that are useful for external functions
ShaderEntries GetEntries() const {
- return {regs.GetConstBuffersDeclarations(), regs.GetSamplers()};
+ return {regs.GetConstBuffersDeclarations(), regs.GetSamplers(), shader_length};
}
private:
@@ -1067,19 +1075,26 @@ private:
const std::string& op_a, const std::string& op_b) const {
using Tegra::Shader::PredCondition;
static const std::unordered_map<PredCondition, const char*> PredicateComparisonStrings = {
- {PredCondition::LessThan, "<"}, {PredCondition::Equal, "=="},
- {PredCondition::LessEqual, "<="}, {PredCondition::GreaterThan, ">"},
- {PredCondition::NotEqual, "!="}, {PredCondition::GreaterEqual, ">="},
- {PredCondition::LessThanWithNan, "<"}, {PredCondition::NotEqualWithNan, "!="},
- {PredCondition::GreaterThanWithNan, ">"}, {PredCondition::GreaterEqualWithNan, ">="}};
+ {PredCondition::LessThan, "<"},
+ {PredCondition::Equal, "=="},
+ {PredCondition::LessEqual, "<="},
+ {PredCondition::GreaterThan, ">"},
+ {PredCondition::NotEqual, "!="},
+ {PredCondition::GreaterEqual, ">="},
+ {PredCondition::LessThanWithNan, "<"},
+ {PredCondition::NotEqualWithNan, "!="},
+ {PredCondition::LessEqualWithNan, "<="},
+ {PredCondition::GreaterThanWithNan, ">"},
+ {PredCondition::GreaterEqualWithNan, ">="}};
const auto& comparison{PredicateComparisonStrings.find(condition)};
- ASSERT_MSG(comparison != PredicateComparisonStrings.end(),
- "Unknown predicate comparison operation");
+ UNIMPLEMENTED_IF_MSG(comparison == PredicateComparisonStrings.end(),
+ "Unknown predicate comparison operation");
std::string predicate{'(' + op_a + ") " + comparison->second + " (" + op_b + ')'};
if (condition == PredCondition::LessThanWithNan ||
condition == PredCondition::NotEqualWithNan ||
+ condition == PredCondition::LessEqualWithNan ||
condition == PredCondition::GreaterThanWithNan ||
condition == PredCondition::GreaterEqualWithNan) {
predicate += " || isnan(" + op_a + ") || isnan(" + op_b + ')';
@@ -1103,7 +1118,7 @@ private:
};
auto op = PredicateOperationStrings.find(operation);
- ASSERT_MSG(op != PredicateOperationStrings.end(), "Unknown predicate operation");
+ UNIMPLEMENTED_IF_MSG(op == PredicateOperationStrings.end(), "Unknown predicate operation");
return op->second;
}
@@ -1201,8 +1216,7 @@ private:
break;
}
default:
- LOG_CRITICAL(HW_GPU, "Unimplemented logic operation: {}", static_cast<u32>(logic_op));
- UNREACHABLE();
+ UNIMPLEMENTED_MSG("Unimplemented logic operation={}", static_cast<u32>(logic_op));
}
if (dest != Tegra::Shader::Register::ZeroIndex) {
@@ -1220,9 +1234,8 @@ private:
SetPredicate(static_cast<u64>(predicate), '(' + result + ") != 0");
break;
default:
- LOG_CRITICAL(HW_GPU, "Unimplemented predicate result mode: {}",
- static_cast<u32>(predicate_mode));
- UNREACHABLE();
+ UNIMPLEMENTED_MSG("Unimplemented predicate result mode: {}",
+ static_cast<u32>(predicate_mode));
}
}
@@ -1253,14 +1266,7 @@ private:
regs.SetRegisterToInteger(dest, true, 0, result, 1, 1);
}
- void WriteTexsInstruction(const Instruction& instr, const std::string& coord,
- const std::string& texture) {
- // Add an extra scope and declare the texture coords inside to prevent
- // overwriting them in case they are used as outputs of the texs instruction.
- shader.AddLine('{');
- ++shader.scope;
- shader.AddLine(coord);
-
+ void WriteTexsInstruction(const Instruction& instr, const std::string& texture) {
// TEXS has two destination registers and a swizzle. The first two elements in the swizzle
// go into gpr0+0 and gpr0+1, and the rest goes into gpr28+0 and gpr28+1
@@ -1283,26 +1289,19 @@ private:
++written_components;
}
-
- --shader.scope;
- shader.AddLine('}');
}
static u32 TextureCoordinates(Tegra::Shader::TextureType texture_type) {
switch (texture_type) {
- case Tegra::Shader::TextureType::Texture1D: {
+ case Tegra::Shader::TextureType::Texture1D:
return 1;
- }
- case Tegra::Shader::TextureType::Texture2D: {
+ case Tegra::Shader::TextureType::Texture2D:
return 2;
- }
case Tegra::Shader::TextureType::Texture3D:
- case Tegra::Shader::TextureType::TextureCube: {
+ case Tegra::Shader::TextureType::TextureCube:
return 3;
- }
default:
- LOG_CRITICAL(HW_GPU, "Unhandled texture type {}", static_cast<u32>(texture_type));
- UNREACHABLE();
+ UNIMPLEMENTED_MSG("Unhandled texture type: {}", static_cast<u32>(texture_type));
return 0;
}
}
@@ -1338,7 +1337,7 @@ private:
void EmitFragmentOutputsWrite() {
ASSERT(stage == Maxwell3D::Regs::ShaderStage::Fragment);
- ASSERT_MSG(header.ps.omap.sample_mask == 0, "Samplemask write is unimplemented");
+ UNIMPLEMENTED_IF_MSG(header.ps.omap.sample_mask != 0, "Samplemask write is unimplemented");
shader.AddLine("if (alpha_test[0] != 0) {");
++shader.scope;
@@ -1404,7 +1403,7 @@ private:
case Tegra::Shader::VideoType::Size32:
// TODO(Rodrigo): From my hardware tests it becomes a bit "mad" when
// this type is used (1 * 1 + 0 == 0x5b800000). Until a better
- // explanation is found: assert.
+ // explanation is found: abort.
UNIMPLEMENTED();
return zero;
case Tegra::Shader::VideoType::Invalid:
@@ -1460,8 +1459,7 @@ private:
// Decoding failure
if (!opcode) {
- LOG_CRITICAL(HW_GPU, "Unhandled instruction: {0:x}", instr.value);
- UNREACHABLE();
+ UNIMPLEMENTED_MSG("Unhandled instruction: {0:x}", instr.value);
return offset + 1;
}
@@ -1469,8 +1467,8 @@ private:
fmt::format("// {}: {} (0x{:016x})", offset, opcode->get().GetName(), instr.value));
using Tegra::Shader::Pred;
- ASSERT_MSG(instr.pred.full_pred != Pred::NeverExecute,
- "NeverExecute predicate not implemented");
+ UNIMPLEMENTED_IF_MSG(instr.pred.full_pred == Pred::NeverExecute,
+ "NeverExecute predicate not implemented");
// Some instructions (like SSY) don't have a predicate field, they are always
// unconditionally executed.
@@ -1513,37 +1511,36 @@ private:
case OpCode::Id::FMUL_R:
case OpCode::Id::FMUL_IMM: {
// FMUL does not have 'abs' bits and only the second operand has a 'neg' bit.
- ASSERT_MSG(instr.fmul.tab5cb8_2 == 0, "FMUL tab5cb8_2({}) is not implemented",
- instr.fmul.tab5cb8_2.Value());
- ASSERT_MSG(instr.fmul.tab5c68_1 == 0, "FMUL tab5cb8_1({}) is not implemented",
- instr.fmul.tab5c68_1.Value());
- ASSERT_MSG(instr.fmul.tab5c68_0 == 1, "FMUL tab5cb8_0({}) is not implemented",
- instr.fmul.tab5c68_0
- .Value()); // SMO typical sends 1 here which seems to be the default
- ASSERT_MSG(instr.fmul.cc == 0, "FMUL cc is not implemented");
+ UNIMPLEMENTED_IF_MSG(instr.fmul.tab5cb8_2 != 0,
+ "FMUL tab5cb8_2({}) is not implemented",
+ instr.fmul.tab5cb8_2.Value());
+ UNIMPLEMENTED_IF_MSG(instr.fmul.tab5c68_1 != 0,
+ "FMUL tab5cb8_1({}) is not implemented",
+ instr.fmul.tab5c68_1.Value());
+ UNIMPLEMENTED_IF_MSG(
+ instr.fmul.tab5c68_0 != 1, "FMUL tab5cb8_0({}) is not implemented",
+ instr.fmul.tab5c68_0
+ .Value()); // SMO typical sends 1 here which seems to be the default
+ UNIMPLEMENTED_IF_MSG(instr.generates_cc,
+ "Condition codes generation in FMUL is not implemented");
op_b = GetOperandAbsNeg(op_b, false, instr.fmul.negate_b);
regs.SetRegisterToFloat(instr.gpr0, 0, op_a + " * " + op_b, 1, 1,
instr.alu.saturate_d, 0, true);
- if (instr.generates_cc) {
- LOG_CRITICAL(HW_GPU, "FMUL Generates an unhandled Control Code");
- UNREACHABLE();
- }
break;
}
case OpCode::Id::FADD_C:
case OpCode::Id::FADD_R:
case OpCode::Id::FADD_IMM: {
+ UNIMPLEMENTED_IF_MSG(instr.generates_cc,
+ "Condition codes generation in FADD is not implemented");
+
op_a = GetOperandAbsNeg(op_a, instr.alu.abs_a, instr.alu.negate_a);
op_b = GetOperandAbsNeg(op_b, instr.alu.abs_b, instr.alu.negate_b);
regs.SetRegisterToFloat(instr.gpr0, 0, op_a + " + " + op_b, 1, 1,
instr.alu.saturate_d, 0, true);
- if (instr.generates_cc) {
- LOG_CRITICAL(HW_GPU, "FADD Generates an unhandled Control Code");
- UNREACHABLE();
- }
break;
}
case OpCode::Id::MUFU: {
@@ -1578,15 +1575,17 @@ private:
instr.alu.saturate_d, 0, true);
break;
default:
- LOG_CRITICAL(HW_GPU, "Unhandled MUFU sub op: {0:x}",
- static_cast<unsigned>(instr.sub_op.Value()));
- UNREACHABLE();
+ UNIMPLEMENTED_MSG("Unhandled MUFU sub op={0:x}",
+ static_cast<unsigned>(instr.sub_op.Value()));
}
break;
}
case OpCode::Id::FMNMX_C:
case OpCode::Id::FMNMX_R:
case OpCode::Id::FMNMX_IMM: {
+ UNIMPLEMENTED_IF_MSG(instr.generates_cc,
+ "Condition codes generation in FMNMX is not implemented");
+
op_a = GetOperandAbsNeg(op_a, instr.alu.abs_a, instr.alu.negate_a);
op_b = GetOperandAbsNeg(op_b, instr.alu.abs_b, instr.alu.negate_b);
@@ -1597,10 +1596,6 @@ private:
'(' + condition + ") ? min(" + parameters + ") : max(" +
parameters + ')',
1, 1, false, 0, true);
- if (instr.generates_cc) {
- LOG_CRITICAL(HW_GPU, "FMNMX Generates an unhandled Control Code");
- UNREACHABLE();
- }
break;
}
case OpCode::Id::RRO_C:
@@ -1613,9 +1608,7 @@ private:
break;
}
default: {
- LOG_CRITICAL(HW_GPU, "Unhandled arithmetic instruction: {}",
- opcode->get().GetName());
- UNREACHABLE();
+ UNIMPLEMENTED_MSG("Unhandled arithmetic instruction: {}", opcode->get().GetName());
}
}
break;
@@ -1627,17 +1620,19 @@ private:
break;
}
case OpCode::Id::FMUL32_IMM: {
+ UNIMPLEMENTED_IF_MSG(instr.op_32.generates_cc,
+ "Condition codes generation in FMUL32 is not implemented");
+
regs.SetRegisterToFloat(instr.gpr0, 0,
regs.GetRegisterAsFloat(instr.gpr8) + " * " +
GetImmediate32(instr),
1, 1, instr.fmul32.saturate, 0, true);
- if (instr.op_32.generates_cc) {
- LOG_CRITICAL(HW_GPU, "FMUL32 Generates an unhandled Control Code");
- UNREACHABLE();
- }
break;
}
case OpCode::Id::FADD32I: {
+ UNIMPLEMENTED_IF_MSG(instr.op_32.generates_cc,
+ "Condition codes generation in FADD32I is not implemented");
+
std::string op_a = regs.GetRegisterAsFloat(instr.gpr8);
std::string op_b = GetImmediate32(instr);
@@ -1658,23 +1653,22 @@ private:
}
regs.SetRegisterToFloat(instr.gpr0, 0, op_a + " + " + op_b, 1, 1, false, 0, true);
- if (instr.op_32.generates_cc) {
- LOG_CRITICAL(HW_GPU, "FADD32 Generates an unhandled Control Code");
- UNREACHABLE();
- }
break;
}
}
break;
}
case OpCode::Type::Bfe: {
- ASSERT_MSG(!instr.bfe.negate_b, "Unimplemented");
+ UNIMPLEMENTED_IF(instr.bfe.negate_b);
std::string op_a = instr.bfe.negate_a ? "-" : "";
op_a += regs.GetRegisterAsInteger(instr.gpr8);
switch (opcode->get().GetId()) {
case OpCode::Id::BFE_IMM: {
+ UNIMPLEMENTED_IF_MSG(instr.generates_cc,
+ "Condition codes generation in BFE is not implemented");
+
std::string inner_shift =
'(' + op_a + " << " + std::to_string(instr.bfe.GetLeftShiftValue()) + ')';
std::string outer_shift =
@@ -1682,15 +1676,10 @@ private:
std::to_string(instr.bfe.GetLeftShiftValue() + instr.bfe.shift_position) + ')';
regs.SetRegisterToInteger(instr.gpr0, true, 0, outer_shift, 1, 1);
- if (instr.generates_cc) {
- LOG_CRITICAL(HW_GPU, "BFE Generates an unhandled Control Code");
- UNREACHABLE();
- }
break;
}
default: {
- LOG_CRITICAL(HW_GPU, "Unhandled BFE instruction: {}", opcode->get().GetName());
- UNREACHABLE();
+ UNIMPLEMENTED_MSG("Unhandled BFE instruction: {}", opcode->get().GetName());
}
}
@@ -1715,6 +1704,9 @@ private:
case OpCode::Id::SHR_C:
case OpCode::Id::SHR_R:
case OpCode::Id::SHR_IMM: {
+ UNIMPLEMENTED_IF_MSG(instr.generates_cc,
+ "Condition codes generation in SHR is not implemented");
+
if (!instr.shift.is_signed) {
// Logical shift right
op_a = "uint(" + op_a + ')';
@@ -1723,24 +1715,17 @@ private:
// Cast to int is superfluous for arithmetic shift, it's only for a logical shift
regs.SetRegisterToInteger(instr.gpr0, true, 0, "int(" + op_a + " >> " + op_b + ')',
1, 1);
- if (instr.generates_cc) {
- LOG_CRITICAL(HW_GPU, "SHR Generates an unhandled Control Code");
- UNREACHABLE();
- }
break;
}
case OpCode::Id::SHL_C:
case OpCode::Id::SHL_R:
case OpCode::Id::SHL_IMM:
+ UNIMPLEMENTED_IF_MSG(instr.generates_cc,
+ "Condition codes generation in SHL is not implemented");
regs.SetRegisterToInteger(instr.gpr0, true, 0, op_a + " << " + op_b, 1, 1);
- if (instr.generates_cc) {
- LOG_CRITICAL(HW_GPU, "SHL Generates an unhandled Control Code");
- UNREACHABLE();
- }
break;
default: {
- LOG_CRITICAL(HW_GPU, "Unhandled shift instruction: {}", opcode->get().GetName());
- UNREACHABLE();
+ UNIMPLEMENTED_MSG("Unhandled shift instruction: {}", opcode->get().GetName());
}
}
break;
@@ -1751,17 +1736,19 @@ private:
switch (opcode->get().GetId()) {
case OpCode::Id::IADD32I:
+ UNIMPLEMENTED_IF_MSG(instr.op_32.generates_cc,
+ "Condition codes generation in IADD32I is not implemented");
+
if (instr.iadd32i.negate_a)
op_a = "-(" + op_a + ')';
regs.SetRegisterToInteger(instr.gpr0, true, 0, op_a + " + " + op_b, 1, 1,
instr.iadd32i.saturate != 0);
- if (instr.op_32.generates_cc) {
- LOG_CRITICAL(HW_GPU, "IADD32 Generates an unhandled Control Code");
- UNREACHABLE();
- }
break;
case OpCode::Id::LOP32I: {
+ UNIMPLEMENTED_IF_MSG(instr.op_32.generates_cc,
+ "Condition codes generation in LOP32I is not implemented");
+
if (instr.alu.lop32i.invert_a)
op_a = "~(" + op_a + ')';
@@ -1771,16 +1758,11 @@ private:
WriteLogicOperation(instr.gpr0, instr.alu.lop32i.operation, op_a, op_b,
Tegra::Shader::PredicateResultMode::None,
Tegra::Shader::Pred::UnusedIndex);
- if (instr.op_32.generates_cc) {
- LOG_CRITICAL(HW_GPU, "LOP32I Generates an unhandled Control Code");
- UNREACHABLE();
- }
break;
}
default: {
- LOG_CRITICAL(HW_GPU, "Unhandled ArithmeticIntegerImmediate instruction: {}",
- opcode->get().GetName());
- UNREACHABLE();
+ UNIMPLEMENTED_MSG("Unhandled ArithmeticIntegerImmediate instruction: {}",
+ opcode->get().GetName());
}
}
break;
@@ -1803,6 +1785,9 @@ private:
case OpCode::Id::IADD_C:
case OpCode::Id::IADD_R:
case OpCode::Id::IADD_IMM: {
+ UNIMPLEMENTED_IF_MSG(instr.generates_cc,
+ "Condition codes generation in IADD is not implemented");
+
if (instr.alu_integer.negate_a)
op_a = "-(" + op_a + ')';
@@ -1811,15 +1796,14 @@ private:
regs.SetRegisterToInteger(instr.gpr0, true, 0, op_a + " + " + op_b, 1, 1,
instr.alu.saturate_d);
- if (instr.generates_cc) {
- LOG_CRITICAL(HW_GPU, "IADD Generates an unhandled Control Code");
- UNREACHABLE();
- }
break;
}
case OpCode::Id::IADD3_C:
case OpCode::Id::IADD3_R:
case OpCode::Id::IADD3_IMM: {
+ UNIMPLEMENTED_IF_MSG(instr.generates_cc,
+ "Condition codes generation in IADD3 is not implemented");
+
std::string op_c = regs.GetRegisterAsInteger(instr.gpr39);
auto apply_height = [](auto height, auto& oprand) {
@@ -1833,9 +1817,8 @@ private:
oprand = "((" + oprand + ") >> 16)";
break;
default:
- LOG_CRITICAL(HW_GPU, "Unhandled IADD3 height: {}",
- static_cast<u32>(height.Value()));
- UNREACHABLE();
+ UNIMPLEMENTED_MSG("Unhandled IADD3 height: {}",
+ static_cast<u32>(height.Value()));
}
};
@@ -1876,16 +1859,14 @@ private:
}
regs.SetRegisterToInteger(instr.gpr0, true, 0, result, 1, 1);
-
- if (instr.generates_cc) {
- LOG_CRITICAL(HW_GPU, "IADD3 Generates an unhandled Control Code");
- UNREACHABLE();
- }
break;
}
case OpCode::Id::ISCADD_C:
case OpCode::Id::ISCADD_R:
case OpCode::Id::ISCADD_IMM: {
+ UNIMPLEMENTED_IF_MSG(instr.generates_cc,
+ "Condition codes generation in ISCADD is not implemented");
+
if (instr.alu_integer.negate_a)
op_a = "-(" + op_a + ')';
@@ -1896,10 +1877,6 @@ private:
regs.SetRegisterToInteger(instr.gpr0, true, 0,
"((" + op_a + " << " + shift + ") + " + op_b + ')', 1, 1);
- if (instr.generates_cc) {
- LOG_CRITICAL(HW_GPU, "ISCADD Generates an unhandled Control Code");
- UNREACHABLE();
- }
break;
}
case OpCode::Id::POPC_C:
@@ -1923,6 +1900,9 @@ private:
case OpCode::Id::LOP_C:
case OpCode::Id::LOP_R:
case OpCode::Id::LOP_IMM: {
+ UNIMPLEMENTED_IF_MSG(instr.generates_cc,
+ "Condition codes generation in LOP is not implemented");
+
if (instr.alu.lop.invert_a)
op_a = "~(" + op_a + ')';
@@ -1931,15 +1911,14 @@ private:
WriteLogicOperation(instr.gpr0, instr.alu.lop.operation, op_a, op_b,
instr.alu.lop.pred_result_mode, instr.alu.lop.pred48);
- if (instr.generates_cc) {
- LOG_CRITICAL(HW_GPU, "LOP Generates an unhandled Control Code");
- UNREACHABLE();
- }
break;
}
case OpCode::Id::LOP3_C:
case OpCode::Id::LOP3_R:
case OpCode::Id::LOP3_IMM: {
+ UNIMPLEMENTED_IF_MSG(instr.generates_cc,
+ "Condition codes generation in LOP3 is not implemented");
+
const std::string op_c = regs.GetRegisterAsInteger(instr.gpr39);
std::string lut;
@@ -1950,17 +1929,15 @@ private:
}
WriteLop3Instruction(instr.gpr0, op_a, op_b, op_c, lut);
- if (instr.generates_cc) {
- LOG_CRITICAL(HW_GPU, "LOP3 Generates an unhandled Control Code");
- UNREACHABLE();
- }
break;
}
case OpCode::Id::IMNMX_C:
case OpCode::Id::IMNMX_R:
case OpCode::Id::IMNMX_IMM: {
- ASSERT_MSG(instr.imnmx.exchange == Tegra::Shader::IMinMaxExchange::None,
- "Unimplemented");
+ UNIMPLEMENTED_IF(instr.imnmx.exchange != Tegra::Shader::IMinMaxExchange::None);
+ UNIMPLEMENTED_IF_MSG(instr.generates_cc,
+ "Condition codes generation in IMNMX is not implemented");
+
const std::string condition =
GetPredicateCondition(instr.imnmx.pred, instr.imnmx.negate_pred != 0);
const std::string parameters = op_a + ',' + op_b;
@@ -1968,10 +1945,6 @@ private:
'(' + condition + ") ? min(" + parameters + ") : max(" +
parameters + ')',
1, 1);
- if (instr.generates_cc) {
- LOG_CRITICAL(HW_GPU, "IMNMX Generates an unhandled Control Code");
- UNREACHABLE();
- }
break;
}
case OpCode::Id::LEA_R2:
@@ -2026,24 +1999,19 @@ private:
op_b = regs.GetRegisterAsInteger(instr.gpr8);
op_a = std::to_string(instr.lea.imm.entry_a);
op_c = std::to_string(instr.lea.imm.entry_b);
- LOG_CRITICAL(HW_GPU, "Unhandled LEA subinstruction: {}",
- opcode->get().GetName());
- UNREACHABLE();
- }
+ UNIMPLEMENTED_MSG("Unhandled LEA subinstruction: {}", opcode->get().GetName());
}
- if (instr.lea.pred48 != static_cast<u64>(Pred::UnusedIndex)) {
- LOG_ERROR(HW_GPU, "Unhandled LEA Predicate");
- UNREACHABLE();
}
+ UNIMPLEMENTED_IF_MSG(instr.lea.pred48 != static_cast<u64>(Pred::UnusedIndex),
+ "Unhandled LEA Predicate");
const std::string value = '(' + op_a + " + (" + op_b + "*(1 << " + op_c + ")))";
regs.SetRegisterToInteger(instr.gpr0, true, 0, value, 1, 1);
break;
}
default: {
- LOG_CRITICAL(HW_GPU, "Unhandled ArithmeticInteger instruction: {}",
- opcode->get().GetName());
- UNREACHABLE();
+ UNIMPLEMENTED_MSG("Unhandled ArithmeticInteger instruction: {}",
+ opcode->get().GetName());
}
}
@@ -2052,7 +2020,7 @@ private:
case OpCode::Type::ArithmeticHalf: {
if (opcode->get().GetId() == OpCode::Id::HADD2_C ||
opcode->get().GetId() == OpCode::Id::HADD2_R) {
- ASSERT_MSG(instr.alu_half.ftz == 0, "Unimplemented");
+ UNIMPLEMENTED_IF(instr.alu_half.ftz != 0);
}
const bool negate_a =
opcode->get().GetId() != OpCode::Id::HMUL2_R && instr.alu_half.negate_a != 0;
@@ -2090,9 +2058,8 @@ private:
case OpCode::Id::HMUL2_R:
return '(' + op_a + " * " + op_b + ')';
default:
- LOG_CRITICAL(HW_GPU, "Unhandled half float instruction: {}",
- opcode->get().GetName());
- UNREACHABLE();
+ UNIMPLEMENTED_MSG("Unhandled half float instruction: {}",
+ opcode->get().GetName());
return std::string("0");
}
}();
@@ -2103,10 +2070,10 @@ private:
}
case OpCode::Type::ArithmeticHalfImmediate: {
if (opcode->get().GetId() == OpCode::Id::HADD2_IMM) {
- ASSERT_MSG(instr.alu_half_imm.ftz == 0, "Unimplemented");
+ UNIMPLEMENTED_IF(instr.alu_half_imm.ftz != 0);
} else {
- ASSERT_MSG(instr.alu_half_imm.precision == Tegra::Shader::HalfPrecision::None,
- "Unimplemented");
+ UNIMPLEMENTED_IF(instr.alu_half_imm.precision !=
+ Tegra::Shader::HalfPrecision::None);
}
const std::string op_a = GetHalfFloat(
@@ -2136,11 +2103,14 @@ private:
std::string op_b = instr.ffma.negate_b ? "-" : "";
std::string op_c = instr.ffma.negate_c ? "-" : "";
- ASSERT_MSG(instr.ffma.cc == 0, "FFMA cc not implemented");
- ASSERT_MSG(instr.ffma.tab5980_0 == 1, "FFMA tab5980_0({}) not implemented",
- instr.ffma.tab5980_0.Value()); // Seems to be 1 by default based on SMO
- ASSERT_MSG(instr.ffma.tab5980_1 == 0, "FFMA tab5980_1({}) not implemented",
- instr.ffma.tab5980_1.Value());
+ UNIMPLEMENTED_IF_MSG(instr.ffma.cc != 0, "FFMA cc not implemented");
+ UNIMPLEMENTED_IF_MSG(
+ instr.ffma.tab5980_0 != 1, "FFMA tab5980_0({}) not implemented",
+ instr.ffma.tab5980_0.Value()); // Seems to be 1 by default based on SMO
+ UNIMPLEMENTED_IF_MSG(instr.ffma.tab5980_1 != 0, "FFMA tab5980_1({}) not implemented",
+ instr.ffma.tab5980_1.Value());
+ UNIMPLEMENTED_IF_MSG(instr.generates_cc,
+ "Condition codes generation in FFMA is not implemented");
switch (opcode->get().GetId()) {
case OpCode::Id::FFMA_CR: {
@@ -2166,27 +2136,19 @@ private:
break;
}
default: {
- LOG_CRITICAL(HW_GPU, "Unhandled FFMA instruction: {}", opcode->get().GetName());
- UNREACHABLE();
+ UNIMPLEMENTED_MSG("Unhandled FFMA instruction: {}", opcode->get().GetName());
}
}
regs.SetRegisterToFloat(instr.gpr0, 0, "fma(" + op_a + ", " + op_b + ", " + op_c + ')',
1, 1, instr.alu.saturate_d, 0, true);
- if (instr.generates_cc) {
- LOG_CRITICAL(HW_GPU, "FFMA Generates an unhandled Control Code");
- UNREACHABLE();
- }
-
break;
}
case OpCode::Type::Hfma2: {
if (opcode->get().GetId() == OpCode::Id::HFMA2_RR) {
- ASSERT_MSG(instr.hfma2.rr.precision == Tegra::Shader::HalfPrecision::None,
- "Unimplemented");
+ UNIMPLEMENTED_IF(instr.hfma2.rr.precision != Tegra::Shader::HalfPrecision::None);
} else {
- ASSERT_MSG(instr.hfma2.precision == Tegra::Shader::HalfPrecision::None,
- "Unimplemented");
+ UNIMPLEMENTED_IF(instr.hfma2.precision != Tegra::Shader::HalfPrecision::None);
}
const bool saturate = opcode->get().GetId() == OpCode::Id::HFMA2_RR
? instr.hfma2.rr.saturate != 0
@@ -2236,7 +2198,7 @@ private:
case OpCode::Type::Conversion: {
switch (opcode->get().GetId()) {
case OpCode::Id::I2I_R: {
- ASSERT_MSG(!instr.conversion.selector, "Unimplemented");
+ UNIMPLEMENTED_IF(instr.conversion.selector);
std::string op_a = regs.GetRegisterAsInteger(
instr.gpr20, 0, instr.conversion.is_input_signed, instr.conversion.src_size);
@@ -2256,8 +2218,10 @@ private:
}
case OpCode::Id::I2F_R:
case OpCode::Id::I2F_C: {
- ASSERT_MSG(instr.conversion.dest_size == Register::Size::Word, "Unimplemented");
- ASSERT_MSG(!instr.conversion.selector, "Unimplemented");
+ UNIMPLEMENTED_IF(instr.conversion.dest_size != Register::Size::Word);
+ UNIMPLEMENTED_IF(instr.conversion.selector);
+ UNIMPLEMENTED_IF_MSG(instr.generates_cc,
+ "Condition codes generation in I2F is not implemented");
std::string op_a{};
@@ -2282,16 +2246,13 @@ private:
}
regs.SetRegisterToFloat(instr.gpr0, 0, op_a, 1, 1);
-
- if (instr.generates_cc) {
- LOG_CRITICAL(HW_GPU, "I2F Generates an unhandled Control Code");
- UNREACHABLE();
- }
break;
}
case OpCode::Id::F2F_R: {
- ASSERT_MSG(instr.conversion.dest_size == Register::Size::Word, "Unimplemented");
- ASSERT_MSG(instr.conversion.src_size == Register::Size::Word, "Unimplemented");
+ UNIMPLEMENTED_IF(instr.conversion.dest_size != Register::Size::Word);
+ UNIMPLEMENTED_IF(instr.conversion.src_size != Register::Size::Word);
+ UNIMPLEMENTED_IF_MSG(instr.generates_cc,
+ "Condition codes generation in F2F is not implemented");
std::string op_a = regs.GetRegisterAsFloat(instr.gpr20);
if (instr.conversion.abs_a) {
@@ -2318,23 +2279,19 @@ private:
op_a = "trunc(" + op_a + ')';
break;
default:
- LOG_CRITICAL(HW_GPU, "Unimplemented f2f rounding mode {}",
- static_cast<u32>(instr.conversion.f2f.rounding.Value()));
- UNREACHABLE();
+ UNIMPLEMENTED_MSG("Unimplemented F2F rounding mode {}",
+ static_cast<u32>(instr.conversion.f2f.rounding.Value()));
break;
}
regs.SetRegisterToFloat(instr.gpr0, 0, op_a, 1, 1, instr.alu.saturate_d);
-
- if (instr.generates_cc) {
- LOG_CRITICAL(HW_GPU, "F2F Generates an unhandled Control Code");
- UNREACHABLE();
- }
break;
}
case OpCode::Id::F2I_R:
case OpCode::Id::F2I_C: {
- ASSERT_MSG(instr.conversion.src_size == Register::Size::Word, "Unimplemented");
+ UNIMPLEMENTED_IF(instr.conversion.src_size != Register::Size::Word);
+ UNIMPLEMENTED_IF_MSG(instr.generates_cc,
+ "Condition codes generation in F2I is not implemented");
std::string op_a{};
if (instr.is_b_gpr) {
@@ -2365,9 +2322,8 @@ private:
op_a = "trunc(" + op_a + ')';
break;
default:
- LOG_CRITICAL(HW_GPU, "Unimplemented f2i rounding mode {}",
- static_cast<u32>(instr.conversion.f2i.rounding.Value()));
- UNREACHABLE();
+ UNIMPLEMENTED_MSG("Unimplemented F2I rounding mode {}",
+ static_cast<u32>(instr.conversion.f2i.rounding.Value()));
break;
}
@@ -2379,16 +2335,10 @@ private:
regs.SetRegisterToInteger(instr.gpr0, instr.conversion.is_output_signed, 0, op_a, 1,
1, false, 0, instr.conversion.dest_size);
- if (instr.generates_cc) {
- LOG_CRITICAL(HW_GPU, "F2I Generates an unhandled Control Code");
- UNREACHABLE();
- }
break;
}
default: {
- LOG_CRITICAL(HW_GPU, "Unhandled conversion instruction: {}",
- opcode->get().GetName());
- UNREACHABLE();
+ UNIMPLEMENTED_MSG("Unhandled conversion instruction: {}", opcode->get().GetName());
}
}
break;
@@ -2397,10 +2347,10 @@ private:
switch (opcode->get().GetId()) {
case OpCode::Id::LD_A: {
// Note: Shouldn't this be interp mode flat? As in no interpolation made.
- ASSERT_MSG(instr.gpr8.Value() == Register::ZeroIndex,
- "Indirect attribute loads are not supported");
- ASSERT_MSG((instr.attribute.fmt20.immediate.Value() % sizeof(u32)) == 0,
- "Unaligned attribute loads are not supported");
+ UNIMPLEMENTED_IF_MSG(instr.gpr8.Value() != Register::ZeroIndex,
+ "Indirect attribute loads are not supported");
+ UNIMPLEMENTED_IF_MSG((instr.attribute.fmt20.immediate.Value() % sizeof(u32)) != 0,
+ "Unaligned attribute loads are not supported");
Tegra::Shader::IpaMode input_mode{Tegra::Shader::IpaInterpMode::Perspective,
Tegra::Shader::IpaSampleMode::Default};
@@ -2427,7 +2377,7 @@ private:
break;
}
case OpCode::Id::LD_C: {
- ASSERT_MSG(instr.ld_c.unknown == 0, "Unimplemented");
+ UNIMPLEMENTED_IF(instr.ld_c.unknown != 0);
// Add an extra scope and declare the index register inside to prevent
// overwriting it in case it is used as an output of the LD instruction.
@@ -2455,9 +2405,8 @@ private:
break;
}
default:
- LOG_CRITICAL(HW_GPU, "Unhandled type: {}",
- static_cast<unsigned>(instr.ld_c.type.Value()));
- UNREACHABLE();
+ UNIMPLEMENTED_MSG("Unhandled type: {}",
+ static_cast<unsigned>(instr.ld_c.type.Value()));
}
--shader.scope;
@@ -2465,6 +2414,9 @@ private:
break;
}
case OpCode::Id::LD_L: {
+ UNIMPLEMENTED_IF_MSG(instr.ld_l.unknown == 1, "LD_L Unhandled mode: {}",
+ static_cast<unsigned>(instr.ld_l.unknown.Value()));
+
// Add an extra scope and declare the index register inside to prevent
// overwriting it in case it is used as an output of the LD instruction.
shader.AddLine('{');
@@ -2477,20 +2429,13 @@ private:
const std::string op_a = regs.GetLocalMemoryAsFloat("index");
- if (instr.ld_l.unknown != 1) {
- LOG_CRITICAL(HW_GPU, "LD_L Unhandled mode: {}",
- static_cast<unsigned>(instr.ld_l.unknown.Value()));
- UNREACHABLE();
- }
-
switch (instr.ldst_sl.type.Value()) {
case Tegra::Shader::StoreType::Bytes32:
regs.SetRegisterToFloat(instr.gpr0, 0, op_a, 1, 1);
break;
default:
- LOG_CRITICAL(HW_GPU, "LD_L Unhandled type: {}",
- static_cast<unsigned>(instr.ldst_sl.type.Value()));
- UNREACHABLE();
+ UNIMPLEMENTED_MSG("LD_L Unhandled type: {}",
+ static_cast<unsigned>(instr.ldst_sl.type.Value()));
}
--shader.scope;
@@ -2498,10 +2443,10 @@ private:
break;
}
case OpCode::Id::ST_A: {
- ASSERT_MSG(instr.gpr8.Value() == Register::ZeroIndex,
- "Indirect attribute loads are not supported");
- ASSERT_MSG((instr.attribute.fmt20.immediate.Value() % sizeof(u32)) == 0,
- "Unaligned attribute loads are not supported");
+ UNIMPLEMENTED_IF_MSG(instr.gpr8.Value() != Register::ZeroIndex,
+ "Indirect attribute loads are not supported");
+ UNIMPLEMENTED_IF_MSG((instr.attribute.fmt20.immediate.Value() % sizeof(u32)) != 0,
+ "Unaligned attribute loads are not supported");
u64 next_element = instr.attribute.fmt20.element;
u64 next_index = static_cast<u64>(instr.attribute.fmt20.index.Value());
@@ -2526,6 +2471,9 @@ private:
break;
}
case OpCode::Id::ST_L: {
+ UNIMPLEMENTED_IF_MSG(instr.st_l.unknown == 0, "ST_L Unhandled mode: {}",
+ static_cast<unsigned>(instr.st_l.unknown.Value()));
+
// Add an extra scope and declare the index register inside to prevent
// overwriting it in case it is used as an output of the LD instruction.
shader.AddLine('{');
@@ -2536,20 +2484,13 @@ private:
shader.AddLine("uint index = (" + op + " / 4);");
- if (instr.st_l.unknown != 0) {
- LOG_CRITICAL(HW_GPU, "ST_L Unhandled mode: {}",
- static_cast<unsigned>(instr.st_l.unknown.Value()));
- UNREACHABLE();
- }
-
switch (instr.ldst_sl.type.Value()) {
case Tegra::Shader::StoreType::Bytes32:
regs.SetLocalMemoryAsFloat("index", regs.GetRegisterAsFloat(instr.gpr0));
break;
default:
- LOG_CRITICAL(HW_GPU, "ST_L Unhandled type: {}",
- static_cast<unsigned>(instr.ldst_sl.type.Value()));
- UNREACHABLE();
+ UNIMPLEMENTED_MSG("ST_L Unhandled type: {}",
+ static_cast<unsigned>(instr.ldst_sl.type.Value()));
}
--shader.scope;
@@ -2561,10 +2502,10 @@ private:
std::string coord;
const bool is_array = instr.tex.array != 0;
- ASSERT_MSG(!instr.tex.UsesMiscMode(Tegra::Shader::TextureMiscMode::NODEP),
- "NODEP is not implemented");
- ASSERT_MSG(!instr.tex.UsesMiscMode(Tegra::Shader::TextureMiscMode::AOFFI),
- "AOFFI is not implemented");
+ UNIMPLEMENTED_IF_MSG(instr.tex.UsesMiscMode(Tegra::Shader::TextureMiscMode::NODEP),
+ "NODEP is not implemented");
+ UNIMPLEMENTED_IF_MSG(instr.tex.UsesMiscMode(Tegra::Shader::TextureMiscMode::AOFFI),
+ "AOFFI is not implemented");
const bool depth_compare =
instr.tex.UsesMiscMode(Tegra::Shader::TextureMiscMode::DC);
@@ -2630,9 +2571,8 @@ private:
break;
}
default:
- LOG_CRITICAL(HW_GPU, "Unhandled coordinates number {}",
- static_cast<u32>(num_coordinates));
- UNREACHABLE();
+ UNIMPLEMENTED_MSG("Unhandled coordinates number {}",
+ static_cast<u32>(num_coordinates));
// Fallback to interpreting as a 2D texture for now
const std::string x = regs.GetRegisterAsFloat(instr.gpr8);
@@ -2642,7 +2582,6 @@ private:
}
// TODO: make sure coordinates are always indexed to gpr8 and gpr20 is always bias
// or lod.
- std::string op_c;
const std::string sampler =
GetSampler(instr.sampler, texture_type, is_array, depth_compare);
@@ -2665,34 +2604,41 @@ private:
}
case Tegra::Shader::TextureProcessMode::LB:
case Tegra::Shader::TextureProcessMode::LBA: {
- if (depth_compare) {
- if (is_array)
- op_c = regs.GetRegisterAsFloat(instr.gpr20.Value() + 2);
- else
- op_c = regs.GetRegisterAsFloat(instr.gpr20.Value() + 1);
- } else {
- op_c = regs.GetRegisterAsFloat(instr.gpr20);
- }
+ const std::string bias = [&]() {
+ if (depth_compare) {
+ if (is_array)
+ return regs.GetRegisterAsFloat(instr.gpr20.Value() + 2);
+ else
+ return regs.GetRegisterAsFloat(instr.gpr20.Value() + 1);
+ } else {
+ return regs.GetRegisterAsFloat(instr.gpr20);
+ }
+ }();
+ shader.AddLine("float bias = " + bias + ';');
+
// TODO: Figure if A suffix changes the equation at all.
- texture = "texture(" + sampler + ", coords, " + op_c + ')';
+ texture = "texture(" + sampler + ", coords, bias)";
break;
}
case Tegra::Shader::TextureProcessMode::LL:
case Tegra::Shader::TextureProcessMode::LLA: {
- if (num_coordinates <= 2) {
- op_c = regs.GetRegisterAsFloat(instr.gpr20);
- } else {
- op_c = regs.GetRegisterAsFloat(instr.gpr20.Value() + 1);
- }
+ const std::string lod = [&]() {
+ if (num_coordinates <= 2) {
+ return regs.GetRegisterAsFloat(instr.gpr20);
+ } else {
+ return regs.GetRegisterAsFloat(instr.gpr20.Value() + 1);
+ }
+ }();
+ shader.AddLine("float lod = " + lod + ';');
+
// TODO: Figure if A suffix changes the equation at all.
- texture = "textureLod(" + sampler + ", coords, " + op_c + ')';
+ texture = "textureLod(" + sampler + ", coords, lod)";
break;
}
default: {
texture = "texture(" + sampler + ", coords)";
- LOG_CRITICAL(HW_GPU, "Unhandled texture process mode {}",
- static_cast<u32>(instr.tex.GetTextureProcessMode()));
- UNREACHABLE();
+ UNIMPLEMENTED_MSG("Unhandled texture process mode {}",
+ static_cast<u32>(instr.tex.GetTextureProcessMode()));
}
}
if (!depth_compare) {
@@ -2713,12 +2659,11 @@ private:
break;
}
case OpCode::Id::TEXS: {
- std::string coord;
Tegra::Shader::TextureType texture_type{instr.texs.GetTextureType()};
bool is_array{instr.texs.IsArrayTexture()};
- ASSERT_MSG(!instr.texs.UsesMiscMode(Tegra::Shader::TextureMiscMode::NODEP),
- "NODEP is not implemented");
+ UNIMPLEMENTED_IF_MSG(instr.texs.UsesMiscMode(Tegra::Shader::TextureMiscMode::NODEP),
+ "NODEP is not implemented");
const bool depth_compare =
instr.texs.UsesMiscMode(Tegra::Shader::TextureMiscMode::DC);
@@ -2726,45 +2671,48 @@ private:
if (depth_compare)
num_coordinates += 1;
+ // Scope to avoid variable name overlaps.
+ shader.AddLine('{');
+ ++shader.scope;
+
switch (num_coordinates) {
case 2: {
if (is_array) {
const std::string index = regs.GetRegisterAsInteger(instr.gpr8);
const std::string x = regs.GetRegisterAsFloat(instr.gpr8.Value() + 1);
const std::string y = regs.GetRegisterAsFloat(instr.gpr20);
- coord = "vec3 coords = vec3(" + x + ", " + y + ", " + index + ");";
+ shader.AddLine("vec3 coords = vec3(" + x + ", " + y + ", " + index + ");");
} else {
const std::string x = regs.GetRegisterAsFloat(instr.gpr8);
const std::string y = regs.GetRegisterAsFloat(instr.gpr20);
- coord = "vec2 coords = vec2(" + x + ", " + y + ");";
+ shader.AddLine("vec2 coords = vec2(" + x + ", " + y + ");");
}
break;
}
case 3: {
if (is_array) {
- UNIMPLEMENTED_MSG("3-coordinate arrays not fully implemented");
- const std::string x = regs.GetRegisterAsFloat(instr.gpr8);
- const std::string y = regs.GetRegisterAsFloat(instr.gpr20);
- coord = "vec2 coords = vec2(" + x + ", " + y + ");";
- texture_type = Tegra::Shader::TextureType::Texture2D;
- is_array = false;
+ const std::string index = regs.GetRegisterAsInteger(instr.gpr8);
+ const std::string x = regs.GetRegisterAsFloat(instr.gpr8.Value() + 1);
+ const std::string y = regs.GetRegisterAsFloat(instr.gpr8.Value() + 2);
+ const std::string z = regs.GetRegisterAsFloat(instr.gpr20);
+ shader.AddLine("vec4 coords = vec4(" + x + ", " + y + ", " + z + ", " +
+ index + ");");
} else {
const std::string x = regs.GetRegisterAsFloat(instr.gpr8);
const std::string y = regs.GetRegisterAsFloat(instr.gpr8.Value() + 1);
const std::string z = regs.GetRegisterAsFloat(instr.gpr20);
- coord = "vec3 coords = vec3(" + x + ", " + y + ", " + z + ");";
+ shader.AddLine("vec3 coords = vec3(" + x + ", " + y + ", " + z + ");");
}
break;
}
default:
- LOG_CRITICAL(HW_GPU, "Unhandled coordinates number {}",
- static_cast<u32>(num_coordinates));
- UNREACHABLE();
+ UNIMPLEMENTED_MSG("Unhandled coordinates number {}",
+ static_cast<u32>(num_coordinates));
// Fallback to interpreting as a 2D texture for now
const std::string x = regs.GetRegisterAsFloat(instr.gpr8);
const std::string y = regs.GetRegisterAsFloat(instr.gpr20);
- coord = "vec2 coords = vec2(" + x + ", " + y + ");";
+ shader.AddLine("vec2 coords = vec2(" + x + ", " + y + ");");
texture_type = Tegra::Shader::TextureType::Texture2D;
is_array = false;
}
@@ -2777,7 +2725,11 @@ private:
break;
}
case Tegra::Shader::TextureProcessMode::LZ: {
- texture = "textureLod(" + sampler + ", coords, 0.0)";
+ if (depth_compare && is_array) {
+ texture = "texture(" + sampler + ", coords)";
+ } else {
+ texture = "textureLod(" + sampler + ", coords, 0.0)";
+ }
break;
}
case Tegra::Shader::TextureProcessMode::LL: {
@@ -2787,57 +2739,57 @@ private:
}
default: {
texture = "texture(" + sampler + ", coords)";
- LOG_CRITICAL(HW_GPU, "Unhandled texture process mode {}",
- static_cast<u32>(instr.texs.GetTextureProcessMode()));
- UNREACHABLE();
+ UNIMPLEMENTED_MSG("Unhandled texture process mode {}",
+ static_cast<u32>(instr.texs.GetTextureProcessMode()));
}
}
if (!depth_compare) {
- WriteTexsInstruction(instr, coord, texture);
+ WriteTexsInstruction(instr, texture);
} else {
- WriteTexsInstruction(instr, coord, "vec4(" + texture + ')');
+ WriteTexsInstruction(instr, "vec4(" + texture + ')');
}
+
+ shader.AddLine('}');
+ --shader.scope;
break;
}
case OpCode::Id::TLDS: {
- std::string coord;
const Tegra::Shader::TextureType texture_type{instr.tlds.GetTextureType()};
const bool is_array{instr.tlds.IsArrayTexture()};
ASSERT(texture_type == Tegra::Shader::TextureType::Texture2D);
ASSERT(is_array == false);
- ASSERT_MSG(!instr.tlds.UsesMiscMode(Tegra::Shader::TextureMiscMode::NODEP),
- "NODEP is not implemented");
- ASSERT_MSG(!instr.tlds.UsesMiscMode(Tegra::Shader::TextureMiscMode::AOFFI),
- "AOFFI is not implemented");
- ASSERT_MSG(!instr.tlds.UsesMiscMode(Tegra::Shader::TextureMiscMode::MZ),
- "MZ is not implemented");
+ UNIMPLEMENTED_IF_MSG(instr.tlds.UsesMiscMode(Tegra::Shader::TextureMiscMode::NODEP),
+ "NODEP is not implemented");
+ UNIMPLEMENTED_IF_MSG(instr.tlds.UsesMiscMode(Tegra::Shader::TextureMiscMode::AOFFI),
+ "AOFFI is not implemented");
+ UNIMPLEMENTED_IF_MSG(instr.tlds.UsesMiscMode(Tegra::Shader::TextureMiscMode::MZ),
+ "MZ is not implemented");
- u32 op_c_offset = 0;
+ u32 extra_op_offset = 0;
+
+ // Scope to avoid variable name overlaps.
+ shader.AddLine('{');
+ ++shader.scope;
switch (texture_type) {
case Tegra::Shader::TextureType::Texture1D: {
const std::string x = regs.GetRegisterAsInteger(instr.gpr8);
- coord = "int coords = " + x + ';';
+ shader.AddLine("int coords = " + x + ';');
break;
}
case Tegra::Shader::TextureType::Texture2D: {
- if (is_array) {
- LOG_CRITICAL(HW_GPU, "Unhandled 2d array texture");
- UNREACHABLE();
- } else {
- const std::string x = regs.GetRegisterAsInteger(instr.gpr8);
- const std::string y = regs.GetRegisterAsInteger(instr.gpr20);
- coord = "ivec2 coords = ivec2(" + x + ", " + y + ");";
- op_c_offset = 1;
- }
+ UNIMPLEMENTED_IF_MSG(is_array, "Unhandled 2d array texture");
+
+ const std::string x = regs.GetRegisterAsInteger(instr.gpr8);
+ const std::string y = regs.GetRegisterAsInteger(instr.gpr20);
+ shader.AddLine("ivec2 coords = ivec2(" + x + ", " + y + ");");
+ extra_op_offset = 1;
break;
}
default:
- LOG_CRITICAL(HW_GPU, "Unhandled texture type {}",
- static_cast<u32>(texture_type));
- UNREACHABLE();
+ UNIMPLEMENTED_MSG("Unhandled texture type {}", static_cast<u32>(texture_type));
}
const std::string sampler =
GetSampler(instr.sampler, texture_type, is_array, false);
@@ -2848,19 +2800,22 @@ private:
break;
}
case Tegra::Shader::TextureProcessMode::LL: {
- const std::string op_c =
- regs.GetRegisterAsInteger(instr.gpr20.Value() + op_c_offset);
- texture = "texelFetch(" + sampler + ", coords, " + op_c + ')';
+ shader.AddLine(
+ "float lod = " +
+ regs.GetRegisterAsInteger(instr.gpr20.Value() + extra_op_offset) + ';');
+ texture = "texelFetch(" + sampler + ", coords, lod)";
break;
}
default: {
texture = "texelFetch(" + sampler + ", coords, 0)";
- LOG_CRITICAL(HW_GPU, "Unhandled texture process mode {}",
- static_cast<u32>(instr.tlds.GetTextureProcessMode()));
- UNREACHABLE();
+ UNIMPLEMENTED_MSG("Unhandled texture process mode {}",
+ static_cast<u32>(instr.tlds.GetTextureProcessMode()));
}
}
- WriteTexsInstruction(instr, coord, texture);
+ WriteTexsInstruction(instr, texture);
+
+ --shader.scope;
+ shader.AddLine('}');
break;
}
case OpCode::Id::TLD4: {
@@ -2868,14 +2823,14 @@ private:
ASSERT(instr.tld4.array == 0);
std::string coord;
- ASSERT_MSG(!instr.tld4.UsesMiscMode(Tegra::Shader::TextureMiscMode::NODEP),
- "NODEP is not implemented");
- ASSERT_MSG(!instr.tld4.UsesMiscMode(Tegra::Shader::TextureMiscMode::AOFFI),
- "AOFFI is not implemented");
- ASSERT_MSG(!instr.tld4.UsesMiscMode(Tegra::Shader::TextureMiscMode::NDV),
- "NDV is not implemented");
- ASSERT_MSG(!instr.tld4.UsesMiscMode(Tegra::Shader::TextureMiscMode::PTP),
- "PTP is not implemented");
+ UNIMPLEMENTED_IF_MSG(instr.tld4.UsesMiscMode(Tegra::Shader::TextureMiscMode::NODEP),
+ "NODEP is not implemented");
+ UNIMPLEMENTED_IF_MSG(instr.tld4.UsesMiscMode(Tegra::Shader::TextureMiscMode::AOFFI),
+ "AOFFI is not implemented");
+ UNIMPLEMENTED_IF_MSG(instr.tld4.UsesMiscMode(Tegra::Shader::TextureMiscMode::NDV),
+ "NDV is not implemented");
+ UNIMPLEMENTED_IF_MSG(instr.tld4.UsesMiscMode(Tegra::Shader::TextureMiscMode::PTP),
+ "PTP is not implemented");
const bool depth_compare =
instr.tld4.UsesMiscMode(Tegra::Shader::TextureMiscMode::DC);
auto texture_type = instr.tld4.texture_type.Value();
@@ -2883,37 +2838,37 @@ private:
if (depth_compare)
num_coordinates += 1;
+ // Add an extra scope and declare the texture coords inside to prevent
+ // overwriting them in case they are used as outputs of the texs instruction.
+ shader.AddLine('{');
+ ++shader.scope;
+
switch (num_coordinates) {
case 2: {
const std::string x = regs.GetRegisterAsFloat(instr.gpr8);
const std::string y = regs.GetRegisterAsFloat(instr.gpr8.Value() + 1);
- coord = "vec2 coords = vec2(" + x + ", " + y + ");";
+ shader.AddLine("vec2 coords = vec2(" + x + ", " + y + ");");
break;
}
case 3: {
const std::string x = regs.GetRegisterAsFloat(instr.gpr8);
const std::string y = regs.GetRegisterAsFloat(instr.gpr8.Value() + 1);
const std::string z = regs.GetRegisterAsFloat(instr.gpr8.Value() + 2);
- coord = "vec3 coords = vec3(" + x + ", " + y + ", " + z + ");";
+ shader.AddLine("vec3 coords = vec3(" + x + ", " + y + ", " + z + ");");
break;
}
default:
- LOG_CRITICAL(HW_GPU, "Unhandled coordinates number {}",
- static_cast<u32>(num_coordinates));
- UNREACHABLE();
+ UNIMPLEMENTED_MSG("Unhandled coordinates number {}",
+ static_cast<u32>(num_coordinates));
const std::string x = regs.GetRegisterAsFloat(instr.gpr8);
const std::string y = regs.GetRegisterAsFloat(instr.gpr8.Value() + 1);
- coord = "vec2 coords = vec2(" + x + ", " + y + ");";
+ shader.AddLine("vec2 coords = vec2(" + x + ", " + y + ");");
texture_type = Tegra::Shader::TextureType::Texture2D;
}
const std::string sampler =
GetSampler(instr.sampler, texture_type, false, depth_compare);
- // Add an extra scope and declare the texture coords inside to prevent
- // overwriting them in case they are used as outputs of the texs instruction.
- shader.AddLine("{");
- ++shader.scope;
- shader.AddLine(coord);
+
const std::string texture = "textureGather(" + sampler + ", coords, " +
std::to_string(instr.tld4.component) + ')';
if (!depth_compare) {
@@ -2930,14 +2885,20 @@ private:
regs.SetRegisterToFloat(instr.gpr0, 0, texture, 1, 1, false);
}
--shader.scope;
- shader.AddLine("}");
+ shader.AddLine('}');
break;
}
case OpCode::Id::TLD4S: {
- ASSERT_MSG(!instr.tld4s.UsesMiscMode(Tegra::Shader::TextureMiscMode::NODEP),
- "NODEP is not implemented");
- ASSERT_MSG(!instr.tld4s.UsesMiscMode(Tegra::Shader::TextureMiscMode::AOFFI),
- "AOFFI is not implemented");
+ UNIMPLEMENTED_IF_MSG(
+ instr.tld4s.UsesMiscMode(Tegra::Shader::TextureMiscMode::NODEP),
+ "NODEP is not implemented");
+ UNIMPLEMENTED_IF_MSG(
+ instr.tld4s.UsesMiscMode(Tegra::Shader::TextureMiscMode::AOFFI),
+ "AOFFI is not implemented");
+
+ // Scope to avoid variable name overlaps.
+ shader.AddLine('{');
+ ++shader.scope;
const bool depth_compare =
instr.tld4s.UsesMiscMode(Tegra::Shader::TextureMiscMode::DC);
@@ -2946,28 +2907,33 @@ private:
// TODO(Subv): Figure out how the sampler type is encoded in the TLD4S instruction.
const std::string sampler = GetSampler(
instr.sampler, Tegra::Shader::TextureType::Texture2D, false, depth_compare);
- std::string coord;
if (!depth_compare) {
- coord = "vec2 coords = vec2(" + op_a + ", " + op_b + ");";
+ shader.AddLine("vec2 coords = vec2(" + op_a + ", " + op_b + ");");
} else {
// Note: TLD4S coordinate encoding works just like TEXS's
- const std::string op_c = regs.GetRegisterAsFloat(instr.gpr8.Value() + 1);
- coord = "vec3 coords = vec3(" + op_a + ", " + op_c + ", " + op_b + ");";
+ shader.AddLine(
+ "float op_y = " + regs.GetRegisterAsFloat(instr.gpr8.Value() + 1) + ';');
+ shader.AddLine("vec3 coords = vec3(" + op_a + ", op_y, " + op_b + ");");
}
const std::string texture = "textureGather(" + sampler + ", coords, " +
std::to_string(instr.tld4s.component) + ')';
if (!depth_compare) {
- WriteTexsInstruction(instr, coord, texture);
+ WriteTexsInstruction(instr, texture);
} else {
- WriteTexsInstruction(instr, coord, "vec4(" + texture + ')');
+ WriteTexsInstruction(instr, "vec4(" + texture + ')');
}
+
+ --shader.scope;
+ shader.AddLine('}');
break;
}
case OpCode::Id::TXQ: {
- ASSERT_MSG(!instr.txq.UsesMiscMode(Tegra::Shader::TextureMiscMode::NODEP),
- "NODEP is not implemented");
+ UNIMPLEMENTED_IF_MSG(instr.txq.UsesMiscMode(Tegra::Shader::TextureMiscMode::NODEP),
+ "NODEP is not implemented");
+ ++shader.scope;
+ shader.AddLine('{');
// TODO: the new commits on the texture refactor, change the way samplers work.
// Sadly, not all texture instructions specify the type of texture their sampler
// uses. This must be fixed at a later instance.
@@ -2975,23 +2941,30 @@ private:
GetSampler(instr.sampler, Tegra::Shader::TextureType::Texture2D, false, false);
switch (instr.txq.query_type) {
case Tegra::Shader::TextureQueryType::Dimension: {
- const std::string texture = "textureQueryLevels(" + sampler + ')';
- regs.SetRegisterToInteger(instr.gpr0, true, 0, texture, 1, 1);
+ const std::string texture = "textureSize(" + sampler + ", " +
+ regs.GetRegisterAsInteger(instr.gpr8) + ')';
+ const std::string mip_level = "textureQueryLevels(" + sampler + ')';
+ shader.AddLine("ivec2 sizes = " + texture + ';');
+ regs.SetRegisterToInteger(instr.gpr0, true, 0, "sizes.x", 1, 1);
+ regs.SetRegisterToInteger(instr.gpr0.Value() + 1, true, 0, "sizes.y", 1, 1);
+ regs.SetRegisterToInteger(instr.gpr0.Value() + 2, true, 0, "0", 1, 1);
+ regs.SetRegisterToInteger(instr.gpr0.Value() + 3, true, 0, mip_level, 1, 1);
break;
}
default: {
- LOG_CRITICAL(HW_GPU, "Unhandled texture query type: {}",
- static_cast<u32>(instr.txq.query_type.Value()));
- UNREACHABLE();
+ UNIMPLEMENTED_MSG("Unhandled texture query type: {}",
+ static_cast<u32>(instr.txq.query_type.Value()));
}
}
+ --shader.scope;
+ shader.AddLine('}');
break;
}
case OpCode::Id::TMML: {
- ASSERT_MSG(!instr.tmml.UsesMiscMode(Tegra::Shader::TextureMiscMode::NODEP),
- "NODEP is not implemented");
- ASSERT_MSG(!instr.tmml.UsesMiscMode(Tegra::Shader::TextureMiscMode::NDV),
- "NDV is not implemented");
+ UNIMPLEMENTED_IF_MSG(instr.tmml.UsesMiscMode(Tegra::Shader::TextureMiscMode::NODEP),
+ "NODEP is not implemented");
+ UNIMPLEMENTED_IF_MSG(instr.tmml.UsesMiscMode(Tegra::Shader::TextureMiscMode::NDV),
+ "NDV is not implemented");
const std::string x = regs.GetRegisterAsFloat(instr.gpr8);
const bool is_array = instr.tmml.array != 0;
@@ -3013,9 +2986,7 @@ private:
break;
}
default:
- LOG_CRITICAL(HW_GPU, "Unhandled texture type {}",
- static_cast<u32>(texture_type));
- UNREACHABLE();
+ UNIMPLEMENTED_MSG("Unhandled texture type {}", static_cast<u32>(texture_type));
// Fallback to interpreting as a 2D texture for now
const std::string y = regs.GetRegisterAsFloat(instr.gpr8.Value() + 1);
@@ -3038,8 +3009,7 @@ private:
break;
}
default: {
- LOG_CRITICAL(HW_GPU, "Unhandled memory instruction: {}", opcode->get().GetName());
- UNREACHABLE();
+ UNIMPLEMENTED_MSG("Unhandled memory instruction: {}", opcode->get().GetName());
}
}
break;
@@ -3125,7 +3095,7 @@ private:
break;
}
case OpCode::Type::HalfSetPredicate: {
- ASSERT_MSG(instr.hsetp2.ftz == 0, "Unimplemented");
+ UNIMPLEMENTED_IF(instr.hsetp2.ftz != 0);
const std::string op_a =
GetHalfFloat(regs.GetRegisterAsInteger(instr.gpr8, 0, false), instr.hsetp2.type_a,
@@ -3170,6 +3140,9 @@ private:
break;
}
case OpCode::Type::PredicateSetRegister: {
+ UNIMPLEMENTED_IF_MSG(instr.generates_cc,
+ "Condition codes generation in PSET is not implemented");
+
const std::string op_a =
GetPredicateCondition(instr.pset.pred12, instr.pset.neg_pred12 != 0);
const std::string op_b =
@@ -3190,12 +3163,6 @@ private:
const std::string value = '(' + result + ") ? 1.0 : 0.0";
regs.SetRegisterToFloat(instr.gpr0, 0, value, 1, 1);
}
-
- if (instr.generates_cc) {
- LOG_CRITICAL(HW_GPU, "PSET Generates an unhandled Control Code");
- UNREACHABLE();
- }
-
break;
}
case OpCode::Type::PredicateSetPredicate: {
@@ -3233,21 +3200,19 @@ private:
const std::string pred =
GetPredicateCondition(instr.csetp.pred39, instr.csetp.neg_pred39 != 0);
const std::string combiner = GetPredicateCombiner(instr.csetp.op);
- const std::string control_code = regs.GetControlCode(instr.csetp.cc);
+ const std::string condition_code = regs.GetConditionCode(instr.csetp.cc);
if (instr.csetp.pred3 != static_cast<u64>(Pred::UnusedIndex)) {
SetPredicate(instr.csetp.pred3,
- '(' + control_code + ") " + combiner + " (" + pred + ')');
+ '(' + condition_code + ") " + combiner + " (" + pred + ')');
}
if (instr.csetp.pred0 != static_cast<u64>(Pred::UnusedIndex)) {
SetPredicate(instr.csetp.pred0,
- "!(" + control_code + ") " + combiner + " (" + pred + ')');
+ "!(" + condition_code + ") " + combiner + " (" + pred + ')');
}
break;
}
default: {
- LOG_CRITICAL(HW_GPU, "Unhandled predicate instruction: {}",
- opcode->get().GetName());
- UNREACHABLE();
+ UNIMPLEMENTED_MSG("Unhandled predicate instruction: {}", opcode->get().GetName());
}
}
break;
@@ -3327,7 +3292,7 @@ private:
break;
}
case OpCode::Type::HalfSet: {
- ASSERT_MSG(instr.hset2.ftz == 0, "Unimplemented");
+ UNIMPLEMENTED_IF(instr.hset2.ftz != 0);
const std::string op_a =
GetHalfFloat(regs.GetRegisterAsInteger(instr.gpr8, 0, false), instr.hset2.type_a,
@@ -3371,15 +3336,17 @@ private:
break;
}
case OpCode::Type::Xmad: {
- ASSERT_MSG(!instr.xmad.sign_a, "Unimplemented");
- ASSERT_MSG(!instr.xmad.sign_b, "Unimplemented");
+ UNIMPLEMENTED_IF(instr.xmad.sign_a);
+ UNIMPLEMENTED_IF(instr.xmad.sign_b);
+ UNIMPLEMENTED_IF_MSG(instr.generates_cc,
+ "Condition codes generation in XMAD is not implemented");
std::string op_a{regs.GetRegisterAsInteger(instr.gpr8, 0, instr.xmad.sign_a)};
std::string op_b;
std::string op_c;
// TODO(bunnei): Needs to be fixed once op_a or op_b is signed
- ASSERT_MSG(instr.xmad.sign_a == instr.xmad.sign_b, "Unimplemented");
+ UNIMPLEMENTED_IF(instr.xmad.sign_a != instr.xmad.sign_b);
const bool is_signed{instr.xmad.sign_a == 1};
bool is_merge{};
@@ -3412,8 +3379,7 @@ private:
break;
}
default: {
- LOG_CRITICAL(HW_GPU, "Unhandled XMAD instruction: {}", opcode->get().GetName());
- UNREACHABLE();
+ UNIMPLEMENTED_MSG("Unhandled XMAD instruction: {}", opcode->get().GetName());
}
}
@@ -3449,9 +3415,8 @@ private:
op_c = "((" + op_c + ") + (" + src2 + "<< 16))";
break;
default: {
- LOG_CRITICAL(HW_GPU, "Unhandled XMAD mode: {}",
- static_cast<u32>(instr.xmad.mode.Value()));
- UNREACHABLE();
+ UNIMPLEMENTED_MSG("Unhandled XMAD mode: {}",
+ static_cast<u32>(instr.xmad.mode.Value()));
}
}
@@ -3461,25 +3426,19 @@ private:
}
regs.SetRegisterToInteger(instr.gpr0, is_signed, 0, sum, 1, 1);
- if (instr.generates_cc) {
- LOG_CRITICAL(HW_GPU, "XMAD Generates an unhandled Control Code");
- UNREACHABLE();
- }
break;
}
default: {
switch (opcode->get().GetId()) {
case OpCode::Id::EXIT: {
+ const Tegra::Shader::ConditionCode cc = instr.flow_condition_code;
+ UNIMPLEMENTED_IF_MSG(cc != Tegra::Shader::ConditionCode::T,
+ "EXIT condition code used: {}", static_cast<u32>(cc));
+
if (stage == Maxwell3D::Regs::ShaderStage::Fragment) {
EmitFragmentOutputsWrite();
}
- const Tegra::Shader::ControlCode cc = instr.flow_control_code;
- if (cc != Tegra::Shader::ControlCode::T) {
- LOG_CRITICAL(HW_GPU, "EXIT Control Code used: {}", static_cast<u32>(cc));
- UNREACHABLE();
- }
-
switch (instr.flow.cond) {
case Tegra::Shader::FlowCondition::Always:
shader.AddLine("return true;");
@@ -3494,26 +3453,24 @@ private:
case Tegra::Shader::FlowCondition::Fcsm_Tr:
// TODO(bunnei): What is this used for? If we assume this conditon is not
// satisifed, dual vertex shaders in Farming Simulator make more sense
- LOG_CRITICAL(HW_GPU, "Skipping unknown FlowCondition::Fcsm_Tr");
+ UNIMPLEMENTED_MSG("Skipping unknown FlowCondition::Fcsm_Tr");
break;
default:
- LOG_CRITICAL(HW_GPU, "Unhandled flow condition: {}",
- static_cast<u32>(instr.flow.cond.Value()));
- UNREACHABLE();
+ UNIMPLEMENTED_MSG("Unhandled flow condition: {}",
+ static_cast<u32>(instr.flow.cond.Value()));
}
break;
}
case OpCode::Id::KIL: {
- ASSERT(instr.flow.cond == Tegra::Shader::FlowCondition::Always);
+ UNIMPLEMENTED_IF(instr.flow.cond != Tegra::Shader::FlowCondition::Always);
+
+ const Tegra::Shader::ConditionCode cc = instr.flow_condition_code;
+ UNIMPLEMENTED_IF_MSG(cc != Tegra::Shader::ConditionCode::T,
+ "KIL condition code used: {}", static_cast<u32>(cc));
// Enclose "discard" in a conditional, so that GLSL compilation does not complain
// about unexecuted instructions that may follow this.
- const Tegra::Shader::ControlCode cc = instr.flow_control_code;
- if (cc != Tegra::Shader::ControlCode::T) {
- LOG_CRITICAL(HW_GPU, "KIL Control Code used: {}", static_cast<u32>(cc));
- UNREACHABLE();
- }
shader.AddLine("if (true) {");
++shader.scope;
shader.AddLine("discard;");
@@ -3523,7 +3480,8 @@ private:
break;
}
case OpCode::Id::OUT_R: {
- ASSERT(instr.gpr20.Value() == Register::ZeroIndex);
+ UNIMPLEMENTED_IF_MSG(instr.gpr20.Value() != Register::ZeroIndex,
+ "Stream buffer is not supported");
ASSERT_MSG(stage == Maxwell3D::Regs::ShaderStage::Geometry,
"OUT is expected to be used in a geometry shader.");
@@ -3550,18 +3508,17 @@ private:
break;
}
default: {
- LOG_CRITICAL(HW_GPU, "Unhandled system move: {}",
- static_cast<u32>(instr.sys20.Value()));
- UNREACHABLE();
+ UNIMPLEMENTED_MSG("Unhandled system move: {}",
+ static_cast<u32>(instr.sys20.Value()));
}
}
break;
}
case OpCode::Id::ISBERD: {
- ASSERT(instr.isberd.o == 0);
- ASSERT(instr.isberd.skew == 0);
- ASSERT(instr.isberd.shift == Tegra::Shader::IsberdShift::None);
- ASSERT(instr.isberd.mode == Tegra::Shader::IsberdMode::None);
+ UNIMPLEMENTED_IF(instr.isberd.o != 0);
+ UNIMPLEMENTED_IF(instr.isberd.skew != 0);
+ UNIMPLEMENTED_IF(instr.isberd.shift != Tegra::Shader::IsberdShift::None);
+ UNIMPLEMENTED_IF(instr.isberd.mode != Tegra::Shader::IsberdMode::None);
ASSERT_MSG(stage == Maxwell3D::Regs::ShaderStage::Geometry,
"ISBERD is expected to be used in a geometry shader.");
LOG_WARNING(HW_GPU, "ISBERD instruction is incomplete");
@@ -3569,13 +3526,13 @@ private:
break;
}
case OpCode::Id::BRA: {
- ASSERT_MSG(instr.bra.constant_buffer == 0,
- "BRA with constant buffers are not implemented");
- const Tegra::Shader::ControlCode cc = instr.flow_control_code;
- if (cc != Tegra::Shader::ControlCode::T) {
- LOG_CRITICAL(HW_GPU, "BRA Control Code used: {}", static_cast<u32>(cc));
- UNREACHABLE();
- }
+ UNIMPLEMENTED_IF_MSG(instr.bra.constant_buffer != 0,
+ "BRA with constant buffers are not implemented");
+
+ const Tegra::Shader::ConditionCode cc = instr.flow_condition_code;
+ UNIMPLEMENTED_IF_MSG(cc != Tegra::Shader::ConditionCode::T,
+ "BRA condition code used: {}", static_cast<u32>(cc));
+
const u32 target = offset + instr.bra.GetBranchTarget();
shader.AddLine("{ jmp_to = " + std::to_string(target) + "u; break; }");
break;
@@ -3598,7 +3555,8 @@ private:
// The SSY opcode tells the GPU where to re-converge divergent execution paths, it
// sets the target of the jump that the SYNC instruction will make. The SSY opcode
// has a similar structure to the BRA opcode.
- ASSERT_MSG(instr.bra.constant_buffer == 0, "Constant buffer flow is not supported");
+ UNIMPLEMENTED_IF_MSG(instr.bra.constant_buffer != 0,
+ "Constant buffer flow is not supported");
const u32 target = offset + instr.bra.GetBranchTarget();
EmitPushToFlowStack(target);
@@ -3608,29 +3566,28 @@ private:
// PBK pushes to a stack the address where BRK will jump to. This shares stack with
// SSY but using SYNC on a PBK address will kill the shader execution. We don't
// emulate this because it's very unlikely a driver will emit such invalid shader.
- ASSERT_MSG(instr.bra.constant_buffer == 0, "Constant buffer PBK is not supported");
+ UNIMPLEMENTED_IF_MSG(instr.bra.constant_buffer != 0,
+ "Constant buffer PBK is not supported");
const u32 target = offset + instr.bra.GetBranchTarget();
EmitPushToFlowStack(target);
break;
}
case OpCode::Id::SYNC: {
+ const Tegra::Shader::ConditionCode cc = instr.flow_condition_code;
+ UNIMPLEMENTED_IF_MSG(cc != Tegra::Shader::ConditionCode::T,
+ "SYNC condition code used: {}", static_cast<u32>(cc));
+
// The SYNC opcode jumps to the address previously set by the SSY opcode
- const Tegra::Shader::ControlCode cc = instr.flow_control_code;
- if (cc != Tegra::Shader::ControlCode::T) {
- LOG_CRITICAL(HW_GPU, "SYNC Control Code used: {}", static_cast<u32>(cc));
- UNREACHABLE();
- }
EmitPopFromFlowStack();
break;
}
case OpCode::Id::BRK: {
// The BRK opcode jumps to the address previously set by the PBK opcode
- const Tegra::Shader::ControlCode cc = instr.flow_control_code;
- if (cc != Tegra::Shader::ControlCode::T) {
- LOG_CRITICAL(HW_GPU, "BRK Control Code used: {}", static_cast<u32>(cc));
- UNREACHABLE();
- }
+ const Tegra::Shader::ConditionCode cc = instr.flow_condition_code;
+ UNIMPLEMENTED_IF_MSG(cc != Tegra::Shader::ConditionCode::T,
+ "BRK condition code used: {}", static_cast<u32>(cc));
+
EmitPopFromFlowStack();
break;
}
@@ -3641,6 +3598,9 @@ private:
break;
}
case OpCode::Id::VMAD: {
+ UNIMPLEMENTED_IF_MSG(instr.generates_cc,
+ "Condition codes generation in VMAD is not implemented");
+
const bool result_signed = instr.video.signed_a == 1 || instr.video.signed_b == 1;
const std::string op_a = GetVideoOperandA(instr);
const std::string op_b = GetVideoOperandB(instr);
@@ -3660,11 +3620,6 @@ private:
regs.SetRegisterToInteger(instr.gpr0, result_signed, 1, result, 1, 1,
instr.vmad.saturate == 1, 0, Register::Size::Word,
instr.vmad.cc);
- if (instr.generates_cc) {
- LOG_CRITICAL(HW_GPU, "VMAD Generates an unhandled Control Code");
- UNREACHABLE();
- }
-
break;
}
case OpCode::Id::VSETP: {
@@ -3691,10 +3646,7 @@ private:
}
break;
}
- default: {
- LOG_CRITICAL(HW_GPU, "Unhandled instruction: {}", opcode->get().GetName());
- UNREACHABLE();
- }
+ default: { UNIMPLEMENTED_MSG("Unhandled instruction: {}", opcode->get().GetName()); }
}
break;
@@ -3819,6 +3771,7 @@ private:
Maxwell3D::Regs::ShaderStage stage;
const std::string& suffix;
u64 local_memory_size;
+ std::size_t shader_length;
ShaderWriter shader;
ShaderWriter declarations;
@@ -3837,9 +3790,10 @@ std::optional<ProgramResult> DecompileProgram(const ProgramCode& program_code, u
Maxwell3D::Regs::ShaderStage stage,
const std::string& suffix) {
try {
- const auto subroutines =
- ControlFlowAnalyzer(program_code, main_offset, suffix).GetSubroutines();
- GLSLGenerator generator(subroutines, program_code, main_offset, stage, suffix);
+ ControlFlowAnalyzer analyzer(program_code, main_offset, suffix);
+ const auto subroutines = analyzer.GetSubroutines();
+ GLSLGenerator generator(subroutines, program_code, main_offset, stage, suffix,
+ analyzer.GetShaderLength());
return ProgramResult{generator.GetShaderCode(), generator.GetEntries()};
} catch (const DecompileFail& exception) {
LOG_ERROR(HW_GPU, "Shader decompilation failed: {}", exception.what());
diff --git a/src/video_core/renderer_opengl/gl_shader_gen.cpp b/src/video_core/renderer_opengl/gl_shader_gen.cpp
index 9d17edd63..eea090e52 100644
--- a/src/video_core/renderer_opengl/gl_shader_gen.cpp
+++ b/src/video_core/renderer_opengl/gl_shader_gen.cpp
@@ -82,8 +82,8 @@ void main() {
}
ProgramResult GenerateGeometryShader(const ShaderSetup& setup) {
- std::string out = "#version 430 core\n";
- out += "#extension GL_ARB_separate_shader_objects : enable\n\n";
+ // Version is intentionally skipped in shader generation, it's added by the lazy compilation.
+ std::string out = "#extension GL_ARB_separate_shader_objects : enable\n\n";
out += Decompiler::GetCommonDeclarations();
out += "bool exec_geometry();\n";
diff --git a/src/video_core/renderer_opengl/gl_shader_gen.h b/src/video_core/renderer_opengl/gl_shader_gen.h
index 520b9d4e3..b425d98ae 100644
--- a/src/video_core/renderer_opengl/gl_shader_gen.h
+++ b/src/video_core/renderer_opengl/gl_shader_gen.h
@@ -163,6 +163,7 @@ private:
struct ShaderEntries {
std::vector<ConstBufferEntry> const_buffer_entries;
std::vector<SamplerEntry> texture_samplers;
+ std::size_t shader_length;
};
using ProgramResult = std::pair<std::string, ShaderEntries>;
diff --git a/src/video_core/renderer_opengl/gl_shader_manager.h b/src/video_core/renderer_opengl/gl_shader_manager.h
index 36fe1f04c..9a5d7e289 100644
--- a/src/video_core/renderer_opengl/gl_shader_manager.h
+++ b/src/video_core/renderer_opengl/gl_shader_manager.h
@@ -7,6 +7,7 @@
#include <glad/glad.h>
#include "video_core/renderer_opengl/gl_resource_manager.h"
+#include "video_core/renderer_opengl/gl_state.h"
#include "video_core/renderer_opengl/maxwell_to_gl.h"
namespace OpenGL::GLShader {
@@ -66,6 +67,7 @@ public:
glUseProgramStages(pipeline.handle, GL_FRAGMENT_SHADER_BIT, fs);
state.draw.shader_program = 0;
state.draw.program_pipeline = pipeline.handle;
+ state.geometry_shaders.enabled = (gs != 0);
}
private:
diff --git a/src/video_core/renderer_opengl/gl_state.cpp b/src/video_core/renderer_opengl/gl_state.cpp
index b6b426f34..934f4db78 100644
--- a/src/video_core/renderer_opengl/gl_state.cpp
+++ b/src/video_core/renderer_opengl/gl_state.cpp
@@ -14,7 +14,10 @@ OpenGLState OpenGLState::cur_state;
bool OpenGLState::s_rgb_used;
OpenGLState::OpenGLState() {
// These all match default OpenGL values
+ geometry_shaders.enabled = false;
framebuffer_srgb.enabled = false;
+ multisample_control.alpha_to_coverage = false;
+ multisample_control.alpha_to_one = false;
cull.enabled = false;
cull.mode = GL_BACK;
cull.front_face = GL_CCW;
@@ -22,17 +25,15 @@ OpenGLState::OpenGLState() {
depth.test_enabled = false;
depth.test_func = GL_LESS;
depth.write_mask = GL_TRUE;
- depth.depth_range_near = 0.0f;
- depth.depth_range_far = 1.0f;
primitive_restart.enabled = false;
primitive_restart.index = 0;
-
- color_mask.red_enabled = GL_TRUE;
- color_mask.green_enabled = GL_TRUE;
- color_mask.blue_enabled = GL_TRUE;
- color_mask.alpha_enabled = GL_TRUE;
-
+ for (auto& item : color_mask) {
+ item.red_enabled = GL_TRUE;
+ item.green_enabled = GL_TRUE;
+ item.blue_enabled = GL_TRUE;
+ item.alpha_enabled = GL_TRUE;
+ }
stencil.test_enabled = false;
auto reset_stencil = [](auto& config) {
config.test_func = GL_ALWAYS;
@@ -45,19 +46,33 @@ OpenGLState::OpenGLState() {
};
reset_stencil(stencil.front);
reset_stencil(stencil.back);
-
- blend.enabled = true;
- blend.rgb_equation = GL_FUNC_ADD;
- blend.a_equation = GL_FUNC_ADD;
- blend.src_rgb_func = GL_ONE;
- blend.dst_rgb_func = GL_ZERO;
- blend.src_a_func = GL_ONE;
- blend.dst_a_func = GL_ZERO;
- blend.color.red = 0.0f;
- blend.color.green = 0.0f;
- blend.color.blue = 0.0f;
- blend.color.alpha = 0.0f;
-
+ for (auto& item : viewports) {
+ item.x = 0;
+ item.y = 0;
+ item.width = 0;
+ item.height = 0;
+ item.depth_range_near = 0.0f;
+ item.depth_range_far = 1.0f;
+ item.scissor.enabled = false;
+ item.scissor.x = 0;
+ item.scissor.y = 0;
+ item.scissor.width = 0;
+ item.scissor.height = 0;
+ }
+ for (auto& item : blend) {
+ item.enabled = true;
+ item.rgb_equation = GL_FUNC_ADD;
+ item.a_equation = GL_FUNC_ADD;
+ item.src_rgb_func = GL_ONE;
+ item.dst_rgb_func = GL_ZERO;
+ item.src_a_func = GL_ONE;
+ item.dst_a_func = GL_ZERO;
+ }
+ independant_blend.enabled = false;
+ blend_color.red = 0.0f;
+ blend_color.green = 0.0f;
+ blend_color.blue = 0.0f;
+ blend_color.alpha = 0.0f;
logic_op.enabled = false;
logic_op.operation = GL_COPY;
@@ -73,20 +88,10 @@ OpenGLState::OpenGLState() {
draw.shader_program = 0;
draw.program_pipeline = 0;
- scissor.enabled = false;
- scissor.x = 0;
- scissor.y = 0;
- scissor.width = 0;
- scissor.height = 0;
-
- viewport.x = 0;
- viewport.y = 0;
- viewport.width = 0;
- viewport.height = 0;
-
clip_distance = {};
point.size = 1;
+ fragment_color_clamp.enabled = false;
}
void OpenGLState::ApplyDefaultState() {
@@ -134,6 +139,32 @@ void OpenGLState::ApplyCulling() const {
}
}
+void OpenGLState::ApplyColorMask() const {
+ if (GLAD_GL_ARB_viewport_array && independant_blend.enabled) {
+ for (size_t i = 0; i < Tegra::Engines::Maxwell3D::Regs::NumRenderTargets; i++) {
+ const auto& updated = color_mask[i];
+ const auto& current = cur_state.color_mask[i];
+ if (updated.red_enabled != current.red_enabled ||
+ updated.green_enabled != current.green_enabled ||
+ updated.blue_enabled != current.blue_enabled ||
+ updated.alpha_enabled != current.alpha_enabled) {
+ glColorMaski(static_cast<GLuint>(i), updated.red_enabled, updated.green_enabled,
+ updated.blue_enabled, updated.alpha_enabled);
+ }
+ }
+ } else {
+ const auto& updated = color_mask[0];
+ const auto& current = cur_state.color_mask[0];
+ if (updated.red_enabled != current.red_enabled ||
+ updated.green_enabled != current.green_enabled ||
+ updated.blue_enabled != current.blue_enabled ||
+ updated.alpha_enabled != current.alpha_enabled) {
+ glColorMask(updated.red_enabled, updated.green_enabled, updated.blue_enabled,
+ updated.alpha_enabled);
+ }
+ }
+}
+
void OpenGLState::ApplyDepth() const {
// Depth test
const bool depth_test_changed = depth.test_enabled != cur_state.depth.test_enabled;
@@ -152,11 +183,6 @@ void OpenGLState::ApplyDepth() const {
if (depth.write_mask != cur_state.depth.write_mask) {
glDepthMask(depth.write_mask);
}
- // Depth range
- if (depth.depth_range_near != cur_state.depth.depth_range_near ||
- depth.depth_range_far != cur_state.depth.depth_range_far) {
- glDepthRange(depth.depth_range_near, depth.depth_range_far);
- }
}
void OpenGLState::ApplyPrimitiveRestart() const {
@@ -207,53 +233,160 @@ void OpenGLState::ApplyStencilTest() const {
config_stencil(GL_BACK, stencil.back, cur_state.stencil.back);
}
}
+// Viewport does not affects glClearBuffer so emulate viewport using scissor test
+void OpenGLState::EmulateViewportWithScissor() {
+ auto& current = viewports[0];
+ if (current.scissor.enabled) {
+ const GLint left = std::max(current.x, current.scissor.x);
+ const GLint right =
+ std::max(current.x + current.width, current.scissor.x + current.scissor.width);
+ const GLint bottom = std::max(current.y, current.scissor.y);
+ const GLint top =
+ std::max(current.y + current.height, current.scissor.y + current.scissor.height);
+ current.scissor.x = std::max(left, 0);
+ current.scissor.y = std::max(bottom, 0);
+ current.scissor.width = std::max(right - left, 0);
+ current.scissor.height = std::max(top - bottom, 0);
+ } else {
+ current.scissor.enabled = true;
+ current.scissor.x = current.x;
+ current.scissor.y = current.y;
+ current.scissor.width = current.width;
+ current.scissor.height = current.height;
+ }
+}
-void OpenGLState::ApplyScissorTest() const {
- const bool scissor_changed = scissor.enabled != cur_state.scissor.enabled;
- if (scissor_changed) {
- if (scissor.enabled) {
- glEnable(GL_SCISSOR_TEST);
- } else {
- glDisable(GL_SCISSOR_TEST);
+void OpenGLState::ApplyViewport() const {
+ if (GLAD_GL_ARB_viewport_array && geometry_shaders.enabled) {
+ for (GLuint i = 0; i < static_cast<GLuint>(Tegra::Engines::Maxwell3D::Regs::NumViewports);
+ i++) {
+ const auto& current = cur_state.viewports[i];
+ const auto& updated = viewports[i];
+ if (updated.x != current.x || updated.y != current.y ||
+ updated.width != current.width || updated.height != current.height) {
+ glViewportIndexedf(
+ i, static_cast<GLfloat>(updated.x), static_cast<GLfloat>(updated.y),
+ static_cast<GLfloat>(updated.width), static_cast<GLfloat>(updated.height));
+ }
+ if (updated.depth_range_near != current.depth_range_near ||
+ updated.depth_range_far != current.depth_range_far) {
+ glDepthRangeIndexed(i, updated.depth_range_near, updated.depth_range_far);
+ }
+ const bool scissor_changed = updated.scissor.enabled != current.scissor.enabled;
+ if (scissor_changed) {
+ if (updated.scissor.enabled) {
+ glEnablei(GL_SCISSOR_TEST, i);
+ } else {
+ glDisablei(GL_SCISSOR_TEST, i);
+ }
+ }
+ if (updated.scissor.enabled &&
+ (scissor_changed || updated.scissor.x != current.scissor.x ||
+ updated.scissor.y != current.scissor.y ||
+ updated.scissor.width != current.scissor.width ||
+ updated.scissor.height != current.scissor.height)) {
+ glScissorIndexed(i, updated.scissor.x, updated.scissor.y, updated.scissor.width,
+ updated.scissor.height);
+ }
+ }
+ } else {
+ const auto& current = cur_state.viewports[0];
+ const auto& updated = viewports[0];
+ if (updated.x != current.x || updated.y != current.y || updated.width != current.width ||
+ updated.height != current.height) {
+ glViewport(updated.x, updated.y, updated.width, updated.height);
+ }
+ if (updated.depth_range_near != current.depth_range_near ||
+ updated.depth_range_far != current.depth_range_far) {
+ glDepthRange(updated.depth_range_near, updated.depth_range_far);
+ }
+ const bool scissor_changed = updated.scissor.enabled != current.scissor.enabled;
+ if (scissor_changed) {
+ if (updated.scissor.enabled) {
+ glEnable(GL_SCISSOR_TEST);
+ } else {
+ glDisable(GL_SCISSOR_TEST);
+ }
+ }
+ if (updated.scissor.enabled && (scissor_changed || updated.scissor.x != current.scissor.x ||
+ updated.scissor.y != current.scissor.y ||
+ updated.scissor.width != current.scissor.width ||
+ updated.scissor.height != current.scissor.height)) {
+ glScissor(updated.scissor.x, updated.scissor.y, updated.scissor.width,
+ updated.scissor.height);
}
- }
- if (scissor_changed || scissor_changed || scissor.x != cur_state.scissor.x ||
- scissor.y != cur_state.scissor.y || scissor.width != cur_state.scissor.width ||
- scissor.height != cur_state.scissor.height) {
- glScissor(scissor.x, scissor.y, scissor.width, scissor.height);
}
}
-void OpenGLState::ApplyBlending() const {
- const bool blend_changed = blend.enabled != cur_state.blend.enabled;
+void OpenGLState::ApplyGlobalBlending() const {
+ const Blend& current = cur_state.blend[0];
+ const Blend& updated = blend[0];
+ const bool blend_changed = updated.enabled != current.enabled;
if (blend_changed) {
- if (blend.enabled) {
- ASSERT(!logic_op.enabled);
+ if (updated.enabled) {
glEnable(GL_BLEND);
} else {
glDisable(GL_BLEND);
}
}
- if (blend.enabled) {
- if (blend_changed || blend.color.red != cur_state.blend.color.red ||
- blend.color.green != cur_state.blend.color.green ||
- blend.color.blue != cur_state.blend.color.blue ||
- blend.color.alpha != cur_state.blend.color.alpha) {
- glBlendColor(blend.color.red, blend.color.green, blend.color.blue, blend.color.alpha);
- }
+ if (!updated.enabled) {
+ return;
+ }
+ if (blend_changed || updated.src_rgb_func != current.src_rgb_func ||
+ updated.dst_rgb_func != current.dst_rgb_func || updated.src_a_func != current.src_a_func ||
+ updated.dst_a_func != current.dst_a_func) {
+ glBlendFuncSeparate(updated.src_rgb_func, updated.dst_rgb_func, updated.src_a_func,
+ updated.dst_a_func);
+ }
+
+ if (blend_changed || updated.rgb_equation != current.rgb_equation ||
+ updated.a_equation != current.a_equation) {
+ glBlendEquationSeparate(updated.rgb_equation, updated.a_equation);
+ }
+}
- if (blend_changed || blend.src_rgb_func != cur_state.blend.src_rgb_func ||
- blend.dst_rgb_func != cur_state.blend.dst_rgb_func ||
- blend.src_a_func != cur_state.blend.src_a_func ||
- blend.dst_a_func != cur_state.blend.dst_a_func) {
- glBlendFuncSeparate(blend.src_rgb_func, blend.dst_rgb_func, blend.src_a_func,
- blend.dst_a_func);
+void OpenGLState::ApplyTargetBlending(std::size_t target, bool force) const {
+ const Blend& updated = blend[target];
+ const Blend& current = cur_state.blend[target];
+ const bool blend_changed = updated.enabled != current.enabled || force;
+ if (blend_changed) {
+ if (updated.enabled) {
+ glEnablei(GL_BLEND, static_cast<GLuint>(target));
+ } else {
+ glDisablei(GL_BLEND, static_cast<GLuint>(target));
}
+ }
+ if (!updated.enabled) {
+ return;
+ }
+ if (blend_changed || updated.src_rgb_func != current.src_rgb_func ||
+ updated.dst_rgb_func != current.dst_rgb_func || updated.src_a_func != current.src_a_func ||
+ updated.dst_a_func != current.dst_a_func) {
+ glBlendFuncSeparatei(static_cast<GLuint>(target), updated.src_rgb_func,
+ updated.dst_rgb_func, updated.src_a_func, updated.dst_a_func);
+ }
- if (blend_changed || blend.rgb_equation != cur_state.blend.rgb_equation ||
- blend.a_equation != cur_state.blend.a_equation) {
- glBlendEquationSeparate(blend.rgb_equation, blend.a_equation);
+ if (blend_changed || updated.rgb_equation != current.rgb_equation ||
+ updated.a_equation != current.a_equation) {
+ glBlendEquationSeparatei(static_cast<GLuint>(target), updated.rgb_equation,
+ updated.a_equation);
+ }
+}
+
+void OpenGLState::ApplyBlending() const {
+ if (independant_blend.enabled) {
+ for (size_t i = 0; i < Tegra::Engines::Maxwell3D::Regs::NumRenderTargets; i++) {
+ ApplyTargetBlending(i,
+ independant_blend.enabled != cur_state.independant_blend.enabled);
}
+ } else {
+ ApplyGlobalBlending();
+ }
+ if (blend_color.red != cur_state.blend_color.red ||
+ blend_color.green != cur_state.blend_color.green ||
+ blend_color.blue != cur_state.blend_color.blue ||
+ blend_color.alpha != cur_state.blend_color.alpha) {
+ glBlendColor(blend_color.red, blend_color.green, blend_color.blue, blend_color.alpha);
}
}
@@ -261,7 +394,6 @@ void OpenGLState::ApplyLogicOp() const {
const bool logic_op_changed = logic_op.enabled != cur_state.logic_op.enabled;
if (logic_op_changed) {
if (logic_op.enabled) {
- ASSERT(!blend.enabled);
glEnable(GL_COLOR_LOGIC_OP);
} else {
glDisable(GL_COLOR_LOGIC_OP);
@@ -315,7 +447,7 @@ void OpenGLState::ApplySamplers() const {
}
}
-void OpenGLState::Apply() const {
+void OpenGLState::ApplyFramebufferState() const {
// Framebuffer
if (draw.read_framebuffer != cur_state.draw.read_framebuffer) {
glBindFramebuffer(GL_READ_FRAMEBUFFER, draw.read_framebuffer);
@@ -323,7 +455,9 @@ void OpenGLState::Apply() const {
if (draw.draw_framebuffer != cur_state.draw.draw_framebuffer) {
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, draw.draw_framebuffer);
}
+}
+void OpenGLState::ApplyVertexBufferState() const {
// Vertex array
if (draw.vertex_array != cur_state.draw.vertex_array) {
glBindVertexArray(draw.vertex_array);
@@ -333,7 +467,11 @@ void OpenGLState::Apply() const {
if (draw.vertex_buffer != cur_state.draw.vertex_buffer) {
glBindBuffer(GL_ARRAY_BUFFER, draw.vertex_buffer);
}
+}
+void OpenGLState::Apply() const {
+ ApplyFramebufferState();
+ ApplyVertexBufferState();
// Uniform buffer
if (draw.uniform_buffer != cur_state.draw.uniform_buffer) {
glBindBuffer(GL_UNIFORM_BUFFER, draw.uniform_buffer);
@@ -348,12 +486,6 @@ void OpenGLState::Apply() const {
if (draw.program_pipeline != cur_state.draw.program_pipeline) {
glBindProgramPipeline(draw.program_pipeline);
}
- // Viewport
- if (viewport.x != cur_state.viewport.x || viewport.y != cur_state.viewport.y ||
- viewport.width != cur_state.viewport.width ||
- viewport.height != cur_state.viewport.height) {
- glViewport(viewport.x, viewport.y, viewport.width, viewport.height);
- }
// Clip distance
for (std::size_t i = 0; i < clip_distance.size(); ++i) {
if (clip_distance[i] != cur_state.clip_distance[i]) {
@@ -364,19 +496,33 @@ void OpenGLState::Apply() const {
}
}
}
- // Color mask
- if (color_mask.red_enabled != cur_state.color_mask.red_enabled ||
- color_mask.green_enabled != cur_state.color_mask.green_enabled ||
- color_mask.blue_enabled != cur_state.color_mask.blue_enabled ||
- color_mask.alpha_enabled != cur_state.color_mask.alpha_enabled) {
- glColorMask(color_mask.red_enabled, color_mask.green_enabled, color_mask.blue_enabled,
- color_mask.alpha_enabled);
- }
// Point
if (point.size != cur_state.point.size) {
glPointSize(point.size);
}
- ApplyScissorTest();
+ if (GLAD_GL_ARB_color_buffer_float) {
+ if (fragment_color_clamp.enabled != cur_state.fragment_color_clamp.enabled) {
+ glClampColor(GL_CLAMP_FRAGMENT_COLOR_ARB,
+ fragment_color_clamp.enabled ? GL_TRUE : GL_FALSE);
+ }
+ }
+ if (multisample_control.alpha_to_coverage != cur_state.multisample_control.alpha_to_coverage) {
+ if (multisample_control.alpha_to_coverage) {
+ glEnable(GL_SAMPLE_ALPHA_TO_COVERAGE);
+ } else {
+ glDisable(GL_SAMPLE_ALPHA_TO_COVERAGE);
+ }
+ }
+ if (multisample_control.alpha_to_one != cur_state.multisample_control.alpha_to_one) {
+ if (multisample_control.alpha_to_one) {
+ glEnable(GL_SAMPLE_ALPHA_TO_ONE);
+ } else {
+ glDisable(GL_SAMPLE_ALPHA_TO_ONE);
+ }
+ }
+
+ ApplyColorMask();
+ ApplyViewport();
ApplyStencilTest();
ApplySRgb();
ApplyCulling();
diff --git a/src/video_core/renderer_opengl/gl_state.h b/src/video_core/renderer_opengl/gl_state.h
index fe648aff6..032fc43f0 100644
--- a/src/video_core/renderer_opengl/gl_state.h
+++ b/src/video_core/renderer_opengl/gl_state.h
@@ -40,17 +40,28 @@ public:
} framebuffer_srgb;
struct {
+ bool alpha_to_coverage; // GL_ALPHA_TO_COVERAGE
+ bool alpha_to_one; // GL_ALPHA_TO_ONE
+ } multisample_control;
+
+ struct {
+ bool enabled; // GL_CLAMP_FRAGMENT_COLOR_ARB
+ } fragment_color_clamp;
+
+ struct {
+ bool enabled; // viewports arrays are only supported when geometry shaders are enabled.
+ } geometry_shaders;
+
+ struct {
bool enabled; // GL_CULL_FACE
GLenum mode; // GL_CULL_FACE_MODE
GLenum front_face; // GL_FRONT_FACE
} cull;
struct {
- bool test_enabled; // GL_DEPTH_TEST
- GLenum test_func; // GL_DEPTH_FUNC
- GLboolean write_mask; // GL_DEPTH_WRITEMASK
- GLfloat depth_range_near; // GL_DEPTH_RANGE
- GLfloat depth_range_far; // GL_DEPTH_RANGE
+ bool test_enabled; // GL_DEPTH_TEST
+ GLenum test_func; // GL_DEPTH_FUNC
+ GLboolean write_mask; // GL_DEPTH_WRITEMASK
} depth;
struct {
@@ -58,13 +69,14 @@ public:
GLuint index;
} primitive_restart; // GL_PRIMITIVE_RESTART
- struct {
+ struct ColorMask {
GLboolean red_enabled;
GLboolean green_enabled;
GLboolean blue_enabled;
GLboolean alpha_enabled;
- } color_mask; // GL_COLOR_WRITEMASK
-
+ };
+ std::array<ColorMask, Tegra::Engines::Maxwell3D::Regs::NumRenderTargets>
+ color_mask; // GL_COLOR_WRITEMASK
struct {
bool test_enabled; // GL_STENCIL_TEST
struct {
@@ -78,7 +90,7 @@ public:
} front, back;
} stencil;
- struct {
+ struct Blend {
bool enabled; // GL_BLEND
GLenum rgb_equation; // GL_BLEND_EQUATION_RGB
GLenum a_equation; // GL_BLEND_EQUATION_ALPHA
@@ -86,14 +98,19 @@ public:
GLenum dst_rgb_func; // GL_BLEND_DST_RGB
GLenum src_a_func; // GL_BLEND_SRC_ALPHA
GLenum dst_a_func; // GL_BLEND_DST_ALPHA
+ };
+ std::array<Blend, Tegra::Engines::Maxwell3D::Regs::NumRenderTargets> blend;
- struct {
- GLclampf red;
- GLclampf green;
- GLclampf blue;
- GLclampf alpha;
- } color; // GL_BLEND_COLOR
- } blend;
+ struct {
+ bool enabled;
+ } independant_blend;
+
+ struct {
+ GLclampf red;
+ GLclampf green;
+ GLclampf blue;
+ GLclampf alpha;
+ } blend_color; // GL_BLEND_COLOR
struct {
bool enabled; // GL_LOGIC_OP_MODE
@@ -138,20 +155,22 @@ public:
GLuint program_pipeline; // GL_PROGRAM_PIPELINE_BINDING
} draw;
- struct {
- bool enabled; // GL_SCISSOR_TEST
+ struct viewport {
GLint x;
GLint y;
- GLsizei width;
- GLsizei height;
- } scissor;
-
- struct {
- GLint x;
- GLint y;
- GLsizei width;
- GLsizei height;
- } viewport;
+ GLint width;
+ GLint height;
+ GLfloat depth_range_near; // GL_DEPTH_RANGE
+ GLfloat depth_range_far; // GL_DEPTH_RANGE
+ struct {
+ bool enabled; // GL_SCISSOR_TEST
+ GLint x;
+ GLint y;
+ GLsizei width;
+ GLsizei height;
+ } scissor;
+ };
+ std::array<viewport, Tegra::Engines::Maxwell3D::Regs::NumViewports> viewports;
struct {
float size; // GL_POINT_SIZE
@@ -173,6 +192,10 @@ public:
}
/// Apply this state as the current OpenGL state
void Apply() const;
+ /// Apply only the state afecting the framebuffer
+ void ApplyFramebufferState() const;
+ /// Apply only the state afecting the vertex buffer
+ void ApplyVertexBufferState() const;
/// Set the initial OpenGL state
static void ApplyDefaultState();
/// Resets any references to the given resource
@@ -183,6 +206,7 @@ public:
OpenGLState& ResetBuffer(GLuint handle);
OpenGLState& ResetVertexArray(GLuint handle);
OpenGLState& ResetFramebuffer(GLuint handle);
+ void EmulateViewportWithScissor();
private:
static OpenGLState cur_state;
@@ -191,10 +215,13 @@ private:
static bool s_rgb_used;
void ApplySRgb() const;
void ApplyCulling() const;
+ void ApplyColorMask() const;
void ApplyDepth() const;
void ApplyPrimitiveRestart() const;
void ApplyStencilTest() const;
- void ApplyScissorTest() const;
+ void ApplyViewport() const;
+ void ApplyTargetBlending(std::size_t target, bool force) const;
+ void ApplyGlobalBlending() const;
void ApplyBlending() const;
void ApplyLogicOp() const;
void ApplyTextures() const;
diff --git a/src/video_core/renderer_opengl/gl_stream_buffer.cpp b/src/video_core/renderer_opengl/gl_stream_buffer.cpp
index e409228cc..b97b895a4 100644
--- a/src/video_core/renderer_opengl/gl_stream_buffer.cpp
+++ b/src/video_core/renderer_opengl/gl_stream_buffer.cpp
@@ -6,9 +6,13 @@
#include <vector>
#include "common/alignment.h"
#include "common/assert.h"
+#include "common/microprofile.h"
#include "video_core/renderer_opengl/gl_state.h"
#include "video_core/renderer_opengl/gl_stream_buffer.h"
+MICROPROFILE_DEFINE(OpenGL_StreamBuffer, "OpenGL", "Stream Buffer Orphaning",
+ MP_RGB(128, 128, 192));
+
namespace OpenGL {
OGLStreamBuffer::OGLStreamBuffer(GLenum target, GLsizeiptr size, bool prefer_coherent)
@@ -75,6 +79,7 @@ std::tuple<u8*, GLintptr, bool> OGLStreamBuffer::Map(GLsizeiptr size, GLintptr a
}
if (invalidate || !persistent) {
+ MICROPROFILE_SCOPE(OpenGL_StreamBuffer);
GLbitfield flags = GL_MAP_WRITE_BIT | (persistent ? GL_MAP_PERSISTENT_BIT : 0) |
(coherent ? GL_MAP_COHERENT_BIT : GL_MAP_FLUSH_EXPLICIT_BIT) |
(invalidate ? GL_MAP_INVALIDATE_BUFFER_BIT : GL_MAP_UNSYNCHRONIZED_BIT);
diff --git a/src/video_core/renderer_opengl/maxwell_to_gl.h b/src/video_core/renderer_opengl/maxwell_to_gl.h
index 87d511c38..a8833c06e 100644
--- a/src/video_core/renderer_opengl/maxwell_to_gl.h
+++ b/src/video_core/renderer_opengl/maxwell_to_gl.h
@@ -159,10 +159,8 @@ inline GLenum TextureFilterMode(Tegra::Texture::TextureFilter filter_mode,
}
}
}
- LOG_CRITICAL(Render_OpenGL, "Unimplemented texture filter mode={}",
- static_cast<u32>(filter_mode));
- UNREACHABLE();
- return {};
+ LOG_ERROR(Render_OpenGL, "Unimplemented texture filter mode={}", static_cast<u32>(filter_mode));
+ return GL_LINEAR;
}
inline GLenum WrapMode(Tegra::Texture::WrapMode wrap_mode) {
@@ -182,10 +180,15 @@ inline GLenum WrapMode(Tegra::Texture::WrapMode wrap_mode) {
return GL_CLAMP_TO_BORDER;
case Tegra::Texture::WrapMode::MirrorOnceClampToEdge:
return GL_MIRROR_CLAMP_TO_EDGE;
+ case Tegra::Texture::WrapMode::MirrorOnceBorder:
+ if (GL_EXT_texture_mirror_clamp) {
+ return GL_MIRROR_CLAMP_TO_BORDER_EXT;
+ } else {
+ return GL_MIRROR_CLAMP_TO_EDGE;
+ }
}
- LOG_CRITICAL(Render_OpenGL, "Unimplemented texture wrap mode={}", static_cast<u32>(wrap_mode));
- UNREACHABLE();
- return {};
+ LOG_ERROR(Render_OpenGL, "Unimplemented texture wrap mode={}", static_cast<u32>(wrap_mode));
+ return GL_REPEAT;
}
inline GLenum DepthCompareFunc(Tegra::Texture::DepthCompareFunc func) {
@@ -207,28 +210,31 @@ inline GLenum DepthCompareFunc(Tegra::Texture::DepthCompareFunc func) {
case Tegra::Texture::DepthCompareFunc::Always:
return GL_ALWAYS;
}
- LOG_CRITICAL(Render_OpenGL, "Unimplemented texture depth compare function ={}",
- static_cast<u32>(func));
- UNREACHABLE();
- return {};
+ LOG_ERROR(Render_OpenGL, "Unimplemented texture depth compare function ={}",
+ static_cast<u32>(func));
+ return GL_GREATER;
}
inline GLenum BlendEquation(Maxwell::Blend::Equation equation) {
switch (equation) {
case Maxwell::Blend::Equation::Add:
+ case Maxwell::Blend::Equation::AddGL:
return GL_FUNC_ADD;
case Maxwell::Blend::Equation::Subtract:
+ case Maxwell::Blend::Equation::SubtractGL:
return GL_FUNC_SUBTRACT;
case Maxwell::Blend::Equation::ReverseSubtract:
+ case Maxwell::Blend::Equation::ReverseSubtractGL:
return GL_FUNC_REVERSE_SUBTRACT;
case Maxwell::Blend::Equation::Min:
+ case Maxwell::Blend::Equation::MinGL:
return GL_MIN;
case Maxwell::Blend::Equation::Max:
+ case Maxwell::Blend::Equation::MaxGL:
return GL_MAX;
}
- LOG_CRITICAL(Render_OpenGL, "Unimplemented blend equation={}", static_cast<u32>(equation));
- UNREACHABLE();
- return {};
+ LOG_ERROR(Render_OpenGL, "Unimplemented blend equation={}", static_cast<u32>(equation));
+ return GL_FUNC_ADD;
}
inline GLenum BlendFunc(Maxwell::Blend::Factor factor) {
@@ -291,9 +297,8 @@ inline GLenum BlendFunc(Maxwell::Blend::Factor factor) {
case Maxwell::Blend::Factor::OneMinusConstantAlphaGL:
return GL_ONE_MINUS_CONSTANT_ALPHA;
}
- LOG_CRITICAL(Render_OpenGL, "Unimplemented blend factor={}", static_cast<u32>(factor));
- UNREACHABLE();
- return {};
+ LOG_ERROR(Render_OpenGL, "Unimplemented blend factor={}", static_cast<u32>(factor));
+ return GL_ZERO;
}
inline GLenum SwizzleSource(Tegra::Texture::SwizzleSource source) {
@@ -312,9 +317,8 @@ inline GLenum SwizzleSource(Tegra::Texture::SwizzleSource source) {
case Tegra::Texture::SwizzleSource::OneFloat:
return GL_ONE;
}
- LOG_CRITICAL(Render_OpenGL, "Unimplemented swizzle source={}", static_cast<u32>(source));
- UNREACHABLE();
- return {};
+ LOG_ERROR(Render_OpenGL, "Unimplemented swizzle source={}", static_cast<u32>(source));
+ return GL_ZERO;
}
inline GLenum ComparisonOp(Maxwell::ComparisonOp comparison) {
@@ -344,33 +348,39 @@ inline GLenum ComparisonOp(Maxwell::ComparisonOp comparison) {
case Maxwell::ComparisonOp::AlwaysOld:
return GL_ALWAYS;
}
- LOG_CRITICAL(Render_OpenGL, "Unimplemented comparison op={}", static_cast<u32>(comparison));
- UNREACHABLE();
- return {};
+ LOG_ERROR(Render_OpenGL, "Unimplemented comparison op={}", static_cast<u32>(comparison));
+ return GL_ALWAYS;
}
inline GLenum StencilOp(Maxwell::StencilOp stencil) {
switch (stencil) {
case Maxwell::StencilOp::Keep:
+ case Maxwell::StencilOp::KeepOGL:
return GL_KEEP;
case Maxwell::StencilOp::Zero:
+ case Maxwell::StencilOp::ZeroOGL:
return GL_ZERO;
case Maxwell::StencilOp::Replace:
+ case Maxwell::StencilOp::ReplaceOGL:
return GL_REPLACE;
case Maxwell::StencilOp::Incr:
+ case Maxwell::StencilOp::IncrOGL:
return GL_INCR;
case Maxwell::StencilOp::Decr:
+ case Maxwell::StencilOp::DecrOGL:
return GL_DECR;
case Maxwell::StencilOp::Invert:
+ case Maxwell::StencilOp::InvertOGL:
return GL_INVERT;
case Maxwell::StencilOp::IncrWrap:
+ case Maxwell::StencilOp::IncrWrapOGL:
return GL_INCR_WRAP;
case Maxwell::StencilOp::DecrWrap:
+ case Maxwell::StencilOp::DecrWrapOGL:
return GL_DECR_WRAP;
}
- LOG_CRITICAL(Render_OpenGL, "Unimplemented stencil op={}", static_cast<u32>(stencil));
- UNREACHABLE();
- return {};
+ LOG_ERROR(Render_OpenGL, "Unimplemented stencil op={}", static_cast<u32>(stencil));
+ return GL_KEEP;
}
inline GLenum FrontFace(Maxwell::Cull::FrontFace front_face) {
@@ -380,9 +390,8 @@ inline GLenum FrontFace(Maxwell::Cull::FrontFace front_face) {
case Maxwell::Cull::FrontFace::CounterClockWise:
return GL_CCW;
}
- LOG_CRITICAL(Render_OpenGL, "Unimplemented front face cull={}", static_cast<u32>(front_face));
- UNREACHABLE();
- return {};
+ LOG_ERROR(Render_OpenGL, "Unimplemented front face cull={}", static_cast<u32>(front_face));
+ return GL_CCW;
}
inline GLenum CullFace(Maxwell::Cull::CullFace cull_face) {
@@ -394,9 +403,8 @@ inline GLenum CullFace(Maxwell::Cull::CullFace cull_face) {
case Maxwell::Cull::CullFace::FrontAndBack:
return GL_FRONT_AND_BACK;
}
- LOG_CRITICAL(Render_OpenGL, "Unimplemented cull face={}", static_cast<u32>(cull_face));
- UNREACHABLE();
- return {};
+ LOG_ERROR(Render_OpenGL, "Unimplemented cull face={}", static_cast<u32>(cull_face));
+ return GL_BACK;
}
inline GLenum LogicOp(Maxwell::LogicOperation operation) {
@@ -434,9 +442,8 @@ inline GLenum LogicOp(Maxwell::LogicOperation operation) {
case Maxwell::LogicOperation::Set:
return GL_SET;
}
- LOG_CRITICAL(Render_OpenGL, "Unimplemented logic operation={}", static_cast<u32>(operation));
- UNREACHABLE();
- return {};
+ LOG_ERROR(Render_OpenGL, "Unimplemented logic operation={}", static_cast<u32>(operation));
+ return GL_COPY;
}
} // namespace MaxwellToGL
diff --git a/src/video_core/renderer_opengl/renderer_opengl.cpp b/src/video_core/renderer_opengl/renderer_opengl.cpp
index ea38da932..1492e063a 100644
--- a/src/video_core/renderer_opengl/renderer_opengl.cpp
+++ b/src/video_core/renderer_opengl/renderer_opengl.cpp
@@ -304,6 +304,12 @@ void RendererOpenGL::ConfigureFramebufferTexture(TextureInfo& texture,
gl_framebuffer_data.resize(texture.width * texture.height * 4);
break;
default:
+ internal_format = GL_RGBA;
+ texture.gl_format = GL_RGBA;
+ texture.gl_type = GL_UNSIGNED_INT_8_8_8_8_REV;
+ gl_framebuffer_data.resize(texture.width * texture.height * 4);
+ LOG_CRITICAL(Render_OpenGL, "Unknown framebuffer pixel format: {}",
+ static_cast<u32>(framebuffer.pixel_format));
UNREACHABLE();
}
@@ -484,7 +490,7 @@ bool RendererOpenGL::Init() {
Core::Telemetry().AddField(Telemetry::FieldType::UserSystem, "GPU_Model", gpu_model);
Core::Telemetry().AddField(Telemetry::FieldType::UserSystem, "GPU_OpenGL_Version", gl_version);
- if (!GLAD_GL_VERSION_3_3) {
+ if (!GLAD_GL_VERSION_4_3) {
return false;
}
diff --git a/src/video_core/surface.cpp b/src/video_core/surface.cpp
index d9a97e30b..9582dd2ca 100644
--- a/src/video_core/surface.cpp
+++ b/src/video_core/surface.cpp
@@ -19,6 +19,8 @@ SurfaceTarget SurfaceTargetFromTextureType(Tegra::Texture::TextureType texture_t
return SurfaceTarget::Texture3D;
case Tegra::Texture::TextureType::TextureCubemap:
return SurfaceTarget::TextureCubemap;
+ case Tegra::Texture::TextureType::TextureCubeArray:
+ return SurfaceTarget::TextureCubeArray;
case Tegra::Texture::TextureType::Texture1DArray:
return SurfaceTarget::Texture1DArray;
case Tegra::Texture::TextureType::Texture2DArray:
@@ -39,6 +41,7 @@ bool SurfaceTargetIsLayered(SurfaceTarget target) {
case SurfaceTarget::Texture1DArray:
case SurfaceTarget::Texture2DArray:
case SurfaceTarget::TextureCubemap:
+ case SurfaceTarget::TextureCubeArray:
return true;
default:
LOG_CRITICAL(HW_GPU, "Unimplemented surface_target={}", static_cast<u32>(target));
@@ -297,10 +300,14 @@ PixelFormat PixelFormatFromTextureFormat(Tegra::Texture::TextureFormat format,
return is_srgb ? PixelFormat::ASTC_2D_4X4_SRGB : PixelFormat::ASTC_2D_4X4;
case Tegra::Texture::TextureFormat::ASTC_2D_5X4:
return is_srgb ? PixelFormat::ASTC_2D_5X4_SRGB : PixelFormat::ASTC_2D_5X4;
+ case Tegra::Texture::TextureFormat::ASTC_2D_5X5:
+ return is_srgb ? PixelFormat::ASTC_2D_5X5_SRGB : PixelFormat::ASTC_2D_5X5;
case Tegra::Texture::TextureFormat::ASTC_2D_8X8:
return is_srgb ? PixelFormat::ASTC_2D_8X8_SRGB : PixelFormat::ASTC_2D_8X8;
case Tegra::Texture::TextureFormat::ASTC_2D_8X5:
return is_srgb ? PixelFormat::ASTC_2D_8X5_SRGB : PixelFormat::ASTC_2D_8X5;
+ case Tegra::Texture::TextureFormat::ASTC_2D_10X8:
+ return is_srgb ? PixelFormat::ASTC_2D_10X8_SRGB : PixelFormat::ASTC_2D_10X8;
case Tegra::Texture::TextureFormat::R16_G16:
switch (component_type) {
case Tegra::Texture::ComponentType::FLOAT:
@@ -440,12 +447,16 @@ bool IsPixelFormatASTC(PixelFormat format) {
switch (format) {
case PixelFormat::ASTC_2D_4X4:
case PixelFormat::ASTC_2D_5X4:
+ case PixelFormat::ASTC_2D_5X5:
case PixelFormat::ASTC_2D_8X8:
case PixelFormat::ASTC_2D_8X5:
case PixelFormat::ASTC_2D_4X4_SRGB:
case PixelFormat::ASTC_2D_5X4_SRGB:
+ case PixelFormat::ASTC_2D_5X5_SRGB:
case PixelFormat::ASTC_2D_8X8_SRGB:
case PixelFormat::ASTC_2D_8X5_SRGB:
+ case PixelFormat::ASTC_2D_10X8:
+ case PixelFormat::ASTC_2D_10X8_SRGB:
return true;
default:
return false;
@@ -453,27 +464,7 @@ bool IsPixelFormatASTC(PixelFormat format) {
}
std::pair<u32, u32> GetASTCBlockSize(PixelFormat format) {
- switch (format) {
- case PixelFormat::ASTC_2D_4X4:
- return {4, 4};
- case PixelFormat::ASTC_2D_5X4:
- return {5, 4};
- case PixelFormat::ASTC_2D_8X8:
- return {8, 8};
- case PixelFormat::ASTC_2D_8X5:
- return {8, 5};
- case PixelFormat::ASTC_2D_4X4_SRGB:
- return {4, 4};
- case PixelFormat::ASTC_2D_5X4_SRGB:
- return {5, 4};
- case PixelFormat::ASTC_2D_8X8_SRGB:
- return {8, 8};
- case PixelFormat::ASTC_2D_8X5_SRGB:
- return {8, 5};
- default:
- LOG_CRITICAL(HW_GPU, "Unhandled format: {}", static_cast<u32>(format));
- UNREACHABLE();
- }
+ return {GetDefaultBlockWidth(format), GetDefaultBlockHeight(format)};
}
bool IsFormatBCn(PixelFormat format) {
diff --git a/src/video_core/surface.h b/src/video_core/surface.h
index 3232e437f..0dd3eb2e4 100644
--- a/src/video_core/surface.h
+++ b/src/video_core/surface.h
@@ -72,19 +72,23 @@ enum class PixelFormat {
ASTC_2D_8X8_SRGB = 54,
ASTC_2D_8X5_SRGB = 55,
ASTC_2D_5X4_SRGB = 56,
+ ASTC_2D_5X5 = 57,
+ ASTC_2D_5X5_SRGB = 58,
+ ASTC_2D_10X8 = 59,
+ ASTC_2D_10X8_SRGB = 60,
MaxColorFormat,
// Depth formats
- Z32F = 57,
- Z16 = 58,
+ Z32F = 61,
+ Z16 = 62,
MaxDepthFormat,
// DepthStencil formats
- Z24S8 = 59,
- S8Z24 = 60,
- Z32FS8 = 61,
+ Z24S8 = 63,
+ S8Z24 = 64,
+ Z32FS8 = 65,
MaxDepthStencilFormat,
@@ -118,6 +122,7 @@ enum class SurfaceTarget {
Texture1DArray,
Texture2DArray,
TextureCubemap,
+ TextureCubeArray,
};
/**
@@ -188,6 +193,10 @@ static constexpr u32 GetCompressionFactor(PixelFormat format) {
4, // ASTC_2D_8X8_SRGB
4, // ASTC_2D_8X5_SRGB
4, // ASTC_2D_5X4_SRGB
+ 4, // ASTC_2D_5X5
+ 4, // ASTC_2D_5X5_SRGB
+ 4, // ASTC_2D_10X8
+ 4, // ASTC_2D_10X8_SRGB
1, // Z32F
1, // Z16
1, // Z24S8
@@ -199,6 +208,81 @@ static constexpr u32 GetCompressionFactor(PixelFormat format) {
return compression_factor_table[static_cast<std::size_t>(format)];
}
+static constexpr u32 GetDefaultBlockWidth(PixelFormat format) {
+ if (format == PixelFormat::Invalid)
+ return 0;
+ constexpr std::array<u32, MaxPixelFormat> block_width_table = {{
+ 1, // ABGR8U
+ 1, // ABGR8S
+ 1, // ABGR8UI
+ 1, // B5G6R5U
+ 1, // A2B10G10R10U
+ 1, // A1B5G5R5U
+ 1, // R8U
+ 1, // R8UI
+ 1, // RGBA16F
+ 1, // RGBA16U
+ 1, // RGBA16UI
+ 1, // R11FG11FB10F
+ 1, // RGBA32UI
+ 4, // DXT1
+ 4, // DXT23
+ 4, // DXT45
+ 4, // DXN1
+ 4, // DXN2UNORM
+ 4, // DXN2SNORM
+ 4, // BC7U
+ 4, // BC6H_UF16
+ 4, // BC6H_SF16
+ 4, // ASTC_2D_4X4
+ 1, // G8R8U
+ 1, // G8R8S
+ 1, // BGRA8
+ 1, // RGBA32F
+ 1, // RG32F
+ 1, // R32F
+ 1, // R16F
+ 1, // R16U
+ 1, // R16S
+ 1, // R16UI
+ 1, // R16I
+ 1, // RG16
+ 1, // RG16F
+ 1, // RG16UI
+ 1, // RG16I
+ 1, // RG16S
+ 1, // RGB32F
+ 1, // RGBA8_SRGB
+ 1, // RG8U
+ 1, // RG8S
+ 1, // RG32UI
+ 1, // R32UI
+ 8, // ASTC_2D_8X8
+ 8, // ASTC_2D_8X5
+ 5, // ASTC_2D_5X4
+ 1, // BGRA8_SRGB
+ 4, // DXT1_SRGB
+ 4, // DXT23_SRGB
+ 4, // DXT45_SRGB
+ 4, // BC7U_SRGB
+ 4, // ASTC_2D_4X4_SRGB
+ 8, // ASTC_2D_8X8_SRGB
+ 8, // ASTC_2D_8X5_SRGB
+ 5, // ASTC_2D_5X4_SRGB
+ 5, // ASTC_2D_5X5
+ 5, // ASTC_2D_5X5_SRGB
+ 10, // ASTC_2D_10X8
+ 10, // ASTC_2D_10X8_SRGB
+ 1, // Z32F
+ 1, // Z16
+ 1, // Z24S8
+ 1, // S8Z24
+ 1, // Z32FS8
+ }};
+ ASSERT(static_cast<std::size_t>(format) < block_width_table.size());
+ return block_width_table[static_cast<std::size_t>(format)];
+}
+
static constexpr u32 GetDefaultBlockHeight(PixelFormat format) {
if (format == PixelFormat::Invalid)
return 0;
@@ -261,6 +345,10 @@ static constexpr u32 GetDefaultBlockHeight(PixelFormat format) {
8, // ASTC_2D_8X8_SRGB
5, // ASTC_2D_8X5_SRGB
4, // ASTC_2D_5X4_SRGB
+ 5, // ASTC_2D_5X5
+ 5, // ASTC_2D_5X5_SRGB
+ 8, // ASTC_2D_10X8
+ 8, // ASTC_2D_10X8_SRGB
1, // Z32F
1, // Z16
1, // Z24S8
@@ -299,7 +387,7 @@ static constexpr u32 GetFormatBpp(PixelFormat format) {
128, // BC7U
128, // BC6H_UF16
128, // BC6H_SF16
- 32, // ASTC_2D_4X4
+ 128, // ASTC_2D_4X4
16, // G8R8U
16, // G8R8S
32, // BGRA8
@@ -322,18 +410,22 @@ static constexpr u32 GetFormatBpp(PixelFormat format) {
16, // RG8S
64, // RG32UI
32, // R32UI
- 16, // ASTC_2D_8X8
- 16, // ASTC_2D_8X5
- 32, // ASTC_2D_5X4
+ 128, // ASTC_2D_8X8
+ 128, // ASTC_2D_8X5
+ 128, // ASTC_2D_5X4
32, // BGRA8_SRGB
64, // DXT1_SRGB
128, // DXT23_SRGB
128, // DXT45_SRGB
128, // BC7U
- 32, // ASTC_2D_4X4_SRGB
- 16, // ASTC_2D_8X8_SRGB
- 16, // ASTC_2D_8X5_SRGB
- 32, // ASTC_2D_5X4_SRGB
+ 128, // ASTC_2D_4X4_SRGB
+ 128, // ASTC_2D_8X8_SRGB
+ 128, // ASTC_2D_8X5_SRGB
+ 128, // ASTC_2D_5X4_SRGB
+ 128, // ASTC_2D_5X5
+ 128, // ASTC_2D_5X5_SRGB
+ 128, // ASTC_2D_10X8
+ 128, // ASTC_2D_10X8_SRGB
32, // Z32F
16, // Z16
32, // Z24S8
diff --git a/src/video_core/textures/astc.cpp b/src/video_core/textures/astc.cpp
index b1feacae9..bc50a4876 100644
--- a/src/video_core/textures/astc.cpp
+++ b/src/video_core/textures/astc.cpp
@@ -1598,27 +1598,29 @@ static void DecompressBlock(uint8_t inBuf[16], const uint32_t blockWidth,
namespace Tegra::Texture::ASTC {
std::vector<uint8_t> Decompress(std::vector<uint8_t>& data, uint32_t width, uint32_t height,
- uint32_t block_width, uint32_t block_height) {
+ uint32_t depth, uint32_t block_width, uint32_t block_height) {
uint32_t blockIdx = 0;
- std::vector<uint8_t> outData(height * width * 4);
- for (uint32_t j = 0; j < height; j += block_height) {
- for (uint32_t i = 0; i < width; i += block_width) {
+ std::vector<uint8_t> outData(height * width * depth * 4);
+ for (uint32_t k = 0; k < depth; k++) {
+ for (uint32_t j = 0; j < height; j += block_height) {
+ for (uint32_t i = 0; i < width; i += block_width) {
- uint8_t* blockPtr = data.data() + blockIdx * 16;
+ uint8_t* blockPtr = data.data() + blockIdx * 16;
- // Blocks can be at most 12x12
- uint32_t uncompData[144];
- ASTCC::DecompressBlock(blockPtr, block_width, block_height, uncompData);
+ // Blocks can be at most 12x12
+ uint32_t uncompData[144];
+ ASTCC::DecompressBlock(blockPtr, block_width, block_height, uncompData);
- uint32_t decompWidth = std::min(block_width, width - i);
- uint32_t decompHeight = std::min(block_height, height - j);
+ uint32_t decompWidth = std::min(block_width, width - i);
+ uint32_t decompHeight = std::min(block_height, height - j);
- uint8_t* outRow = outData.data() + (j * width + i) * 4;
- for (uint32_t jj = 0; jj < decompHeight; jj++) {
- memcpy(outRow + jj * width * 4, uncompData + jj * block_width, decompWidth * 4);
- }
+ uint8_t* outRow = outData.data() + (j * width + i) * 4;
+ for (uint32_t jj = 0; jj < decompHeight; jj++) {
+ memcpy(outRow + jj * width * 4, uncompData + jj * block_width, decompWidth * 4);
+ }
- blockIdx++;
+ blockIdx++;
+ }
}
}
diff --git a/src/video_core/textures/astc.h b/src/video_core/textures/astc.h
index f0d7c0e56..d419dd025 100644
--- a/src/video_core/textures/astc.h
+++ b/src/video_core/textures/astc.h
@@ -10,6 +10,6 @@
namespace Tegra::Texture::ASTC {
std::vector<uint8_t> Decompress(std::vector<uint8_t>& data, uint32_t width, uint32_t height,
- uint32_t block_width, uint32_t block_height);
+ uint32_t depth, uint32_t block_width, uint32_t block_height);
} // namespace Tegra::Texture::ASTC
diff --git a/src/video_core/textures/decoders.cpp b/src/video_core/textures/decoders.cpp
index 550ca856c..7eabd34f1 100644
--- a/src/video_core/textures/decoders.cpp
+++ b/src/video_core/textures/decoders.cpp
@@ -37,25 +37,28 @@ struct alignas(64) SwizzleTable {
std::array<std::array<u16, M>, N> values{};
};
-constexpr auto legacy_swizzle_table = SwizzleTable<8, 64, 1>();
-constexpr auto fast_swizzle_table = SwizzleTable<8, 4, 16>();
+constexpr u32 gob_size_x = 64;
+constexpr u32 gob_size_y = 8;
+constexpr u32 gob_size_z = 1;
+constexpr u32 gob_size = gob_size_x * gob_size_y * gob_size_z;
+constexpr u32 fast_swizzle_align = 16;
+
+constexpr auto legacy_swizzle_table = SwizzleTable<gob_size_y, gob_size_x, gob_size_z>();
+constexpr auto fast_swizzle_table = SwizzleTable<gob_size_y, 4, fast_swizzle_align>();
/**
* This function manages ALL the GOBs(Group of Bytes) Inside a single block.
* Instead of going gob by gob, we map the coordinates inside a block and manage from
* those. Block_Width is assumed to be 1.
*/
-void PreciseProcessBlock(u8* swizzled_data, u8* unswizzled_data, const bool unswizzle,
+void PreciseProcessBlock(u8* const swizzled_data, u8* const unswizzled_data, const bool unswizzle,
const u32 x_start, const u32 y_start, const u32 z_start, const u32 x_end,
const u32 y_end, const u32 z_end, const u32 tile_offset,
const u32 xy_block_size, const u32 layer_z, const u32 stride_x,
const u32 bytes_per_pixel, const u32 out_bytes_per_pixel) {
std::array<u8*, 2> data_ptrs;
u32 z_address = tile_offset;
- const u32 gob_size_x = 64;
- const u32 gob_size_y = 8;
- const u32 gob_size_z = 1;
- const u32 gob_size = gob_size_x * gob_size_y * gob_size_z;
+
for (u32 z = z_start; z < z_end; z++) {
u32 y_address = z_address;
u32 pixel_base = layer_z * z + y_start * stride_x;
@@ -81,7 +84,7 @@ void PreciseProcessBlock(u8* swizzled_data, u8* unswizzled_data, const bool unsw
* Instead of going gob by gob, we map the coordinates inside a block and manage from
* those. Block_Width is assumed to be 1.
*/
-void FastProcessBlock(u8* swizzled_data, u8* unswizzled_data, const bool unswizzle,
+void FastProcessBlock(u8* const swizzled_data, u8* const unswizzled_data, const bool unswizzle,
const u32 x_start, const u32 y_start, const u32 z_start, const u32 x_end,
const u32 y_end, const u32 z_end, const u32 tile_offset,
const u32 xy_block_size, const u32 layer_z, const u32 stride_x,
@@ -90,23 +93,19 @@ void FastProcessBlock(u8* swizzled_data, u8* unswizzled_data, const bool unswizz
u32 z_address = tile_offset;
const u32 x_startb = x_start * bytes_per_pixel;
const u32 x_endb = x_end * bytes_per_pixel;
- const u32 copy_size = 16;
- const u32 gob_size_x = 64;
- const u32 gob_size_y = 8;
- const u32 gob_size_z = 1;
- const u32 gob_size = gob_size_x * gob_size_y * gob_size_z;
+
for (u32 z = z_start; z < z_end; z++) {
u32 y_address = z_address;
u32 pixel_base = layer_z * z + y_start * stride_x;
for (u32 y = y_start; y < y_end; y++) {
const auto& table = fast_swizzle_table[y % gob_size_y];
- for (u32 xb = x_startb; xb < x_endb; xb += copy_size) {
- const u32 swizzle_offset{y_address + table[(xb / copy_size) % 4]};
+ for (u32 xb = x_startb; xb < x_endb; xb += fast_swizzle_align) {
+ const u32 swizzle_offset{y_address + table[(xb / fast_swizzle_align) % 4]};
const u32 out_x = xb * out_bytes_per_pixel / bytes_per_pixel;
const u32 pixel_index{out_x + pixel_base};
data_ptrs[unswizzle] = swizzled_data + swizzle_offset;
data_ptrs[!unswizzle] = unswizzled_data + pixel_index;
- std::memcpy(data_ptrs[0], data_ptrs[1], copy_size);
+ std::memcpy(data_ptrs[0], data_ptrs[1], fast_swizzle_align);
}
pixel_base += stride_x;
if ((y + 1) % gob_size_y == 0)
@@ -126,23 +125,21 @@ void FastProcessBlock(u8* swizzled_data, u8* unswizzled_data, const bool unswizz
* https://envytools.readthedocs.io/en/latest/hw/memory/g80-surface.html#blocklinear-surfaces
*/
template <bool fast>
-void SwizzledData(u8* swizzled_data, u8* unswizzled_data, const bool unswizzle, const u32 width,
- const u32 height, const u32 depth, const u32 bytes_per_pixel,
+void SwizzledData(u8* const swizzled_data, u8* const unswizzled_data, const bool unswizzle,
+ const u32 width, const u32 height, const u32 depth, const u32 bytes_per_pixel,
const u32 out_bytes_per_pixel, const u32 block_height, const u32 block_depth) {
auto div_ceil = [](const u32 x, const u32 y) { return ((x + y - 1) / y); };
const u32 stride_x = width * out_bytes_per_pixel;
const u32 layer_z = height * stride_x;
- const u32 gob_x_bytes = 64;
- const u32 gob_elements_x = gob_x_bytes / bytes_per_pixel;
- const u32 gob_elements_y = 8;
- const u32 gob_elements_z = 1;
+ const u32 gob_elements_x = gob_size_x / bytes_per_pixel;
+ constexpr u32 gob_elements_y = gob_size_y;
+ constexpr u32 gob_elements_z = gob_size_z;
const u32 block_x_elements = gob_elements_x;
const u32 block_y_elements = gob_elements_y * block_height;
const u32 block_z_elements = gob_elements_z * block_depth;
const u32 blocks_on_x = div_ceil(width, block_x_elements);
const u32 blocks_on_y = div_ceil(height, block_y_elements);
const u32 blocks_on_z = div_ceil(depth, block_z_elements);
- const u32 gob_size = gob_x_bytes * gob_elements_y * gob_elements_z;
const u32 xy_block_size = gob_size * block_height;
const u32 block_size = xy_block_size * block_depth;
u32 tile_offset = 0;
@@ -171,9 +168,9 @@ void SwizzledData(u8* swizzled_data, u8* unswizzled_data, const bool unswizzle,
}
void CopySwizzledData(u32 width, u32 height, u32 depth, u32 bytes_per_pixel,
- u32 out_bytes_per_pixel, u8* swizzled_data, u8* unswizzled_data,
+ u32 out_bytes_per_pixel, u8* const swizzled_data, u8* const unswizzled_data,
bool unswizzle, u32 block_height, u32 block_depth) {
- if (bytes_per_pixel % 3 != 0 && (width * bytes_per_pixel) % 16 == 0) {
+ if (bytes_per_pixel % 3 != 0 && (width * bytes_per_pixel) % fast_swizzle_align == 0) {
SwizzledData<true>(swizzled_data, unswizzled_data, unswizzle, width, height, depth,
bytes_per_pixel, out_bytes_per_pixel, block_height, block_depth);
} else {
@@ -202,6 +199,8 @@ u32 BytesPerPixel(TextureFormat format) {
case TextureFormat::ASTC_2D_5X4:
case TextureFormat::ASTC_2D_8X8:
case TextureFormat::ASTC_2D_8X5:
+ case TextureFormat::ASTC_2D_10X8:
+ case TextureFormat::ASTC_2D_5X5:
case TextureFormat::A8R8G8B8:
case TextureFormat::A2B10G10R10:
case TextureFormat::BF10GF11RF11:
@@ -227,27 +226,38 @@ u32 BytesPerPixel(TextureFormat format) {
}
}
-std::vector<u8> UnswizzleTexture(VAddr address, u32 tile_size, u32 bytes_per_pixel, u32 width,
- u32 height, u32 depth, u32 block_height, u32 block_depth) {
+void UnswizzleTexture(u8* const unswizzled_data, VAddr address, u32 tile_size_x, u32 tile_size_y,
+ u32 bytes_per_pixel, u32 width, u32 height, u32 depth, u32 block_height,
+ u32 block_depth) {
+ CopySwizzledData((width + tile_size_x - 1) / tile_size_x,
+ (height + tile_size_y - 1) / tile_size_y, depth, bytes_per_pixel,
+ bytes_per_pixel, Memory::GetPointer(address), unswizzled_data, true,
+ block_height, block_depth);
+}
+
+std::vector<u8> UnswizzleTexture(VAddr address, u32 tile_size_x, u32 tile_size_y,
+ u32 bytes_per_pixel, u32 width, u32 height, u32 depth,
+ u32 block_height, u32 block_depth) {
std::vector<u8> unswizzled_data(width * height * depth * bytes_per_pixel);
- CopySwizzledData(width / tile_size, height / tile_size, depth, bytes_per_pixel, bytes_per_pixel,
- Memory::GetPointer(address), unswizzled_data.data(), true, block_height,
- block_depth);
+ UnswizzleTexture(unswizzled_data.data(), address, tile_size_x, tile_size_y, bytes_per_pixel,
+ width, height, depth, block_height, block_depth);
return unswizzled_data;
}
void SwizzleSubrect(u32 subrect_width, u32 subrect_height, u32 source_pitch, u32 swizzled_width,
u32 bytes_per_pixel, VAddr swizzled_data, VAddr unswizzled_data,
u32 block_height) {
- const u32 image_width_in_gobs{(swizzled_width * bytes_per_pixel + 63) / 64};
+ const u32 image_width_in_gobs{(swizzled_width * bytes_per_pixel + (gob_size_x - 1)) /
+ gob_size_x};
for (u32 line = 0; line < subrect_height; ++line) {
const u32 gob_address_y =
- (line / (8 * block_height)) * 512 * block_height * image_width_in_gobs +
- (line % (8 * block_height) / 8) * 512;
- const auto& table = legacy_swizzle_table[line % 8];
+ (line / (gob_size_y * block_height)) * gob_size * block_height * image_width_in_gobs +
+ ((line % (gob_size_y * block_height)) / gob_size_y) * gob_size;
+ const auto& table = legacy_swizzle_table[line % gob_size_y];
for (u32 x = 0; x < subrect_width; ++x) {
- const u32 gob_address = gob_address_y + (x * bytes_per_pixel / 64) * 512 * block_height;
- const u32 swizzled_offset = gob_address + table[(x * bytes_per_pixel) % 64];
+ const u32 gob_address =
+ gob_address_y + (x * bytes_per_pixel / gob_size_x) * gob_size * block_height;
+ const u32 swizzled_offset = gob_address + table[(x * bytes_per_pixel) % gob_size_x];
const VAddr source_line = unswizzled_data + line * source_pitch + x * bytes_per_pixel;
const VAddr dest_addr = swizzled_data + swizzled_offset;
@@ -261,13 +271,13 @@ void UnswizzleSubrect(u32 subrect_width, u32 subrect_height, u32 dest_pitch, u32
u32 block_height, u32 offset_x, u32 offset_y) {
for (u32 line = 0; line < subrect_height; ++line) {
const u32 y2 = line + offset_y;
- const u32 gob_address_y =
- (y2 / (8 * block_height)) * 512 * block_height + (y2 % (8 * block_height) / 8) * 512;
- const auto& table = legacy_swizzle_table[y2 % 8];
+ const u32 gob_address_y = (y2 / (gob_size_y * block_height)) * gob_size * block_height +
+ ((y2 % (gob_size_y * block_height)) / gob_size_y) * gob_size;
+ const auto& table = legacy_swizzle_table[y2 % gob_size_y];
for (u32 x = 0; x < subrect_width; ++x) {
const u32 x2 = (x + offset_x) * bytes_per_pixel;
- const u32 gob_address = gob_address_y + (x2 / 64) * 512 * block_height;
- const u32 swizzled_offset = gob_address + table[x2 % 64];
+ const u32 gob_address = gob_address_y + (x2 / gob_size_x) * gob_size * block_height;
+ const u32 swizzled_offset = gob_address + table[x2 % gob_size_x];
const VAddr dest_line = unswizzled_data + line * dest_pitch + x * bytes_per_pixel;
const VAddr source_addr = swizzled_data + swizzled_offset;
@@ -292,6 +302,8 @@ std::vector<u8> DecodeTexture(const std::vector<u8>& texture_data, TextureFormat
case TextureFormat::BC6H_SF16:
case TextureFormat::ASTC_2D_4X4:
case TextureFormat::ASTC_2D_8X8:
+ case TextureFormat::ASTC_2D_5X5:
+ case TextureFormat::ASTC_2D_10X8:
case TextureFormat::A8R8G8B8:
case TextureFormat::A2B10G10R10:
case TextureFormat::A1B5G5R5:
@@ -319,12 +331,9 @@ std::vector<u8> DecodeTexture(const std::vector<u8>& texture_data, TextureFormat
std::size_t CalculateSize(bool tiled, u32 bytes_per_pixel, u32 width, u32 height, u32 depth,
u32 block_height, u32 block_depth) {
if (tiled) {
- const u32 gobs_in_x = 64;
- const u32 gobs_in_y = 8;
- const u32 gobs_in_z = 1;
- const u32 aligned_width = Common::AlignUp(width * bytes_per_pixel, gobs_in_x);
- const u32 aligned_height = Common::AlignUp(height, gobs_in_y * block_height);
- const u32 aligned_depth = Common::AlignUp(depth, gobs_in_z * block_depth);
+ const u32 aligned_width = Common::AlignUp(width * bytes_per_pixel, gob_size_x);
+ const u32 aligned_height = Common::AlignUp(height, gob_size_y * block_height);
+ const u32 aligned_depth = Common::AlignUp(depth, gob_size_z * block_depth);
return aligned_width * aligned_height * aligned_depth;
} else {
return width * height * depth * bytes_per_pixel;
diff --git a/src/video_core/textures/decoders.h b/src/video_core/textures/decoders.h
index b390219e4..f4ef7c73e 100644
--- a/src/video_core/textures/decoders.h
+++ b/src/video_core/textures/decoders.h
@@ -19,8 +19,15 @@ inline std::size_t GetGOBSize() {
/**
* Unswizzles a swizzled texture without changing its format.
*/
-std::vector<u8> UnswizzleTexture(VAddr address, u32 tile_size, u32 bytes_per_pixel, u32 width,
- u32 height, u32 depth,
+void UnswizzleTexture(u8* unswizzled_data, VAddr address, u32 tile_size_x, u32 tile_size_y,
+ u32 bytes_per_pixel, u32 width, u32 height, u32 depth,
+ u32 block_height = TICEntry::DefaultBlockHeight,
+ u32 block_depth = TICEntry::DefaultBlockHeight);
+/**
+ * Unswizzles a swizzled texture without changing its format.
+ */
+std::vector<u8> UnswizzleTexture(VAddr address, u32 tile_size_x, u32 tile_size_y,
+ u32 bytes_per_pixel, u32 width, u32 height, u32 depth,
u32 block_height = TICEntry::DefaultBlockHeight,
u32 block_depth = TICEntry::DefaultBlockHeight);
diff --git a/src/video_core/textures/texture.h b/src/video_core/textures/texture.h
index d12d2ecb8..ffa08f5c1 100644
--- a/src/video_core/textures/texture.h
+++ b/src/video_core/textures/texture.h
@@ -168,20 +168,30 @@ struct TICEntry {
// High 16 bits of the pitch value
BitField<0, 16, u32> pitch_high;
-
+ BitField<26, 1, u32> use_header_opt_control;
+ BitField<27, 1, u32> depth_texture;
BitField<28, 4, u32> max_mip_level;
};
union {
BitField<0, 16, u32> width_minus_1;
BitField<22, 1, u32> srgb_conversion;
BitField<23, 4, TextureType> texture_type;
+ BitField<29, 3, u32> border_size;
};
union {
BitField<0, 16, u32> height_minus_1;
BitField<16, 15, u32> depth_minus_1;
};
+ union {
+ BitField<6, 13, u32> mip_lod_bias;
+ BitField<27, 3, u32> max_anisotropy;
+ };
- INSERT_PADDING_BYTES(8);
+ union {
+ BitField<0, 4, u32> res_min_mip_level;
+ BitField<4, 4, u32> res_max_mip_level;
+ BitField<12, 12, u32> min_lod_clamp;
+ };
GPUVAddr Address() const {
return static_cast<GPUVAddr>((static_cast<GPUVAddr>(address_high) << 32) | address_low);
@@ -275,13 +285,25 @@ struct TSCEntry {
BitField<6, 3, WrapMode> wrap_p;
BitField<9, 1, u32> depth_compare_enabled;
BitField<10, 3, DepthCompareFunc> depth_compare_func;
+ BitField<13, 1, u32> srgb_conversion;
+ BitField<20, 3, u32> max_anisotropy;
};
union {
BitField<0, 2, TextureFilter> mag_filter;
BitField<4, 2, TextureFilter> min_filter;
BitField<6, 2, TextureMipmapFilter> mip_filter;
+ BitField<9, 1, u32> cubemap_interface_filtering;
+ BitField<12, 13, u32> mip_lod_bias;
+ };
+ union {
+ BitField<0, 12, u32> min_lod_clamp;
+ BitField<12, 12, u32> max_lod_clamp;
+ BitField<24, 8, u32> srgb_border_color_r;
+ };
+ union {
+ BitField<12, 8, u32> srgb_border_color_g;
+ BitField<20, 8, u32> srgb_border_color_b;
};
- INSERT_PADDING_BYTES(8);
float border_color_r;
float border_color_g;
float border_color_b;
diff --git a/src/yuzu/CMakeLists.txt b/src/yuzu/CMakeLists.txt
index f9ca2948e..cfca8f4a8 100644
--- a/src/yuzu/CMakeLists.txt
+++ b/src/yuzu/CMakeLists.txt
@@ -7,6 +7,8 @@ add_executable(yuzu
Info.plist
about_dialog.cpp
about_dialog.h
+ applets/software_keyboard.cpp
+ applets/software_keyboard.h
bootmanager.cpp
bootmanager.h
compatibility_list.cpp
@@ -27,8 +29,14 @@ add_executable(yuzu
configuration/configure_graphics.h
configuration/configure_input.cpp
configuration/configure_input.h
+ configuration/configure_input_player.cpp
+ configuration/configure_input_player.h
+ configuration/configure_mouse_advanced.cpp
+ configuration/configure_mouse_advanced.h
configuration/configure_system.cpp
configuration/configure_system.h
+ configuration/configure_touchscreen_advanced.cpp
+ configuration/configure_touchscreen_advanced.h
configuration/configure_web.cpp
configuration/configure_web.h
debugger/graphics/graphics_breakpoint_observer.cpp
@@ -76,7 +84,10 @@ set(UIS
configuration/configure_general.ui
configuration/configure_graphics.ui
configuration/configure_input.ui
+ configuration/configure_input_player.ui
+ configuration/configure_mouse_advanced.ui
configuration/configure_system.ui
+ configuration/configure_touchscreen_advanced.ui
configuration/configure_web.ui
hotkeys.ui
main.ui
diff --git a/src/yuzu/applets/software_keyboard.cpp b/src/yuzu/applets/software_keyboard.cpp
new file mode 100644
index 000000000..8a26fdff1
--- /dev/null
+++ b/src/yuzu/applets/software_keyboard.cpp
@@ -0,0 +1,152 @@
+// Copyright 2018 yuzu Emulator Project
+// Licensed under GPLv2 or any later version
+// Refer to the license.txt file included.
+
+#include <algorithm>
+#include <mutex>
+#include <QDialogButtonBox>
+#include <QFont>
+#include <QLabel>
+#include <QLineEdit>
+#include <QVBoxLayout>
+#include "core/hle/lock.h"
+#include "yuzu/applets/software_keyboard.h"
+#include "yuzu/main.h"
+
+QtSoftwareKeyboardValidator::QtSoftwareKeyboardValidator(
+ Core::Frontend::SoftwareKeyboardParameters parameters)
+ : parameters(std::move(parameters)) {}
+
+QValidator::State QtSoftwareKeyboardValidator::validate(QString& input, int& pos) const {
+ if (input.size() > parameters.max_length)
+ return Invalid;
+ if (parameters.disable_space && input.contains(' '))
+ return Invalid;
+ if (parameters.disable_address && input.contains('@'))
+ return Invalid;
+ if (parameters.disable_percent && input.contains('%'))
+ return Invalid;
+ if (parameters.disable_slash && (input.contains('/') || input.contains('\\')))
+ return Invalid;
+ if (parameters.disable_number &&
+ std::any_of(input.begin(), input.end(), [](QChar c) { return c.isDigit(); })) {
+ return Invalid;
+ }
+
+ if (parameters.disable_download_code &&
+ std::any_of(input.begin(), input.end(), [](QChar c) { return c == 'O' || c == 'I'; })) {
+ return Invalid;
+ }
+
+ return Acceptable;
+}
+
+QtSoftwareKeyboardDialog::QtSoftwareKeyboardDialog(
+ QWidget* parent, Core::Frontend::SoftwareKeyboardParameters parameters_)
+ : QDialog(parent), parameters(std::move(parameters_)) {
+ layout = new QVBoxLayout;
+
+ header_label = new QLabel(QString::fromStdU16String(parameters.header_text));
+ header_label->setFont({header_label->font().family(), 11, QFont::Bold});
+ if (header_label->text().isEmpty())
+ header_label->setText(tr("Enter text:"));
+
+ sub_label = new QLabel(QString::fromStdU16String(parameters.sub_text));
+ sub_label->setFont({sub_label->font().family(), sub_label->font().pointSize(),
+ sub_label->font().weight(), true});
+ sub_label->setHidden(parameters.sub_text.empty());
+
+ guide_label = new QLabel(QString::fromStdU16String(parameters.guide_text));
+ guide_label->setHidden(parameters.guide_text.empty());
+
+ length_label = new QLabel(QStringLiteral("0/%1").arg(parameters.max_length));
+ length_label->setAlignment(Qt::AlignRight);
+ length_label->setFont({length_label->font().family(), 8});
+
+ line_edit = new QLineEdit;
+ line_edit->setValidator(new QtSoftwareKeyboardValidator(parameters));
+ line_edit->setMaxLength(static_cast<int>(parameters.max_length));
+ line_edit->setText(QString::fromStdU16String(parameters.initial_text));
+ line_edit->setCursorPosition(
+ parameters.cursor_at_beginning ? 0 : static_cast<int>(parameters.initial_text.size()));
+ line_edit->setEchoMode(parameters.password ? QLineEdit::Password : QLineEdit::Normal);
+
+ connect(line_edit, &QLineEdit::textChanged, this, [this](const QString& text) {
+ length_label->setText(QStringLiteral("%1/%2").arg(text.size()).arg(parameters.max_length));
+ });
+
+ buttons = new QDialogButtonBox;
+ buttons->addButton(tr("Cancel"), QDialogButtonBox::RejectRole);
+ buttons->addButton(parameters.submit_text.empty()
+ ? tr("OK")
+ : QString::fromStdU16String(parameters.submit_text),
+ QDialogButtonBox::AcceptRole);
+
+ connect(buttons, &QDialogButtonBox::accepted, this, &QtSoftwareKeyboardDialog::accept);
+ connect(buttons, &QDialogButtonBox::rejected, this, &QtSoftwareKeyboardDialog::reject);
+ layout->addWidget(header_label);
+ layout->addWidget(sub_label);
+ layout->addWidget(guide_label);
+ layout->addWidget(length_label);
+ layout->addWidget(line_edit);
+ layout->addWidget(buttons);
+ setLayout(layout);
+ setWindowTitle(tr("Software Keyboard"));
+}
+
+QtSoftwareKeyboardDialog::~QtSoftwareKeyboardDialog() = default;
+
+void QtSoftwareKeyboardDialog::accept() {
+ ok = true;
+ text = line_edit->text().toStdU16String();
+ QDialog::accept();
+}
+
+void QtSoftwareKeyboardDialog::reject() {
+ ok = false;
+ text.clear();
+ QDialog::reject();
+}
+
+std::u16string QtSoftwareKeyboardDialog::GetText() const {
+ return text;
+}
+
+bool QtSoftwareKeyboardDialog::GetStatus() const {
+ return ok;
+}
+
+QtSoftwareKeyboard::QtSoftwareKeyboard(GMainWindow& main_window) {
+ connect(this, &QtSoftwareKeyboard::MainWindowGetText, &main_window,
+ &GMainWindow::SoftwareKeyboardGetText, Qt::QueuedConnection);
+ connect(this, &QtSoftwareKeyboard::MainWindowTextCheckDialog, &main_window,
+ &GMainWindow::SoftwareKeyboardInvokeCheckDialog, Qt::BlockingQueuedConnection);
+ connect(&main_window, &GMainWindow::SoftwareKeyboardFinishedText, this,
+ &QtSoftwareKeyboard::MainWindowFinishedText, Qt::QueuedConnection);
+}
+
+QtSoftwareKeyboard::~QtSoftwareKeyboard() = default;
+
+void QtSoftwareKeyboard::RequestText(std::function<void(std::optional<std::u16string>)> out,
+ Core::Frontend::SoftwareKeyboardParameters parameters) const {
+ text_output = std::move(out);
+ emit MainWindowGetText(parameters);
+}
+
+void QtSoftwareKeyboard::SendTextCheckDialog(std::u16string error_message,
+ std::function<void()> finished_check) const {
+ this->finished_check = std::move(finished_check);
+ emit MainWindowTextCheckDialog(error_message);
+}
+
+void QtSoftwareKeyboard::MainWindowFinishedText(std::optional<std::u16string> text) {
+ // Acquire the HLE mutex
+ std::lock_guard<std::recursive_mutex> lock(HLE::g_hle_lock);
+ text_output(text);
+}
+
+void QtSoftwareKeyboard::MainWindowFinishedCheckDialog() {
+ // Acquire the HLE mutex
+ std::lock_guard<std::recursive_mutex> lock(HLE::g_hle_lock);
+ finished_check();
+}
diff --git a/src/yuzu/applets/software_keyboard.h b/src/yuzu/applets/software_keyboard.h
new file mode 100644
index 000000000..c63720ba4
--- /dev/null
+++ b/src/yuzu/applets/software_keyboard.h
@@ -0,0 +1,79 @@
+// Copyright 2018 yuzu Emulator Project
+// Licensed under GPLv2 or any later version
+// Refer to the license.txt file included.
+
+#pragma once
+
+#include <QDialog>
+#include <QValidator>
+#include "common/assert.h"
+#include "core/frontend/applets/software_keyboard.h"
+
+class GMainWindow;
+class QDialogButtonBox;
+class QLabel;
+class QLineEdit;
+class QVBoxLayout;
+class QtSoftwareKeyboard;
+
+class QtSoftwareKeyboardValidator final : public QValidator {
+public:
+ explicit QtSoftwareKeyboardValidator(Core::Frontend::SoftwareKeyboardParameters parameters);
+ State validate(QString& input, int& pos) const override;
+
+private:
+ Core::Frontend::SoftwareKeyboardParameters parameters;
+};
+
+class QtSoftwareKeyboardDialog final : public QDialog {
+ Q_OBJECT
+
+public:
+ QtSoftwareKeyboardDialog(QWidget* parent,
+ Core::Frontend::SoftwareKeyboardParameters parameters);
+ ~QtSoftwareKeyboardDialog() override;
+
+ void accept() override;
+ void reject() override;
+
+ std::u16string GetText() const;
+ bool GetStatus() const;
+
+private:
+ bool ok = false;
+ std::u16string text;
+
+ QDialogButtonBox* buttons;
+ QLabel* header_label;
+ QLabel* sub_label;
+ QLabel* guide_label;
+ QLabel* length_label;
+ QLineEdit* line_edit;
+ QVBoxLayout* layout;
+
+ Core::Frontend::SoftwareKeyboardParameters parameters;
+};
+
+class QtSoftwareKeyboard final : public QObject, public Core::Frontend::SoftwareKeyboardApplet {
+ Q_OBJECT
+
+public:
+ explicit QtSoftwareKeyboard(GMainWindow& parent);
+ ~QtSoftwareKeyboard() override;
+
+ void RequestText(std::function<void(std::optional<std::u16string>)> out,
+ Core::Frontend::SoftwareKeyboardParameters parameters) const override;
+ void SendTextCheckDialog(std::u16string error_message,
+ std::function<void()> finished_check) const override;
+
+signals:
+ void MainWindowGetText(Core::Frontend::SoftwareKeyboardParameters parameters) const;
+ void MainWindowTextCheckDialog(std::u16string error_message) const;
+
+private:
+ void MainWindowFinishedText(std::optional<std::u16string> text);
+ void MainWindowFinishedCheckDialog();
+
+ mutable std::function<void(std::optional<std::u16string>)> text_output;
+ mutable std::function<void()> finished_check;
+};
diff --git a/src/yuzu/bootmanager.cpp b/src/yuzu/bootmanager.cpp
index 39eef8858..384e17921 100644
--- a/src/yuzu/bootmanager.cpp
+++ b/src/yuzu/bootmanager.cpp
@@ -310,7 +310,7 @@ void GRenderWindow::InitRenderTarget() {
// TODO: One of these flags might be interesting: WA_OpaquePaintEvent, WA_NoBackground,
// WA_DontShowOnScreen, WA_DeleteOnClose
QGLFormat fmt;
- fmt.setVersion(3, 3);
+ fmt.setVersion(4, 3);
fmt.setProfile(QGLFormat::CoreProfile);
fmt.setSwapInterval(false);
diff --git a/src/yuzu/configuration/config.cpp b/src/yuzu/configuration/config.cpp
index d4fd60a73..83ebbd1fe 100644
--- a/src/yuzu/configuration/config.cpp
+++ b/src/yuzu/configuration/config.cpp
@@ -5,6 +5,7 @@
#include <QSettings>
#include "common/file_util.h"
#include "core/hle/service/acc/profile_manager.h"
+#include "core/hle/service/hid/controllers/npad.h"
#include "input_common/main.h"
#include "yuzu/configuration/config.h"
#include "yuzu/ui_settings.h"
@@ -47,40 +48,313 @@ const std::array<std::array<int, 5>, Settings::NativeAnalog::NumAnalogs> Config:
},
}};
-void Config::ReadValues() {
- qt_config->beginGroup("Controls");
+const std::array<int, Settings::NativeMouseButton::NumMouseButtons> Config::default_mouse_buttons =
+ {
+ Qt::Key_BracketLeft, Qt::Key_BracketRight, Qt::Key_Apostrophe, Qt::Key_Minus, Qt::Key_Equal,
+};
+
+const std::array<int, Settings::NativeKeyboard::NumKeyboardKeys> Config::default_keyboard_keys = {
+ 0,
+ 0,
+ 0,
+ 0,
+ Qt::Key_A,
+ Qt::Key_B,
+ Qt::Key_C,
+ Qt::Key_D,
+ Qt::Key_E,
+ Qt::Key_F,
+ Qt::Key_G,
+ Qt::Key_H,
+ Qt::Key_I,
+ Qt::Key_J,
+ Qt::Key_K,
+ Qt::Key_L,
+ Qt::Key_M,
+ Qt::Key_N,
+ Qt::Key_O,
+ Qt::Key_P,
+ Qt::Key_Q,
+ Qt::Key_R,
+ Qt::Key_S,
+ Qt::Key_T,
+ Qt::Key_U,
+ Qt::Key_V,
+ Qt::Key_W,
+ Qt::Key_X,
+ Qt::Key_Y,
+ Qt::Key_Z,
+ Qt::Key_1,
+ Qt::Key_2,
+ Qt::Key_3,
+ Qt::Key_4,
+ Qt::Key_5,
+ Qt::Key_6,
+ Qt::Key_7,
+ Qt::Key_8,
+ Qt::Key_9,
+ Qt::Key_0,
+ Qt::Key_Enter,
+ Qt::Key_Escape,
+ Qt::Key_Backspace,
+ Qt::Key_Tab,
+ Qt::Key_Space,
+ Qt::Key_Minus,
+ Qt::Key_Equal,
+ Qt::Key_BracketLeft,
+ Qt::Key_BracketRight,
+ Qt::Key_Backslash,
+ Qt::Key_Dead_Tilde,
+ Qt::Key_Semicolon,
+ Qt::Key_Apostrophe,
+ Qt::Key_Dead_Grave,
+ Qt::Key_Comma,
+ Qt::Key_Period,
+ Qt::Key_Slash,
+ Qt::Key_CapsLock,
+
+ Qt::Key_F1,
+ Qt::Key_F2,
+ Qt::Key_F3,
+ Qt::Key_F4,
+ Qt::Key_F5,
+ Qt::Key_F6,
+ Qt::Key_F7,
+ Qt::Key_F8,
+ Qt::Key_F9,
+ Qt::Key_F10,
+ Qt::Key_F11,
+ Qt::Key_F12,
+
+ Qt::Key_SysReq,
+ Qt::Key_ScrollLock,
+ Qt::Key_Pause,
+ Qt::Key_Insert,
+ Qt::Key_Home,
+ Qt::Key_PageUp,
+ Qt::Key_Delete,
+ Qt::Key_End,
+ Qt::Key_PageDown,
+ Qt::Key_Right,
+ Qt::Key_Left,
+ Qt::Key_Down,
+ Qt::Key_Up,
+
+ Qt::Key_NumLock,
+ Qt::Key_Slash,
+ Qt::Key_Asterisk,
+ Qt::Key_Minus,
+ Qt::Key_Plus,
+ Qt::Key_Enter,
+ Qt::Key_1,
+ Qt::Key_2,
+ Qt::Key_3,
+ Qt::Key_4,
+ Qt::Key_5,
+ Qt::Key_6,
+ Qt::Key_7,
+ Qt::Key_8,
+ Qt::Key_9,
+ Qt::Key_0,
+ Qt::Key_Period,
+
+ 0,
+ 0,
+ Qt::Key_PowerOff,
+ Qt::Key_Equal,
+
+ Qt::Key_F13,
+ Qt::Key_F14,
+ Qt::Key_F15,
+ Qt::Key_F16,
+ Qt::Key_F17,
+ Qt::Key_F18,
+ Qt::Key_F19,
+ Qt::Key_F20,
+ Qt::Key_F21,
+ Qt::Key_F22,
+ Qt::Key_F23,
+ Qt::Key_F24,
+
+ Qt::Key_Open,
+ Qt::Key_Help,
+ Qt::Key_Menu,
+ 0,
+ Qt::Key_Stop,
+ Qt::Key_AudioRepeat,
+ Qt::Key_Undo,
+ Qt::Key_Cut,
+ Qt::Key_Copy,
+ Qt::Key_Paste,
+ Qt::Key_Find,
+ Qt::Key_VolumeMute,
+ Qt::Key_VolumeUp,
+ Qt::Key_VolumeDown,
+ Qt::Key_CapsLock,
+ Qt::Key_NumLock,
+ Qt::Key_ScrollLock,
+ Qt::Key_Comma,
+
+ Qt::Key_ParenLeft,
+ Qt::Key_ParenRight,
+};
+
+const std::array<int, Settings::NativeKeyboard::NumKeyboardMods> Config::default_keyboard_mods = {
+ Qt::Key_Control, Qt::Key_Shift, Qt::Key_Alt, Qt::Key_ApplicationLeft,
+ Qt::Key_Control, Qt::Key_Shift, Qt::Key_AltGr, Qt::Key_ApplicationRight,
+};
+
+void Config::ReadPlayerValues() {
+ for (std::size_t p = 0; p < Settings::values.players.size(); ++p) {
+ Settings::values.players[p].connected =
+ qt_config->value(QString("player_%1_connected").arg(p), false).toBool();
+
+ Settings::values.players[p].type = static_cast<Settings::ControllerType>(
+ qt_config
+ ->value(QString("player_%1_type").arg(p),
+ static_cast<u8>(Settings::ControllerType::DualJoycon))
+ .toUInt());
+
+ Settings::values.players[p].body_color_left =
+ qt_config
+ ->value(QString("player_%1_body_color_left").arg(p),
+ Settings::JOYCON_BODY_NEON_BLUE)
+ .toUInt();
+ Settings::values.players[p].body_color_right =
+ qt_config
+ ->value(QString("player_%1_body_color_right").arg(p),
+ Settings::JOYCON_BODY_NEON_RED)
+ .toUInt();
+ Settings::values.players[p].button_color_left =
+ qt_config
+ ->value(QString("player_%1_button_color_left").arg(p),
+ Settings::JOYCON_BUTTONS_NEON_BLUE)
+ .toUInt();
+ Settings::values.players[p].button_color_right =
+ qt_config
+ ->value(QString("player_%1_button_color_right").arg(p),
+ Settings::JOYCON_BUTTONS_NEON_RED)
+ .toUInt();
+
+ for (int i = 0; i < Settings::NativeButton::NumButtons; ++i) {
+ std::string default_param = InputCommon::GenerateKeyboardParam(default_buttons[i]);
+ Settings::values.players[p].buttons[i] =
+ qt_config
+ ->value(QString("player_%1_").arg(p) + Settings::NativeButton::mapping[i],
+ QString::fromStdString(default_param))
+ .toString()
+ .toStdString();
+ if (Settings::values.players[p].buttons[i].empty())
+ Settings::values.players[p].buttons[i] = default_param;
+ }
+
+ for (int i = 0; i < Settings::NativeAnalog::NumAnalogs; ++i) {
+ std::string default_param = InputCommon::GenerateAnalogParamFromKeys(
+ default_analogs[i][0], default_analogs[i][1], default_analogs[i][2],
+ default_analogs[i][3], default_analogs[i][4], 0.5f);
+ Settings::values.players[p].analogs[i] =
+ qt_config
+ ->value(QString("player_%1_").arg(p) + Settings::NativeAnalog::mapping[i],
+ QString::fromStdString(default_param))
+ .toString()
+ .toStdString();
+ if (Settings::values.players[p].analogs[i].empty())
+ Settings::values.players[p].analogs[i] = default_param;
+ }
+ }
+
+ std::stable_partition(
+ Settings::values.players.begin(),
+ Settings::values.players.begin() +
+ Service::HID::Controller_NPad::NPadIdToIndex(Service::HID::NPAD_HANDHELD),
+ [](const auto& player) { return player.connected; });
+}
+
+void Config::ReadDebugValues() {
+ Settings::values.debug_pad_enabled = qt_config->value("debug_pad_enabled", false).toBool();
for (int i = 0; i < Settings::NativeButton::NumButtons; ++i) {
std::string default_param = InputCommon::GenerateKeyboardParam(default_buttons[i]);
- Settings::values.buttons[i] =
+ Settings::values.debug_pad_buttons[i] =
qt_config
- ->value(Settings::NativeButton::mapping[i], QString::fromStdString(default_param))
+ ->value(QString("debug_pad_") + Settings::NativeButton::mapping[i],
+ QString::fromStdString(default_param))
.toString()
.toStdString();
- if (Settings::values.buttons[i].empty())
- Settings::values.buttons[i] = default_param;
+ if (Settings::values.debug_pad_buttons[i].empty())
+ Settings::values.debug_pad_buttons[i] = default_param;
}
for (int i = 0; i < Settings::NativeAnalog::NumAnalogs; ++i) {
std::string default_param = InputCommon::GenerateAnalogParamFromKeys(
default_analogs[i][0], default_analogs[i][1], default_analogs[i][2],
default_analogs[i][3], default_analogs[i][4], 0.5f);
- Settings::values.analogs[i] =
+ Settings::values.debug_pad_analogs[i] =
+ qt_config
+ ->value(QString("debug_pad_") + Settings::NativeAnalog::mapping[i],
+ QString::fromStdString(default_param))
+ .toString()
+ .toStdString();
+ if (Settings::values.debug_pad_analogs[i].empty())
+ Settings::values.debug_pad_analogs[i] = default_param;
+ }
+}
+
+void Config::ReadKeyboardValues() {
+ Settings::values.keyboard_enabled = qt_config->value("keyboard_enabled", false).toBool();
+
+ std::transform(default_keyboard_keys.begin(), default_keyboard_keys.end(),
+ Settings::values.keyboard_keys.begin(), InputCommon::GenerateKeyboardParam);
+ std::transform(default_keyboard_mods.begin(), default_keyboard_mods.end(),
+ Settings::values.keyboard_keys.begin() +
+ Settings::NativeKeyboard::LeftControlKey,
+ InputCommon::GenerateKeyboardParam);
+ std::transform(default_keyboard_mods.begin(), default_keyboard_mods.end(),
+ Settings::values.keyboard_mods.begin(), InputCommon::GenerateKeyboardParam);
+}
+
+void Config::ReadMouseValues() {
+ Settings::values.mouse_enabled = qt_config->value("mouse_enabled", false).toBool();
+
+ for (int i = 0; i < Settings::NativeMouseButton::NumMouseButtons; ++i) {
+ std::string default_param = InputCommon::GenerateKeyboardParam(default_mouse_buttons[i]);
+ Settings::values.mouse_buttons[i] =
qt_config
- ->value(Settings::NativeAnalog::mapping[i], QString::fromStdString(default_param))
+ ->value(QString("mouse_") + Settings::NativeMouseButton::mapping[i],
+ QString::fromStdString(default_param))
.toString()
.toStdString();
- if (Settings::values.analogs[i].empty())
- Settings::values.analogs[i] = default_param;
+ if (Settings::values.mouse_buttons[i].empty())
+ Settings::values.mouse_buttons[i] = default_param;
}
+}
+
+void Config::ReadTouchscreenValues() {
+ Settings::values.touchscreen.enabled = qt_config->value("touchscreen_enabled", true).toBool();
+ Settings::values.touchscreen.device =
+ qt_config->value("touchscreen_device", "engine:emu_window").toString().toStdString();
+
+ Settings::values.touchscreen.finger = qt_config->value("touchscreen_finger", 0).toUInt();
+ Settings::values.touchscreen.rotation_angle = qt_config->value("touchscreen_angle", 0).toUInt();
+ Settings::values.touchscreen.diameter_x =
+ qt_config->value("touchscreen_diameter_x", 15).toUInt();
+ Settings::values.touchscreen.diameter_y =
+ qt_config->value("touchscreen_diameter_y", 15).toUInt();
+ qt_config->endGroup();
+}
+
+void Config::ReadValues() {
+ qt_config->beginGroup("Controls");
+
+ ReadPlayerValues();
+ ReadDebugValues();
+ ReadKeyboardValues();
+ ReadMouseValues();
+ ReadTouchscreenValues();
Settings::values.motion_device =
qt_config->value("motion_device", "engine:motion_emu,update_period:100,sensitivity:0.01")
.toString()
.toStdString();
- Settings::values.touch_device =
- qt_config->value("touch_device", "engine:emu_window").toString().toStdString();
-
- qt_config->endGroup();
qt_config->beginGroup("Core");
Settings::values.use_cpu_jit = qt_config->value("use_cpu_jit", true).toBool();
@@ -126,6 +400,11 @@ void Config::ReadValues() {
.toStdString());
qt_config->endGroup();
+ qt_config->beginGroup("Core");
+ Settings::values.use_cpu_jit = qt_config->value("use_cpu_jit", true).toBool();
+ Settings::values.use_multi_core = qt_config->value("use_multi_core", false).toBool();
+ qt_config->endGroup();
+
qt_config->beginGroup("System");
Settings::values.use_docked_mode = qt_config->value("use_docked_mode", false).toBool();
Settings::values.enable_nfc = qt_config->value("enable_nfc", true).toBool();
@@ -134,6 +413,14 @@ void Config::ReadValues() {
Service::Account::MAX_USERS - 1);
Settings::values.language_index = qt_config->value("language_index", 1).toInt();
+
+ const auto enabled = qt_config->value("rng_seed_enabled", false).toBool();
+ if (enabled) {
+ Settings::values.rng_seed = qt_config->value("rng_seed", 0).toULongLong();
+ } else {
+ Settings::values.rng_seed = std::nullopt;
+ }
+
qt_config->endGroup();
qt_config->beginGroup("Miscellaneous");
@@ -145,6 +432,8 @@ void Config::ReadValues() {
Settings::values.use_gdbstub = qt_config->value("use_gdbstub", false).toBool();
Settings::values.gdbstub_port = qt_config->value("gdbstub_port", 24689).toInt();
Settings::values.program_args = qt_config->value("program_args", "").toString().toStdString();
+ Settings::values.dump_exefs = qt_config->value("dump_exefs", false).toBool();
+ Settings::values.dump_nso = qt_config->value("dump_nso", false).toBool();
qt_config->endGroup();
qt_config->beginGroup("WebService");
@@ -162,6 +451,7 @@ void Config::ReadValues() {
qt_config->beginGroup("UIGameList");
UISettings::values.show_unknown = qt_config->value("show_unknown", true).toBool();
+ UISettings::values.show_add_ons = qt_config->value("show_add_ons", true).toBool();
UISettings::values.icon_size = qt_config->value("icon_size", 64).toUInt();
UISettings::values.row_1_text_id = qt_config->value("row_1_text_id", 3).toUInt();
UISettings::values.row_2_text_id = qt_config->value("row_2_text_id", 2).toUInt();
@@ -220,18 +510,81 @@ void Config::ReadValues() {
qt_config->endGroup();
}
-void Config::SaveValues() {
- qt_config->beginGroup("Controls");
+void Config::SavePlayerValues() {
+ for (int p = 0; p < Settings::values.players.size(); ++p) {
+ qt_config->setValue(QString("player_%1_connected").arg(p),
+ Settings::values.players[p].connected);
+ qt_config->setValue(QString("player_%1_type").arg(p),
+ static_cast<u8>(Settings::values.players[p].type));
+
+ qt_config->setValue(QString("player_%1_body_color_left").arg(p),
+ Settings::values.players[p].body_color_left);
+ qt_config->setValue(QString("player_%1_body_color_right").arg(p),
+ Settings::values.players[p].body_color_right);
+ qt_config->setValue(QString("player_%1_button_color_left").arg(p),
+ Settings::values.players[p].button_color_left);
+ qt_config->setValue(QString("player_%1_button_color_right").arg(p),
+ Settings::values.players[p].button_color_right);
+
+ for (int i = 0; i < Settings::NativeButton::NumButtons; ++i) {
+ qt_config->setValue(QString("player_%1_").arg(p) +
+ QString::fromStdString(Settings::NativeButton::mapping[i]),
+ QString::fromStdString(Settings::values.players[p].buttons[i]));
+ }
+ for (int i = 0; i < Settings::NativeAnalog::NumAnalogs; ++i) {
+ qt_config->setValue(QString("player_%1_").arg(p) +
+ QString::fromStdString(Settings::NativeAnalog::mapping[i]),
+ QString::fromStdString(Settings::values.players[p].analogs[i]));
+ }
+ }
+}
+
+void Config::SaveDebugValues() {
+ qt_config->setValue("debug_pad_enabled", Settings::values.debug_pad_enabled);
for (int i = 0; i < Settings::NativeButton::NumButtons; ++i) {
- qt_config->setValue(QString::fromStdString(Settings::NativeButton::mapping[i]),
- QString::fromStdString(Settings::values.buttons[i]));
+ qt_config->setValue(QString("debug_pad_") +
+ QString::fromStdString(Settings::NativeButton::mapping[i]),
+ QString::fromStdString(Settings::values.debug_pad_buttons[i]));
}
for (int i = 0; i < Settings::NativeAnalog::NumAnalogs; ++i) {
- qt_config->setValue(QString::fromStdString(Settings::NativeAnalog::mapping[i]),
- QString::fromStdString(Settings::values.analogs[i]));
+ qt_config->setValue(QString("debug_pad_") +
+ QString::fromStdString(Settings::NativeAnalog::mapping[i]),
+ QString::fromStdString(Settings::values.debug_pad_analogs[i]));
+ }
+}
+
+void Config::SaveMouseValues() {
+ qt_config->setValue("mouse_enabled", Settings::values.mouse_enabled);
+
+ for (int i = 0; i < Settings::NativeMouseButton::NumMouseButtons; ++i) {
+ qt_config->setValue(QString("mouse_") +
+ QString::fromStdString(Settings::NativeMouseButton::mapping[i]),
+ QString::fromStdString(Settings::values.mouse_buttons[i]));
}
+}
+
+void Config::SaveTouchscreenValues() {
+ qt_config->setValue("touchscreen_enabled", Settings::values.touchscreen.enabled);
+ qt_config->setValue("touchscreen_device",
+ QString::fromStdString(Settings::values.touchscreen.device));
+
+ qt_config->setValue("touchscreen_finger", Settings::values.touchscreen.finger);
+ qt_config->setValue("touchscreen_angle", Settings::values.touchscreen.rotation_angle);
+ qt_config->setValue("touchscreen_diameter_x", Settings::values.touchscreen.diameter_x);
+ qt_config->setValue("touchscreen_diameter_y", Settings::values.touchscreen.diameter_y);
+}
+
+void Config::SaveValues() {
+ qt_config->beginGroup("Controls");
+
+ SavePlayerValues();
+ SaveDebugValues();
+ SaveMouseValues();
+ SaveTouchscreenValues();
+
qt_config->setValue("motion_device", QString::fromStdString(Settings::values.motion_device));
- qt_config->setValue("touch_device", QString::fromStdString(Settings::values.touch_device));
+ qt_config->setValue("keyboard_enabled", Settings::values.keyboard_enabled);
+
qt_config->endGroup();
qt_config->beginGroup("Core");
@@ -270,8 +623,11 @@ void Config::SaveValues() {
qt_config->setValue("use_docked_mode", Settings::values.use_docked_mode);
qt_config->setValue("enable_nfc", Settings::values.enable_nfc);
qt_config->setValue("current_user", Settings::values.current_user);
-
qt_config->setValue("language_index", Settings::values.language_index);
+
+ qt_config->setValue("rng_seed_enabled", Settings::values.rng_seed.has_value());
+ qt_config->setValue("rng_seed", Settings::values.rng_seed.value_or(0));
+
qt_config->endGroup();
qt_config->beginGroup("Miscellaneous");
@@ -283,6 +639,8 @@ void Config::SaveValues() {
qt_config->setValue("use_gdbstub", Settings::values.use_gdbstub);
qt_config->setValue("gdbstub_port", Settings::values.gdbstub_port);
qt_config->setValue("program_args", QString::fromStdString(Settings::values.program_args));
+ qt_config->setValue("dump_exefs", Settings::values.dump_exefs);
+ qt_config->setValue("dump_nso", Settings::values.dump_nso);
qt_config->endGroup();
qt_config->beginGroup("WebService");
@@ -298,6 +656,7 @@ void Config::SaveValues() {
qt_config->beginGroup("UIGameList");
qt_config->setValue("show_unknown", UISettings::values.show_unknown);
+ qt_config->setValue("show_add_ons", UISettings::values.show_add_ons);
qt_config->setValue("icon_size", UISettings::values.icon_size);
qt_config->setValue("row_1_text_id", UISettings::values.row_1_text_id);
qt_config->setValue("row_2_text_id", UISettings::values.row_2_text_id);
diff --git a/src/yuzu/configuration/config.h b/src/yuzu/configuration/config.h
index 9c99c1b75..a1c27bbf9 100644
--- a/src/yuzu/configuration/config.h
+++ b/src/yuzu/configuration/config.h
@@ -22,10 +22,24 @@ public:
static const std::array<int, Settings::NativeButton::NumButtons> default_buttons;
static const std::array<std::array<int, 5>, Settings::NativeAnalog::NumAnalogs> default_analogs;
+ static const std::array<int, Settings::NativeMouseButton::NumMouseButtons>
+ default_mouse_buttons;
+ static const std::array<int, Settings::NativeKeyboard::NumKeyboardKeys> default_keyboard_keys;
+ static const std::array<int, Settings::NativeKeyboard::NumKeyboardMods> default_keyboard_mods;
private:
void ReadValues();
+ void ReadPlayerValues();
+ void ReadDebugValues();
+ void ReadKeyboardValues();
+ void ReadMouseValues();
+ void ReadTouchscreenValues();
+
void SaveValues();
+ void SavePlayerValues();
+ void SaveDebugValues();
+ void SaveMouseValues();
+ void SaveTouchscreenValues();
std::unique_ptr<QSettings> qt_config;
std::string qt_config_loc;
diff --git a/src/yuzu/configuration/configure_debug.cpp b/src/yuzu/configuration/configure_debug.cpp
index 9e765fc93..aa7de7b54 100644
--- a/src/yuzu/configuration/configure_debug.cpp
+++ b/src/yuzu/configuration/configure_debug.cpp
@@ -34,6 +34,8 @@ void ConfigureDebug::setConfiguration() {
ui->toggle_console->setChecked(UISettings::values.show_console);
ui->log_filter_edit->setText(QString::fromStdString(Settings::values.log_filter));
ui->homebrew_args_edit->setText(QString::fromStdString(Settings::values.program_args));
+ ui->dump_exefs->setChecked(Settings::values.dump_exefs);
+ ui->dump_decompressed_nso->setChecked(Settings::values.dump_nso);
}
void ConfigureDebug::applyConfiguration() {
@@ -42,6 +44,8 @@ void ConfigureDebug::applyConfiguration() {
UISettings::values.show_console = ui->toggle_console->isChecked();
Settings::values.log_filter = ui->log_filter_edit->text().toStdString();
Settings::values.program_args = ui->homebrew_args_edit->text().toStdString();
+ Settings::values.dump_exefs = ui->dump_exefs->isChecked();
+ Settings::values.dump_nso = ui->dump_decompressed_nso->isChecked();
Debugger::ToggleConsole();
Log::Filter filter;
filter.ParseFilterString(Settings::values.log_filter);
diff --git a/src/yuzu/configuration/configure_debug.ui b/src/yuzu/configuration/configure_debug.ui
index ff4987604..758a92335 100644
--- a/src/yuzu/configuration/configure_debug.ui
+++ b/src/yuzu/configuration/configure_debug.ui
@@ -7,7 +7,7 @@
<x>0</x>
<y>0</y>
<width>400</width>
- <height>300</height>
+ <height>357</height>
</rect>
</property>
<property name="windowTitle">
@@ -130,6 +130,35 @@
</widget>
</item>
<item>
+ <widget class="QGroupBox" name="groupBox_4">
+ <property name="title">
+ <string>Dump</string>
+ </property>
+ <layout class="QVBoxLayout" name="verticalLayout_4">
+ <item>
+ <widget class="QCheckBox" name="dump_decompressed_nso">
+ <property name="whatsThis">
+ <string>When checked, any NSO yuzu tries to load or patch will be copied decompressed to the yuzu/dump directory.</string>
+ </property>
+ <property name="text">
+ <string>Dump Decompressed NSOs</string>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <widget class="QCheckBox" name="dump_exefs">
+ <property name="whatsThis">
+ <string>When checked, any game that yuzu loads will have its ExeFS dumped to the yuzu/dump directory.</string>
+ </property>
+ <property name="text">
+ <string>Dump ExeFS</string>
+ </property>
+ </widget>
+ </item>
+ </layout>
+ </widget>
+ </item>
+ <item>
<spacer name="verticalSpacer">
<property name="orientation">
<enum>Qt::Vertical</enum>
diff --git a/src/yuzu/configuration/configure_gamelist.cpp b/src/yuzu/configuration/configure_gamelist.cpp
index 8743ce982..ae8cac243 100644
--- a/src/yuzu/configuration/configure_gamelist.cpp
+++ b/src/yuzu/configuration/configure_gamelist.cpp
@@ -36,20 +36,36 @@ ConfigureGameList::ConfigureGameList(QWidget* parent)
InitializeRowComboBoxes();
this->setConfiguration();
+
+ // Force game list reload if any of the relevant settings are changed.
+ connect(ui->show_unknown, &QCheckBox::stateChanged, this,
+ &ConfigureGameList::RequestGameListUpdate);
+ connect(ui->icon_size_combobox, QOverload<int>::of(&QComboBox::currentIndexChanged), this,
+ &ConfigureGameList::RequestGameListUpdate);
+ connect(ui->row_1_text_combobox, QOverload<int>::of(&QComboBox::currentIndexChanged), this,
+ &ConfigureGameList::RequestGameListUpdate);
+ connect(ui->row_2_text_combobox, QOverload<int>::of(&QComboBox::currentIndexChanged), this,
+ &ConfigureGameList::RequestGameListUpdate);
}
ConfigureGameList::~ConfigureGameList() = default;
void ConfigureGameList::applyConfiguration() {
UISettings::values.show_unknown = ui->show_unknown->isChecked();
+ UISettings::values.show_add_ons = ui->show_add_ons->isChecked();
UISettings::values.icon_size = ui->icon_size_combobox->currentData().toUInt();
UISettings::values.row_1_text_id = ui->row_1_text_combobox->currentData().toUInt();
UISettings::values.row_2_text_id = ui->row_2_text_combobox->currentData().toUInt();
Settings::Apply();
}
+void ConfigureGameList::RequestGameListUpdate() {
+ UISettings::values.is_game_list_reload_pending.exchange(true);
+}
+
void ConfigureGameList::setConfiguration() {
ui->show_unknown->setChecked(UISettings::values.show_unknown);
+ ui->show_add_ons->setChecked(UISettings::values.show_add_ons);
ui->icon_size_combobox->setCurrentIndex(
ui->icon_size_combobox->findData(UISettings::values.icon_size));
ui->row_1_text_combobox->setCurrentIndex(
diff --git a/src/yuzu/configuration/configure_gamelist.h b/src/yuzu/configuration/configure_gamelist.h
index ff7406c60..bbf7e25f1 100644
--- a/src/yuzu/configuration/configure_gamelist.h
+++ b/src/yuzu/configuration/configure_gamelist.h
@@ -21,6 +21,8 @@ public:
void applyConfiguration();
private:
+ void RequestGameListUpdate();
+
void setConfiguration();
void changeEvent(QEvent*) override;
diff --git a/src/yuzu/configuration/configure_gamelist.ui b/src/yuzu/configuration/configure_gamelist.ui
index 7471fdb60..7a69377e7 100644
--- a/src/yuzu/configuration/configure_gamelist.ui
+++ b/src/yuzu/configuration/configure_gamelist.ui
@@ -1,126 +1,133 @@
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>ConfigureGameList</class>
- <widget class="QWidget" name="ConfigureGeneral">
- <property name="geometry">
- <rect>
- <x>0</x>
- <y>0</y>
- <width>300</width>
- <height>377</height>
- </rect>
- </property>
- <property name="windowTitle">
- <string>Form</string>
- </property>
- <layout class="QHBoxLayout" name="HorizontalLayout">
- <item>
- <layout class="QVBoxLayout" name="VerticalLayout">
+ <widget class="QWidget" name="ConfigureGameList">
+ <property name="geometry">
+ <rect>
+ <x>0</x>
+ <y>0</y>
+ <width>300</width>
+ <height>377</height>
+ </rect>
+ </property>
+ <property name="windowTitle">
+ <string>Form</string>
+ </property>
+ <layout class="QHBoxLayout" name="HorizontalLayout">
+ <item>
+ <layout class="QVBoxLayout" name="VerticalLayout">
+ <item>
+ <widget class="QGroupBox" name="GeneralGroupBox">
+ <property name="title">
+ <string>General</string>
+ </property>
+ <layout class="QHBoxLayout" name="GeneralHorizontalLayout">
+ <item>
+ <layout class="QVBoxLayout" name="GeneralVerticalLayout">
<item>
- <widget class="QGroupBox" name="GeneralGroupBox">
- <property name="title">
- <string>General</string>
- </property>
- <layout class="QHBoxLayout" name="GeneralHorizontalLayout">
- <item>
- <layout class="QVBoxLayout" name="GeneralVerticalLayout">
- <item>
- <widget class="QCheckBox" name="show_unknown">
- <property name="text">
- <string>Show files with type 'Unknown'</string>
- </property>
- </widget>
- </item>
- </layout>
- </item>
- </layout>
- </widget>
+ <widget class="QCheckBox" name="show_unknown">
+ <property name="text">
+ <string>Show files with type 'Unknown'</string>
+ </property>
+ </widget>
</item>
<item>
- <widget class="QGroupBox" name="IconSizeGroupBox">
- <property name="title">
- <string>Icon Size</string>
- </property>
- <layout class="QHBoxLayout" name="icon_size_qhbox_layout">
- <item>
- <layout class="QVBoxLayout" name="icon_size_qvbox_layout">
- <item>
- <layout class="QHBoxLayout" name="icon_size_qhbox_layout_2">
- <item>
- <widget class="QLabel" name="icon_size_label">
- <property name="text">
- <string>Icon Size:</string>
- </property>
- </widget>
- </item>
- <item>
- <widget class="QComboBox" name="icon_size_combobox"/>
- </item>
- </layout>
- </item>
- </layout>
- </item>
- </layout>
- </widget>
+ <widget class="QCheckBox" name="show_add_ons">
+ <property name="text">
+ <string>Show Add-Ons Column</string>
+ </property>
+ </widget>
</item>
+ </layout>
+ </item>
+ </layout>
+ </widget>
+ </item>
+ <item>
+ <widget class="QGroupBox" name="IconSizeGroupBox">
+ <property name="title">
+ <string>Icon Size</string>
+ </property>
+ <layout class="QHBoxLayout" name="icon_size_qhbox_layout">
+ <item>
+ <layout class="QVBoxLayout" name="icon_size_qvbox_layout">
<item>
- <widget class="QGroupBox" name="RowGroupBox">
- <property name="title">
- <string>Row Text</string>
+ <layout class="QHBoxLayout" name="icon_size_qhbox_layout_2">
+ <item>
+ <widget class="QLabel" name="icon_size_label">
+ <property name="text">
+ <string>Icon Size:</string>
</property>
- <layout class="QHBoxLayout" name="RowHorizontalLayout">
- <item>
- <layout class="QVBoxLayout" name="RowVerticalLayout">
- <item>
- <layout class="QHBoxLayout" name="row_1_qhbox_layout">
- <item>
- <widget class="QLabel" name="row_1_label">
- <property name="text">
- <string>Row 1 Text:</string>
- </property>
- </widget>
- </item>
- <item>
- <widget class="QComboBox" name="row_1_text_combobox"/>
- </item>
- </layout>
- </item>
- <item>
- <layout class="QHBoxLayout" name="row_2_qhbox_layout">
- <item>
- <widget class="QLabel" name="row_2_label">
- <property name="text">
- <string>Row 2 Text:</string>
- </property>
- </widget>
- </item>
- <item>
- <widget class="QComboBox" name="row_2_text_combobox"/>
- </item>
- </layout>
- </item>
- </layout>
- </item>
- </layout>
- </widget>
+ </widget>
+ </item>
+ <item>
+ <widget class="QComboBox" name="icon_size_combobox"/>
+ </item>
+ </layout>
</item>
+ </layout>
+ </item>
+ </layout>
+ </widget>
+ </item>
+ <item>
+ <widget class="QGroupBox" name="RowGroupBox">
+ <property name="title">
+ <string>Row Text</string>
+ </property>
+ <layout class="QHBoxLayout" name="RowHorizontalLayout">
+ <item>
+ <layout class="QVBoxLayout" name="RowVerticalLayout">
<item>
- <spacer name="verticalSpacer">
- <property name="orientation">
- <enum>Qt::Vertical</enum>
+ <layout class="QHBoxLayout" name="row_1_qhbox_layout">
+ <item>
+ <widget class="QLabel" name="row_1_label">
+ <property name="text">
+ <string>Row 1 Text:</string>
</property>
- <property name="sizeHint" stdset="0">
- <size>
- <width>20</width>
- <height>40</height>
- </size>
+ </widget>
+ </item>
+ <item>
+ <widget class="QComboBox" name="row_1_text_combobox"/>
+ </item>
+ </layout>
+ </item>
+ <item>
+ <layout class="QHBoxLayout" name="row_2_qhbox_layout">
+ <item>
+ <widget class="QLabel" name="row_2_label">
+ <property name="text">
+ <string>Row 2 Text:</string>
</property>
- </spacer>
+ </widget>
+ </item>
+ <item>
+ <widget class="QComboBox" name="row_2_text_combobox"/>
+ </item>
+ </layout>
</item>
- </layout>
- </item>
+ </layout>
+ </item>
+ </layout>
+ </widget>
+ </item>
+ <item>
+ <spacer name="verticalSpacer">
+ <property name="orientation">
+ <enum>Qt::Vertical</enum>
+ </property>
+ <property name="sizeHint" stdset="0">
+ <size>
+ <width>20</width>
+ <height>40</height>
+ </size>
+ </property>
+ </spacer>
+ </item>
</layout>
- </widget>
+ </item>
+ </layout>
+ </widget>
<resources/>
<connections/>
</ui>
diff --git a/src/yuzu/configuration/configure_general.cpp b/src/yuzu/configuration/configure_general.cpp
index 537d6e576..92a441308 100644
--- a/src/yuzu/configuration/configure_general.cpp
+++ b/src/yuzu/configuration/configure_general.cpp
@@ -19,8 +19,10 @@ ConfigureGeneral::ConfigureGeneral(QWidget* parent)
this->setConfiguration();
+ connect(ui->toggle_deepscan, &QCheckBox::stateChanged, this,
+ [] { UISettings::values.is_game_list_reload_pending.exchange(true); });
+
ui->use_cpu_jit->setEnabled(!Core::System::GetInstance().IsPoweredOn());
- ui->use_docked_mode->setEnabled(!Core::System::GetInstance().IsPoweredOn());
}
ConfigureGeneral::~ConfigureGeneral() = default;
@@ -30,7 +32,6 @@ void ConfigureGeneral::setConfiguration() {
ui->toggle_check_exit->setChecked(UISettings::values.confirm_before_closing);
ui->theme_combobox->setCurrentIndex(ui->theme_combobox->findData(UISettings::values.theme));
ui->use_cpu_jit->setChecked(Settings::values.use_cpu_jit);
- ui->use_docked_mode->setChecked(Settings::values.use_docked_mode);
ui->enable_nfc->setChecked(Settings::values.enable_nfc);
}
@@ -45,6 +46,5 @@ void ConfigureGeneral::applyConfiguration() {
ui->theme_combobox->itemData(ui->theme_combobox->currentIndex()).toString();
Settings::values.use_cpu_jit = ui->use_cpu_jit->isChecked();
- Settings::values.use_docked_mode = ui->use_docked_mode->isChecked();
Settings::values.enable_nfc = ui->enable_nfc->isChecked();
}
diff --git a/src/yuzu/configuration/configure_general.ui b/src/yuzu/configuration/configure_general.ui
index b82fffde8..bf37446c6 100644
--- a/src/yuzu/configuration/configure_general.ui
+++ b/src/yuzu/configuration/configure_general.ui
@@ -7,7 +7,7 @@
<x>0</x>
<y>0</y>
<width>300</width>
- <height>377</height>
+ <height>407</height>
</rect>
</property>
<property name="windowTitle">
@@ -72,13 +72,6 @@
<item>
<layout class="QVBoxLayout" name="EmulationVerticalLayout">
<item>
- <widget class="QCheckBox" name="use_docked_mode">
- <property name="text">
- <string>Enable docked mode</string>
- </property>
- </widget>
- </item>
- <item>
<widget class="QCheckBox" name="enable_nfc">
<property name="text">
<string>Enable NFC</string>
diff --git a/src/yuzu/configuration/configure_graphics.ui b/src/yuzu/configuration/configure_graphics.ui
index 91fcad994..e278cdd05 100644
--- a/src/yuzu/configuration/configure_graphics.ui
+++ b/src/yuzu/configuration/configure_graphics.ui
@@ -23,31 +23,31 @@
</property>
<layout class="QVBoxLayout" name="verticalLayout_2">
<item>
- <layout class="QHBoxLayout" name="horizontalLayout_2">
- <item>
- <widget class="QCheckBox" name="toggle_frame_limit">
- <property name="text">
- <string>Limit Speed Percent</string>
- </property>
- </widget>
- </item>
- <item>
- <widget class="QSpinBox" name="frame_limit">
- <property name="suffix">
- <string>%</string>
- </property>
- <property name="minimum">
- <number>1</number>
- </property>
- <property name="maximum">
- <number>9999</number>
- </property>
- <property name="value">
- <number>100</number>
- </property>
- </widget>
- </item>
- </layout>
+ <layout class="QHBoxLayout" name="horizontalLayout_2">
+ <item>
+ <widget class="QCheckBox" name="toggle_frame_limit">
+ <property name="text">
+ <string>Limit Speed Percent</string>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <widget class="QSpinBox" name="frame_limit">
+ <property name="suffix">
+ <string>%</string>
+ </property>
+ <property name="minimum">
+ <number>1</number>
+ </property>
+ <property name="maximum">
+ <number>9999</number>
+ </property>
+ <property name="value">
+ <number>100</number>
+ </property>
+ </widget>
+ </item>
+ </layout>
</item>
<item>
<widget class="QCheckBox" name="use_accurate_gpu_emulation">
@@ -61,7 +61,7 @@
<item>
<widget class="QLabel" name="label">
<property name="text">
- <string>Internal Resolution:(Currently does nothing.)</string>
+ <string>Internal Resolution</string>
</property>
</widget>
</item>
@@ -96,27 +96,27 @@
</item>
</layout>
</item>
- <item>
- <layout class="QHBoxLayout" name="horizontalLayout_6">
- <item>
- <widget class="QLabel" name="bg_label">
- <property name="text">
- <string>Background Color:</string>
- </property>
- </widget>
- </item>
- <item>
- <widget class="QPushButton" name="bg_button">
- <property name="maximumSize">
- <size>
- <width>40</width>
- <height>16777215</height>
- </size>
- </property>
- </widget>
- </item>
- </layout>
- </item>
+ <item>
+ <layout class="QHBoxLayout" name="horizontalLayout_6">
+ <item>
+ <widget class="QLabel" name="bg_label">
+ <property name="text">
+ <string>Background Color:</string>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <widget class="QPushButton" name="bg_button">
+ <property name="maximumSize">
+ <size>
+ <width>40</width>
+ <height>16777215</height>
+ </size>
+ </property>
+ </widget>
+ </item>
+ </layout>
+ </item>
</layout>
</widget>
</item>
diff --git a/src/yuzu/configuration/configure_input.cpp b/src/yuzu/configuration/configure_input.cpp
index 42a7beac6..7ee572761 100644
--- a/src/yuzu/configuration/configure_input.cpp
+++ b/src/yuzu/configuration/configure_input.cpp
@@ -9,334 +9,202 @@
#include <QMessageBox>
#include <QTimer>
#include "common/param_package.h"
+#include "configuration/configure_touchscreen_advanced.h"
+#include "core/core.h"
+#include "core/hle/service/am/am.h"
+#include "core/hle/service/am/applet_ae.h"
+#include "core/hle/service/am/applet_oe.h"
+#include "core/hle/service/hid/controllers/npad.h"
+#include "core/hle/service/sm/sm.h"
#include "input_common/main.h"
+#include "ui_configure_input.h"
+#include "ui_configure_input_player.h"
+#include "ui_configure_mouse_advanced.h"
+#include "ui_configure_touchscreen_advanced.h"
#include "yuzu/configuration/config.h"
#include "yuzu/configuration/configure_input.h"
+#include "yuzu/configuration/configure_input_player.h"
+#include "yuzu/configuration/configure_mouse_advanced.h"
-const std::array<std::string, ConfigureInput::ANALOG_SUB_BUTTONS_NUM>
- ConfigureInput::analog_sub_buttons{{
- "up",
- "down",
- "left",
- "right",
- "modifier",
- }};
-
-static QString getKeyName(int key_code) {
- switch (key_code) {
- case Qt::Key_Shift:
- return QObject::tr("Shift");
- case Qt::Key_Control:
- return QObject::tr("Ctrl");
- case Qt::Key_Alt:
- return QObject::tr("Alt");
- case Qt::Key_Meta:
- return "";
- default:
- return QKeySequence(key_code).toString();
- }
-}
+ConfigureInput::ConfigureInput(QWidget* parent)
+ : QWidget(parent), ui(std::make_unique<Ui::ConfigureInput>()) {
+ ui->setupUi(this);
-static void SetAnalogButton(const Common::ParamPackage& input_param,
- Common::ParamPackage& analog_param, const std::string& button_name) {
- if (analog_param.Get("engine", "") != "analog_from_button") {
- analog_param = {
- {"engine", "analog_from_button"},
- {"modifier_scale", "0.5"},
- };
- }
- analog_param.Set(button_name, input_param.Serialize());
-}
+ players_controller = {
+ ui->player1_combobox, ui->player2_combobox, ui->player3_combobox, ui->player4_combobox,
+ ui->player5_combobox, ui->player6_combobox, ui->player7_combobox, ui->player8_combobox,
+ };
-static QString ButtonToText(const Common::ParamPackage& param) {
- if (!param.Has("engine")) {
- return QObject::tr("[not set]");
- } else if (param.Get("engine", "") == "keyboard") {
- return getKeyName(param.Get("code", 0));
- } else if (param.Get("engine", "") == "sdl") {
- if (param.Has("hat")) {
- return QString(QObject::tr("Hat %1 %2"))
- .arg(param.Get("hat", "").c_str(), param.Get("direction", "").c_str());
- }
- if (param.Has("axis")) {
- return QString(QObject::tr("Axis %1%2"))
- .arg(param.Get("axis", "").c_str(), param.Get("direction", "").c_str());
- }
- if (param.Has("button")) {
- return QString(QObject::tr("Button %1")).arg(param.Get("button", "").c_str());
- }
- return QString();
- } else {
- return QObject::tr("[unknown]");
- }
-};
-
-static QString AnalogToText(const Common::ParamPackage& param, const std::string& dir) {
- if (!param.Has("engine")) {
- return QObject::tr("[not set]");
- } else if (param.Get("engine", "") == "analog_from_button") {
- return ButtonToText(Common::ParamPackage{param.Get(dir, "")});
- } else if (param.Get("engine", "") == "sdl") {
- if (dir == "modifier") {
- return QString(QObject::tr("[unused]"));
- }
+ players_configure = {
+ ui->player1_configure, ui->player2_configure, ui->player3_configure, ui->player4_configure,
+ ui->player5_configure, ui->player6_configure, ui->player7_configure, ui->player8_configure,
+ };
- if (dir == "left" || dir == "right") {
- return QString(QObject::tr("Axis %1")).arg(param.Get("axis_x", "").c_str());
- } else if (dir == "up" || dir == "down") {
- return QString(QObject::tr("Axis %1")).arg(param.Get("axis_y", "").c_str());
- }
- return QString();
- } else {
- return QObject::tr("[unknown]");
+ for (auto* controller_box : players_controller) {
+ controller_box->addItems({"None", "Pro Controller", "Dual Joycons", "Single Right Joycon",
+ "Single Left Joycon"});
}
-};
-ConfigureInput::ConfigureInput(QWidget* parent)
- : QWidget(parent), ui(std::make_unique<Ui::ConfigureInput>()),
- timeout_timer(std::make_unique<QTimer>()), poll_timer(std::make_unique<QTimer>()) {
+ this->loadConfiguration();
+ updateUIEnabled();
- ui->setupUi(this);
- setFocusPolicy(Qt::ClickFocus);
-
- button_map = {
- ui->buttonA, ui->buttonB, ui->buttonX, ui->buttonY,
- ui->buttonLStick, ui->buttonRStick, ui->buttonL, ui->buttonR,
- ui->buttonZL, ui->buttonZR, ui->buttonPlus, ui->buttonMinus,
- ui->buttonDpadLeft, ui->buttonDpadUp, ui->buttonDpadRight, ui->buttonDpadDown,
- ui->buttonLStickLeft, ui->buttonLStickUp, ui->buttonLStickRight, ui->buttonLStickDown,
- ui->buttonRStickLeft, ui->buttonRStickUp, ui->buttonRStickRight, ui->buttonRStickDown,
- ui->buttonSL, ui->buttonSR, ui->buttonHome, ui->buttonScreenshot,
- };
+ connect(ui->restore_defaults_button, &QPushButton::pressed, this,
+ &ConfigureInput::restoreDefaults);
- analog_map_buttons = {{
- {
- ui->buttonLStickUp,
- ui->buttonLStickDown,
- ui->buttonLStickLeft,
- ui->buttonLStickRight,
- ui->buttonLStickMod,
- },
- {
- ui->buttonRStickUp,
- ui->buttonRStickDown,
- ui->buttonRStickLeft,
- ui->buttonRStickRight,
- ui->buttonRStickMod,
- },
- }};
-
- analog_map_stick = {ui->buttonLStickAnalog, ui->buttonRStickAnalog};
-
- for (int button_id = 0; button_id < Settings::NativeButton::NumButtons; button_id++) {
- if (!button_map[button_id])
- continue;
- button_map[button_id]->setContextMenuPolicy(Qt::CustomContextMenu);
- connect(button_map[button_id], &QPushButton::released, [=]() {
- handleClick(
- button_map[button_id],
- [=](const Common::ParamPackage& params) { buttons_param[button_id] = params; },
- InputCommon::Polling::DeviceType::Button);
- });
- connect(button_map[button_id], &QPushButton::customContextMenuRequested,
- [=](const QPoint& menu_location) {
- QMenu context_menu;
- context_menu.addAction(tr("Clear"), [&] {
- buttons_param[button_id].Clear();
- button_map[button_id]->setText(tr("[not set]"));
- });
- context_menu.addAction(tr("Restore Default"), [&] {
- buttons_param[button_id] = Common::ParamPackage{
- InputCommon::GenerateKeyboardParam(Config::default_buttons[button_id])};
- button_map[button_id]->setText(ButtonToText(buttons_param[button_id]));
- });
- context_menu.exec(button_map[button_id]->mapToGlobal(menu_location));
- });
- }
+ for (auto* enabled : players_controller)
+ connect(enabled, QOverload<int>::of(&QComboBox::currentIndexChanged), this,
+ &ConfigureInput::updateUIEnabled);
+ connect(ui->use_docked_mode, &QCheckBox::stateChanged, this, &ConfigureInput::updateUIEnabled);
+ connect(ui->handheld_connected, &QCheckBox::stateChanged, this,
+ &ConfigureInput::updateUIEnabled);
+ connect(ui->mouse_enabled, &QCheckBox::stateChanged, this, &ConfigureInput::updateUIEnabled);
+ connect(ui->keyboard_enabled, &QCheckBox::stateChanged, this, &ConfigureInput::updateUIEnabled);
+ connect(ui->debug_enabled, &QCheckBox::stateChanged, this, &ConfigureInput::updateUIEnabled);
+ connect(ui->touchscreen_enabled, &QCheckBox::stateChanged, this,
+ &ConfigureInput::updateUIEnabled);
- for (int analog_id = 0; analog_id < Settings::NativeAnalog::NumAnalogs; analog_id++) {
- for (int sub_button_id = 0; sub_button_id < ANALOG_SUB_BUTTONS_NUM; sub_button_id++) {
- if (!analog_map_buttons[analog_id][sub_button_id])
- continue;
- analog_map_buttons[analog_id][sub_button_id]->setContextMenuPolicy(
- Qt::CustomContextMenu);
- connect(analog_map_buttons[analog_id][sub_button_id], &QPushButton::released, [=]() {
- handleClick(analog_map_buttons[analog_id][sub_button_id],
- [=](const Common::ParamPackage& params) {
- SetAnalogButton(params, analogs_param[analog_id],
- analog_sub_buttons[sub_button_id]);
- },
- InputCommon::Polling::DeviceType::Button);
- });
- connect(analog_map_buttons[analog_id][sub_button_id],
- &QPushButton::customContextMenuRequested, [=](const QPoint& menu_location) {
- QMenu context_menu;
- context_menu.addAction(tr("Clear"), [&] {
- analogs_param[analog_id].Erase(analog_sub_buttons[sub_button_id]);
- analog_map_buttons[analog_id][sub_button_id]->setText(tr("[not set]"));
- });
- context_menu.addAction(tr("Restore Default"), [&] {
- Common::ParamPackage params{InputCommon::GenerateKeyboardParam(
- Config::default_analogs[analog_id][sub_button_id])};
- SetAnalogButton(params, analogs_param[analog_id],
- analog_sub_buttons[sub_button_id]);
- analog_map_buttons[analog_id][sub_button_id]->setText(AnalogToText(
- analogs_param[analog_id], analog_sub_buttons[sub_button_id]));
- });
- context_menu.exec(analog_map_buttons[analog_id][sub_button_id]->mapToGlobal(
- menu_location));
- });
- }
- connect(analog_map_stick[analog_id], &QPushButton::released, [=]() {
- QMessageBox::information(this, tr("Information"),
- tr("After pressing OK, first move your joystick horizontally, "
- "and then vertically."));
- handleClick(
- analog_map_stick[analog_id],
- [=](const Common::ParamPackage& params) { analogs_param[analog_id] = params; },
- InputCommon::Polling::DeviceType::Analog);
- });
+ for (std::size_t i = 0; i < players_configure.size(); ++i) {
+ connect(players_configure[i], &QPushButton::pressed, this,
+ [this, i]() { CallConfigureDialog<ConfigureInputPlayer>(i, false); });
}
- connect(ui->buttonClearAll, &QPushButton::released, [this] { ClearAll(); });
- connect(ui->buttonRestoreDefaults, &QPushButton::released, [this]() { restoreDefaults(); });
-
- timeout_timer->setSingleShot(true);
- connect(timeout_timer.get(), &QTimer::timeout, [this]() { setPollingResult({}, true); });
+ connect(ui->handheld_configure, &QPushButton::pressed, this,
+ [this]() { CallConfigureDialog<ConfigureInputPlayer>(8, false); });
- connect(poll_timer.get(), &QTimer::timeout, [this]() {
- Common::ParamPackage params;
- for (auto& poller : device_pollers) {
- params = poller->GetNextInput();
- if (params.Has("engine")) {
- setPollingResult(params, false);
- return;
- }
- }
- });
+ connect(ui->debug_configure, &QPushButton::pressed, this,
+ [this]() { CallConfigureDialog<ConfigureInputPlayer>(9, true); });
- this->loadConfiguration();
+ connect(ui->mouse_advanced, &QPushButton::pressed, this,
+ [this]() { CallConfigureDialog<ConfigureMouseAdvanced>(); });
- // TODO(wwylele): enable this when we actually emulate it
- ui->buttonHome->setEnabled(false);
+ connect(ui->touchscreen_advanced, &QPushButton::pressed, this,
+ [this]() { CallConfigureDialog<ConfigureTouchscreenAdvanced>(); });
}
-void ConfigureInput::applyConfiguration() {
- std::transform(buttons_param.begin(), buttons_param.end(), Settings::values.buttons.begin(),
- [](const Common::ParamPackage& param) { return param.Serialize(); });
- std::transform(analogs_param.begin(), analogs_param.end(), Settings::values.analogs.begin(),
- [](const Common::ParamPackage& param) { return param.Serialize(); });
-}
+template <typename Dialog, typename... Args>
+void ConfigureInput::CallConfigureDialog(Args&&... args) {
+ this->applyConfiguration();
+ Dialog dialog(this, std::forward<Args>(args)...);
-void ConfigureInput::loadConfiguration() {
- std::transform(Settings::values.buttons.begin(), Settings::values.buttons.end(),
- buttons_param.begin(),
- [](const std::string& str) { return Common::ParamPackage(str); });
- std::transform(Settings::values.analogs.begin(), Settings::values.analogs.end(),
- analogs_param.begin(),
- [](const std::string& str) { return Common::ParamPackage(str); });
- updateButtonLabels();
+ const auto res = dialog.exec();
+ if (res == QDialog::Accepted) {
+ dialog.applyConfiguration();
+ }
}
-void ConfigureInput::restoreDefaults() {
- for (int button_id = 0; button_id < Settings::NativeButton::NumButtons; button_id++) {
- buttons_param[button_id] = Common::ParamPackage{
- InputCommon::GenerateKeyboardParam(Config::default_buttons[button_id])};
+void ConfigureInput::OnDockedModeChanged(bool last_state, bool new_state) {
+ if (last_state == new_state) {
+ return;
}
- for (int analog_id = 0; analog_id < Settings::NativeAnalog::NumAnalogs; analog_id++) {
- for (int sub_button_id = 0; sub_button_id < ANALOG_SUB_BUTTONS_NUM; sub_button_id++) {
- Common::ParamPackage params{InputCommon::GenerateKeyboardParam(
- Config::default_analogs[analog_id][sub_button_id])};
- SetAnalogButton(params, analogs_param[analog_id], analog_sub_buttons[sub_button_id]);
- }
+ Core::System& system{Core::System::GetInstance()};
+ if (!system.IsPoweredOn()) {
+ return;
}
- updateButtonLabels();
-}
+ Service::SM::ServiceManager& sm = system.ServiceManager();
-void ConfigureInput::ClearAll() {
- for (int button_id = 0; button_id < Settings::NativeButton::NumButtons; button_id++) {
- if (button_map[button_id] && button_map[button_id]->isEnabled())
- buttons_param[button_id].Clear();
- }
- for (int analog_id = 0; analog_id < Settings::NativeAnalog::NumAnalogs; analog_id++) {
- for (int sub_button_id = 0; sub_button_id < ANALOG_SUB_BUTTONS_NUM; sub_button_id++) {
- if (analog_map_buttons[analog_id][sub_button_id] &&
- analog_map_buttons[analog_id][sub_button_id]->isEnabled())
- analogs_param[analog_id].Erase(analog_sub_buttons[sub_button_id]);
- }
- }
- updateButtonLabels();
-}
+ // Message queue is shared between these services, we just need to signal an operation
+ // change to one and it will handle both automatically
+ auto applet_oe = sm.GetService<Service::AM::AppletOE>("appletOE");
+ auto applet_ae = sm.GetService<Service::AM::AppletAE>("appletAE");
+ bool has_signalled = false;
-void ConfigureInput::updateButtonLabels() {
- for (int button = 0; button < Settings::NativeButton::NumButtons; button++) {
- button_map[button]->setText(ButtonToText(buttons_param[button]));
+ if (applet_oe != nullptr) {
+ applet_oe->GetMessageQueue()->OperationModeChanged();
+ has_signalled = true;
}
- for (int analog_id = 0; analog_id < Settings::NativeAnalog::NumAnalogs; analog_id++) {
- for (int sub_button_id = 0; sub_button_id < ANALOG_SUB_BUTTONS_NUM; sub_button_id++) {
- if (analog_map_buttons[analog_id][sub_button_id]) {
- analog_map_buttons[analog_id][sub_button_id]->setText(
- AnalogToText(analogs_param[analog_id], analog_sub_buttons[sub_button_id]));
- }
- }
- analog_map_stick[analog_id]->setText(tr("Set Analog Stick"));
+ if (applet_ae != nullptr && !has_signalled) {
+ applet_ae->GetMessageQueue()->OperationModeChanged();
}
}
-void ConfigureInput::handleClick(QPushButton* button,
- std::function<void(const Common::ParamPackage&)> new_input_setter,
- InputCommon::Polling::DeviceType type) {
- button->setText(tr("[press key]"));
- button->setFocus();
-
- input_setter = new_input_setter;
-
- device_pollers = InputCommon::Polling::GetPollers(type);
+void ConfigureInput::applyConfiguration() {
+ for (std::size_t i = 0; i < players_controller.size(); ++i) {
+ const auto controller_type_index = players_controller[i]->currentIndex();
- // Keyboard keys can only be used as button devices
- want_keyboard_keys = type == InputCommon::Polling::DeviceType::Button;
+ Settings::values.players[i].connected = controller_type_index != 0;
- for (auto& poller : device_pollers) {
- poller->Start();
+ if (controller_type_index > 0) {
+ Settings::values.players[i].type =
+ static_cast<Settings::ControllerType>(controller_type_index - 1);
+ } else {
+ Settings::values.players[i].type = Settings::ControllerType::DualJoycon;
+ }
}
- grabKeyboard();
- grabMouse();
- timeout_timer->start(5000); // Cancel after 5 seconds
- poll_timer->start(200); // Check for new inputs every 200ms
+ const bool pre_docked_mode = Settings::values.use_docked_mode;
+ Settings::values.use_docked_mode = ui->use_docked_mode->isChecked();
+ OnDockedModeChanged(pre_docked_mode, Settings::values.use_docked_mode);
+ Settings::values
+ .players[Service::HID::Controller_NPad::NPadIdToIndex(Service::HID::NPAD_HANDHELD)]
+ .connected = ui->handheld_connected->isChecked();
+ Settings::values.debug_pad_enabled = ui->debug_enabled->isChecked();
+ Settings::values.mouse_enabled = ui->mouse_enabled->isChecked();
+ Settings::values.keyboard_enabled = ui->keyboard_enabled->isChecked();
+ Settings::values.touchscreen.enabled = ui->touchscreen_enabled->isChecked();
}
-void ConfigureInput::setPollingResult(const Common::ParamPackage& params, bool abort) {
- releaseKeyboard();
- releaseMouse();
- timeout_timer->stop();
- poll_timer->stop();
- for (auto& poller : device_pollers) {
- poller->Stop();
+void ConfigureInput::updateUIEnabled() {
+ bool hit_disabled = false;
+ for (auto* player : players_controller) {
+ player->setDisabled(hit_disabled);
+ if (hit_disabled)
+ player->setCurrentIndex(0);
+ if (!hit_disabled && player->currentIndex() == 0)
+ hit_disabled = true;
}
- if (!abort) {
- (*input_setter)(params);
+ for (std::size_t i = 0; i < players_controller.size(); ++i) {
+ players_configure[i]->setEnabled(players_controller[i]->currentIndex() != 0);
}
- updateButtonLabels();
- input_setter = {};
+ ui->handheld_connected->setEnabled(!ui->use_docked_mode->isChecked());
+ ui->handheld_configure->setEnabled(ui->handheld_connected->isChecked() &&
+ !ui->use_docked_mode->isChecked());
+ ui->mouse_advanced->setEnabled(ui->mouse_enabled->isChecked());
+ ui->debug_configure->setEnabled(ui->debug_enabled->isChecked());
+ ui->touchscreen_advanced->setEnabled(ui->touchscreen_enabled->isChecked());
}
-void ConfigureInput::keyPressEvent(QKeyEvent* event) {
- if (!input_setter || !event)
- return;
+void ConfigureInput::loadConfiguration() {
+ std::stable_partition(
+ Settings::values.players.begin(),
+ Settings::values.players.begin() +
+ Service::HID::Controller_NPad::NPadIdToIndex(Service::HID::NPAD_HANDHELD),
+ [](const auto& player) { return player.connected; });
+
+ for (std::size_t i = 0; i < players_controller.size(); ++i) {
+ const auto connected = Settings::values.players[i].connected;
+ players_controller[i]->setCurrentIndex(
+ connected ? static_cast<u8>(Settings::values.players[i].type) + 1 : 0);
+ }
+
+ ui->use_docked_mode->setChecked(Settings::values.use_docked_mode);
+ ui->handheld_connected->setChecked(
+ Settings::values
+ .players[Service::HID::Controller_NPad::NPadIdToIndex(Service::HID::NPAD_HANDHELD)]
+ .connected);
+ ui->debug_enabled->setChecked(Settings::values.debug_pad_enabled);
+ ui->mouse_enabled->setChecked(Settings::values.mouse_enabled);
+ ui->keyboard_enabled->setChecked(Settings::values.keyboard_enabled);
+ ui->touchscreen_enabled->setChecked(Settings::values.touchscreen.enabled);
+
+ updateUIEnabled();
+}
- if (event->key() != Qt::Key_Escape) {
- if (want_keyboard_keys) {
- setPollingResult(Common::ParamPackage{InputCommon::GenerateKeyboardParam(event->key())},
- false);
- } else {
- // Escape key wasn't pressed and we don't want any keyboard keys, so don't stop polling
- return;
- }
+void ConfigureInput::restoreDefaults() {
+ players_controller[0]->setCurrentIndex(2);
+
+ for (std::size_t i = 1; i < players_controller.size(); ++i) {
+ players_controller[i]->setCurrentIndex(0);
}
- setPollingResult({}, true);
+
+ ui->use_docked_mode->setCheckState(Qt::Unchecked);
+ ui->handheld_connected->setCheckState(Qt::Unchecked);
+ ui->mouse_enabled->setCheckState(Qt::Unchecked);
+ ui->keyboard_enabled->setCheckState(Qt::Unchecked);
+ ui->debug_enabled->setCheckState(Qt::Unchecked);
+ ui->touchscreen_enabled->setCheckState(Qt::Checked);
+ updateUIEnabled();
}
diff --git a/src/yuzu/configuration/configure_input.h b/src/yuzu/configuration/configure_input.h
index 32c7183f9..29a8a03f8 100644
--- a/src/yuzu/configuration/configure_input.h
+++ b/src/yuzu/configuration/configure_input.h
@@ -18,6 +18,7 @@
#include "core/settings.h"
#include "input_common/main.h"
#include "ui_configure_input.h"
+#include "yuzu/configuration/config.h"
class QPushButton;
class QString;
@@ -37,57 +38,20 @@ public:
void applyConfiguration();
private:
- std::unique_ptr<Ui::ConfigureInput> ui;
-
- std::unique_ptr<QTimer> timeout_timer;
- std::unique_ptr<QTimer> poll_timer;
-
- /// This will be the the setting function when an input is awaiting configuration.
- std::optional<std::function<void(const Common::ParamPackage&)>> input_setter;
-
- std::array<Common::ParamPackage, Settings::NativeButton::NumButtons> buttons_param;
- std::array<Common::ParamPackage, Settings::NativeAnalog::NumAnalogs> analogs_param;
-
- static constexpr int ANALOG_SUB_BUTTONS_NUM = 5;
-
- /// Each button input is represented by a QPushButton.
- std::array<QPushButton*, Settings::NativeButton::NumButtons> button_map;
+ void updateUIEnabled();
- /// A group of five QPushButtons represent one analog input. The buttons each represent up,
- /// down, left, right, and modifier, respectively.
- std::array<std::array<QPushButton*, ANALOG_SUB_BUTTONS_NUM>, Settings::NativeAnalog::NumAnalogs>
- analog_map_buttons;
+ template <typename Dialog, typename... Args>
+ void CallConfigureDialog(Args&&... args);
- /// Analog inputs are also represented each with a single button, used to configure with an
- /// actual analog stick
- std::array<QPushButton*, Settings::NativeAnalog::NumAnalogs> analog_map_stick;
-
- static const std::array<std::string, ANALOG_SUB_BUTTONS_NUM> analog_sub_buttons;
-
- std::vector<std::unique_ptr<InputCommon::Polling::DevicePoller>> device_pollers;
-
- /// A flag to indicate if keyboard keys are okay when configuring an input. If this is false,
- /// keyboard events are ignored.
- bool want_keyboard_keys = false;
+ void OnDockedModeChanged(bool last_state, bool new_state);
/// Load configuration settings.
void loadConfiguration();
/// Restore all buttons to their default values.
void restoreDefaults();
- /// Clear all input configuration
- void ClearAll();
- /// Update UI to reflect current configuration.
- void updateButtonLabels();
-
- /// Called when the button was pressed.
- void handleClick(QPushButton* button,
- std::function<void(const Common::ParamPackage&)> new_input_setter,
- InputCommon::Polling::DeviceType type);
-
- /// Finish polling and configure input using the input_setter
- void setPollingResult(const Common::ParamPackage& params, bool abort);
+ std::unique_ptr<Ui::ConfigureInput> ui;
- /// Handle key press events.
- void keyPressEvent(QKeyEvent* event) override;
+ std::array<QComboBox*, 8> players_controller;
+ std::array<QPushButton*, 8> players_configure;
};
diff --git a/src/yuzu/configuration/configure_input.ui b/src/yuzu/configuration/configure_input.ui
index 8a019a693..dae8277bc 100644
--- a/src/yuzu/configuration/configure_input.ui
+++ b/src/yuzu/configuration/configure_input.ui
@@ -6,8 +6,8 @@
<rect>
<x>0</x>
<y>0</y>
- <width>343</width>
- <height>677</height>
+ <width>473</width>
+ <height>685</height>
</rect>
</property>
<property name="windowTitle">
@@ -15,740 +15,470 @@
</property>
<layout class="QVBoxLayout" name="verticalLayout_5">
<item>
- <layout class="QGridLayout" name="buttons">
- <item row="3" column="1">
- <widget class="QGroupBox" name="misc">
+ <layout class="QVBoxLayout" name="verticalLayout">
+ <item>
+ <widget class="QGroupBox" name="gridGroupBox">
<property name="title">
- <string>Misc.</string>
- </property>
- <property name="flat">
- <bool>false</bool>
- </property>
- <property name="checkable">
- <bool>false</bool>
+ <string>Players</string>
</property>
- <layout class="QGridLayout" name="gridLayout_6">
- <item row="0" column="0">
- <layout class="QVBoxLayout" name="buttonMiscMinusVerticalLayout">
- <item>
- <widget class="QLabel" name="labelMinus">
- <property name="text">
- <string>Minus:</string>
- </property>
- </widget>
- </item>
- <item>
- <widget class="QPushButton" name="buttonMinus">
- <property name="text">
- <string/>
- </property>
- </widget>
- </item>
- </layout>
+ <layout class="QGridLayout" name="gridLayout">
+ <item row="1" column="2">
+ <widget class="QComboBox" name="player1_combobox">
+ <property name="minimumSize">
+ <size>
+ <width>110</width>
+ <height>0</height>
+ </size>
+ </property>
+ </widget>
</item>
- <item row="0" column="1">
- <layout class="QVBoxLayout" name="buttonMiscPlusVerticalLayout">
- <item>
- <widget class="QLabel" name="labelPlus">
- <property name="text">
- <string>Plus:</string>
- </property>
- </widget>
- </item>
- <item>
- <widget class="QPushButton" name="buttonPlus">
- <property name="text">
- <string/>
- </property>
- </widget>
- </item>
- </layout>
+ <item row="1" column="3">
+ <widget class="QPushButton" name="player1_configure">
+ <property name="text">
+ <string>Configure</string>
+ </property>
+ </widget>
</item>
- <item row="1" column="0">
- <layout class="QVBoxLayout" name="buttonMiscHomeVerticalLayout">
- <item>
- <widget class="QLabel" name="labelHome">
- <property name="text">
- <string>Home:</string>
- </property>
- </widget>
- </item>
- <item>
- <widget class="QPushButton" name="buttonHome">
- <property name="text">
- <string/>
- </property>
- </widget>
- </item>
- </layout>
+ <item row="0" column="2">
+ <widget class="QLabel" name="label">
+ <property name="text">
+ <string>Controller Type</string>
+ </property>
+ <property name="alignment">
+ <set>Qt::AlignCenter</set>
+ </property>
+ </widget>
</item>
- <item row="1" column="1">
- <layout class="QVBoxLayout" name="buttonMiscScrCapVerticalLayout">
- <item>
- <widget class="QLabel" name="labelScrCap">
- <property name="text">
- <string>Screen
-Capture:</string>
- </property>
- </widget>
- </item>
- <item>
- <widget class="QPushButton" name="buttonScreenshot">
- <property name="text">
- <string/>
- </property>
- </widget>
- </item>
- </layout>
+ <item row="2" column="2">
+ <widget class="QComboBox" name="player2_combobox">
+ <property name="minimumSize">
+ <size>
+ <width>110</width>
+ <height>0</height>
+ </size>
+ </property>
+ </widget>
</item>
- <item row="2" column="1">
- <spacer name="verticalSpacer">
+ <item row="3" column="2">
+ <widget class="QComboBox" name="player3_combobox">
+ <property name="minimumSize">
+ <size>
+ <width>110</width>
+ <height>0</height>
+ </size>
+ </property>
+ </widget>
+ </item>
+ <item row="4" column="2">
+ <widget class="QComboBox" name="player4_combobox">
+ <property name="minimumSize">
+ <size>
+ <width>110</width>
+ <height>0</height>
+ </size>
+ </property>
+ </widget>
+ </item>
+ <item row="5" column="2">
+ <widget class="QComboBox" name="player5_combobox">
+ <property name="minimumSize">
+ <size>
+ <width>110</width>
+ <height>0</height>
+ </size>
+ </property>
+ </widget>
+ </item>
+ <item row="6" column="2">
+ <widget class="QComboBox" name="player6_combobox">
+ <property name="minimumSize">
+ <size>
+ <width>110</width>
+ <height>0</height>
+ </size>
+ </property>
+ </widget>
+ </item>
+ <item row="7" column="2">
+ <widget class="QComboBox" name="player7_combobox">
+ <property name="minimumSize">
+ <size>
+ <width>110</width>
+ <height>0</height>
+ </size>
+ </property>
+ </widget>
+ </item>
+ <item row="8" column="2">
+ <widget class="QComboBox" name="player8_combobox">
+ <property name="minimumSize">
+ <size>
+ <width>110</width>
+ <height>0</height>
+ </size>
+ </property>
+ </widget>
+ </item>
+ <item row="2" column="3">
+ <widget class="QPushButton" name="player2_configure">
+ <property name="text">
+ <string>Configure</string>
+ </property>
+ </widget>
+ </item>
+ <item row="3" column="3">
+ <widget class="QPushButton" name="player3_configure">
+ <property name="text">
+ <string>Configure</string>
+ </property>
+ </widget>
+ </item>
+ <item row="4" column="3">
+ <widget class="QPushButton" name="player4_configure">
+ <property name="text">
+ <string>Configure</string>
+ </property>
+ </widget>
+ </item>
+ <item row="5" column="3">
+ <widget class="QPushButton" name="player5_configure">
+ <property name="text">
+ <string>Configure</string>
+ </property>
+ </widget>
+ </item>
+ <item row="6" column="3">
+ <widget class="QPushButton" name="player6_configure">
+ <property name="text">
+ <string>Configure</string>
+ </property>
+ </widget>
+ </item>
+ <item row="7" column="3">
+ <widget class="QPushButton" name="player7_configure">
+ <property name="text">
+ <string>Configure</string>
+ </property>
+ </widget>
+ </item>
+ <item row="8" column="3">
+ <widget class="QPushButton" name="player8_configure">
+ <property name="text">
+ <string>Configure</string>
+ </property>
+ </widget>
+ </item>
+ <item row="0" column="0">
+ <spacer name="horizontalSpacer">
<property name="orientation">
- <enum>Qt::Vertical</enum>
+ <enum>Qt::Horizontal</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
- <width>20</width>
- <height>40</height>
+ <width>40</width>
+ <height>20</height>
</size>
</property>
</spacer>
</item>
- </layout>
- </widget>
- </item>
- <item row="0" column="0">
- <widget class="QGroupBox" name="faceButtons">
- <property name="title">
- <string>Face Buttons</string>
- </property>
- <property name="flat">
- <bool>false</bool>
- </property>
- <property name="checkable">
- <bool>false</bool>
- </property>
- <layout class="QGridLayout" name="gridLayout">
- <item row="0" column="0">
- <layout class="QVBoxLayout" name="buttonFaceButtonsAVerticalLayout">
- <item>
- <widget class="QLabel" name="labelA">
- <property name="text">
- <string>A:</string>
- </property>
- </widget>
- </item>
- <item>
- <widget class="QPushButton" name="buttonA">
- <property name="text">
- <string/>
- </property>
- </widget>
- </item>
- </layout>
+ <item row="0" column="4">
+ <spacer name="horizontalSpacer_2">
+ <property name="orientation">
+ <enum>Qt::Horizontal</enum>
+ </property>
+ <property name="sizeHint" stdset="0">
+ <size>
+ <width>40</width>
+ <height>20</height>
+ </size>
+ </property>
+ </spacer>
</item>
- <item row="0" column="1">
- <layout class="QVBoxLayout" name="buttonFaceButtonsBVerticalLayout">
- <item>
- <widget class="QLabel" name="labelB">
- <property name="text">
- <string>B:</string>
- </property>
- </widget>
- </item>
- <item>
- <widget class="QPushButton" name="buttonB">
- <property name="text">
- <string/>
- </property>
- </widget>
- </item>
- </layout>
+ <item row="1" column="1">
+ <widget class="QLabel" name="label_3">
+ <property name="minimumSize">
+ <size>
+ <width>55</width>
+ <height>0</height>
+ </size>
+ </property>
+ <property name="text">
+ <string>Player 1</string>
+ </property>
+ </widget>
</item>
- <item row="1" column="0">
- <layout class="QVBoxLayout" name="buttonFaceButtonsXVerticalLayout">
- <item>
- <widget class="QLabel" name="labelX">
- <property name="text">
- <string>X:</string>
- </property>
- </widget>
- </item>
- <item>
- <widget class="QPushButton" name="buttonX">
- <property name="text">
- <string/>
- </property>
- </widget>
- </item>
- </layout>
+ <item row="2" column="1">
+ <widget class="QLabel" name="label_4">
+ <property name="text">
+ <string>Player 2</string>
+ </property>
+ </widget>
</item>
- <item row="1" column="1">
- <layout class="QVBoxLayout" name="buttonFaceButtonsYVerticalLayout">
- <item>
- <widget class="QLabel" name="labelY">
- <property name="text">
- <string>Y:</string>
- </property>
- </widget>
- </item>
- <item>
- <widget class="QPushButton" name="buttonY">
- <property name="text">
- <string/>
- </property>
- </widget>
- </item>
- </layout>
+ <item row="3" column="1">
+ <widget class="QLabel" name="label_5">
+ <property name="text">
+ <string>Player 3</string>
+ </property>
+ </widget>
</item>
- </layout>
- </widget>
- </item>
- <item row="0" column="1">
- <widget class="QGroupBox" name="Dpad">
- <property name="title">
- <string>Directional Pad</string>
- </property>
- <property name="flat">
- <bool>false</bool>
- </property>
- <property name="checkable">
- <bool>false</bool>
- </property>
- <layout class="QGridLayout" name="gridLayout_2">
- <item row="1" column="0">
- <layout class="QVBoxLayout" name="buttonDpadUpVerticalLayout">
- <item>
- <widget class="QLabel" name="labelDpadUp">
- <property name="text">
- <string>Up:</string>
- </property>
- </widget>
- </item>
- <item>
- <widget class="QPushButton" name="buttonDpadUp">
- <property name="text">
- <string/>
- </property>
- </widget>
- </item>
- </layout>
+ <item row="4" column="1">
+ <widget class="QLabel" name="label_6">
+ <property name="text">
+ <string>Player 4</string>
+ </property>
+ </widget>
</item>
- <item row="1" column="1">
- <layout class="QVBoxLayout" name="buttonDpadDownVerticalLayout">
- <item>
- <widget class="QLabel" name="labelDpadDown">
- <property name="text">
- <string>Down:</string>
- </property>
- </widget>
- </item>
- <item>
- <widget class="QPushButton" name="buttonDpadDown">
- <property name="text">
- <string/>
- </property>
- </widget>
- </item>
- </layout>
+ <item row="5" column="1">
+ <widget class="QLabel" name="label_7">
+ <property name="text">
+ <string>Player 5</string>
+ </property>
+ </widget>
</item>
- <item row="0" column="0">
- <layout class="QVBoxLayout" name="buttonDpadLeftVerticalLayout">
- <item>
- <widget class="QLabel" name="labelDpadLeft">
- <property name="text">
- <string>Left:</string>
- </property>
- </widget>
- </item>
- <item>
- <widget class="QPushButton" name="buttonDpadLeft">
- <property name="text">
- <string/>
- </property>
- </widget>
- </item>
- </layout>
+ <item row="6" column="1">
+ <widget class="QLabel" name="label_8">
+ <property name="text">
+ <string>Player 6</string>
+ </property>
+ </widget>
</item>
- <item row="0" column="1">
- <layout class="QVBoxLayout" name="buttonDpadRightVerticalLayout">
- <item>
- <widget class="QLabel" name="labelDpadRight">
- <property name="text">
- <string>Right:</string>
- </property>
- </widget>
- </item>
- <item>
- <widget class="QPushButton" name="buttonDpadRight">
- <property name="text">
- <string/>
- </property>
- </widget>
- </item>
- </layout>
+ <item row="7" column="1">
+ <widget class="QLabel" name="label_9">
+ <property name="text">
+ <string>Player 7</string>
+ </property>
+ </widget>
+ </item>
+ <item row="8" column="1">
+ <widget class="QLabel" name="label_10">
+ <property name="text">
+ <string>Player 8</string>
+ </property>
+ </widget>
</item>
</layout>
</widget>
</item>
- <item row="3" column="0">
- <widget class="QGroupBox" name="shoulderButtons">
+ <item>
+ <widget class="QGroupBox" name="gridGroupBox">
<property name="title">
- <string>Shoulder Buttons</string>
- </property>
- <property name="flat">
- <bool>false</bool>
+ <string>Handheld</string>
</property>
- <property name="checkable">
- <bool>false</bool>
- </property>
- <layout class="QGridLayout" name="gridLayout_3">
- <item row="0" column="0">
- <layout class="QVBoxLayout" name="buttonShoulderButtonsLVerticalLayout">
- <item>
- <widget class="QLabel" name="labelL">
- <property name="text">
- <string>L:</string>
- </property>
- </widget>
- </item>
- <item>
- <widget class="QPushButton" name="buttonL">
- <property name="text">
- <string/>
- </property>
- </widget>
- </item>
- </layout>
+ <layout class="QGridLayout" name="gridLayout_2">
+ <item row="1" column="2">
+ <spacer name="horizontalSpacer_5">
+ <property name="orientation">
+ <enum>Qt::Horizontal</enum>
+ </property>
+ <property name="sizeType">
+ <enum>QSizePolicy::Fixed</enum>
+ </property>
+ <property name="sizeHint" stdset="0">
+ <size>
+ <width>72</width>
+ <height>20</height>
+ </size>
+ </property>
+ </spacer>
</item>
- <item row="0" column="1">
- <layout class="QVBoxLayout" name="buttonShoulderButtonsRVerticalLayout">
- <item>
- <widget class="QLabel" name="labelR">
- <property name="text">
- <string>R:</string>
- </property>
- </widget>
- </item>
- <item>
- <widget class="QPushButton" name="buttonR">
- <property name="text">
- <string/>
- </property>
- </widget>
- </item>
- </layout>
+ <item row="1" column="4">
+ <spacer name="horizontalSpacer_4">
+ <property name="orientation">
+ <enum>Qt::Horizontal</enum>
+ </property>
+ <property name="sizeHint" stdset="0">
+ <size>
+ <width>40</width>
+ <height>20</height>
+ </size>
+ </property>
+ </spacer>
+ </item>
+ <item row="1" column="3">
+ <widget class="QPushButton" name="handheld_configure">
+ <property name="text">
+ <string>Configure</string>
+ </property>
+ </widget>
</item>
<item row="1" column="0">
- <layout class="QVBoxLayout" name="buttonShoulderButtonsZLVerticalLayout">
- <item>
- <widget class="QLabel" name="labelZL">
- <property name="text">
- <string>ZL:</string>
- </property>
- </widget>
- </item>
- <item>
- <widget class="QPushButton" name="buttonZL">
- <property name="text">
- <string/>
- </property>
- </widget>
- </item>
- </layout>
+ <spacer name="horizontalSpacer_3">
+ <property name="orientation">
+ <enum>Qt::Horizontal</enum>
+ </property>
+ <property name="sizeHint" stdset="0">
+ <size>
+ <width>40</width>
+ <height>20</height>
+ </size>
+ </property>
+ </spacer>
</item>
<item row="1" column="1">
- <layout class="QVBoxLayout" name="buttonShoulderButtonsZRVerticalLayout">
- <item>
- <widget class="QLabel" name="labelZR">
- <property name="text">
- <string>ZR:</string>
- </property>
- </widget>
- </item>
- <item>
- <widget class="QPushButton" name="buttonZR">
- <property name="text">
- <string/>
- </property>
- </widget>
- </item>
- </layout>
- </item>
- <item row="2" column="0">
- <layout class="QVBoxLayout" name="buttonShoulderButtonsSLVerticalLayout">
- <item>
- <widget class="QLabel" name="labelSL">
- <property name="text">
- <string>SL:</string>
- </property>
- </widget>
- </item>
- <item>
- <widget class="QPushButton" name="buttonSL">
- <property name="text">
- <string/>
- </property>
- </widget>
- </item>
- </layout>
+ <widget class="QCheckBox" name="handheld_connected">
+ <property name="text">
+ <string>Joycons Docked</string>
+ </property>
+ </widget>
</item>
- <item row="2" column="1">
- <layout class="QVBoxLayout" name="buttonShoulderButtonsSRVerticalLayout">
- <item>
- <widget class="QLabel" name="labelSR">
- <property name="text">
- <string>SR:</string>
- </property>
- </widget>
- </item>
- <item>
- <widget class="QPushButton" name="buttonSR">
- <property name="text">
- <string/>
- </property>
- </widget>
- </item>
- </layout>
+ <item row="0" column="1">
+ <widget class="QCheckBox" name="use_docked_mode">
+ <property name="text">
+ <string>Use Docked Mode</string>
+ </property>
+ </widget>
</item>
</layout>
</widget>
</item>
- <item row="1" column="1">
- <widget class="QGroupBox" name="RStick">
+ <item>
+ <widget class="QGroupBox" name="gridGroupBox">
<property name="title">
- <string>Right Stick</string>
- </property>
- <property name="alignment">
- <set>Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter</set>
- </property>
- <property name="flat">
- <bool>false</bool>
+ <string>Other</string>
</property>
- <property name="checkable">
- <bool>false</bool>
- </property>
- <layout class="QGridLayout" name="gridLayout_5">
+ <layout class="QGridLayout" name="gridLayout_3">
<item row="1" column="1">
- <layout class="QVBoxLayout" name="buttonRStickDownVerticalLayout">
- <item>
- <widget class="QLabel" name="labelRStickDown">
- <property name="text">
- <string>Down:</string>
- </property>
- </widget>
- </item>
- <item>
- <widget class="QPushButton" name="buttonRStickDown">
- <property name="text">
- <string/>
- </property>
- </widget>
- </item>
- </layout>
- </item>
- <item row="0" column="1">
- <layout class="QVBoxLayout" name="buttonRStickRightVerticalLayout">
- <item>
- <widget class="QLabel" name="labelRStickRight">
- <property name="text">
- <string>Right:</string>
- </property>
- </widget>
- </item>
- <item>
- <widget class="QPushButton" name="buttonRStickRight">
- <property name="text">
- <string/>
- </property>
- </widget>
- </item>
- </layout>
- </item>
- <item row="3" column="0" colspan="2">
- <widget class="QPushButton" name="buttonRStickAnalog">
+ <widget class="QCheckBox" name="keyboard_enabled">
+ <property name="minimumSize">
+ <size>
+ <width>0</width>
+ <height>23</height>
+ </size>
+ </property>
<property name="text">
- <string>Set Analog Stick</string>
+ <string>Keyboard</string>
</property>
</widget>
</item>
- <item row="0" column="0">
- <layout class="QVBoxLayout" name="buttonRStickLeftVerticalLayout">
- <item>
- <widget class="QLabel" name="labelRStickLeft">
- <property name="text">
- <string>Left:</string>
- </property>
- </widget>
- </item>
- <item>
- <widget class="QPushButton" name="buttonRStickLeft">
- <property name="text">
- <string/>
- </property>
- </widget>
- </item>
- </layout>
- </item>
- <item row="1" column="0">
- <layout class="QVBoxLayout" name="buttonRStickUpVerticalLayout">
- <item>
- <widget class="QLabel" name="labelRStickUp">
- <property name="text">
- <string>Up:</string>
- </property>
- </widget>
- </item>
- <item>
- <widget class="QPushButton" name="buttonRStickUp">
- <property name="text">
- <string/>
- </property>
- </widget>
- </item>
- </layout>
- </item>
- <item row="2" column="0">
- <layout class="QVBoxLayout" name="buttonRStickPressedVerticalLayout">
- <item>
- <widget class="QLabel" name="labelRStickPressed">
- <property name="text">
- <string>Pressed:</string>
- </property>
- </widget>
- </item>
- <item>
- <widget class="QPushButton" name="buttonRStick">
- <property name="text">
- <string/>
- </property>
- </widget>
- </item>
- </layout>
- </item>
<item row="2" column="1">
- <layout class="QVBoxLayout" name="buttonRStickModVerticalLayout">
- <item>
- <widget class="QLabel" name="labelRStickMod">
- <property name="text">
- <string>Modifier:</string>
- </property>
- </widget>
- </item>
- <item>
- <widget class="QPushButton" name="buttonRStickMod">
- <property name="text">
- <string/>
- </property>
- </widget>
- </item>
- </layout>
+ <widget class="QCheckBox" name="debug_enabled">
+ <property name="text">
+ <string>Debug Controller</string>
+ </property>
+ </widget>
</item>
- </layout>
- </widget>
- </item>
- <item row="1" column="0">
- <widget class="QGroupBox" name="LStick">
- <property name="title">
- <string>Left Stick</string>
- </property>
- <property name="flat">
- <bool>false</bool>
- </property>
- <property name="checkable">
- <bool>false</bool>
- </property>
- <layout class="QGridLayout" name="gridLayout_4">
- <item row="1" column="1">
- <layout class="QVBoxLayout" name="buttonLStickDownVerticalLayout">
- <item>
- <widget class="QLabel" name="labelLStickDown">
- <property name="text">
- <string>Down:</string>
- </property>
- </widget>
- </item>
- <item>
- <widget class="QPushButton" name="buttonLStickDown">
- <property name="text">
- <string/>
- </property>
- </widget>
- </item>
- </layout>
- </item>
- <item row="4" column="0" colspan="2">
- <widget class="QPushButton" name="buttonLStickAnalog">
+ <item row="3" column="1">
+ <widget class="QCheckBox" name="touchscreen_enabled">
<property name="text">
- <string>Set Analog Stick</string>
+ <string>Touchscreen</string>
</property>
</widget>
</item>
<item row="0" column="1">
- <layout class="QVBoxLayout" name="buttonLStickRightVerticalLayout">
- <item>
- <widget class="QLabel" name="labelLStickRight">
- <property name="text">
- <string>Right:</string>
- </property>
- </widget>
- </item>
- <item>
- <widget class="QPushButton" name="buttonLStickRight">
- <property name="text">
- <string/>
- </property>
- </widget>
- </item>
- </layout>
+ <widget class="QCheckBox" name="mouse_enabled">
+ <property name="minimumSize">
+ <size>
+ <width>0</width>
+ <height>23</height>
+ </size>
+ </property>
+ <property name="text">
+ <string>Mouse</string>
+ </property>
+ </widget>
+ </item>
+ <item row="0" column="4">
+ <spacer name="horizontalSpacer_7">
+ <property name="orientation">
+ <enum>Qt::Horizontal</enum>
+ </property>
+ <property name="sizeHint" stdset="0">
+ <size>
+ <width>40</width>
+ <height>20</height>
+ </size>
+ </property>
+ </spacer>
+ </item>
+ <item row="0" column="2">
+ <spacer name="horizontalSpacer_8">
+ <property name="orientation">
+ <enum>Qt::Horizontal</enum>
+ </property>
+ <property name="sizeType">
+ <enum>QSizePolicy::Fixed</enum>
+ </property>
+ <property name="sizeHint" stdset="0">
+ <size>
+ <width>76</width>
+ <height>20</height>
+ </size>
+ </property>
+ </spacer>
</item>
<item row="0" column="0">
- <layout class="QVBoxLayout" name="buttonLStickLeftVerticalLayout">
- <item>
- <widget class="QLabel" name="labelLStickLeft">
- <property name="text">
- <string>Left:</string>
- </property>
- </widget>
- </item>
- <item>
- <widget class="QPushButton" name="buttonLStickLeft">
- <property name="text">
- <string/>
- </property>
- </widget>
- </item>
- </layout>
+ <spacer name="horizontalSpacer_6">
+ <property name="orientation">
+ <enum>Qt::Horizontal</enum>
+ </property>
+ <property name="sizeHint" stdset="0">
+ <size>
+ <width>40</width>
+ <height>20</height>
+ </size>
+ </property>
+ </spacer>
</item>
- <item row="1" column="0">
- <layout class="QVBoxLayout" name="buttonLStickUpVerticalLayout">
- <item>
- <widget class="QLabel" name="labelLStickUp">
- <property name="text">
- <string>Up:</string>
- </property>
- </widget>
- </item>
- <item>
- <widget class="QPushButton" name="buttonLStickUp">
- <property name="text">
- <string/>
- </property>
- </widget>
- </item>
- </layout>
- </item>
- <item row="3" column="0">
- <layout class="QVBoxLayout" name="buttonLStickModVerticalLayout">
- <item>
- <widget class="QLabel" name="labelLStickMod">
- <property name="text">
- <string>Modifier:</string>
- </property>
- </widget>
- </item>
- <item>
- <widget class="QPushButton" name="buttonLStickMod">
- <property name="text">
- <string/>
- </property>
- </widget>
- </item>
- </layout>
+ <item row="3" column="3">
+ <widget class="QPushButton" name="touchscreen_advanced">
+ <property name="text">
+ <string>Advanced</string>
+ </property>
+ </widget>
</item>
- <item row="3" column="1">
- <layout class="QVBoxLayout" name="buttonLStickPressedVerticalLayout" stretch="0,0">
- <item>
- <widget class="QLabel" name="labelLStickPressed">
- <property name="text">
- <string>Pressed:</string>
- </property>
- </widget>
- </item>
- <item>
- <widget class="QPushButton" name="buttonLStick">
- <property name="text">
- <string/>
- </property>
- </widget>
- </item>
- </layout>
+ <item row="2" column="3">
+ <widget class="QPushButton" name="debug_configure">
+ <property name="text">
+ <string>Configure</string>
+ </property>
+ </widget>
+ </item>
+ <item row="0" column="3">
+ <widget class="QPushButton" name="mouse_advanced">
+ <property name="text">
+ <string>Advanced</string>
+ </property>
+ </widget>
</item>
</layout>
</widget>
</item>
- </layout>
- </item>
- <item>
- <layout class="QHBoxLayout" name="horizontalLayout">
<item>
- <spacer name="horizontalSpacer">
+ <spacer name="verticalSpacer">
<property name="orientation">
- <enum>Qt::Horizontal</enum>
+ <enum>Qt::Vertical</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
- <width>40</width>
- <height>20</height>
+ <width>20</width>
+ <height>40</height>
</size>
</property>
</spacer>
</item>
<item>
- <widget class="QPushButton" name="buttonClearAll">
- <property name="sizePolicy">
- <sizepolicy hsizetype="Minimum" vsizetype="Fixed">
- <horstretch>0</horstretch>
- <verstretch>0</verstretch>
- </sizepolicy>
- </property>
- <property name="sizeIncrement">
- <size>
- <width>0</width>
- <height>0</height>
- </size>
- </property>
- <property name="baseSize">
- <size>
- <width>0</width>
- <height>0</height>
- </size>
- </property>
- <property name="layoutDirection">
- <enum>Qt::LeftToRight</enum>
- </property>
- <property name="text">
- <string>Clear All</string>
- </property>
- </widget>
- </item>
- <item>
- <widget class="QPushButton" name="buttonRestoreDefaults">
- <property name="sizePolicy">
- <sizepolicy hsizetype="Minimum" vsizetype="Fixed">
- <horstretch>0</horstretch>
- <verstretch>0</verstretch>
- </sizepolicy>
- </property>
- <property name="sizeIncrement">
- <size>
- <width>0</width>
- <height>0</height>
- </size>
- </property>
- <property name="baseSize">
- <size>
- <width>0</width>
- <height>0</height>
- </size>
- </property>
- <property name="layoutDirection">
- <enum>Qt::LeftToRight</enum>
- </property>
- <property name="text">
- <string>Restore Defaults</string>
- </property>
- </widget>
+ <layout class="QHBoxLayout" name="horizontalLayout">
+ <item>
+ <widget class="QPushButton" name="restore_defaults_button">
+ <property name="text">
+ <string>Restore Defaults</string>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <spacer name="horizontalSpacer_9">
+ <property name="orientation">
+ <enum>Qt::Horizontal</enum>
+ </property>
+ <property name="sizeHint" stdset="0">
+ <size>
+ <width>40</width>
+ <height>20</height>
+ </size>
+ </property>
+ </spacer>
+ </item>
+ </layout>
</item>
</layout>
</item>
diff --git a/src/yuzu/configuration/configure_input_player.cpp b/src/yuzu/configuration/configure_input_player.cpp
new file mode 100644
index 000000000..ba6e09368
--- /dev/null
+++ b/src/yuzu/configuration/configure_input_player.cpp
@@ -0,0 +1,508 @@
+// Copyright 2016 Citra Emulator Project
+// Licensed under GPLv2 or any later version
+// Refer to the license.txt file included.
+
+#include <algorithm>
+#include <memory>
+#include <utility>
+#include <QColorDialog>
+#include <QMenu>
+#include <QMessageBox>
+#include <QTimer>
+#include "common/assert.h"
+#include "common/param_package.h"
+#include "input_common/main.h"
+#include "ui_configure_input_player.h"
+#include "yuzu/configuration/config.h"
+#include "yuzu/configuration/configure_input_player.h"
+
+const std::array<std::string, ConfigureInputPlayer::ANALOG_SUB_BUTTONS_NUM>
+ ConfigureInputPlayer::analog_sub_buttons{{
+ "up",
+ "down",
+ "left",
+ "right",
+ "modifier",
+ }};
+
+static void MoveGridElement(QGridLayout* grid, int row_old, int column_old, int row_new,
+ int column_new) {
+ const auto item = grid->itemAtPosition(row_old, column_old);
+ // grid->removeItem(item);
+ grid->addItem(item, row_new, column_new);
+}
+
+static void LayerGridElements(QGridLayout* grid, QWidget* item, QWidget* onTopOf) {
+ const int index1 = grid->indexOf(item);
+ const int index2 = grid->indexOf(onTopOf);
+ int row, column, rowSpan, columnSpan;
+ grid->getItemPosition(index2, &row, &column, &rowSpan, &columnSpan);
+ grid->takeAt(index1);
+ grid->addWidget(item, row, column, rowSpan, columnSpan);
+}
+
+static QString GetKeyName(int key_code) {
+ switch (key_code) {
+ case Qt::Key_Shift:
+ return QObject::tr("Shift");
+ case Qt::Key_Control:
+ return QObject::tr("Ctrl");
+ case Qt::Key_Alt:
+ return QObject::tr("Alt");
+ case Qt::Key_Meta:
+ return "";
+ default:
+ return QKeySequence(key_code).toString();
+ }
+}
+
+static void SetAnalogButton(const Common::ParamPackage& input_param,
+ Common::ParamPackage& analog_param, const std::string& button_name) {
+ if (analog_param.Get("engine", "") != "analog_from_button") {
+ analog_param = {
+ {"engine", "analog_from_button"},
+ {"modifier_scale", "0.5"},
+ };
+ }
+ analog_param.Set(button_name, input_param.Serialize());
+}
+
+static QString ButtonToText(const Common::ParamPackage& param) {
+ if (!param.Has("engine")) {
+ return QObject::tr("[not set]");
+ } else if (param.Get("engine", "") == "keyboard") {
+ return GetKeyName(param.Get("code", 0));
+ } else if (param.Get("engine", "") == "sdl") {
+ if (param.Has("hat")) {
+ return QString(QObject::tr("Hat %1 %2"))
+ .arg(param.Get("hat", "").c_str(), param.Get("direction", "").c_str());
+ }
+ if (param.Has("axis")) {
+ return QString(QObject::tr("Axis %1%2"))
+ .arg(param.Get("axis", "").c_str(), param.Get("direction", "").c_str());
+ }
+ if (param.Has("button")) {
+ return QString(QObject::tr("Button %1")).arg(param.Get("button", "").c_str());
+ }
+ return QString();
+ } else {
+ return QObject::tr("[unknown]");
+ }
+};
+
+static QString AnalogToText(const Common::ParamPackage& param, const std::string& dir) {
+ if (!param.Has("engine")) {
+ return QObject::tr("[not set]");
+ } else if (param.Get("engine", "") == "analog_from_button") {
+ return ButtonToText(Common::ParamPackage{param.Get(dir, "")});
+ } else if (param.Get("engine", "") == "sdl") {
+ if (dir == "modifier") {
+ return QString(QObject::tr("[unused]"));
+ }
+
+ if (dir == "left" || dir == "right") {
+ return QString(QObject::tr("Axis %1")).arg(param.Get("axis_x", "").c_str());
+ } else if (dir == "up" || dir == "down") {
+ return QString(QObject::tr("Axis %1")).arg(param.Get("axis_y", "").c_str());
+ }
+ return QString();
+ } else {
+ return QObject::tr("[unknown]");
+ }
+};
+
+ConfigureInputPlayer::ConfigureInputPlayer(QWidget* parent, u8 player_index, bool debug)
+ : QDialog(parent), ui(std::make_unique<Ui::ConfigureInputPlayer>()),
+ timeout_timer(std::make_unique<QTimer>()), poll_timer(std::make_unique<QTimer>()),
+ player_index(player_index), debug(debug) {
+
+ ui->setupUi(this);
+ setFocusPolicy(Qt::ClickFocus);
+
+ button_map = {
+ ui->buttonA, ui->buttonB, ui->buttonX, ui->buttonY,
+ ui->buttonLStick, ui->buttonRStick, ui->buttonL, ui->buttonR,
+ ui->buttonZL, ui->buttonZR, ui->buttonPlus, ui->buttonMinus,
+ ui->buttonDpadLeft, ui->buttonDpadUp, ui->buttonDpadRight, ui->buttonDpadDown,
+ ui->buttonLStickLeft, ui->buttonLStickUp, ui->buttonLStickRight, ui->buttonLStickDown,
+ ui->buttonRStickLeft, ui->buttonRStickUp, ui->buttonRStickRight, ui->buttonRStickDown,
+ ui->buttonSL, ui->buttonSR, ui->buttonHome, ui->buttonScreenshot,
+ };
+
+ analog_map_buttons = {{
+ {
+ ui->buttonLStickUp,
+ ui->buttonLStickDown,
+ ui->buttonLStickLeft,
+ ui->buttonLStickRight,
+ ui->buttonLStickMod,
+ },
+ {
+ ui->buttonRStickUp,
+ ui->buttonRStickDown,
+ ui->buttonRStickLeft,
+ ui->buttonRStickRight,
+ ui->buttonRStickMod,
+ },
+ }};
+
+ debug_hidden = {
+ ui->buttonSL, ui->labelSL,
+ ui->buttonSR, ui->labelSR,
+ ui->buttonLStick, ui->labelLStickPressed,
+ ui->buttonRStick, ui->labelRStickPressed,
+ ui->buttonHome, ui->labelHome,
+ ui->buttonScreenshot, ui->labelScreenshot,
+ };
+
+ auto layout = Settings::values.players[player_index].type;
+ if (debug)
+ layout = Settings::ControllerType::DualJoycon;
+
+ switch (layout) {
+ case Settings::ControllerType::ProController:
+ case Settings::ControllerType::DualJoycon:
+ layout_hidden = {
+ ui->buttonSL,
+ ui->labelSL,
+ ui->buttonSR,
+ ui->labelSR,
+ };
+ break;
+ case Settings::ControllerType::LeftJoycon:
+ layout_hidden = {
+ ui->right_body_button,
+ ui->right_buttons_button,
+ ui->right_body_label,
+ ui->right_buttons_label,
+ ui->buttonR,
+ ui->labelR,
+ ui->buttonZR,
+ ui->labelZR,
+ ui->labelHome,
+ ui->buttonHome,
+ ui->buttonPlus,
+ ui->labelPlus,
+ ui->RStick,
+ ui->faceButtons,
+ };
+ break;
+ case Settings::ControllerType::RightJoycon:
+ layout_hidden = {
+ ui->left_body_button, ui->left_buttons_button,
+ ui->left_body_label, ui->left_buttons_label,
+ ui->buttonL, ui->labelL,
+ ui->buttonZL, ui->labelZL,
+ ui->labelScreenshot, ui->buttonScreenshot,
+ ui->buttonMinus, ui->labelMinus,
+ ui->LStick, ui->Dpad,
+ };
+ break;
+ }
+
+ if (debug || layout == Settings::ControllerType::ProController) {
+ ui->controller_color->hide();
+ } else {
+ if (layout == Settings::ControllerType::LeftJoycon ||
+ layout == Settings::ControllerType::RightJoycon) {
+ ui->horizontalSpacer_4->setGeometry({0, 0, 0, 0});
+
+ LayerGridElements(ui->buttons, ui->shoulderButtons, ui->Dpad);
+ LayerGridElements(ui->buttons, ui->misc, ui->RStick);
+ LayerGridElements(ui->buttons, ui->Dpad, ui->faceButtons);
+ LayerGridElements(ui->buttons, ui->RStick, ui->LStick);
+ }
+ }
+
+ for (auto* widget : layout_hidden)
+ widget->setVisible(false);
+
+ analog_map_stick = {ui->buttonLStickAnalog, ui->buttonRStickAnalog};
+
+ for (int button_id = 0; button_id < Settings::NativeButton::NumButtons; button_id++) {
+ if (!button_map[button_id])
+ continue;
+ button_map[button_id]->setContextMenuPolicy(Qt::CustomContextMenu);
+ connect(button_map[button_id], &QPushButton::released, [=]() {
+ handleClick(
+ button_map[button_id],
+ [=](const Common::ParamPackage& params) { buttons_param[button_id] = params; },
+ InputCommon::Polling::DeviceType::Button);
+ });
+ connect(button_map[button_id], &QPushButton::customContextMenuRequested,
+ [=](const QPoint& menu_location) {
+ QMenu context_menu;
+ context_menu.addAction(tr("Clear"), [&] {
+ buttons_param[button_id].Clear();
+ button_map[button_id]->setText(tr("[not set]"));
+ });
+ context_menu.addAction(tr("Restore Default"), [&] {
+ buttons_param[button_id] = Common::ParamPackage{
+ InputCommon::GenerateKeyboardParam(Config::default_buttons[button_id])};
+ button_map[button_id]->setText(ButtonToText(buttons_param[button_id]));
+ });
+ context_menu.exec(button_map[button_id]->mapToGlobal(menu_location));
+ });
+ }
+
+ for (int analog_id = 0; analog_id < Settings::NativeAnalog::NumAnalogs; analog_id++) {
+ for (int sub_button_id = 0; sub_button_id < ANALOG_SUB_BUTTONS_NUM; sub_button_id++) {
+ if (!analog_map_buttons[analog_id][sub_button_id])
+ continue;
+ analog_map_buttons[analog_id][sub_button_id]->setContextMenuPolicy(
+ Qt::CustomContextMenu);
+ connect(analog_map_buttons[analog_id][sub_button_id], &QPushButton::released, [=]() {
+ handleClick(analog_map_buttons[analog_id][sub_button_id],
+ [=](const Common::ParamPackage& params) {
+ SetAnalogButton(params, analogs_param[analog_id],
+ analog_sub_buttons[sub_button_id]);
+ },
+ InputCommon::Polling::DeviceType::Button);
+ });
+ connect(analog_map_buttons[analog_id][sub_button_id],
+ &QPushButton::customContextMenuRequested, [=](const QPoint& menu_location) {
+ QMenu context_menu;
+ context_menu.addAction(tr("Clear"), [&] {
+ analogs_param[analog_id].Erase(analog_sub_buttons[sub_button_id]);
+ analog_map_buttons[analog_id][sub_button_id]->setText(tr("[not set]"));
+ });
+ context_menu.addAction(tr("Restore Default"), [&] {
+ Common::ParamPackage params{InputCommon::GenerateKeyboardParam(
+ Config::default_analogs[analog_id][sub_button_id])};
+ SetAnalogButton(params, analogs_param[analog_id],
+ analog_sub_buttons[sub_button_id]);
+ analog_map_buttons[analog_id][sub_button_id]->setText(AnalogToText(
+ analogs_param[analog_id], analog_sub_buttons[sub_button_id]));
+ });
+ context_menu.exec(analog_map_buttons[analog_id][sub_button_id]->mapToGlobal(
+ menu_location));
+ });
+ }
+ connect(analog_map_stick[analog_id], &QPushButton::released, [=]() {
+ QMessageBox::information(this, tr("Information"),
+ tr("After pressing OK, first move your joystick horizontally, "
+ "and then vertically."));
+ handleClick(
+ analog_map_stick[analog_id],
+ [=](const Common::ParamPackage& params) { analogs_param[analog_id] = params; },
+ InputCommon::Polling::DeviceType::Analog);
+ });
+ }
+
+ connect(ui->buttonClearAll, &QPushButton::released, [this] { ClearAll(); });
+ connect(ui->buttonRestoreDefaults, &QPushButton::released, [this]() { restoreDefaults(); });
+
+ timeout_timer->setSingleShot(true);
+ connect(timeout_timer.get(), &QTimer::timeout, [this]() { setPollingResult({}, true); });
+
+ connect(poll_timer.get(), &QTimer::timeout, [this]() {
+ Common::ParamPackage params;
+ for (auto& poller : device_pollers) {
+ params = poller->GetNextInput();
+ if (params.Has("engine")) {
+ setPollingResult(params, false);
+ return;
+ }
+ }
+ });
+
+ controller_color_buttons = {
+ ui->left_body_button,
+ ui->left_buttons_button,
+ ui->right_body_button,
+ ui->right_buttons_button,
+ };
+
+ for (std::size_t i = 0; i < controller_color_buttons.size(); ++i) {
+ connect(controller_color_buttons[i], &QPushButton::clicked, this,
+ std::bind(&ConfigureInputPlayer::OnControllerButtonClick, this, i));
+ }
+
+ this->loadConfiguration();
+ this->resize(0, 0);
+
+ // TODO(wwylele): enable this when we actually emulate it
+ ui->buttonHome->setEnabled(false);
+}
+
+ConfigureInputPlayer::~ConfigureInputPlayer() = default;
+
+void ConfigureInputPlayer::applyConfiguration() {
+ auto& buttons =
+ debug ? Settings::values.debug_pad_buttons : Settings::values.players[player_index].buttons;
+ auto& analogs =
+ debug ? Settings::values.debug_pad_analogs : Settings::values.players[player_index].analogs;
+
+ std::transform(buttons_param.begin(), buttons_param.end(), buttons.begin(),
+ [](const Common::ParamPackage& param) { return param.Serialize(); });
+ std::transform(analogs_param.begin(), analogs_param.end(), analogs.begin(),
+ [](const Common::ParamPackage& param) { return param.Serialize(); });
+
+ if (debug)
+ return;
+
+ std::array<u32, 4> colors{};
+ std::transform(controller_colors.begin(), controller_colors.end(), colors.begin(),
+ [](QColor color) { return color.rgb(); });
+
+ Settings::values.players[player_index].body_color_left = colors[0];
+ Settings::values.players[player_index].button_color_left = colors[1];
+ Settings::values.players[player_index].body_color_right = colors[2];
+ Settings::values.players[player_index].button_color_right = colors[3];
+}
+
+void ConfigureInputPlayer::OnControllerButtonClick(int i) {
+ const QColor new_bg_color = QColorDialog::getColor(controller_colors[i]);
+ if (!new_bg_color.isValid())
+ return;
+ controller_colors[i] = new_bg_color;
+ controller_color_buttons[i]->setStyleSheet(
+ QString("QPushButton { background-color: %1 }").arg(controller_colors[i].name()));
+}
+
+void ConfigureInputPlayer::loadConfiguration() {
+ if (debug) {
+ std::transform(Settings::values.debug_pad_buttons.begin(),
+ Settings::values.debug_pad_buttons.end(), buttons_param.begin(),
+ [](const std::string& str) { return Common::ParamPackage(str); });
+ std::transform(Settings::values.debug_pad_analogs.begin(),
+ Settings::values.debug_pad_analogs.end(), analogs_param.begin(),
+ [](const std::string& str) { return Common::ParamPackage(str); });
+ } else {
+ std::transform(Settings::values.players[player_index].buttons.begin(),
+ Settings::values.players[player_index].buttons.end(), buttons_param.begin(),
+ [](const std::string& str) { return Common::ParamPackage(str); });
+ std::transform(Settings::values.players[player_index].analogs.begin(),
+ Settings::values.players[player_index].analogs.end(), analogs_param.begin(),
+ [](const std::string& str) { return Common::ParamPackage(str); });
+ }
+
+ updateButtonLabels();
+
+ if (debug)
+ return;
+
+ std::array<u32, 4> colors = {
+ Settings::values.players[player_index].body_color_left,
+ Settings::values.players[player_index].button_color_left,
+ Settings::values.players[player_index].body_color_right,
+ Settings::values.players[player_index].button_color_right,
+ };
+
+ std::transform(colors.begin(), colors.end(), controller_colors.begin(),
+ [](u32 rgb) { return QColor::fromRgb(rgb); });
+
+ for (std::size_t i = 0; i < colors.size(); ++i) {
+ controller_color_buttons[i]->setStyleSheet(
+ QString("QPushButton { background-color: %1 }").arg(controller_colors[i].name()));
+ }
+}
+
+void ConfigureInputPlayer::restoreDefaults() {
+ for (int button_id = 0; button_id < Settings::NativeButton::NumButtons; button_id++) {
+ buttons_param[button_id] = Common::ParamPackage{
+ InputCommon::GenerateKeyboardParam(Config::default_buttons[button_id])};
+ }
+
+ for (int analog_id = 0; analog_id < Settings::NativeAnalog::NumAnalogs; analog_id++) {
+ for (int sub_button_id = 0; sub_button_id < ANALOG_SUB_BUTTONS_NUM; sub_button_id++) {
+ Common::ParamPackage params{InputCommon::GenerateKeyboardParam(
+ Config::default_analogs[analog_id][sub_button_id])};
+ SetAnalogButton(params, analogs_param[analog_id], analog_sub_buttons[sub_button_id]);
+ }
+ }
+ updateButtonLabels();
+}
+
+void ConfigureInputPlayer::ClearAll() {
+ for (int button_id = 0; button_id < Settings::NativeButton::NumButtons; button_id++) {
+ if (button_map[button_id] && button_map[button_id]->isEnabled())
+ buttons_param[button_id].Clear();
+ }
+ for (int analog_id = 0; analog_id < Settings::NativeAnalog::NumAnalogs; analog_id++) {
+ for (int sub_button_id = 0; sub_button_id < ANALOG_SUB_BUTTONS_NUM; sub_button_id++) {
+ if (analog_map_buttons[analog_id][sub_button_id] &&
+ analog_map_buttons[analog_id][sub_button_id]->isEnabled())
+ analogs_param[analog_id].Erase(analog_sub_buttons[sub_button_id]);
+ }
+ }
+
+ updateButtonLabels();
+}
+
+void ConfigureInputPlayer::updateButtonLabels() {
+ for (int button = 0; button < Settings::NativeButton::NumButtons; button++) {
+ button_map[button]->setText(ButtonToText(buttons_param[button]));
+ }
+
+ for (int analog_id = 0; analog_id < Settings::NativeAnalog::NumAnalogs; analog_id++) {
+ for (int sub_button_id = 0; sub_button_id < ANALOG_SUB_BUTTONS_NUM; sub_button_id++) {
+ if (analog_map_buttons[analog_id][sub_button_id]) {
+ analog_map_buttons[analog_id][sub_button_id]->setText(
+ AnalogToText(analogs_param[analog_id], analog_sub_buttons[sub_button_id]));
+ }
+ }
+ analog_map_stick[analog_id]->setText(tr("Set Analog Stick"));
+ }
+}
+
+void ConfigureInputPlayer::handleClick(
+ QPushButton* button, std::function<void(const Common::ParamPackage&)> new_input_setter,
+ InputCommon::Polling::DeviceType type) {
+ button->setText(tr("[press key]"));
+ button->setFocus();
+
+ const auto iter = std::find(button_map.begin(), button_map.end(), button);
+ ASSERT(iter != button_map.end());
+ const auto index = std::distance(button_map.begin(), iter);
+ ASSERT(index < Settings::NativeButton::NumButtons && index >= 0);
+
+ input_setter = new_input_setter;
+
+ device_pollers = InputCommon::Polling::GetPollers(type);
+
+ // Keyboard keys can only be used as button devices
+ want_keyboard_keys = type == InputCommon::Polling::DeviceType::Button;
+
+ for (auto& poller : device_pollers) {
+ poller->Start();
+ }
+
+ grabKeyboard();
+ grabMouse();
+ timeout_timer->start(5000); // Cancel after 5 seconds
+ poll_timer->start(200); // Check for new inputs every 200ms
+}
+
+void ConfigureInputPlayer::setPollingResult(const Common::ParamPackage& params, bool abort) {
+ releaseKeyboard();
+ releaseMouse();
+ timeout_timer->stop();
+ poll_timer->stop();
+ for (auto& poller : device_pollers) {
+ poller->Stop();
+ }
+
+ if (!abort) {
+ (*input_setter)(params);
+ }
+
+ updateButtonLabels();
+ input_setter = std::nullopt;
+}
+
+void ConfigureInputPlayer::keyPressEvent(QKeyEvent* event) {
+ if (!input_setter || !event)
+ return;
+
+ if (event->key() != Qt::Key_Escape) {
+ if (want_keyboard_keys) {
+ setPollingResult(Common::ParamPackage{InputCommon::GenerateKeyboardParam(event->key())},
+ false);
+ } else {
+ // Escape key wasn't pressed and we don't want any keyboard keys, so don't stop polling
+ return;
+ }
+ }
+ setPollingResult({}, true);
+}
diff --git a/src/yuzu/configuration/configure_input_player.h b/src/yuzu/configuration/configure_input_player.h
new file mode 100644
index 000000000..b0e5550c5
--- /dev/null
+++ b/src/yuzu/configuration/configure_input_player.h
@@ -0,0 +1,103 @@
+// Copyright 2016 Citra Emulator Project
+// Licensed under GPLv2 or any later version
+// Refer to the license.txt file included.
+
+#pragma once
+
+#include <array>
+#include <functional>
+#include <memory>
+#include <optional>
+#include <string>
+#include <unordered_map>
+#include <QDialog>
+#include <QKeyEvent>
+#include "common/param_package.h"
+#include "core/settings.h"
+#include "input_common/main.h"
+#include "ui_configure_input.h"
+
+class QPushButton;
+class QString;
+class QTimer;
+
+namespace Ui {
+class ConfigureInputPlayer;
+}
+
+class ConfigureInputPlayer : public QDialog {
+ Q_OBJECT
+
+public:
+ explicit ConfigureInputPlayer(QWidget* parent, u8 player_index, bool debug = false);
+ ~ConfigureInputPlayer() override;
+
+ /// Save all button configurations to settings file
+ void applyConfiguration();
+
+private:
+ std::unique_ptr<Ui::ConfigureInputPlayer> ui;
+
+ u8 player_index;
+ bool debug;
+
+ std::unique_ptr<QTimer> timeout_timer;
+ std::unique_ptr<QTimer> poll_timer;
+
+ /// This will be the the setting function when an input is awaiting configuration.
+ std::optional<std::function<void(const Common::ParamPackage&)>> input_setter;
+
+ std::array<Common::ParamPackage, Settings::NativeButton::NumButtons> buttons_param;
+ std::array<Common::ParamPackage, Settings::NativeAnalog::NumAnalogs> analogs_param;
+
+ static constexpr int ANALOG_SUB_BUTTONS_NUM = 5;
+
+ /// Each button input is represented by a QPushButton.
+ std::array<QPushButton*, Settings::NativeButton::NumButtons> button_map;
+
+ std::vector<QWidget*> debug_hidden;
+ std::vector<QWidget*> layout_hidden;
+
+ /// A group of five QPushButtons represent one analog input. The buttons each represent up,
+ /// down, left, right, and modifier, respectively.
+ std::array<std::array<QPushButton*, ANALOG_SUB_BUTTONS_NUM>, Settings::NativeAnalog::NumAnalogs>
+ analog_map_buttons;
+
+ /// Analog inputs are also represented each with a single button, used to configure with an
+ /// actual analog stick
+ std::array<QPushButton*, Settings::NativeAnalog::NumAnalogs> analog_map_stick;
+
+ static const std::array<std::string, ANALOG_SUB_BUTTONS_NUM> analog_sub_buttons;
+
+ std::vector<std::unique_ptr<InputCommon::Polling::DevicePoller>> device_pollers;
+
+ /// A flag to indicate if keyboard keys are okay when configuring an input. If this is false,
+ /// keyboard events are ignored.
+ bool want_keyboard_keys = false;
+
+ std::array<QPushButton*, 4> controller_color_buttons;
+ std::array<QColor, 4> controller_colors;
+
+ void OnControllerButtonClick(int i);
+
+ /// Load configuration settings.
+ void loadConfiguration();
+ /// Restore all buttons to their default values.
+ void restoreDefaults();
+ /// Clear all input configuration
+ void ClearAll();
+
+ /// Update UI to reflect current configuration.
+ void updateButtonLabels();
+
+ /// Called when the button was pressed.
+ void handleClick(QPushButton* button,
+ std::function<void(const Common::ParamPackage&)> new_input_setter,
+ InputCommon::Polling::DeviceType type);
+
+ /// Finish polling and configure input using the input_setter
+ void setPollingResult(const Common::ParamPackage& params, bool abort);
+
+ /// Handle key press events.
+ void keyPressEvent(QKeyEvent* event) override;
+};
diff --git a/src/yuzu/configuration/configure_input_player.ui b/src/yuzu/configuration/configure_input_player.ui
new file mode 100644
index 000000000..42db020be
--- /dev/null
+++ b/src/yuzu/configuration/configure_input_player.ui
@@ -0,0 +1,1164 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ui version="4.0">
+ <class>ConfigureInputPlayer</class>
+ <widget class="QDialog" name="ConfigureInputPlayer">
+ <property name="geometry">
+ <rect>
+ <x>0</x>
+ <y>0</y>
+ <width>408</width>
+ <height>731</height>
+ </rect>
+ </property>
+ <property name="windowTitle">
+ <string>Configure Input</string>
+ </property>
+ <layout class="QVBoxLayout" name="verticalLayout_5">
+ <item>
+ <layout class="QGridLayout" name="buttons">
+ <item row="1" column="1">
+ <widget class="QGroupBox" name="RStick">
+ <property name="title">
+ <string>Right Stick</string>
+ </property>
+ <property name="alignment">
+ <set>Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter</set>
+ </property>
+ <property name="flat">
+ <bool>false</bool>
+ </property>
+ <property name="checkable">
+ <bool>false</bool>
+ </property>
+ <layout class="QGridLayout" name="gridLayout_5">
+ <item row="1" column="1">
+ <layout class="QVBoxLayout" name="buttonRStickDownVerticalLayout">
+ <item>
+ <layout class="QHBoxLayout" name="buttonRStickDownHorizontalLayout">
+ <item>
+ <widget class="QLabel" name="labelRStickDown">
+ <property name="text">
+ <string>Down:</string>
+ </property>
+ </widget>
+ </item>
+ </layout>
+ </item>
+ <item>
+ <widget class="QPushButton" name="buttonRStickDown">
+ <property name="text">
+ <string/>
+ </property>
+ </widget>
+ </item>
+ </layout>
+ </item>
+ <item row="0" column="1">
+ <layout class="QVBoxLayout" name="buttonRStickRightVerticalLayout">
+ <item>
+ <layout class="QHBoxLayout" name="buttonRStickRightHorizontalLayout">
+ <item>
+ <widget class="QLabel" name="labelRStickRight">
+ <property name="text">
+ <string>Right:</string>
+ </property>
+ </widget>
+ </item>
+ </layout>
+ </item>
+ <item>
+ <widget class="QPushButton" name="buttonRStickRight">
+ <property name="text">
+ <string/>
+ </property>
+ </widget>
+ </item>
+ </layout>
+ </item>
+ <item row="3" column="0" colspan="2">
+ <widget class="QPushButton" name="buttonRStickAnalog">
+ <property name="text">
+ <string>Set Analog Stick</string>
+ </property>
+ </widget>
+ </item>
+ <item row="0" column="0">
+ <layout class="QVBoxLayout" name="buttonRStickLeftVerticalLayout">
+ <item>
+ <layout class="QHBoxLayout" name="buttonRStickLeftHorizontalLayout">
+ <item>
+ <widget class="QLabel" name="labelRStickLeft">
+ <property name="text">
+ <string>Left:</string>
+ </property>
+ </widget>
+ </item>
+ </layout>
+ </item>
+ <item>
+ <widget class="QPushButton" name="buttonRStickLeft">
+ <property name="text">
+ <string/>
+ </property>
+ </widget>
+ </item>
+ </layout>
+ </item>
+ <item row="1" column="0">
+ <layout class="QVBoxLayout" name="buttonRStickUpVerticalLayout">
+ <item>
+ <layout class="QHBoxLayout" name="buttonRStickUpHorizontalLayout">
+ <item>
+ <widget class="QLabel" name="labelRStickUp">
+ <property name="text">
+ <string>Up:</string>
+ </property>
+ </widget>
+ </item>
+ </layout>
+ </item>
+ <item>
+ <widget class="QPushButton" name="buttonRStickUp">
+ <property name="text">
+ <string/>
+ </property>
+ </widget>
+ </item>
+ </layout>
+ </item>
+ <item row="2" column="0">
+ <layout class="QVBoxLayout" name="buttonRStickPressedVerticalLayout">
+ <item>
+ <layout class="QHBoxLayout" name="buttonRStickPressedHorizontalLayout">
+ <item>
+ <widget class="QLabel" name="labelRStickPressed">
+ <property name="text">
+ <string>Pressed:</string>
+ </property>
+ </widget>
+ </item>
+ </layout>
+ </item>
+ <item>
+ <widget class="QPushButton" name="buttonRStick">
+ <property name="text">
+ <string/>
+ </property>
+ </widget>
+ </item>
+ </layout>
+ </item>
+ <item row="2" column="1">
+ <layout class="QVBoxLayout" name="buttonRStickModVerticalLayout">
+ <item>
+ <layout class="QHBoxLayout" name="buttonRStickModHorizontalLayout">
+ <item>
+ <widget class="QLabel" name="labelRStickMod">
+ <property name="text">
+ <string>Modifier:</string>
+ </property>
+ </widget>
+ </item>
+ </layout>
+ </item>
+ <item>
+ <widget class="QPushButton" name="buttonRStickMod">
+ <property name="text">
+ <string/>
+ </property>
+ </widget>
+ </item>
+ </layout>
+ </item>
+ </layout>
+ </widget>
+ </item>
+ <item row="0" column="1">
+ <widget class="QGroupBox" name="Dpad">
+ <property name="title">
+ <string>Directional Pad</string>
+ </property>
+ <property name="flat">
+ <bool>false</bool>
+ </property>
+ <property name="checkable">
+ <bool>false</bool>
+ </property>
+ <layout class="QGridLayout" name="gridLayout_2">
+ <item row="1" column="0">
+ <layout class="QVBoxLayout" name="buttonDpadUpVerticalLayout">
+ <item>
+ <layout class="QHBoxLayout" name="buttonDpadUpHorizontalLayout">
+ <item>
+ <widget class="QLabel" name="labelDpadUp">
+ <property name="text">
+ <string>Up:</string>
+ </property>
+ </widget>
+ </item>
+ </layout>
+ </item>
+ <item>
+ <widget class="QPushButton" name="buttonDpadUp">
+ <property name="text">
+ <string/>
+ </property>
+ </widget>
+ </item>
+ </layout>
+ </item>
+ <item row="1" column="1">
+ <layout class="QVBoxLayout" name="buttonDpadDownVerticalLayout">
+ <item>
+ <layout class="QHBoxLayout" name="buttonDpadDownHorizontalLayout">
+ <item>
+ <widget class="QLabel" name="labelDpadDown">
+ <property name="text">
+ <string>Down:</string>
+ </property>
+ </widget>
+ </item>
+ </layout>
+ </item>
+ <item>
+ <widget class="QPushButton" name="buttonDpadDown">
+ <property name="text">
+ <string/>
+ </property>
+ </widget>
+ </item>
+ </layout>
+ </item>
+ <item row="0" column="0">
+ <layout class="QVBoxLayout" name="buttonDpadLeftVerticalLayout">
+ <item>
+ <layout class="QHBoxLayout" name="buttonDpadLeftHorizontalLayout">
+ <item>
+ <widget class="QLabel" name="labelDpadLeft">
+ <property name="minimumSize">
+ <size>
+ <width>80</width>
+ <height>0</height>
+ </size>
+ </property>
+ <property name="text">
+ <string>Left:</string>
+ </property>
+ </widget>
+ </item>
+ </layout>
+ </item>
+ <item>
+ <widget class="QPushButton" name="buttonDpadLeft">
+ <property name="text">
+ <string/>
+ </property>
+ </widget>
+ </item>
+ </layout>
+ </item>
+ <item row="0" column="1">
+ <layout class="QVBoxLayout" name="buttonDpadRightVerticalLayout">
+ <item>
+ <layout class="QHBoxLayout" name="buttonDpadRightHorizontalLayout">
+ <item>
+ <widget class="QLabel" name="labelDpadRight">
+ <property name="minimumSize">
+ <size>
+ <width>80</width>
+ <height>0</height>
+ </size>
+ </property>
+ <property name="text">
+ <string>Right:</string>
+ </property>
+ </widget>
+ </item>
+ </layout>
+ </item>
+ <item>
+ <widget class="QPushButton" name="buttonDpadRight">
+ <property name="text">
+ <string/>
+ </property>
+ </widget>
+ </item>
+ </layout>
+ </item>
+ </layout>
+ </widget>
+ </item>
+ <item row="0" column="0">
+ <widget class="QGroupBox" name="faceButtons">
+ <property name="title">
+ <string>Face Buttons</string>
+ </property>
+ <property name="flat">
+ <bool>false</bool>
+ </property>
+ <property name="checkable">
+ <bool>false</bool>
+ </property>
+ <layout class="QGridLayout" name="gridLayout">
+ <item row="0" column="0">
+ <layout class="QVBoxLayout" name="buttonFaceButtonsAVerticalLayout">
+ <item>
+ <layout class="QHBoxLayout" name="buttonFaceButtonsAHorizontalLayout">
+ <item>
+ <widget class="QLabel" name="labelA">
+ <property name="minimumSize">
+ <size>
+ <width>80</width>
+ <height>0</height>
+ </size>
+ </property>
+ <property name="text">
+ <string>A:</string>
+ </property>
+ </widget>
+ </item>
+ </layout>
+ </item>
+ <item>
+ <widget class="QPushButton" name="buttonA">
+ <property name="text">
+ <string/>
+ </property>
+ </widget>
+ </item>
+ </layout>
+ </item>
+ <item row="0" column="1">
+ <layout class="QVBoxLayout" name="buttonFaceButtonsBVerticalLayout">
+ <item>
+ <layout class="QHBoxLayout" name="buttonFaceButtonsBHorizontalLayout">
+ <item>
+ <widget class="QLabel" name="labelB">
+ <property name="minimumSize">
+ <size>
+ <width>80</width>
+ <height>0</height>
+ </size>
+ </property>
+ <property name="text">
+ <string>B:</string>
+ </property>
+ </widget>
+ </item>
+ </layout>
+ </item>
+ <item>
+ <widget class="QPushButton" name="buttonB">
+ <property name="text">
+ <string/>
+ </property>
+ </widget>
+ </item>
+ </layout>
+ </item>
+ <item row="1" column="0">
+ <layout class="QVBoxLayout" name="buttonFaceButtonsXVerticalLayout">
+ <item>
+ <layout class="QHBoxLayout" name="buttonFaceButtonsXHorizontalLayout">
+ <item>
+ <widget class="QLabel" name="labelX">
+ <property name="text">
+ <string>X:</string>
+ </property>
+ </widget>
+ </item>
+ </layout>
+ </item>
+ <item>
+ <widget class="QPushButton" name="buttonX">
+ <property name="text">
+ <string/>
+ </property>
+ </widget>
+ </item>
+ </layout>
+ </item>
+ <item row="1" column="1">
+ <layout class="QVBoxLayout" name="buttonFaceButtonsYVerticalLayout">
+ <item>
+ <layout class="QHBoxLayout" name="buttonFaceButtonsYHorizontalLayout">
+ <item>
+ <widget class="QLabel" name="labelY">
+ <property name="text">
+ <string>Y:</string>
+ </property>
+ </widget>
+ </item>
+ </layout>
+ </item>
+ <item>
+ <widget class="QPushButton" name="buttonY">
+ <property name="text">
+ <string/>
+ </property>
+ </widget>
+ </item>
+ </layout>
+ </item>
+ </layout>
+ </widget>
+ </item>
+ <item row="5" column="0" colspan="2">
+ <widget class="QGroupBox" name="controller_color">
+ <property name="title">
+ <string>Controller Color</string>
+ </property>
+ <layout class="QGridLayout" name="gridLayout_10" columnstretch="0,0,0,0,0,0,0">
+ <item row="0" column="0">
+ <spacer name="horizontalSpacer_2">
+ <property name="orientation">
+ <enum>Qt::Horizontal</enum>
+ </property>
+ <property name="sizeHint" stdset="0">
+ <size>
+ <width>40</width>
+ <height>20</height>
+ </size>
+ </property>
+ </spacer>
+ </item>
+ <item row="0" column="1">
+ <widget class="QLabel" name="left_body_label">
+ <property name="text">
+ <string>Left Body</string>
+ </property>
+ </widget>
+ </item>
+ <item row="0" column="6">
+ <spacer name="horizontalSpacer_3">
+ <property name="orientation">
+ <enum>Qt::Horizontal</enum>
+ </property>
+ <property name="sizeHint" stdset="0">
+ <size>
+ <width>40</width>
+ <height>20</height>
+ </size>
+ </property>
+ </spacer>
+ </item>
+ <item row="1" column="1">
+ <widget class="QLabel" name="left_buttons_label">
+ <property name="minimumSize">
+ <size>
+ <width>90</width>
+ <height>0</height>
+ </size>
+ </property>
+ <property name="text">
+ <string>Left Buttons</string>
+ </property>
+ </widget>
+ </item>
+ <item row="1" column="5">
+ <widget class="QPushButton" name="right_buttons_button">
+ <property name="sizePolicy">
+ <sizepolicy hsizetype="Fixed" vsizetype="Fixed">
+ <horstretch>0</horstretch>
+ <verstretch>0</verstretch>
+ </sizepolicy>
+ </property>
+ <property name="minimumSize">
+ <size>
+ <width>32</width>
+ <height>0</height>
+ </size>
+ </property>
+ <property name="maximumSize">
+ <size>
+ <width>40</width>
+ <height>16777215</height>
+ </size>
+ </property>
+ <property name="text">
+ <string/>
+ </property>
+ </widget>
+ </item>
+ <item row="0" column="4">
+ <widget class="QLabel" name="right_body_label">
+ <property name="text">
+ <string>Right Body</string>
+ </property>
+ </widget>
+ </item>
+ <item row="1" column="4">
+ <widget class="QLabel" name="right_buttons_label">
+ <property name="minimumSize">
+ <size>
+ <width>90</width>
+ <height>0</height>
+ </size>
+ </property>
+ <property name="text">
+ <string>Right Buttons</string>
+ </property>
+ </widget>
+ </item>
+ <item row="1" column="2">
+ <widget class="QPushButton" name="left_buttons_button">
+ <property name="sizePolicy">
+ <sizepolicy hsizetype="Fixed" vsizetype="Fixed">
+ <horstretch>0</horstretch>
+ <verstretch>0</verstretch>
+ </sizepolicy>
+ </property>
+ <property name="minimumSize">
+ <size>
+ <width>32</width>
+ <height>0</height>
+ </size>
+ </property>
+ <property name="maximumSize">
+ <size>
+ <width>40</width>
+ <height>16777215</height>
+ </size>
+ </property>
+ <property name="text">
+ <string/>
+ </property>
+ </widget>
+ </item>
+ <item row="0" column="2">
+ <widget class="QPushButton" name="left_body_button">
+ <property name="sizePolicy">
+ <sizepolicy hsizetype="Fixed" vsizetype="Fixed">
+ <horstretch>0</horstretch>
+ <verstretch>0</verstretch>
+ </sizepolicy>
+ </property>
+ <property name="minimumSize">
+ <size>
+ <width>32</width>
+ <height>0</height>
+ </size>
+ </property>
+ <property name="maximumSize">
+ <size>
+ <width>40</width>
+ <height>16777215</height>
+ </size>
+ </property>
+ <property name="text">
+ <string/>
+ </property>
+ </widget>
+ </item>
+ <item row="0" column="5">
+ <widget class="QPushButton" name="right_body_button">
+ <property name="sizePolicy">
+ <sizepolicy hsizetype="Fixed" vsizetype="Fixed">
+ <horstretch>0</horstretch>
+ <verstretch>0</verstretch>
+ </sizepolicy>
+ </property>
+ <property name="minimumSize">
+ <size>
+ <width>32</width>
+ <height>0</height>
+ </size>
+ </property>
+ <property name="maximumSize">
+ <size>
+ <width>40</width>
+ <height>16777215</height>
+ </size>
+ </property>
+ <property name="text">
+ <string/>
+ </property>
+ </widget>
+ </item>
+ <item row="0" column="3">
+ <spacer name="horizontalSpacer_4">
+ <property name="orientation">
+ <enum>Qt::Horizontal</enum>
+ </property>
+ <property name="sizeType">
+ <enum>QSizePolicy::Fixed</enum>
+ </property>
+ <property name="sizeHint" stdset="0">
+ <size>
+ <width>20</width>
+ <height>20</height>
+ </size>
+ </property>
+ </spacer>
+ </item>
+ </layout>
+ </widget>
+ </item>
+ <item row="1" column="0">
+ <widget class="QGroupBox" name="LStick">
+ <property name="title">
+ <string>Left Stick</string>
+ </property>
+ <property name="flat">
+ <bool>false</bool>
+ </property>
+ <property name="checkable">
+ <bool>false</bool>
+ </property>
+ <layout class="QGridLayout" name="gridLayout_4">
+ <item row="1" column="1">
+ <layout class="QVBoxLayout" name="buttonLStickUpVerticalLayout">
+ <item>
+ <layout class="QHBoxLayout" name="buttonLStickUpHorizontalLayout">
+ <item>
+ <widget class="QLabel" name="labelLStickUp">
+ <property name="text">
+ <string>Up:</string>
+ </property>
+ </widget>
+ </item>
+ </layout>
+ </item>
+ <item>
+ <widget class="QPushButton" name="buttonLStickUp">
+ <property name="text">
+ <string/>
+ </property>
+ </widget>
+ </item>
+ </layout>
+ </item>
+ <item row="0" column="2">
+ <layout class="QVBoxLayout" name="buttonLStickRightVerticalLayout">
+ <item>
+ <layout class="QHBoxLayout" name="buttonLStickRightHorizontalLayout">
+ <item>
+ <widget class="QLabel" name="labelLStickRight">
+ <property name="text">
+ <string>Right:</string>
+ </property>
+ </widget>
+ </item>
+ </layout>
+ </item>
+ <item>
+ <widget class="QPushButton" name="buttonLStickRight">
+ <property name="text">
+ <string/>
+ </property>
+ </widget>
+ </item>
+ </layout>
+ </item>
+ <item row="4" column="1" colspan="2">
+ <widget class="QPushButton" name="buttonLStickAnalog">
+ <property name="text">
+ <string>Set Analog Stick</string>
+ </property>
+ </widget>
+ </item>
+ <item row="0" column="1">
+ <layout class="QVBoxLayout" name="buttonLStickLeftVerticalLayout">
+ <item>
+ <layout class="QHBoxLayout" name="buttonLStickLeftHorizontalLayout_2">
+ <item>
+ <widget class="QLabel" name="labelLStickLeft">
+ <property name="text">
+ <string>Left:</string>
+ </property>
+ </widget>
+ </item>
+ </layout>
+ </item>
+ <item>
+ <widget class="QPushButton" name="buttonLStickLeft">
+ <property name="text">
+ <string/>
+ </property>
+ </widget>
+ </item>
+ </layout>
+ </item>
+ <item row="1" column="2">
+ <layout class="QVBoxLayout" name="buttonLStickDownVerticalLayout">
+ <item>
+ <layout class="QHBoxLayout" name="buttonLStickDownHorizontalLayout">
+ <item>
+ <widget class="QLabel" name="labelLStickDown">
+ <property name="text">
+ <string>Down:</string>
+ </property>
+ </widget>
+ </item>
+ </layout>
+ </item>
+ <item>
+ <widget class="QPushButton" name="buttonLStickDown">
+ <property name="text">
+ <string/>
+ </property>
+ </widget>
+ </item>
+ </layout>
+ </item>
+ <item row="3" column="2">
+ <layout class="QVBoxLayout" name="buttonLStickModVerticalLayout">
+ <item>
+ <layout class="QHBoxLayout" name="buttonLStickModHorizontalLayout">
+ <item>
+ <widget class="QLabel" name="labelLStickMod">
+ <property name="text">
+ <string>Modifier:</string>
+ </property>
+ </widget>
+ </item>
+ </layout>
+ </item>
+ <item>
+ <widget class="QPushButton" name="buttonLStickMod">
+ <property name="text">
+ <string/>
+ </property>
+ </widget>
+ </item>
+ </layout>
+ </item>
+ <item row="3" column="1">
+ <layout class="QVBoxLayout" name="buttonLStickPressedVerticalLayout" stretch="0,0">
+ <item>
+ <layout class="QHBoxLayout" name="buttonLStickPressedHorizontalLayout">
+ <item>
+ <widget class="QLabel" name="labelLStickPressed">
+ <property name="text">
+ <string>Pressed:</string>
+ </property>
+ </widget>
+ </item>
+ </layout>
+ </item>
+ <item>
+ <widget class="QPushButton" name="buttonLStick">
+ <property name="text">
+ <string/>
+ </property>
+ </widget>
+ </item>
+ </layout>
+ </item>
+ </layout>
+ </widget>
+ </item>
+ <item row="3" column="0">
+ <widget class="QGroupBox" name="shoulderButtons">
+ <property name="title">
+ <string>Shoulder Buttons</string>
+ </property>
+ <property name="flat">
+ <bool>false</bool>
+ </property>
+ <property name="checkable">
+ <bool>false</bool>
+ </property>
+ <layout class="QGridLayout" name="gridLayout_3">
+ <item row="3" column="0">
+ <layout class="QVBoxLayout" name="buttonShoulderButtonsSLVerticalLayout">
+ <item>
+ <layout class="QHBoxLayout" name="buttonShoulderButtonsSLHorizontalLayout">
+ <item>
+ <widget class="QLabel" name="labelSL">
+ <property name="text">
+ <string>SL:</string>
+ </property>
+ </widget>
+ </item>
+ </layout>
+ </item>
+ <item>
+ <widget class="QPushButton" name="buttonSL">
+ <property name="text">
+ <string/>
+ </property>
+ </widget>
+ </item>
+ </layout>
+ </item>
+ <item row="2" column="1">
+ <layout class="QVBoxLayout" name="buttonShoulderButtonsZRVerticalLayout">
+ <item>
+ <layout class="QHBoxLayout" name="buttonShoulderButtonsZRHorizontalLayout">
+ <item>
+ <widget class="QLabel" name="labelZR">
+ <property name="text">
+ <string>ZR:</string>
+ </property>
+ </widget>
+ </item>
+ </layout>
+ </item>
+ <item>
+ <widget class="QPushButton" name="buttonZR">
+ <property name="text">
+ <string/>
+ </property>
+ </widget>
+ </item>
+ </layout>
+ </item>
+ <item row="3" column="1">
+ <layout class="QVBoxLayout" name="buttonShoulderButtonsSRVerticalLayout">
+ <item>
+ <layout class="QHBoxLayout" name="buttonShoulderButtonsSRHorizontalLayout">
+ <item>
+ <widget class="QLabel" name="labelSR">
+ <property name="text">
+ <string>SR:</string>
+ </property>
+ </widget>
+ </item>
+ </layout>
+ </item>
+ <item>
+ <widget class="QPushButton" name="buttonSR">
+ <property name="text">
+ <string/>
+ </property>
+ </widget>
+ </item>
+ </layout>
+ </item>
+ <item row="0" column="1">
+ <layout class="QVBoxLayout" name="buttonShoulderButtonsZLVerticalLayout">
+ <item>
+ <layout class="QHBoxLayout" name="buttonShoulderButtonsZLHorizontalLayout">
+ <item>
+ <widget class="QLabel" name="labelZL">
+ <property name="text">
+ <string>ZL:</string>
+ </property>
+ </widget>
+ </item>
+ </layout>
+ </item>
+ <item>
+ <widget class="QPushButton" name="buttonZL">
+ <property name="text">
+ <string/>
+ </property>
+ </widget>
+ </item>
+ </layout>
+ </item>
+ <item row="0" column="0">
+ <layout class="QVBoxLayout" name="buttonShoulderButtonsLVerticalLayout">
+ <item>
+ <layout class="QHBoxLayout" name="buttonShoulderButtonsLHorizontalLayout">
+ <item>
+ <widget class="QLabel" name="labelL">
+ <property name="text">
+ <string>L:</string>
+ </property>
+ </widget>
+ </item>
+ </layout>
+ </item>
+ <item>
+ <widget class="QPushButton" name="buttonL">
+ <property name="text">
+ <string/>
+ </property>
+ </widget>
+ </item>
+ </layout>
+ </item>
+ <item row="2" column="0">
+ <layout class="QVBoxLayout" name="buttonShoulderButtonsRVerticalLayout">
+ <item>
+ <layout class="QHBoxLayout" name="buttonShoulderButtonsRHorizontalLayout">
+ <item>
+ <widget class="QLabel" name="labelR">
+ <property name="text">
+ <string>R:</string>
+ </property>
+ </widget>
+ </item>
+ </layout>
+ </item>
+ <item>
+ <widget class="QPushButton" name="buttonR">
+ <property name="text">
+ <string/>
+ </property>
+ </widget>
+ </item>
+ </layout>
+ </item>
+ </layout>
+ </widget>
+ </item>
+ <item row="3" column="1">
+ <widget class="QGroupBox" name="misc">
+ <property name="title">
+ <string>Misc.</string>
+ </property>
+ <property name="flat">
+ <bool>false</bool>
+ </property>
+ <property name="checkable">
+ <bool>false</bool>
+ </property>
+ <layout class="QGridLayout" name="gridLayout_6">
+ <item row="1" column="0">
+ <layout class="QVBoxLayout" name="buttonMiscMinusVerticalLayout">
+ <item>
+ <layout class="QHBoxLayout" name="buttonMiscMinusHorizontalLayout">
+ <item>
+ <widget class="QLabel" name="labelMinus">
+ <property name="text">
+ <string>Minus:</string>
+ </property>
+ </widget>
+ </item>
+ </layout>
+ </item>
+ <item>
+ <widget class="QPushButton" name="buttonMinus">
+ <property name="text">
+ <string/>
+ </property>
+ </widget>
+ </item>
+ </layout>
+ </item>
+ <item row="3" column="1">
+ <spacer name="verticalSpacer_2">
+ <property name="orientation">
+ <enum>Qt::Vertical</enum>
+ </property>
+ <property name="sizeHint" stdset="0">
+ <size>
+ <width>20</width>
+ <height>40</height>
+ </size>
+ </property>
+ </spacer>
+ </item>
+ <item row="0" column="0">
+ <layout class="QVBoxLayout" name="buttonMiscPlusVerticalLayout">
+ <item>
+ <layout class="QHBoxLayout" name="buttonMiscPlusHorizontalLayout">
+ <item>
+ <widget class="QLabel" name="labelPlus">
+ <property name="text">
+ <string>Plus:</string>
+ </property>
+ </widget>
+ </item>
+ </layout>
+ </item>
+ <item>
+ <widget class="QPushButton" name="buttonPlus">
+ <property name="text">
+ <string/>
+ </property>
+ </widget>
+ </item>
+ </layout>
+ </item>
+ <item row="0" column="1">
+ <layout class="QVBoxLayout" name="buttonMiscHomeVerticalLayout">
+ <item>
+ <layout class="QHBoxLayout" name="buttonMiscHomeHorizontalLayout">
+ <item>
+ <widget class="QLabel" name="labelHome">
+ <property name="text">
+ <string>Home:</string>
+ </property>
+ </widget>
+ </item>
+ </layout>
+ </item>
+ <item>
+ <widget class="QPushButton" name="buttonHome">
+ <property name="text">
+ <string/>
+ </property>
+ </widget>
+ </item>
+ </layout>
+ </item>
+ <item row="1" column="1">
+ <layout class="QVBoxLayout" name="buttonMiscScrCapVerticalLayout">
+ <item>
+ <layout class="QHBoxLayout" name="buttonMiscScrCapHorizontalLayout">
+ <item>
+ <widget class="QLabel" name="labelScreenshot">
+ <property name="text">
+ <string>Screen Capture:</string>
+ </property>
+ <property name="wordWrap">
+ <bool>false</bool>
+ </property>
+ </widget>
+ </item>
+ </layout>
+ </item>
+ <item>
+ <widget class="QPushButton" name="buttonScreenshot">
+ <property name="sizePolicy">
+ <sizepolicy hsizetype="Fixed" vsizetype="Fixed">
+ <horstretch>0</horstretch>
+ <verstretch>0</verstretch>
+ </sizepolicy>
+ </property>
+ <property name="maximumSize">
+ <size>
+ <width>80</width>
+ <height>16777215</height>
+ </size>
+ </property>
+ <property name="text">
+ <string/>
+ </property>
+ </widget>
+ </item>
+ </layout>
+ </item>
+ </layout>
+ </widget>
+ </item>
+ </layout>
+ </item>
+ <item>
+ <spacer name="verticalSpacer">
+ <property name="orientation">
+ <enum>Qt::Vertical</enum>
+ </property>
+ <property name="sizeHint" stdset="0">
+ <size>
+ <width>20</width>
+ <height>40</height>
+ </size>
+ </property>
+ </spacer>
+ </item>
+ <item>
+ <layout class="QHBoxLayout" name="horizontalLayout"/>
+ </item>
+ <item>
+ <layout class="QHBoxLayout" name="horizontalLayout_2">
+ <item>
+ <widget class="QPushButton" name="buttonClearAll">
+ <property name="sizePolicy">
+ <sizepolicy hsizetype="Minimum" vsizetype="Fixed">
+ <horstretch>0</horstretch>
+ <verstretch>0</verstretch>
+ </sizepolicy>
+ </property>
+ <property name="sizeIncrement">
+ <size>
+ <width>0</width>
+ <height>0</height>
+ </size>
+ </property>
+ <property name="baseSize">
+ <size>
+ <width>0</width>
+ <height>0</height>
+ </size>
+ </property>
+ <property name="layoutDirection">
+ <enum>Qt::LeftToRight</enum>
+ </property>
+ <property name="text">
+ <string>Clear All</string>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <widget class="QPushButton" name="buttonRestoreDefaults">
+ <property name="sizePolicy">
+ <sizepolicy hsizetype="Minimum" vsizetype="Fixed">
+ <horstretch>0</horstretch>
+ <verstretch>0</verstretch>
+ </sizepolicy>
+ </property>
+ <property name="sizeIncrement">
+ <size>
+ <width>0</width>
+ <height>0</height>
+ </size>
+ </property>
+ <property name="baseSize">
+ <size>
+ <width>0</width>
+ <height>0</height>
+ </size>
+ </property>
+ <property name="layoutDirection">
+ <enum>Qt::LeftToRight</enum>
+ </property>
+ <property name="text">
+ <string>Restore Defaults</string>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <spacer name="horizontalSpacer">
+ <property name="orientation">
+ <enum>Qt::Horizontal</enum>
+ </property>
+ <property name="sizeHint" stdset="0">
+ <size>
+ <width>40</width>
+ <height>20</height>
+ </size>
+ </property>
+ </spacer>
+ </item>
+ <item>
+ <widget class="QDialogButtonBox" name="buttonBox">
+ <property name="standardButtons">
+ <set>QDialogButtonBox::Cancel|QDialogButtonBox::Ok</set>
+ </property>
+ </widget>
+ </item>
+ </layout>
+ </item>
+ </layout>
+ </widget>
+ <resources/>
+ <connections>
+ <connection>
+ <sender>buttonBox</sender>
+ <signal>accepted()</signal>
+ <receiver>ConfigureInputPlayer</receiver>
+ <slot>accept()</slot>
+ <hints>
+ <hint type="sourcelabel">
+ <x>371</x>
+ <y>730</y>
+ </hint>
+ <hint type="destinationlabel">
+ <x>229</x>
+ <y>375</y>
+ </hint>
+ </hints>
+ </connection>
+ <connection>
+ <sender>buttonBox</sender>
+ <signal>rejected()</signal>
+ <receiver>ConfigureInputPlayer</receiver>
+ <slot>reject()</slot>
+ <hints>
+ <hint type="sourcelabel">
+ <x>371</x>
+ <y>730</y>
+ </hint>
+ <hint type="destinationlabel">
+ <x>229</x>
+ <y>375</y>
+ </hint>
+ </hints>
+ </connection>
+ </connections>
+</ui>
diff --git a/src/yuzu/configuration/configure_mouse_advanced.cpp b/src/yuzu/configuration/configure_mouse_advanced.cpp
new file mode 100644
index 000000000..dab58fbaa
--- /dev/null
+++ b/src/yuzu/configuration/configure_mouse_advanced.cpp
@@ -0,0 +1,213 @@
+// Copyright 2016 Citra Emulator Project
+// Licensed under GPLv2 or any later version
+// Refer to the license.txt file included.
+
+#include <algorithm>
+#include <memory>
+#include <utility>
+#include <QKeyEvent>
+#include <QMenu>
+#include <QMessageBox>
+#include <QTimer>
+#include "common/assert.h"
+#include "common/param_package.h"
+#include "input_common/main.h"
+#include "ui_configure_mouse_advanced.h"
+#include "yuzu/configuration/config.h"
+#include "yuzu/configuration/configure_mouse_advanced.h"
+
+static QString GetKeyName(int key_code) {
+ switch (key_code) {
+ case Qt::Key_Shift:
+ return QObject::tr("Shift");
+ case Qt::Key_Control:
+ return QObject::tr("Ctrl");
+ case Qt::Key_Alt:
+ return QObject::tr("Alt");
+ case Qt::Key_Meta:
+ return "";
+ default:
+ return QKeySequence(key_code).toString();
+ }
+}
+
+static QString ButtonToText(const Common::ParamPackage& param) {
+ if (!param.Has("engine")) {
+ return QObject::tr("[not set]");
+ } else if (param.Get("engine", "") == "keyboard") {
+ return GetKeyName(param.Get("code", 0));
+ } else if (param.Get("engine", "") == "sdl") {
+ if (param.Has("hat")) {
+ return QString(QObject::tr("Hat %1 %2"))
+ .arg(param.Get("hat", "").c_str(), param.Get("direction", "").c_str());
+ }
+ if (param.Has("axis")) {
+ return QString(QObject::tr("Axis %1%2"))
+ .arg(param.Get("axis", "").c_str(), param.Get("direction", "").c_str());
+ }
+ if (param.Has("button")) {
+ return QString(QObject::tr("Button %1")).arg(param.Get("button", "").c_str());
+ }
+ return QString();
+ } else {
+ return QObject::tr("[unknown]");
+ }
+}
+
+ConfigureMouseAdvanced::ConfigureMouseAdvanced(QWidget* parent)
+ : QDialog(parent), ui(std::make_unique<Ui::ConfigureMouseAdvanced>()),
+ timeout_timer(std::make_unique<QTimer>()), poll_timer(std::make_unique<QTimer>()) {
+ ui->setupUi(this);
+ setFocusPolicy(Qt::ClickFocus);
+
+ button_map = {
+ ui->left_button, ui->right_button, ui->middle_button, ui->forward_button, ui->back_button,
+ };
+
+ for (int button_id = 0; button_id < Settings::NativeMouseButton::NumMouseButtons; button_id++) {
+ if (!button_map[button_id])
+ continue;
+ button_map[button_id]->setContextMenuPolicy(Qt::CustomContextMenu);
+ connect(button_map[button_id], &QPushButton::released, [=]() {
+ handleClick(
+ button_map[button_id],
+ [=](const Common::ParamPackage& params) { buttons_param[button_id] = params; },
+ InputCommon::Polling::DeviceType::Button);
+ });
+ connect(button_map[button_id], &QPushButton::customContextMenuRequested,
+ [=](const QPoint& menu_location) {
+ QMenu context_menu;
+ context_menu.addAction(tr("Clear"), [&] {
+ buttons_param[button_id].Clear();
+ button_map[button_id]->setText(tr("[not set]"));
+ });
+ context_menu.addAction(tr("Restore Default"), [&] {
+ buttons_param[button_id] =
+ Common::ParamPackage{InputCommon::GenerateKeyboardParam(
+ Config::default_mouse_buttons[button_id])};
+ button_map[button_id]->setText(ButtonToText(buttons_param[button_id]));
+ });
+ context_menu.exec(button_map[button_id]->mapToGlobal(menu_location));
+ });
+ }
+
+ connect(ui->buttonClearAll, &QPushButton::released, [this] { ClearAll(); });
+ connect(ui->buttonRestoreDefaults, &QPushButton::released, [this]() { restoreDefaults(); });
+
+ timeout_timer->setSingleShot(true);
+ connect(timeout_timer.get(), &QTimer::timeout, [this]() { setPollingResult({}, true); });
+
+ connect(poll_timer.get(), &QTimer::timeout, [this]() {
+ Common::ParamPackage params;
+ for (auto& poller : device_pollers) {
+ params = poller->GetNextInput();
+ if (params.Has("engine")) {
+ setPollingResult(params, false);
+ return;
+ }
+ }
+ });
+
+ loadConfiguration();
+ resize(0, 0);
+}
+
+ConfigureMouseAdvanced::~ConfigureMouseAdvanced() = default;
+
+void ConfigureMouseAdvanced::applyConfiguration() {
+ std::transform(buttons_param.begin(), buttons_param.end(),
+ Settings::values.mouse_buttons.begin(),
+ [](const Common::ParamPackage& param) { return param.Serialize(); });
+}
+
+void ConfigureMouseAdvanced::loadConfiguration() {
+ std::transform(Settings::values.mouse_buttons.begin(), Settings::values.mouse_buttons.end(),
+ buttons_param.begin(),
+ [](const std::string& str) { return Common::ParamPackage(str); });
+ updateButtonLabels();
+}
+
+void ConfigureMouseAdvanced::restoreDefaults() {
+ for (int button_id = 0; button_id < Settings::NativeMouseButton::NumMouseButtons; button_id++) {
+ buttons_param[button_id] = Common::ParamPackage{
+ InputCommon::GenerateKeyboardParam(Config::default_mouse_buttons[button_id])};
+ }
+
+ updateButtonLabels();
+}
+
+void ConfigureMouseAdvanced::ClearAll() {
+ for (int i = 0; i < Settings::NativeMouseButton::NumMouseButtons; ++i) {
+ if (button_map[i] && button_map[i]->isEnabled())
+ buttons_param[i].Clear();
+ }
+
+ updateButtonLabels();
+}
+
+void ConfigureMouseAdvanced::updateButtonLabels() {
+ for (int button = 0; button < Settings::NativeMouseButton::NumMouseButtons; button++) {
+ button_map[button]->setText(ButtonToText(buttons_param[button]));
+ }
+}
+
+void ConfigureMouseAdvanced::handleClick(
+ QPushButton* button, std::function<void(const Common::ParamPackage&)> new_input_setter,
+ InputCommon::Polling::DeviceType type) {
+ button->setText(tr("[press key]"));
+ button->setFocus();
+
+ const auto iter = std::find(button_map.begin(), button_map.end(), button);
+ ASSERT(iter != button_map.end());
+ const auto index = std::distance(button_map.begin(), iter);
+ ASSERT(index < Settings::NativeButton::NumButtons && index >= 0);
+
+ input_setter = new_input_setter;
+
+ device_pollers = InputCommon::Polling::GetPollers(type);
+
+ // Keyboard keys can only be used as button devices
+ want_keyboard_keys = type == InputCommon::Polling::DeviceType::Button;
+
+ for (auto& poller : device_pollers) {
+ poller->Start();
+ }
+
+ grabKeyboard();
+ grabMouse();
+ timeout_timer->start(5000); // Cancel after 5 seconds
+ poll_timer->start(200); // Check for new inputs every 200ms
+}
+
+void ConfigureMouseAdvanced::setPollingResult(const Common::ParamPackage& params, bool abort) {
+ releaseKeyboard();
+ releaseMouse();
+ timeout_timer->stop();
+ poll_timer->stop();
+ for (auto& poller : device_pollers) {
+ poller->Stop();
+ }
+
+ if (!abort) {
+ (*input_setter)(params);
+ }
+
+ updateButtonLabels();
+ input_setter = std::nullopt;
+}
+
+void ConfigureMouseAdvanced::keyPressEvent(QKeyEvent* event) {
+ if (!input_setter || !event)
+ return;
+
+ if (event->key() != Qt::Key_Escape) {
+ if (want_keyboard_keys) {
+ setPollingResult(Common::ParamPackage{InputCommon::GenerateKeyboardParam(event->key())},
+ false);
+ } else {
+ // Escape key wasn't pressed and we don't want any keyboard keys, so don't stop polling
+ return;
+ }
+ }
+ setPollingResult({}, true);
+}
diff --git a/src/yuzu/configuration/configure_mouse_advanced.h b/src/yuzu/configuration/configure_mouse_advanced.h
new file mode 100644
index 000000000..218df2bda
--- /dev/null
+++ b/src/yuzu/configuration/configure_mouse_advanced.h
@@ -0,0 +1,68 @@
+// Copyright 2016 Citra Emulator Project
+// Licensed under GPLv2 or any later version
+// Refer to the license.txt file included.
+
+#pragma once
+
+#include <memory>
+#include <optional>
+#include <QDialog>
+#include <QWidget>
+#include "core/settings.h"
+
+class QCheckBox;
+class QPushButton;
+class QTimer;
+
+namespace Ui {
+class ConfigureMouseAdvanced;
+}
+
+class ConfigureMouseAdvanced : public QDialog {
+ Q_OBJECT
+
+public:
+ explicit ConfigureMouseAdvanced(QWidget* parent);
+ ~ConfigureMouseAdvanced() override;
+
+ void applyConfiguration();
+
+private:
+ std::unique_ptr<Ui::ConfigureMouseAdvanced> ui;
+
+ /// This will be the the setting function when an input is awaiting configuration.
+ std::optional<std::function<void(const Common::ParamPackage&)>> input_setter;
+
+ std::array<QPushButton*, Settings::NativeMouseButton::NumMouseButtons> button_map;
+ std::array<Common::ParamPackage, Settings::NativeMouseButton::NumMouseButtons> buttons_param;
+
+ std::vector<std::unique_ptr<InputCommon::Polling::DevicePoller>> device_pollers;
+
+ std::unique_ptr<QTimer> timeout_timer;
+ std::unique_ptr<QTimer> poll_timer;
+
+ /// A flag to indicate if keyboard keys are okay when configuring an input. If this is false,
+ /// keyboard events are ignored.
+ bool want_keyboard_keys = false;
+
+ /// Load configuration settings.
+ void loadConfiguration();
+ /// Restore all buttons to their default values.
+ void restoreDefaults();
+ /// Clear all input configuration
+ void ClearAll();
+
+ /// Update UI to reflect current configuration.
+ void updateButtonLabels();
+
+ /// Called when the button was pressed.
+ void handleClick(QPushButton* button,
+ std::function<void(const Common::ParamPackage&)> new_input_setter,
+ InputCommon::Polling::DeviceType type);
+
+ /// Finish polling and configure input using the input_setter
+ void setPollingResult(const Common::ParamPackage& params, bool abort);
+
+ /// Handle key press events.
+ void keyPressEvent(QKeyEvent* event) override;
+};
diff --git a/src/yuzu/configuration/configure_mouse_advanced.ui b/src/yuzu/configuration/configure_mouse_advanced.ui
new file mode 100644
index 000000000..08245ecf0
--- /dev/null
+++ b/src/yuzu/configuration/configure_mouse_advanced.ui
@@ -0,0 +1,261 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ui version="4.0">
+ <class>ConfigureMouseAdvanced</class>
+ <widget class="QDialog" name="ConfigureMouseAdvanced">
+ <property name="geometry">
+ <rect>
+ <x>0</x>
+ <y>0</y>
+ <width>250</width>
+ <height>261</height>
+ </rect>
+ </property>
+ <property name="windowTitle">
+ <string>Configure Mouse</string>
+ </property>
+ <layout class="QVBoxLayout" name="verticalLayout">
+ <item>
+ <widget class="QGroupBox" name="gridGroupBox">
+ <property name="title">
+ <string>Mouse Buttons</string>
+ </property>
+ <layout class="QGridLayout" name="gridLayout">
+ <item row="0" column="4">
+ <spacer name="horizontalSpacer_2">
+ <property name="orientation">
+ <enum>Qt::Horizontal</enum>
+ </property>
+ <property name="sizeType">
+ <enum>QSizePolicy::Fixed</enum>
+ </property>
+ <property name="sizeHint" stdset="0">
+ <size>
+ <width>20</width>
+ <height>20</height>
+ </size>
+ </property>
+ </spacer>
+ </item>
+ <item row="0" column="3">
+ <layout class="QVBoxLayout" name="verticalLayout_4">
+ <item>
+ <layout class="QHBoxLayout" name="horizontalLayout_3">
+ <item>
+ <widget class="QLabel" name="label_3">
+ <property name="text">
+ <string>Right:</string>
+ </property>
+ </widget>
+ </item>
+ </layout>
+ </item>
+ <item>
+ <widget class="QPushButton" name="right_button">
+ <property name="minimumSize">
+ <size>
+ <width>75</width>
+ <height>0</height>
+ </size>
+ </property>
+ <property name="text">
+ <string/>
+ </property>
+ </widget>
+ </item>
+ </layout>
+ </item>
+ <item row="0" column="0">
+ <spacer name="horizontalSpacer">
+ <property name="orientation">
+ <enum>Qt::Horizontal</enum>
+ </property>
+ <property name="sizeType">
+ <enum>QSizePolicy::Fixed</enum>
+ </property>
+ <property name="sizeHint" stdset="0">
+ <size>
+ <width>20</width>
+ <height>20</height>
+ </size>
+ </property>
+ </spacer>
+ </item>
+ <item row="2" column="1">
+ <layout class="QVBoxLayout" name="verticalLayout_3">
+ <item>
+ <layout class="QHBoxLayout" name="horizontalLayout_2">
+ <item>
+ <widget class="QLabel" name="label_2">
+ <property name="text">
+ <string>Middle:</string>
+ </property>
+ </widget>
+ </item>
+ </layout>
+ </item>
+ <item>
+ <widget class="QPushButton" name="middle_button">
+ <property name="text">
+ <string/>
+ </property>
+ </widget>
+ </item>
+ </layout>
+ </item>
+ <item row="3" column="1">
+ <layout class="QVBoxLayout" name="verticalLayout_5">
+ <item>
+ <layout class="QHBoxLayout" name="horizontalLayout_4">
+ <item>
+ <widget class="QLabel" name="label_4">
+ <property name="minimumSize">
+ <size>
+ <width>54</width>
+ <height>0</height>
+ </size>
+ </property>
+ <property name="text">
+ <string>Back:</string>
+ </property>
+ </widget>
+ </item>
+ </layout>
+ </item>
+ <item>
+ <widget class="QPushButton" name="back_button">
+ <property name="text">
+ <string/>
+ </property>
+ </widget>
+ </item>
+ </layout>
+ </item>
+ <item row="0" column="1">
+ <layout class="QVBoxLayout" name="verticalLayout_2">
+ <item>
+ <layout class="QHBoxLayout" name="horizontalLayout">
+ <item>
+ <widget class="QLabel" name="label">
+ <property name="text">
+ <string>Left:</string>
+ </property>
+ </widget>
+ </item>
+ </layout>
+ </item>
+ <item>
+ <widget class="QPushButton" name="left_button">
+ <property name="minimumSize">
+ <size>
+ <width>75</width>
+ <height>0</height>
+ </size>
+ </property>
+ <property name="text">
+ <string/>
+ </property>
+ </widget>
+ </item>
+ </layout>
+ </item>
+ <item row="3" column="3">
+ <layout class="QVBoxLayout" name="verticalLayout_6">
+ <item>
+ <layout class="QHBoxLayout" name="horizontalLayout_5">
+ <item>
+ <widget class="QLabel" name="label_5">
+ <property name="text">
+ <string>Forward:</string>
+ </property>
+ </widget>
+ </item>
+ </layout>
+ </item>
+ <item>
+ <widget class="QPushButton" name="forward_button">
+ <property name="text">
+ <string/>
+ </property>
+ </widget>
+ </item>
+ </layout>
+ </item>
+ </layout>
+ </widget>
+ </item>
+ <item>
+ <layout class="QHBoxLayout" name="horizontalLayout_6">
+ <item>
+ <widget class="QPushButton" name="buttonClearAll">
+ <property name="text">
+ <string>Clear All</string>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <widget class="QPushButton" name="buttonRestoreDefaults">
+ <property name="text">
+ <string>Restore Defaults</string>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <spacer name="horizontalSpacer_3">
+ <property name="orientation">
+ <enum>Qt::Horizontal</enum>
+ </property>
+ <property name="sizeHint" stdset="0">
+ <size>
+ <width>40</width>
+ <height>20</height>
+ </size>
+ </property>
+ </spacer>
+ </item>
+ </layout>
+ </item>
+ <item>
+ <widget class="QDialogButtonBox" name="buttonBox">
+ <property name="standardButtons">
+ <set>QDialogButtonBox::Cancel|QDialogButtonBox::Ok</set>
+ </property>
+ </widget>
+ </item>
+ </layout>
+ </widget>
+ <resources/>
+ <connections>
+ <connection>
+ <sender>buttonBox</sender>
+ <signal>accepted()</signal>
+ <receiver>ConfigureMouseAdvanced</receiver>
+ <slot>accept()</slot>
+ <hints>
+ <hint type="sourcelabel">
+ <x>124</x>
+ <y>266</y>
+ </hint>
+ <hint type="destinationlabel">
+ <x>124</x>
+ <y>143</y>
+ </hint>
+ </hints>
+ </connection>
+ <connection>
+ <sender>buttonBox</sender>
+ <signal>rejected()</signal>
+ <receiver>ConfigureMouseAdvanced</receiver>
+ <slot>reject()</slot>
+ <hints>
+ <hint type="sourcelabel">
+ <x>124</x>
+ <y>266</y>
+ </hint>
+ <hint type="destinationlabel">
+ <x>124</x>
+ <y>143</y>
+ </hint>
+ </hints>
+ </connection>
+ </connections>
+</ui>
diff --git a/src/yuzu/configuration/configure_system.cpp b/src/yuzu/configuration/configure_system.cpp
index b4b4a4a56..ab5d46492 100644
--- a/src/yuzu/configuration/configure_system.cpp
+++ b/src/yuzu/configuration/configure_system.cpp
@@ -137,6 +137,12 @@ ConfigureSystem::ConfigureSystem(QWidget* parent)
connect(ui->pm_remove, &QPushButton::pressed, this, &ConfigureSystem::DeleteUser);
connect(ui->pm_set_image, &QPushButton::pressed, this, &ConfigureSystem::SetUserImage);
+ connect(ui->rng_seed_checkbox, &QCheckBox::stateChanged, this, [this](bool checked) {
+ ui->rng_seed_edit->setEnabled(checked);
+ if (!checked)
+ ui->rng_seed_edit->setText(QStringLiteral("00000000"));
+ });
+
scene = new QGraphicsScene;
ui->current_user_icon->setScene(scene);
@@ -155,6 +161,13 @@ void ConfigureSystem::setConfiguration() {
PopulateUserList();
UpdateCurrentUser();
+
+ ui->rng_seed_checkbox->setChecked(Settings::values.rng_seed.has_value());
+ ui->rng_seed_edit->setEnabled(Settings::values.rng_seed.has_value());
+
+ const auto rng_seed =
+ QString("%1").arg(Settings::values.rng_seed.value_or(0), 8, 16, QLatin1Char{'0'}).toUpper();
+ ui->rng_seed_edit->setText(rng_seed);
}
void ConfigureSystem::PopulateUserList() {
@@ -195,6 +208,12 @@ void ConfigureSystem::applyConfiguration() {
return;
Settings::values.language_index = ui->combo_language->currentIndex();
+
+ if (ui->rng_seed_checkbox->isChecked())
+ Settings::values.rng_seed = ui->rng_seed_edit->text().toULongLong(nullptr, 16);
+ else
+ Settings::values.rng_seed = std::nullopt;
+
Settings::Apply();
}
@@ -240,7 +259,7 @@ void ConfigureSystem::RefreshConsoleID() {
void ConfigureSystem::SelectUser(const QModelIndex& index) {
Settings::values.current_user =
- std::clamp<std::size_t>(index.row(), 0, profile_manager->GetUserCount() - 1);
+ std::clamp<s32>(index.row(), 0, static_cast<s32>(profile_manager->GetUserCount() - 1));
UpdateCurrentUser();
diff --git a/src/yuzu/configuration/configure_system.ui b/src/yuzu/configuration/configure_system.ui
index 020b32a37..a91580893 100644
--- a/src/yuzu/configuration/configure_system.ui
+++ b/src/yuzu/configuration/configure_system.ui
@@ -6,7 +6,7 @@
<rect>
<x>0</x>
<y>0</y>
- <width>360</width>
+ <width>366</width>
<height>483</height>
</rect>
</property>
@@ -22,98 +22,6 @@
<string>System Settings</string>
</property>
<layout class="QGridLayout" name="gridLayout">
- <item row="1" column="0">
- <widget class="QLabel" name="label_language">
- <property name="text">
- <string>Language</string>
- </property>
- </widget>
- </item>
- <item row="0" column="0">
- <widget class="QLabel" name="label_birthday">
- <property name="text">
- <string>Birthday</string>
- </property>
- </widget>
- </item>
- <item row="3" column="0">
- <widget class="QLabel" name="label_console_id">
- <property name="text">
- <string>Console ID:</string>
- </property>
- </widget>
- </item>
- <item row="0" column="1">
- <layout class="QHBoxLayout" name="horizontalLayout_birthday2">
- <item>
- <widget class="QComboBox" name="combo_birthmonth">
- <item>
- <property name="text">
- <string>January</string>
- </property>
- </item>
- <item>
- <property name="text">
- <string>February</string>
- </property>
- </item>
- <item>
- <property name="text">
- <string>March</string>
- </property>
- </item>
- <item>
- <property name="text">
- <string>April</string>
- </property>
- </item>
- <item>
- <property name="text">
- <string>May</string>
- </property>
- </item>
- <item>
- <property name="text">
- <string>June</string>
- </property>
- </item>
- <item>
- <property name="text">
- <string>July</string>
- </property>
- </item>
- <item>
- <property name="text">
- <string>August</string>
- </property>
- </item>
- <item>
- <property name="text">
- <string>September</string>
- </property>
- </item>
- <item>
- <property name="text">
- <string>October</string>
- </property>
- </item>
- <item>
- <property name="text">
- <string>November</string>
- </property>
- </item>
- <item>
- <property name="text">
- <string>December</string>
- </property>
- </item>
- </widget>
- </item>
- <item>
- <widget class="QComboBox" name="combo_birthday"/>
- </item>
- </layout>
- </item>
<item row="1" column="1">
<widget class="QComboBox" name="combo_language">
<property name="toolTip">
@@ -206,6 +114,13 @@
</item>
</widget>
</item>
+ <item row="3" column="0">
+ <widget class="QLabel" name="label_console_id">
+ <property name="text">
+ <string>Console ID:</string>
+ </property>
+ </widget>
+ </item>
<item row="2" column="0">
<widget class="QLabel" name="label_sound">
<property name="text">
@@ -213,6 +128,100 @@
</property>
</widget>
</item>
+ <item row="0" column="0">
+ <widget class="QLabel" name="label_birthday">
+ <property name="text">
+ <string>Birthday</string>
+ </property>
+ </widget>
+ </item>
+ <item row="0" column="1">
+ <layout class="QHBoxLayout" name="horizontalLayout_birthday2">
+ <item>
+ <widget class="QComboBox" name="combo_birthmonth">
+ <item>
+ <property name="text">
+ <string>January</string>
+ </property>
+ </item>
+ <item>
+ <property name="text">
+ <string>February</string>
+ </property>
+ </item>
+ <item>
+ <property name="text">
+ <string>March</string>
+ </property>
+ </item>
+ <item>
+ <property name="text">
+ <string>April</string>
+ </property>
+ </item>
+ <item>
+ <property name="text">
+ <string>May</string>
+ </property>
+ </item>
+ <item>
+ <property name="text">
+ <string>June</string>
+ </property>
+ </item>
+ <item>
+ <property name="text">
+ <string>July</string>
+ </property>
+ </item>
+ <item>
+ <property name="text">
+ <string>August</string>
+ </property>
+ </item>
+ <item>
+ <property name="text">
+ <string>September</string>
+ </property>
+ </item>
+ <item>
+ <property name="text">
+ <string>October</string>
+ </property>
+ </item>
+ <item>
+ <property name="text">
+ <string>November</string>
+ </property>
+ </item>
+ <item>
+ <property name="text">
+ <string>December</string>
+ </property>
+ </item>
+ </widget>
+ </item>
+ <item>
+ <widget class="QComboBox" name="combo_birthday"/>
+ </item>
+ </layout>
+ </item>
+ <item row="3" column="1">
+ <widget class="QPushButton" name="button_regenerate_console_id">
+ <property name="sizePolicy">
+ <sizepolicy hsizetype="Fixed" vsizetype="Fixed">
+ <horstretch>0</horstretch>
+ <verstretch>0</verstretch>
+ </sizepolicy>
+ </property>
+ <property name="layoutDirection">
+ <enum>Qt::RightToLeft</enum>
+ </property>
+ <property name="text">
+ <string>Regenerate</string>
+ </property>
+ </widget>
+ </item>
<item row="2" column="1">
<widget class="QComboBox" name="combo_sound">
<item>
@@ -232,19 +241,38 @@
</item>
</widget>
</item>
- <item row="3" column="1">
- <widget class="QPushButton" name="button_regenerate_console_id">
+ <item row="1" column="0">
+ <widget class="QLabel" name="label_language">
+ <property name="text">
+ <string>Language</string>
+ </property>
+ </widget>
+ </item>
+ <item row="4" column="0">
+ <widget class="QCheckBox" name="rng_seed_checkbox">
+ <property name="text">
+ <string>RNG Seed</string>
+ </property>
+ </widget>
+ </item>
+ <item row="4" column="1">
+ <widget class="QLineEdit" name="rng_seed_edit">
<property name="sizePolicy">
- <sizepolicy hsizetype="Fixed" vsizetype="Fixed">
+ <sizepolicy hsizetype="Minimum" vsizetype="Fixed">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
- <property name="layoutDirection">
- <enum>Qt::RightToLeft</enum>
+ <property name="font">
+ <font>
+ <family>Lucida Console</family>
+ </font>
</property>
- <property name="text">
- <string>Regenerate</string>
+ <property name="inputMask">
+ <string notr="true">HHHHHHHH</string>
+ </property>
+ <property name="maxLength">
+ <number>8</number>
</property>
</widget>
</item>
diff --git a/src/yuzu/configuration/configure_touchscreen_advanced.cpp b/src/yuzu/configuration/configure_touchscreen_advanced.cpp
new file mode 100644
index 000000000..9c1561e9d
--- /dev/null
+++ b/src/yuzu/configuration/configure_touchscreen_advanced.cpp
@@ -0,0 +1,42 @@
+// Copyright 2016 Citra Emulator Project
+// Licensed under GPLv2 or any later version
+// Refer to the license.txt file included.
+
+#include <memory>
+#include "ui_configure_touchscreen_advanced.h"
+#include "yuzu/configuration/config.h"
+#include "yuzu/configuration/configure_touchscreen_advanced.h"
+
+ConfigureTouchscreenAdvanced::ConfigureTouchscreenAdvanced(QWidget* parent)
+ : QDialog(parent), ui(std::make_unique<Ui::ConfigureTouchscreenAdvanced>()) {
+ ui->setupUi(this);
+
+ connect(ui->restore_defaults_button, &QPushButton::pressed, this,
+ &ConfigureTouchscreenAdvanced::restoreDefaults);
+
+ loadConfiguration();
+ resize(0, 0);
+}
+
+ConfigureTouchscreenAdvanced::~ConfigureTouchscreenAdvanced() = default;
+
+void ConfigureTouchscreenAdvanced::applyConfiguration() {
+ Settings::values.touchscreen.finger = ui->finger_box->value();
+ Settings::values.touchscreen.diameter_x = ui->diameter_x_box->value();
+ Settings::values.touchscreen.diameter_y = ui->diameter_y_box->value();
+ Settings::values.touchscreen.rotation_angle = ui->angle_box->value();
+}
+
+void ConfigureTouchscreenAdvanced::loadConfiguration() {
+ ui->finger_box->setValue(Settings::values.touchscreen.finger);
+ ui->diameter_x_box->setValue(Settings::values.touchscreen.diameter_x);
+ ui->diameter_y_box->setValue(Settings::values.touchscreen.diameter_y);
+ ui->angle_box->setValue(Settings::values.touchscreen.rotation_angle);
+}
+
+void ConfigureTouchscreenAdvanced::restoreDefaults() {
+ ui->finger_box->setValue(0);
+ ui->diameter_x_box->setValue(15);
+ ui->diameter_y_box->setValue(15);
+ ui->angle_box->setValue(0);
+}
diff --git a/src/yuzu/configuration/configure_touchscreen_advanced.h b/src/yuzu/configuration/configure_touchscreen_advanced.h
new file mode 100644
index 000000000..41cd255fb
--- /dev/null
+++ b/src/yuzu/configuration/configure_touchscreen_advanced.h
@@ -0,0 +1,32 @@
+// Copyright 2016 Citra Emulator Project
+// Licensed under GPLv2 or any later version
+// Refer to the license.txt file included.
+
+#pragma once
+
+#include <memory>
+#include <QDialog>
+#include <QWidget>
+#include "yuzu/configuration/config.h"
+
+namespace Ui {
+class ConfigureTouchscreenAdvanced;
+}
+
+class ConfigureTouchscreenAdvanced : public QDialog {
+ Q_OBJECT
+
+public:
+ explicit ConfigureTouchscreenAdvanced(QWidget* parent);
+ ~ConfigureTouchscreenAdvanced() override;
+
+ void applyConfiguration();
+
+private:
+ /// Load configuration settings.
+ void loadConfiguration();
+ /// Restore all buttons to their default values.
+ void restoreDefaults();
+
+ std::unique_ptr<Ui::ConfigureTouchscreenAdvanced> ui;
+};
diff --git a/src/yuzu/configuration/configure_touchscreen_advanced.ui b/src/yuzu/configuration/configure_touchscreen_advanced.ui
new file mode 100644
index 000000000..1171c2dd1
--- /dev/null
+++ b/src/yuzu/configuration/configure_touchscreen_advanced.ui
@@ -0,0 +1,199 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ui version="4.0">
+ <class>ConfigureTouchscreenAdvanced</class>
+ <widget class="QDialog" name="ConfigureTouchscreenAdvanced">
+ <property name="geometry">
+ <rect>
+ <x>0</x>
+ <y>0</y>
+ <width>298</width>
+ <height>339</height>
+ </rect>
+ </property>
+ <property name="windowTitle">
+ <string>Configure Touchscreen</string>
+ </property>
+ <layout class="QVBoxLayout" name="verticalLayout">
+ <item>
+ <widget class="QLabel" name="label_2">
+ <property name="minimumSize">
+ <size>
+ <width>280</width>
+ <height>0</height>
+ </size>
+ </property>
+ <property name="text">
+ <string>Warning: The settings in this page affect the inner workings of yuzu's emulated touchscreen. Changing them may result in undesirable behavior, such as the touchscreen partially or not working. You should only use this page if you know what you are doing.</string>
+ </property>
+ <property name="wordWrap">
+ <bool>true</bool>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <spacer name="verticalSpacer_2">
+ <property name="orientation">
+ <enum>Qt::Vertical</enum>
+ </property>
+ <property name="sizeType">
+ <enum>QSizePolicy::Fixed</enum>
+ </property>
+ <property name="sizeHint" stdset="0">
+ <size>
+ <width>20</width>
+ <height>20</height>
+ </size>
+ </property>
+ </spacer>
+ </item>
+ <item>
+ <widget class="QGroupBox" name="gridGroupBox">
+ <property name="title">
+ <string>Touch Parameters</string>
+ </property>
+ <layout class="QGridLayout" name="gridLayout">
+ <item row="0" column="0">
+ <spacer name="horizontalSpacer">
+ <property name="orientation">
+ <enum>Qt::Horizontal</enum>
+ </property>
+ <property name="sizeHint" stdset="0">
+ <size>
+ <width>40</width>
+ <height>20</height>
+ </size>
+ </property>
+ </spacer>
+ </item>
+ <item row="2" column="1">
+ <widget class="QLabel" name="label_4">
+ <property name="text">
+ <string>Touch Diameter Y</string>
+ </property>
+ </widget>
+ </item>
+ <item row="0" column="1">
+ <widget class="QLabel" name="label">
+ <property name="text">
+ <string>Finger</string>
+ </property>
+ </widget>
+ </item>
+ <item row="0" column="3">
+ <spacer name="horizontalSpacer_2">
+ <property name="orientation">
+ <enum>Qt::Horizontal</enum>
+ </property>
+ <property name="sizeHint" stdset="0">
+ <size>
+ <width>40</width>
+ <height>20</height>
+ </size>
+ </property>
+ </spacer>
+ </item>
+ <item row="1" column="1">
+ <widget class="QLabel" name="label_3">
+ <property name="text">
+ <string>Touch Diameter X</string>
+ </property>
+ </widget>
+ </item>
+ <item row="0" column="2">
+ <widget class="QSpinBox" name="finger_box">
+ <property name="minimumSize">
+ <size>
+ <width>80</width>
+ <height>0</height>
+ </size>
+ </property>
+ </widget>
+ </item>
+ <item row="3" column="1">
+ <widget class="QLabel" name="label_5">
+ <property name="text">
+ <string>Rotational Angle</string>
+ </property>
+ </widget>
+ </item>
+ <item row="1" column="2">
+ <widget class="QSpinBox" name="diameter_x_box"/>
+ </item>
+ <item row="2" column="2">
+ <widget class="QSpinBox" name="diameter_y_box"/>
+ </item>
+ <item row="3" column="2">
+ <widget class="QSpinBox" name="angle_box"/>
+ </item>
+ </layout>
+ </widget>
+ </item>
+ <item>
+ <spacer name="verticalSpacer">
+ <property name="orientation">
+ <enum>Qt::Vertical</enum>
+ </property>
+ <property name="sizeHint" stdset="0">
+ <size>
+ <width>20</width>
+ <height>40</height>
+ </size>
+ </property>
+ </spacer>
+ </item>
+ <item>
+ <layout class="QHBoxLayout" name="horizontalLayout">
+ <item>
+ <widget class="QPushButton" name="restore_defaults_button">
+ <property name="text">
+ <string>Restore Defaults</string>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <widget class="QDialogButtonBox" name="buttonBox">
+ <property name="standardButtons">
+ <set>QDialogButtonBox::Cancel|QDialogButtonBox::Ok</set>
+ </property>
+ </widget>
+ </item>
+ </layout>
+ </item>
+ </layout>
+ </widget>
+ <resources/>
+ <connections>
+ <connection>
+ <sender>buttonBox</sender>
+ <signal>accepted()</signal>
+ <receiver>ConfigureTouchscreenAdvanced</receiver>
+ <slot>accept()</slot>
+ <hints>
+ <hint type="sourcelabel">
+ <x>140</x>
+ <y>318</y>
+ </hint>
+ <hint type="destinationlabel">
+ <x>140</x>
+ <y>169</y>
+ </hint>
+ </hints>
+ </connection>
+ <connection>
+ <sender>buttonBox</sender>
+ <signal>rejected()</signal>
+ <receiver>ConfigureTouchscreenAdvanced</receiver>
+ <slot>reject()</slot>
+ <hints>
+ <hint type="sourcelabel">
+ <x>140</x>
+ <y>318</y>
+ </hint>
+ <hint type="destinationlabel">
+ <x>140</x>
+ <y>169</y>
+ </hint>
+ </hints>
+ </connection>
+ </connections>
+</ui>
diff --git a/src/yuzu/debugger/graphics/graphics_surface.cpp b/src/yuzu/debugger/graphics/graphics_surface.cpp
index 0adbab27d..707747422 100644
--- a/src/yuzu/debugger/graphics/graphics_surface.cpp
+++ b/src/yuzu/debugger/graphics/graphics_surface.cpp
@@ -386,9 +386,9 @@ void GraphicsSurfaceWidget::OnUpdate() {
// TODO(bunnei): Will not work with BCn formats that swizzle 4x4 tiles.
// Needs to be fixed if we plan to use this feature more, otherwise we may remove it.
- auto unswizzled_data =
- Tegra::Texture::UnswizzleTexture(*address, 1, Tegra::Texture::BytesPerPixel(surface_format),
- surface_width, surface_height, 1U);
+ auto unswizzled_data = Tegra::Texture::UnswizzleTexture(
+ *address, 1, 1, Tegra::Texture::BytesPerPixel(surface_format), surface_width,
+ surface_height, 1U);
auto texture_data = Tegra::Texture::DecodeTexture(unswizzled_data, surface_format,
surface_width, surface_height);
diff --git a/src/yuzu/game_list.cpp b/src/yuzu/game_list.cpp
index a5a4aa432..11a8c390b 100644
--- a/src/yuzu/game_list.cpp
+++ b/src/yuzu/game_list.cpp
@@ -215,12 +215,18 @@ GameList::GameList(FileSys::VirtualFilesystem vfs, GMainWindow* parent)
tree_view->setUniformRowHeights(true);
tree_view->setContextMenuPolicy(Qt::CustomContextMenu);
- item_model->insertColumns(0, COLUMN_COUNT);
+ item_model->insertColumns(0, UISettings::values.show_add_ons ? COLUMN_COUNT : COLUMN_COUNT - 1);
item_model->setHeaderData(COLUMN_NAME, Qt::Horizontal, tr("Name"));
item_model->setHeaderData(COLUMN_COMPATIBILITY, Qt::Horizontal, tr("Compatibility"));
- item_model->setHeaderData(COLUMN_ADD_ONS, Qt::Horizontal, tr("Add-ons"));
- item_model->setHeaderData(COLUMN_FILE_TYPE, Qt::Horizontal, tr("File type"));
- item_model->setHeaderData(COLUMN_SIZE, Qt::Horizontal, tr("Size"));
+
+ if (UISettings::values.show_add_ons) {
+ item_model->setHeaderData(COLUMN_ADD_ONS, Qt::Horizontal, tr("Add-ons"));
+ item_model->setHeaderData(COLUMN_FILE_TYPE, Qt::Horizontal, tr("File type"));
+ item_model->setHeaderData(COLUMN_SIZE, Qt::Horizontal, tr("Size"));
+ } else {
+ item_model->setHeaderData(COLUMN_FILE_TYPE - 1, Qt::Horizontal, tr("File type"));
+ item_model->setHeaderData(COLUMN_SIZE - 1, Qt::Horizontal, tr("Size"));
+ }
connect(tree_view, &QTreeView::activated, this, &GameList::ValidateEntry);
connect(tree_view, &QTreeView::customContextMenuRequested, this, &GameList::PopupContextMenu);
@@ -394,6 +400,25 @@ void GameList::PopulateAsync(const QString& dir_path, bool deep_scan) {
}
tree_view->setEnabled(false);
+
+ // Update the columns in case UISettings has changed
+ item_model->removeColumns(0, item_model->columnCount());
+ item_model->insertColumns(0, UISettings::values.show_add_ons ? COLUMN_COUNT : COLUMN_COUNT - 1);
+ item_model->setHeaderData(COLUMN_NAME, Qt::Horizontal, tr("Name"));
+ item_model->setHeaderData(COLUMN_COMPATIBILITY, Qt::Horizontal, tr("Compatibility"));
+
+ if (UISettings::values.show_add_ons) {
+ item_model->setHeaderData(COLUMN_ADD_ONS, Qt::Horizontal, tr("Add-ons"));
+ item_model->setHeaderData(COLUMN_FILE_TYPE, Qt::Horizontal, tr("File type"));
+ item_model->setHeaderData(COLUMN_SIZE, Qt::Horizontal, tr("Size"));
+ } else {
+ item_model->setHeaderData(COLUMN_FILE_TYPE - 1, Qt::Horizontal, tr("File type"));
+ item_model->setHeaderData(COLUMN_SIZE - 1, Qt::Horizontal, tr("Size"));
+ item_model->removeColumns(COLUMN_COUNT - 1, 1);
+ }
+
+ LoadInterfaceLayout();
+
// Delete any rows that might already exist if we're repopulating
item_model->removeRows(0, item_model->rowCount());
diff --git a/src/yuzu/game_list_worker.cpp b/src/yuzu/game_list_worker.cpp
index 3d865a12d..362902e46 100644
--- a/src/yuzu/game_list_worker.cpp
+++ b/src/yuzu/game_list_worker.cpp
@@ -123,17 +123,22 @@ void GameListWorker::AddInstalledTitlesToGameList() {
if (it != compatibility_list.end())
compatibility = it->second.first;
- emit EntryReady({
+ QList<QStandardItem*> list{
new GameListItemPath(
FormatGameName(file->GetFullPath()), icon, QString::fromStdString(name),
QString::fromStdString(Loader::GetFileTypeString(loader->GetFileType())),
program_id),
new GameListItemCompat(compatibility),
- new GameListItem(FormatPatchNameVersions(patch, *loader)),
new GameListItem(
QString::fromStdString(Loader::GetFileTypeString(loader->GetFileType()))),
new GameListItemSize(file->GetSize()),
- });
+ };
+
+ if (UISettings::values.show_add_ons) {
+ list.insert(2, new GameListItem(FormatPatchNameVersions(patch, *loader)));
+ }
+
+ emit EntryReady(list);
}
const auto control_data = cache->ListEntriesFilter(FileSys::TitleType::Application,
@@ -216,18 +221,23 @@ void GameListWorker::AddFstEntriesToGameList(const std::string& dir_path, unsign
if (it != compatibility_list.end())
compatibility = it->second.first;
- emit EntryReady({
+ QList<QStandardItem*> list{
new GameListItemPath(
FormatGameName(physical_name), icon, QString::fromStdString(name),
QString::fromStdString(Loader::GetFileTypeString(loader->GetFileType())),
program_id),
new GameListItemCompat(compatibility),
new GameListItem(
- FormatPatchNameVersions(patch, *loader, loader->IsRomFSUpdatable())),
- new GameListItem(
QString::fromStdString(Loader::GetFileTypeString(loader->GetFileType()))),
new GameListItemSize(FileUtil::GetSize(physical_name)),
- });
+ };
+
+ if (UISettings::values.show_add_ons) {
+ list.insert(2, new GameListItem(FormatPatchNameVersions(
+ patch, *loader, loader->IsRomFSUpdatable())));
+ }
+
+ emit EntryReady(std::move(list));
} else if (is_dir && recursion > 0) {
watch_list.append(QString::fromStdString(physical_name));
AddFstEntriesToGameList(physical_name, recursion - 1);
diff --git a/src/yuzu/main.cpp b/src/yuzu/main.cpp
index c5a56cbfd..9c6d150a5 100644
--- a/src/yuzu/main.cpp
+++ b/src/yuzu/main.cpp
@@ -8,11 +8,13 @@
#include <thread>
// VFS includes must be before glad as they will conflict with Windows file api, which uses defines.
+#include "applets/software_keyboard.h"
#include "core/file_sys/vfs.h"
#include "core/file_sys/vfs_real.h"
#include "core/hle/service/acc/profile_manager.h"
+#include "core/hle/service/am/applets/applets.h"
-// These are wrappers to avoid the calls to CreateDirectory and CreateFile becuase of the Windows
+// These are wrappers to avoid the calls to CreateDirectory and CreateFile because of the Windows
// defines.
static FileSys::VirtualDir VfsFilesystemCreateDirectoryWrapper(
const FileSys::VirtualFilesystem& vfs, const std::string& path, FileSys::Mode mode) {
@@ -59,6 +61,7 @@ static FileSys::VirtualFile VfsDirectoryCreateFileWrapper(const FileSys::Virtual
#include "core/file_sys/romfs.h"
#include "core/file_sys/savedata_factory.h"
#include "core/file_sys/submission_package.h"
+#include "core/frontend/applets/software_keyboard.h"
#include "core/hle/kernel/process.h"
#include "core/hle/service/filesystem/filesystem.h"
#include "core/hle/service/filesystem/fsp_ldr.h"
@@ -142,6 +145,9 @@ static void InitializeLogging() {
const std::string& log_dir = FileUtil::GetUserPath(FileUtil::UserPath::LogDir);
FileUtil::CreateFullPath(log_dir);
Log::AddBackend(std::make_unique<Log::FileBackend>(log_dir + LOG_FILE));
+#ifdef _WIN32
+ Log::AddBackend(std::make_unique<Log::DebuggerBackend>());
+#endif
}
GMainWindow::GMainWindow()
@@ -201,6 +207,27 @@ GMainWindow::~GMainWindow() {
delete render_window;
}
+void GMainWindow::SoftwareKeyboardGetText(
+ const Core::Frontend::SoftwareKeyboardParameters& parameters) {
+ QtSoftwareKeyboardDialog dialog(this, parameters);
+ dialog.setWindowFlags(Qt::Dialog | Qt::CustomizeWindowHint | Qt::WindowTitleHint |
+ Qt::WindowSystemMenuHint | Qt::WindowCloseButtonHint);
+ dialog.setWindowModality(Qt::WindowModal);
+ dialog.exec();
+
+ if (!dialog.GetStatus()) {
+ emit SoftwareKeyboardFinishedText(std::nullopt);
+ return;
+ }
+
+ emit SoftwareKeyboardFinishedText(dialog.GetText());
+}
+
+void GMainWindow::SoftwareKeyboardInvokeCheckDialog(std::u16string error_message) {
+ QMessageBox::warning(this, tr("Text Check Failed"), QString::fromStdU16String(error_message));
+ emit SoftwareKeyboardFinishedCheckDialog();
+}
+
void GMainWindow::InitializeWidgets() {
#ifdef YUZU_ENABLE_COMPATIBILITY_REPORTING
ui.action_Report_Compatibility->setVisible(true);
@@ -305,6 +332,8 @@ void GMainWindow::InitializeHotkeys() {
Qt::ApplicationShortcut);
hotkey_registry.RegisterHotkey("Main Window", "Decrease Speed Limit", QKeySequence("-"),
Qt::ApplicationShortcut);
+ hotkey_registry.RegisterHotkey("Main Window", "Load Amiibo", QKeySequence(Qt::Key_F2),
+ Qt::ApplicationShortcut);
hotkey_registry.LoadHotkeys();
connect(hotkey_registry.GetHotkey("Main Window", "Load File", this), &QShortcut::activated,
@@ -358,6 +387,12 @@ void GMainWindow::InitializeHotkeys() {
UpdateStatusBar();
}
});
+ connect(hotkey_registry.GetHotkey("Main Window", "Load Amiibo", this), &QShortcut::activated,
+ this, [&] {
+ if (ui.action_Load_Amiibo->isEnabled()) {
+ OnLoadAmiibo();
+ }
+ });
}
void GMainWindow::SetDefaultUIGeometry() {
@@ -454,6 +489,7 @@ void GMainWindow::ConnectMenuEvents() {
connect(ui.action_Fullscreen, &QAction::triggered, this, &GMainWindow::ToggleFullscreen);
// Help
+ connect(ui.action_Open_yuzu_Folder, &QAction::triggered, this, &GMainWindow::OnOpenYuzuFolder);
connect(ui.action_Rederive, &QAction::triggered, this,
std::bind(&GMainWindow::OnReinitializeKeys, this, ReinitializeKeyBehavior::Warning));
connect(ui.action_About, &QAction::triggered, this, &GMainWindow::OnAbout);
@@ -482,32 +518,18 @@ void GMainWindow::OnDisplayTitleBars(bool show) {
QStringList GMainWindow::GetUnsupportedGLExtensions() {
QStringList unsupported_ext;
- if (!GLAD_GL_ARB_program_interface_query)
- unsupported_ext.append("ARB_program_interface_query");
- if (!GLAD_GL_ARB_separate_shader_objects)
- unsupported_ext.append("ARB_separate_shader_objects");
- if (!GLAD_GL_ARB_vertex_attrib_binding)
- unsupported_ext.append("ARB_vertex_attrib_binding");
if (!GLAD_GL_ARB_vertex_type_10f_11f_11f_rev)
unsupported_ext.append("ARB_vertex_type_10f_11f_11f_rev");
if (!GLAD_GL_ARB_texture_mirror_clamp_to_edge)
unsupported_ext.append("ARB_texture_mirror_clamp_to_edge");
- if (!GLAD_GL_ARB_base_instance)
- unsupported_ext.append("ARB_base_instance");
- if (!GLAD_GL_ARB_texture_storage)
- unsupported_ext.append("ARB_texture_storage");
if (!GLAD_GL_ARB_multi_bind)
unsupported_ext.append("ARB_multi_bind");
- if (!GLAD_GL_ARB_copy_image)
- unsupported_ext.append("ARB_copy_image");
// Extensions required to support some texture formats.
if (!GLAD_GL_EXT_texture_compression_s3tc)
unsupported_ext.append("EXT_texture_compression_s3tc");
if (!GLAD_GL_ARB_texture_compression_rgtc)
unsupported_ext.append("ARB_texture_compression_rgtc");
- if (!GLAD_GL_ARB_texture_compression_bptc)
- unsupported_ext.append("ARB_texture_compression_bptc");
if (!GLAD_GL_ARB_depth_buffer_float)
unsupported_ext.append("ARB_depth_buffer_float");
@@ -526,8 +548,8 @@ bool GMainWindow::LoadROM(const QString& filename) {
render_window->MakeCurrent();
if (!gladLoadGL()) {
- QMessageBox::critical(this, tr("Error while initializing OpenGL 3.3 Core!"),
- tr("Your GPU may not support OpenGL 3.3, or you do not "
+ QMessageBox::critical(this, tr("Error while initializing OpenGL 4.3 Core!"),
+ tr("Your GPU may not support OpenGL 4.3, or you do not "
"have the latest graphics driver."));
return false;
}
@@ -547,6 +569,8 @@ bool GMainWindow::LoadROM(const QString& filename) {
system.SetGPUDebugContext(debug_context);
+ system.SetSoftwareKeyboard(std::make_unique<QtSoftwareKeyboard>(*this));
+
const Core::System::ResultStatus result{system.Load(*render_window, filename.toStdString())};
const auto drd_callout =
@@ -929,7 +953,8 @@ void GMainWindow::OnGameListDumpRomFS(u64 program_id, const std::string& game_pa
const auto full = res == "Full";
const auto entry_size = CalculateRomFSEntrySize(extracted, full);
- QProgressDialog progress(tr("Extracting RomFS..."), tr("Cancel"), 0, entry_size, this);
+ QProgressDialog progress(tr("Extracting RomFS..."), tr("Cancel"), 0,
+ static_cast<s32>(entry_size), this);
progress.setWindowModality(Qt::WindowModal);
progress.setMinimumDuration(100);
@@ -1215,8 +1240,13 @@ void GMainWindow::OnMenuRecentFile() {
void GMainWindow::OnStartGame() {
emu_thread->SetRunning(true);
+
+ qRegisterMetaType<Core::Frontend::SoftwareKeyboardParameters>(
+ "Core::Frontend::SoftwareKeyboardParameters");
qRegisterMetaType<Core::System::ResultStatus>("Core::System::ResultStatus");
qRegisterMetaType<std::string>("std::string");
+ qRegisterMetaType<std::optional<std::u16string>>("std::optional<std::u16string>");
+
connect(emu_thread.get(), &EmuThread::ErrorThrown, this, &GMainWindow::OnCoreError);
ui.action_Start->setEnabled(false);
@@ -1328,7 +1358,13 @@ void GMainWindow::OnConfigure() {
UpdateUITheme();
if (UISettings::values.enable_discord_presence != old_discord_presence)
SetDiscordEnabled(UISettings::values.enable_discord_presence);
- game_list->PopulateAsync(UISettings::values.gamedir, UISettings::values.gamedir_deepscan);
+
+ const auto reload = UISettings::values.is_game_list_reload_pending.exchange(false);
+ if (reload) {
+ game_list->PopulateAsync(UISettings::values.gamedir,
+ UISettings::values.gamedir_deepscan);
+ }
+
config->Save();
}
}
@@ -1374,6 +1410,11 @@ void GMainWindow::OnLoadAmiibo() {
}
}
+void GMainWindow::OnOpenYuzuFolder() {
+ QDesktopServices::openUrl(QUrl::fromLocalFile(
+ QString::fromStdString(FileUtil::GetUserPath(FileUtil::UserPath::UserDir))));
+}
+
void GMainWindow::OnAbout() {
AboutDialog aboutDialog(this);
aboutDialog.exec();
@@ -1532,7 +1573,7 @@ void GMainWindow::OnReinitializeKeys(ReinitializeKeyBehavior behavior) {
"derivation. It will be attempted but may not complete.<br><br>") +
errors +
tr("<br><br>You can get all of these and dump all of your games easily by "
- "following <a href='https://yuzu-emu.org/help/quickstart/quickstart/'>the "
+ "following <a href='https://yuzu-emu.org/help/quickstart/'>the "
"quickstart guide</a>. Alternatively, you can use another method of dumping "
"to obtain all of your keys."));
}
@@ -1612,7 +1653,7 @@ void GMainWindow::closeEvent(QCloseEvent* event) {
return;
}
- if (ui.action_Fullscreen->isChecked()) {
+ if (!ui.action_Fullscreen->isChecked()) {
UISettings::values.geometry = saveGeometry();
UISettings::values.renderwindow_geometry = render_window->saveGeometry();
}
diff --git a/src/yuzu/main.h b/src/yuzu/main.h
index af637d89e..674e73412 100644
--- a/src/yuzu/main.h
+++ b/src/yuzu/main.h
@@ -29,6 +29,10 @@ class ProfilerWidget;
class WaitTreeWidget;
enum class GameListOpenTarget;
+namespace Core::Frontend {
+struct SoftwareKeyboardParameters;
+} // namespace Core::Frontend
+
namespace FileSys {
class RegisteredCacheUnion;
class VfsFilesystem;
@@ -95,6 +99,13 @@ signals:
// Signal that tells widgets to update icons to use the current theme
void UpdateThemedIcons();
+ void SoftwareKeyboardFinishedText(std::optional<std::u16string> text);
+ void SoftwareKeyboardFinishedCheckDialog();
+
+public slots:
+ void SoftwareKeyboardGetText(const Core::Frontend::SoftwareKeyboardParameters& parameters);
+ void SoftwareKeyboardInvokeCheckDialog(std::u16string error_message);
+
private:
void InitializeWidgets();
void InitializeDebugWidgets();
@@ -167,6 +178,7 @@ private slots:
void OnMenuRecentFile();
void OnConfigure();
void OnLoadAmiibo();
+ void OnOpenYuzuFolder();
void OnAbout();
void OnToggleFilterBar();
void OnDisplayTitleBars(bool);
diff --git a/src/yuzu/main.ui b/src/yuzu/main.ui
index 48d099591..75e96387f 100644
--- a/src/yuzu/main.ui
+++ b/src/yuzu/main.ui
@@ -70,6 +70,8 @@
<addaction name="separator"/>
<addaction name="action_Load_Amiibo"/>
<addaction name="separator"/>
+ <addaction name="action_Open_yuzu_Folder"/>
+ <addaction name="separator"/>
<addaction name="action_Exit"/>
</widget>
<widget class="QMenu" name="menu_Emulation">
@@ -277,6 +279,11 @@
<bool>false</bool>
</property>
</action>
+ <action name="action_Open_yuzu_Folder">
+ <property name="text">
+ <string>Open yuzu Folder</string>
+ </property>
+ </action>
</widget>
<resources/>
<connections/>
diff --git a/src/yuzu/ui_settings.h b/src/yuzu/ui_settings.h
index 2e617d52a..e80aebc0a 100644
--- a/src/yuzu/ui_settings.h
+++ b/src/yuzu/ui_settings.h
@@ -5,6 +5,7 @@
#pragma once
#include <array>
+#include <atomic>
#include <vector>
#include <QByteArray>
#include <QString>
@@ -59,9 +60,11 @@ struct Values {
// Game List
bool show_unknown;
+ bool show_add_ons;
uint32_t icon_size;
uint8_t row_1_text_id;
uint8_t row_2_text_id;
+ std::atomic_bool is_game_list_reload_pending{false};
};
extern Values values;
diff --git a/src/yuzu_cmd/config.cpp b/src/yuzu_cmd/config.cpp
index b456266a6..097c1fbe3 100644
--- a/src/yuzu_cmd/config.cpp
+++ b/src/yuzu_cmd/config.cpp
@@ -65,30 +65,271 @@ static const std::array<std::array<int, 5>, Settings::NativeAnalog::NumAnalogs>
},
}};
+static const std::array<int, Settings::NativeMouseButton::NumMouseButtons> default_mouse_buttons = {
+ SDL_SCANCODE_LEFTBRACKET, SDL_SCANCODE_RIGHTBRACKET, SDL_SCANCODE_APOSTROPHE,
+ SDL_SCANCODE_MINUS, SDL_SCANCODE_EQUALS,
+};
+
+static const std::array<int, 0x8A> keyboard_keys = {
+ 0,
+ 0,
+ 0,
+ 0,
+ SDL_SCANCODE_A,
+ SDL_SCANCODE_B,
+ SDL_SCANCODE_C,
+ SDL_SCANCODE_D,
+ SDL_SCANCODE_E,
+ SDL_SCANCODE_F,
+ SDL_SCANCODE_G,
+ SDL_SCANCODE_H,
+ SDL_SCANCODE_I,
+ SDL_SCANCODE_J,
+ SDL_SCANCODE_K,
+ SDL_SCANCODE_L,
+ SDL_SCANCODE_M,
+ SDL_SCANCODE_N,
+ SDL_SCANCODE_O,
+ SDL_SCANCODE_P,
+ SDL_SCANCODE_Q,
+ SDL_SCANCODE_R,
+ SDL_SCANCODE_S,
+ SDL_SCANCODE_T,
+ SDL_SCANCODE_U,
+ SDL_SCANCODE_V,
+ SDL_SCANCODE_W,
+ SDL_SCANCODE_X,
+ SDL_SCANCODE_Y,
+ SDL_SCANCODE_Z,
+ SDL_SCANCODE_1,
+ SDL_SCANCODE_2,
+ SDL_SCANCODE_3,
+ SDL_SCANCODE_4,
+ SDL_SCANCODE_5,
+ SDL_SCANCODE_6,
+ SDL_SCANCODE_7,
+ SDL_SCANCODE_8,
+ SDL_SCANCODE_9,
+ SDL_SCANCODE_0,
+ SDL_SCANCODE_RETURN,
+ SDL_SCANCODE_ESCAPE,
+ SDL_SCANCODE_BACKSPACE,
+ SDL_SCANCODE_TAB,
+ SDL_SCANCODE_SPACE,
+ SDL_SCANCODE_MINUS,
+ SDL_SCANCODE_EQUALS,
+ SDL_SCANCODE_LEFTBRACKET,
+ SDL_SCANCODE_RIGHTBRACKET,
+ SDL_SCANCODE_BACKSLASH,
+ 0,
+ SDL_SCANCODE_SEMICOLON,
+ SDL_SCANCODE_APOSTROPHE,
+ SDL_SCANCODE_GRAVE,
+ SDL_SCANCODE_COMMA,
+ SDL_SCANCODE_PERIOD,
+ SDL_SCANCODE_SLASH,
+ SDL_SCANCODE_CAPSLOCK,
+
+ SDL_SCANCODE_F1,
+ SDL_SCANCODE_F2,
+ SDL_SCANCODE_F3,
+ SDL_SCANCODE_F4,
+ SDL_SCANCODE_F5,
+ SDL_SCANCODE_F6,
+ SDL_SCANCODE_F7,
+ SDL_SCANCODE_F8,
+ SDL_SCANCODE_F9,
+ SDL_SCANCODE_F10,
+ SDL_SCANCODE_F11,
+ SDL_SCANCODE_F12,
+
+ 0,
+ SDL_SCANCODE_SCROLLLOCK,
+ SDL_SCANCODE_PAUSE,
+ SDL_SCANCODE_INSERT,
+ SDL_SCANCODE_HOME,
+ SDL_SCANCODE_PAGEUP,
+ SDL_SCANCODE_DELETE,
+ SDL_SCANCODE_END,
+ SDL_SCANCODE_PAGEDOWN,
+ SDL_SCANCODE_RIGHT,
+ SDL_SCANCODE_LEFT,
+ SDL_SCANCODE_DOWN,
+ SDL_SCANCODE_UP,
+
+ SDL_SCANCODE_NUMLOCKCLEAR,
+ SDL_SCANCODE_KP_DIVIDE,
+ SDL_SCANCODE_KP_MULTIPLY,
+ SDL_SCANCODE_KP_MINUS,
+ SDL_SCANCODE_KP_PLUS,
+ SDL_SCANCODE_KP_ENTER,
+ SDL_SCANCODE_KP_1,
+ SDL_SCANCODE_KP_2,
+ SDL_SCANCODE_KP_3,
+ SDL_SCANCODE_KP_4,
+ SDL_SCANCODE_KP_5,
+ SDL_SCANCODE_KP_6,
+ SDL_SCANCODE_KP_7,
+ SDL_SCANCODE_KP_8,
+ SDL_SCANCODE_KP_9,
+ SDL_SCANCODE_KP_0,
+ SDL_SCANCODE_KP_PERIOD,
+
+ 0,
+ 0,
+ SDL_SCANCODE_POWER,
+ SDL_SCANCODE_KP_EQUALS,
+
+ SDL_SCANCODE_F13,
+ SDL_SCANCODE_F14,
+ SDL_SCANCODE_F15,
+ SDL_SCANCODE_F16,
+ SDL_SCANCODE_F17,
+ SDL_SCANCODE_F18,
+ SDL_SCANCODE_F19,
+ SDL_SCANCODE_F20,
+ SDL_SCANCODE_F21,
+ SDL_SCANCODE_F22,
+ SDL_SCANCODE_F23,
+ SDL_SCANCODE_F24,
+
+ 0,
+ SDL_SCANCODE_HELP,
+ SDL_SCANCODE_MENU,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ SDL_SCANCODE_KP_COMMA,
+ SDL_SCANCODE_KP_LEFTPAREN,
+ SDL_SCANCODE_KP_RIGHTPAREN,
+ 0,
+ 0,
+ 0,
+ 0,
+};
+
+static const std::array<int, 8> keyboard_mods{
+ SDL_SCANCODE_LCTRL, SDL_SCANCODE_LSHIFT, SDL_SCANCODE_LALT, SDL_SCANCODE_LGUI,
+ SDL_SCANCODE_RCTRL, SDL_SCANCODE_RSHIFT, SDL_SCANCODE_RALT, SDL_SCANCODE_RGUI,
+};
+
void Config::ReadValues() {
// Controls
+ for (std::size_t p = 0; p < Settings::values.players.size(); ++p) {
+ const auto group = fmt::format("ControlsP{}", p);
+ for (int i = 0; i < Settings::NativeButton::NumButtons; ++i) {
+ std::string default_param = InputCommon::GenerateKeyboardParam(default_buttons[i]);
+ Settings::values.players[p].buttons[i] =
+ sdl2_config->Get(group, Settings::NativeButton::mapping[i], default_param);
+ if (Settings::values.players[p].buttons[i].empty())
+ Settings::values.players[p].buttons[i] = default_param;
+ }
+
+ for (int i = 0; i < Settings::NativeAnalog::NumAnalogs; ++i) {
+ std::string default_param = InputCommon::GenerateAnalogParamFromKeys(
+ default_analogs[i][0], default_analogs[i][1], default_analogs[i][2],
+ default_analogs[i][3], default_analogs[i][4], 0.5f);
+ Settings::values.players[p].analogs[i] =
+ sdl2_config->Get(group, Settings::NativeAnalog::mapping[i], default_param);
+ if (Settings::values.players[p].analogs[i].empty())
+ Settings::values.players[p].analogs[i] = default_param;
+ }
+ }
+
+ Settings::values.mouse_enabled =
+ sdl2_config->GetBoolean("ControlsGeneral", "mouse_enabled", false);
+ for (int i = 0; i < Settings::NativeMouseButton::NumMouseButtons; ++i) {
+ std::string default_param = InputCommon::GenerateKeyboardParam(default_mouse_buttons[i]);
+ Settings::values.mouse_buttons[i] = sdl2_config->Get(
+ "ControlsGeneral", std::string("mouse_") + Settings::NativeMouseButton::mapping[i],
+ default_param);
+ if (Settings::values.mouse_buttons[i].empty())
+ Settings::values.mouse_buttons[i] = default_param;
+ }
+
+ Settings::values.motion_device = sdl2_config->Get(
+ "ControlsGeneral", "motion_device", "engine:motion_emu,update_period:100,sensitivity:0.01");
+
+ Settings::values.keyboard_enabled =
+ sdl2_config->GetBoolean("ControlsGeneral", "keyboard_enabled", false);
+
+ Settings::values.debug_pad_enabled =
+ sdl2_config->GetBoolean("ControlsGeneral", "debug_pad_enabled", false);
for (int i = 0; i < Settings::NativeButton::NumButtons; ++i) {
std::string default_param = InputCommon::GenerateKeyboardParam(default_buttons[i]);
- Settings::values.buttons[i] =
- sdl2_config->Get("Controls", Settings::NativeButton::mapping[i], default_param);
- if (Settings::values.buttons[i].empty())
- Settings::values.buttons[i] = default_param;
+ Settings::values.debug_pad_buttons[i] = sdl2_config->Get(
+ "ControlsGeneral", std::string("debug_pad_") + Settings::NativeButton::mapping[i],
+ default_param);
+ if (Settings::values.debug_pad_buttons[i].empty())
+ Settings::values.debug_pad_buttons[i] = default_param;
}
for (int i = 0; i < Settings::NativeAnalog::NumAnalogs; ++i) {
std::string default_param = InputCommon::GenerateAnalogParamFromKeys(
default_analogs[i][0], default_analogs[i][1], default_analogs[i][2],
default_analogs[i][3], default_analogs[i][4], 0.5f);
- Settings::values.analogs[i] =
- sdl2_config->Get("Controls", Settings::NativeAnalog::mapping[i], default_param);
- if (Settings::values.analogs[i].empty())
- Settings::values.analogs[i] = default_param;
+ Settings::values.debug_pad_analogs[i] = sdl2_config->Get(
+ "ControlsGeneral", std::string("debug_pad_") + Settings::NativeAnalog::mapping[i],
+ default_param);
+ if (Settings::values.debug_pad_analogs[i].empty())
+ Settings::values.debug_pad_analogs[i] = default_param;
}
- Settings::values.motion_device = sdl2_config->Get(
- "Controls", "motion_device", "engine:motion_emu,update_period:100,sensitivity:0.01");
- Settings::values.touch_device =
- sdl2_config->Get("Controls", "touch_device", "engine:emu_window");
+ Settings::values.touchscreen.enabled =
+ sdl2_config->GetBoolean("ControlsGeneral", "touch_enabled", true);
+ Settings::values.touchscreen.device =
+ sdl2_config->Get("ControlsGeneral", "touch_device", "engine:emu_window");
+ Settings::values.touchscreen.finger =
+ sdl2_config->GetInteger("ControlsGeneral", "touch_finger", 0);
+ Settings::values.touchscreen.rotation_angle =
+ sdl2_config->GetInteger("ControlsGeneral", "touch_angle", 0);
+ Settings::values.touchscreen.diameter_x =
+ sdl2_config->GetInteger("ControlsGeneral", "touch_diameter_x", 15);
+ Settings::values.touchscreen.diameter_y =
+ sdl2_config->GetInteger("ControlsGeneral", "touch_diameter_y", 15);
+
+ std::transform(keyboard_keys.begin(), keyboard_keys.end(),
+ Settings::values.keyboard_keys.begin(), InputCommon::GenerateKeyboardParam);
+ std::transform(keyboard_mods.begin(), keyboard_mods.end(),
+ Settings::values.keyboard_keys.begin() +
+ Settings::NativeKeyboard::LeftControlKey,
+ InputCommon::GenerateKeyboardParam);
+ std::transform(keyboard_mods.begin(), keyboard_mods.end(),
+ Settings::values.keyboard_mods.begin(), InputCommon::GenerateKeyboardParam);
+
+ // Data Storage
+ Settings::values.use_virtual_sd =
+ sdl2_config->GetBoolean("Data Storage", "use_virtual_sd", true);
+ FileUtil::GetUserPath(FileUtil::UserPath::NANDDir,
+ sdl2_config->Get("Data Storage", "nand_directory",
+ FileUtil::GetUserPath(FileUtil::UserPath::NANDDir)));
+ FileUtil::GetUserPath(FileUtil::UserPath::SDMCDir,
+ sdl2_config->Get("Data Storage", "sdmc_directory",
+ FileUtil::GetUserPath(FileUtil::UserPath::SDMCDir)));
+
+ // System
+ Settings::values.use_docked_mode = sdl2_config->GetBoolean("System", "use_docked_mode", false);
+ Settings::values.enable_nfc = sdl2_config->GetBoolean("System", "enable_nfc", true);
+ const auto size = sdl2_config->GetInteger("System", "users_size", 0);
+
+ Settings::values.current_user = std::clamp<int>(
+ sdl2_config->GetInteger("System", "current_user", 0), 0, Service::Account::MAX_USERS - 1);
+
+ const auto enabled = sdl2_config->GetBoolean("System", "rng_seed_enabled", false);
+ if (enabled) {
+ Settings::values.rng_seed = sdl2_config->GetInteger("System", "rng_seed", 0);
+ } else {
+ Settings::values.rng_seed = std::nullopt;
+ }
// Core
Settings::values.use_cpu_jit = sdl2_config->GetBoolean("Core", "use_cpu_jit", true);
@@ -114,23 +355,7 @@ void Config::ReadValues() {
Settings::values.audio_device_id = sdl2_config->Get("Audio", "output_device", "auto");
Settings::values.volume = sdl2_config->GetReal("Audio", "volume", 1);
- // Data Storage
- Settings::values.use_virtual_sd =
- sdl2_config->GetBoolean("Data Storage", "use_virtual_sd", true);
- FileUtil::GetUserPath(FileUtil::UserPath::NANDDir,
- sdl2_config->Get("Data Storage", "nand_directory",
- FileUtil::GetUserPath(FileUtil::UserPath::NANDDir)));
- FileUtil::GetUserPath(FileUtil::UserPath::SDMCDir,
- sdl2_config->Get("Data Storage", "sdmc_directory",
- FileUtil::GetUserPath(FileUtil::UserPath::SDMCDir)));
-
- // System
- Settings::values.use_docked_mode = sdl2_config->GetBoolean("System", "use_docked_mode", false);
- Settings::values.enable_nfc = sdl2_config->GetBoolean("System", "enable_nfc", true);
- const auto size = sdl2_config->GetInteger("System", "users_size", 0);
-
- Settings::values.current_user = std::clamp<int>(
- sdl2_config->GetInteger("System", "current_user", 0), 0, Service::Account::MAX_USERS - 1);
+ Settings::values.language_index = sdl2_config->GetInteger("System", "language_index", 1);
// Miscellaneous
Settings::values.log_filter = sdl2_config->Get("Miscellaneous", "log_filter", "*:Trace");
@@ -141,6 +366,8 @@ void Config::ReadValues() {
Settings::values.gdbstub_port =
static_cast<u16>(sdl2_config->GetInteger("Debugging", "gdbstub_port", 24689));
Settings::values.program_args = sdl2_config->Get("Debugging", "program_args", "");
+ Settings::values.dump_exefs = sdl2_config->GetBoolean("Debugging", "dump_exefs", false);
+ Settings::values.dump_nso = sdl2_config->GetBoolean("Debugging", "dump_nso", false);
// Web Service
Settings::values.enable_telemetry =
diff --git a/src/yuzu_cmd/default_ini.h b/src/yuzu_cmd/default_ini.h
index e0b223cd6..d73669f36 100644
--- a/src/yuzu_cmd/default_ini.h
+++ b/src/yuzu_cmd/default_ini.h
@@ -178,6 +178,11 @@ use_docked_mode =
# 1 (default): Yes, 0 : No
enable_nfc =
+# Sets the seed for the RNG generator built into the switch
+# rng_seed will be ignored and randomly generated if rng_seed_enabled is false
+rng_seed_enabled =
+rng_seed =
+
# Sets the account username, max length is 32 characters
# yuzu (default)
username = yuzu
@@ -201,6 +206,10 @@ log_filter = *:Trace
# Port for listening to GDB connections.
use_gdbstub=false
gdbstub_port=24689
+# Determines whether or not yuzu will dump the ExeFS of all games it attempts to load while loading them
+dump_exefs=false
+# Determines whether or not yuzu will dump all NSOs it attempts to load while loading them
+dump_nso=false
[WebService]
# Whether or not to enable telemetry
diff --git a/src/yuzu_cmd/emu_window/emu_window_sdl2.cpp b/src/yuzu_cmd/emu_window/emu_window_sdl2.cpp
index a9ad92a80..2d6f8cced 100644
--- a/src/yuzu_cmd/emu_window/emu_window_sdl2.cpp
+++ b/src/yuzu_cmd/emu_window/emu_window_sdl2.cpp
@@ -111,32 +111,18 @@ void EmuWindow_SDL2::Fullscreen() {
bool EmuWindow_SDL2::SupportsRequiredGLExtensions() {
std::vector<std::string> unsupported_ext;
- if (!GLAD_GL_ARB_program_interface_query)
- unsupported_ext.push_back("ARB_program_interface_query");
- if (!GLAD_GL_ARB_separate_shader_objects)
- unsupported_ext.push_back("ARB_separate_shader_objects");
- if (!GLAD_GL_ARB_vertex_attrib_binding)
- unsupported_ext.push_back("ARB_vertex_attrib_binding");
if (!GLAD_GL_ARB_vertex_type_10f_11f_11f_rev)
unsupported_ext.push_back("ARB_vertex_type_10f_11f_11f_rev");
if (!GLAD_GL_ARB_texture_mirror_clamp_to_edge)
unsupported_ext.push_back("ARB_texture_mirror_clamp_to_edge");
- if (!GLAD_GL_ARB_base_instance)
- unsupported_ext.push_back("ARB_base_instance");
- if (!GLAD_GL_ARB_texture_storage)
- unsupported_ext.push_back("ARB_texture_storage");
if (!GLAD_GL_ARB_multi_bind)
unsupported_ext.push_back("ARB_multi_bind");
- if (!GLAD_GL_ARB_copy_image)
- unsupported_ext.push_back("ARB_copy_image");
// Extensions required to support some texture formats.
if (!GLAD_GL_EXT_texture_compression_s3tc)
unsupported_ext.push_back("EXT_texture_compression_s3tc");
if (!GLAD_GL_ARB_texture_compression_rgtc)
unsupported_ext.push_back("ARB_texture_compression_rgtc");
- if (!GLAD_GL_ARB_texture_compression_bptc)
- unsupported_ext.push_back("ARB_texture_compression_bptc");
if (!GLAD_GL_ARB_depth_buffer_float)
unsupported_ext.push_back("ARB_depth_buffer_float");
@@ -157,7 +143,7 @@ EmuWindow_SDL2::EmuWindow_SDL2(bool fullscreen) {
exit(1);
}
- SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
+ SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 4);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 3);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
diff --git a/src/yuzu_cmd/yuzu.cpp b/src/yuzu_cmd/yuzu.cpp
index c8b93b85b..806127b12 100644
--- a/src/yuzu_cmd/yuzu.cpp
+++ b/src/yuzu_cmd/yuzu.cpp
@@ -76,6 +76,9 @@ static void InitializeLogging() {
const std::string& log_dir = FileUtil::GetUserPath(FileUtil::UserPath::LogDir);
FileUtil::CreateFullPath(log_dir);
Log::AddBackend(std::make_unique<Log::FileBackend>(log_dir + LOG_FILE));
+#ifdef _WIN32
+ Log::AddBackend(std::make_unique<Log::DebuggerBackend>());
+#endif
}
/// Application entry point