id
int64 0
755k
| file_name
stringlengths 3
109
| file_path
stringlengths 13
185
| content
stringlengths 31
9.38M
| size
int64 31
9.38M
| language
stringclasses 1
value | extension
stringclasses 11
values | total_lines
int64 1
340k
| avg_line_length
float64 2.18
149k
| max_line_length
int64 7
2.22M
| alphanum_fraction
float64 0
1
| repo_name
stringlengths 6
65
| repo_stars
int64 100
47.3k
| repo_forks
int64 0
12k
| repo_open_issues
int64 0
3.4k
| repo_license
stringclasses 9
values | repo_extraction_date
stringclasses 92
values | exact_duplicates_redpajama
bool 2
classes | near_duplicates_redpajama
bool 2
classes | exact_duplicates_githubcode
bool 2
classes | exact_duplicates_stackv2
bool 1
class | exact_duplicates_stackv1
bool 2
classes | near_duplicates_githubcode
bool 2
classes | near_duplicates_stackv1
bool 2
classes | near_duplicates_stackv2
bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
5,613
|
mm_joystick_handler.h
|
RPCS3_rpcs3/rpcs3/Input/mm_joystick_handler.h
|
#pragma once
#ifdef _WIN32
#include "util/types.hpp"
#include "Emu/Io/PadHandler.h"
#ifndef NOMINMAX
#define NOMINMAX
#endif
#include <Windows.h>
#include <mmsystem.h>
#include <string>
#include <vector>
#include <memory>
#include <unordered_map>
class mm_joystick_handler final : public PadHandlerBase
{
static constexpr u64 NO_BUTTON = u64{umax};
// Unique names for the config files and our pad settings dialog
const std::unordered_map<u64, std::string> button_list =
{
{ NO_BUTTON , "" },
{ JOY_BUTTON1 , "Button 1" },
{ JOY_BUTTON2 , "Button 2" },
{ JOY_BUTTON3 , "Button 3" },
{ JOY_BUTTON4 , "Button 4" },
{ JOY_BUTTON5 , "Button 5" },
{ JOY_BUTTON6 , "Button 6" },
{ JOY_BUTTON7 , "Button 7" },
{ JOY_BUTTON8 , "Button 8" },
{ JOY_BUTTON9 , "Button 9" },
{ JOY_BUTTON10, "Button 10" },
{ JOY_BUTTON11, "Button 11" },
{ JOY_BUTTON12, "Button 12" },
{ JOY_BUTTON13, "Button 13" },
{ JOY_BUTTON14, "Button 14" },
{ JOY_BUTTON15, "Button 15" },
{ JOY_BUTTON16, "Button 16" },
{ JOY_BUTTON17, "Button 17" },
{ JOY_BUTTON18, "Button 18" },
{ JOY_BUTTON19, "Button 19" },
{ JOY_BUTTON20, "Button 20" },
{ JOY_BUTTON21, "Button 21" },
{ JOY_BUTTON22, "Button 22" },
{ JOY_BUTTON23, "Button 23" },
{ JOY_BUTTON24, "Button 24" },
{ JOY_BUTTON25, "Button 25" },
{ JOY_BUTTON26, "Button 26" },
{ JOY_BUTTON27, "Button 27" },
{ JOY_BUTTON28, "Button 28" },
{ JOY_BUTTON29, "Button 29" },
{ JOY_BUTTON30, "Button 30" },
{ JOY_BUTTON31, "Button 31" },
{ JOY_BUTTON32, "Button 32" },
};
// Unique names for the config files and our pad settings dialog
const std::unordered_map<u64, std::string> pov_list =
{
{ JOY_POVFORWARD, "POV Up" },
{ JOY_POVRIGHT, "POV Right" },
{ JOY_POVBACKWARD, "POV Down" },
{ JOY_POVLEFT, "POV Left" }
};
enum mmjoy_axis
{
joy_x_pos = 9700,
joy_x_neg,
joy_y_pos,
joy_y_neg,
joy_z_pos,
joy_z_neg,
joy_r_pos,
joy_r_neg,
joy_u_pos,
joy_u_neg,
joy_v_pos,
joy_v_neg,
};
// Unique names for the config files and our pad settings dialog
const std::unordered_map<u64, std::string> axis_list =
{
{ joy_x_pos, "X+" },
{ joy_x_neg, "X-" },
{ joy_y_pos, "Y+" },
{ joy_y_neg, "Y-" },
{ joy_z_pos, "Z+" },
{ joy_z_neg, "Z-" },
{ joy_r_pos, "R+" },
{ joy_r_neg, "R-" },
{ joy_u_pos, "U+" },
{ joy_u_neg, "U-" },
{ joy_v_pos, "V+" },
{ joy_v_neg, "V-" },
};
struct MMJOYDevice : public PadDevice
{
u32 device_id{ umax };
std::string device_name;
JOYINFOEX device_info{};
JOYCAPS device_caps{};
MMRESULT device_status = JOYERR_UNPLUGGED;
steady_clock::time_point last_update{};
};
public:
mm_joystick_handler();
bool Init() override;
std::vector<pad_list_entry> list_devices() override;
connection get_next_button_press(const std::string& padId, const pad_callback& callback, const pad_fail_callback& fail_callback, gui_call_type call_type, const std::vector<std::string>& buttons) override;
void init_config(cfg_pad* cfg) override;
private:
std::unordered_map<u64, u16> GetButtonValues(const JOYINFOEX& js_info, const JOYCAPS& js_caps);
std::shared_ptr<MMJOYDevice> get_device_by_name(const std::string& name);
std::shared_ptr<MMJOYDevice> create_device_by_name(const std::string& name);
bool GetMMJOYDevice(int index, MMJOYDevice* dev) const;
void enumerate_devices();
bool m_is_init = false;
std::set<u64> m_blacklist;
std::unordered_map<u64, u16> m_min_button_values;
std::map<std::string, std::shared_ptr<MMJOYDevice>> m_devices;
template <typename T>
std::set<T> find_keys(const std::vector<std::string>& names) const;
template <typename T>
std::set<T> find_keys(const cfg::string& cfg_string) const;
std::array<std::set<u32>, PadHandlerBase::button::button_count> get_mapped_key_codes(const std::shared_ptr<PadDevice>& device, const cfg_pad* cfg) override;
std::shared_ptr<PadDevice> get_device(const std::string& device) override;
bool get_is_left_trigger(const std::shared_ptr<PadDevice>& device, u64 keyCode) override;
bool get_is_right_trigger(const std::shared_ptr<PadDevice>& device, u64 keyCode) override;
bool get_is_left_stick(const std::shared_ptr<PadDevice>& device, u64 keyCode) override;
bool get_is_right_stick(const std::shared_ptr<PadDevice>& device, u64 keyCode) override;
PadHandlerBase::connection update_connection(const std::shared_ptr<PadDevice>& device) override;
std::unordered_map<u64, u16> get_button_values(const std::shared_ptr<PadDevice>& device) override;
};
#endif
| 4,535
|
C++
|
.h
| 131
| 32.122137
| 205
| 0.67586
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,614
|
pad_thread.h
|
RPCS3_rpcs3/rpcs3/Input/pad_thread.h
|
#pragma once
#include "util/types.hpp"
#include "util/atomic.hpp"
#include "Emu/Io/pad_types.h"
#include "Emu/Io/pad_config.h"
#include "Emu/Io/pad_config_types.h"
#include "Utilities/mutex.h"
#include <map>
#include <mutex>
#include <string_view>
#include <string>
class PadHandlerBase;
class pad_thread
{
public:
pad_thread(void* curthread, void* curwindow, std::string_view title_id); // void * instead of QThread * and QWindow * because of include in emucore
pad_thread(const pad_thread&) = delete;
pad_thread& operator=(const pad_thread&) = delete;
~pad_thread();
void operator()();
PadInfo& GetInfo() { return m_info; }
auto& GetPads() { return m_pads; }
void SetRumble(const u32 pad, u8 large_motor, bool small_motor);
void SetIntercepted(bool intercepted);
s32 AddLddPad();
void UnregisterLddPad(u32 handle);
void open_home_menu();
std::map<pad_handler, std::shared_ptr<PadHandlerBase>>& get_handlers() { return m_handlers; }
static std::shared_ptr<PadHandlerBase> GetHandler(pad_handler type);
static void InitPadConfig(cfg_pad& cfg, pad_handler type, std::shared_ptr<PadHandlerBase>& handler);
static auto constexpr thread_name = "Pad Thread"sv;
protected:
void Init();
void InitLddPad(u32 handle, const u32* port_status);
// List of all handlers
std::map<pad_handler, std::shared_ptr<PadHandlerBase>> m_handlers;
// Used for pad_handler::keyboard
void* m_curthread = nullptr;
void* m_curwindow = nullptr;
PadInfo m_info{ 0, 0, false };
std::array<std::shared_ptr<Pad>, CELL_PAD_MAX_PORT_NUM> m_pads{};
std::array<bool, CELL_PAD_MAX_PORT_NUM> m_pads_connected{};
u32 num_ldd_pad = 0;
private:
void update_pad_states();
u32 m_mask_start_press_to_resume = 0;
u64 m_track_start_press_begin_timestamp = 0;
bool m_resume_emulation_flag = false;
bool m_ps_button_pressed = false;
atomic_t<bool> m_home_menu_open = false;
};
namespace pad
{
extern atomic_t<pad_thread*> g_current;
extern shared_mutex g_pad_mutex;
extern std::string g_title_id;
extern atomic_t<bool> g_enabled;
extern atomic_t<bool> g_reset;
extern atomic_t<bool> g_started;
extern atomic_t<bool> g_home_menu_requested;
static inline class pad_thread* get_current_handler(bool relaxed = false)
{
if (relaxed)
{
return g_current.observe();
}
return ensure(g_current.load());
}
static inline void set_enabled(bool enabled)
{
g_enabled = enabled;
}
static inline void reset(std::string_view title_id)
{
g_title_id = title_id;
g_reset = true;
}
static inline void SetIntercepted(bool intercepted)
{
std::lock_guard lock(g_pad_mutex);
const auto handler = get_current_handler();
handler->SetIntercepted(intercepted);
}
}
| 2,685
|
C++
|
.h
| 84
| 29.785714
| 148
| 0.740008
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,615
|
raw_mouse_config.h
|
RPCS3_rpcs3/rpcs3/Input/raw_mouse_config.h
|
#pragma once
#include "Utilities/Config.h"
#include "Utilities/mutex.h"
#include <array>
LOG_CHANNEL(cfg_log, "CFG");
std::string mouse_button_id(int code);
struct raw_mouse_config : cfg::node
{
public:
using cfg::node::node;
cfg::string device{this, "Device", ""};
cfg::_float<10, 1000> mouse_acceleration{ this, "Mouse Acceleration", 100.0f, true };
cfg::string mouse_button_1{ this, "Button 1", "Button 1", true };
cfg::string mouse_button_2{ this, "Button 2", "Button 2", true };
cfg::string mouse_button_3{ this, "Button 3", "Button 3", true };
cfg::string mouse_button_4{ this, "Button 4", "Button 4", true };
cfg::string mouse_button_5{ this, "Button 5", "Button 5", true };
cfg::string mouse_button_6{ this, "Button 6", "", true };
cfg::string mouse_button_7{ this, "Button 7", "", true };
cfg::string mouse_button_8{ this, "Button 8", "", true };
cfg::string& get_button_by_index(int index);
cfg::string& get_button(int code);
};
struct raw_mice_config : cfg::node
{
raw_mice_config();
shared_mutex m_mutex;
static constexpr std::string_view cfg_id = "raw_mouse";
std::array<std::shared_ptr<raw_mouse_config>, 4> players;
atomic_t<bool> reload_requested = false;
bool load();
void save();
};
extern raw_mice_config g_cfg_raw_mouse;
| 1,274
|
C++
|
.h
| 34
| 35.5
| 86
| 0.691117
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,616
|
skateboard_pad_handler.h
|
RPCS3_rpcs3/rpcs3/Input/skateboard_pad_handler.h
|
#pragma once
#include "hid_pad_handler.h"
#include <array>
#include <unordered_map>
namespace reports
{
// Descriptor
// 0x09, 0x05, // Usage (0x05)
// 0xA1, 0x01, // Collection (Application)
// 0x05, 0x09, // Usage Page (Button)
// 0x19, 0x01, // Usage Minimum (0x01)
// 0x29, 0x0D, // Usage Maximum (0x0D)
// 0x15, 0x00, // Logical Minimum (0)
// 0x25, 0x01, // Logical Maximum (1)
// 0x75, 0x01, // Report Size (1)
// 0x95, 0x0D, // Report Count (13)
// 0x81, 0x02, // Input (Data,Var,Abs,No Wrap,Linear,Preferred State,No Null Position)
// 0x75, 0x03, // Report Size (3)
// 0x95, 0x01, // Report Count (1)
// 0x81, 0x03, // Input (Const,Var,Abs,No Wrap,Linear,Preferred State,No Null Position)
// 0x05, 0x01, // Usage Page (Generic Desktop Ctrls)
// 0x09, 0x39, // Usage (Hat switch)
// 0x15, 0x00, // Logical Minimum (0)
// 0x25, 0x07, // Logical Maximum (7)
// 0x35, 0x00, // Physical Minimum (0)
// 0x46, 0x3B, 0x01, // Physical Maximum (315)
// 0x65, 0x14, // Unit (System: English Rotation, Length: Centimeter)
// 0x75, 0x04, // Report Size (4)
// 0x95, 0x01, // Report Count (1)
// 0x81, 0x42, // Input (Data,Var,Abs,No Wrap,Linear,Preferred State,Null State)
// 0x75, 0x04, // Report Size (4)
// 0x95, 0x01, // Report Count (1)
// 0x81, 0x03, // Input (Const,Var,Abs,No Wrap,Linear,Preferred State,No Null Position)
// 0x09, 0x30, // Usage (X)
// 0x09, 0x31, // Usage (Y)
// 0x09, 0x32, // Usage (Z)
// 0x09, 0x35, // Usage (Rz)
// 0x15, 0x00, // Logical Minimum (0)
// 0x26, 0xFF, 0x00, // Logical Maximum (255)
// 0x35, 0x00, // Physical Minimum (0)
// 0x46, 0xFF, 0x00, // Physical Maximum (255)
// 0x65, 0x00, // Unit (None)
// 0x75, 0x08, // Report Size (8)
// 0x95, 0x04, // Report Count (4)
// 0x81, 0x02, // Input (Data,Var,Abs,No Wrap,Linear,Preferred State,No Null Position)
// 0x06, 0x00, 0xFF, // Usage Page (Vendor Defined 0xFF00)
// 0x09, 0x20, // Usage (0x20)
// 0x09, 0x21, // Usage (0x21)
// 0x09, 0x22, // Usage (0x22)
// 0x09, 0x23, // Usage (0x23)
// 0x09, 0x24, // Usage (0x24)
// 0x09, 0x25, // Usage (0x25)
// 0x09, 0x26, // Usage (0x26)
// 0x09, 0x27, // Usage (0x27)
// 0x09, 0x28, // Usage (0x28)
// 0x09, 0x29, // Usage (0x29)
// 0x09, 0x2A, // Usage (0x2A)
// 0x09, 0x2B, // Usage (0x2B)
// 0x15, 0x00, // Logical Minimum (0)
// 0x26, 0xFF, 0x00, // Logical Maximum (255)
// 0x75, 0x08, // Report Size (8)
// 0x95, 0x0C, // Report Count (12)
// 0x81, 0x02, // Input (Data,Var,Abs,No Wrap,Linear,Preferred State,No Null Position)
// 0x09, 0x2C, // Usage (0x2C)
// 0x09, 0x2D, // Usage (0x2D)
// 0x09, 0x2E, // Usage (0x2E)
// 0x09, 0x2F, // Usage (0x2F)
// 0x15, 0x00, // Logical Minimum (0)
// 0x26, 0xFF, 0x03, // Logical Maximum (1023)
// 0x35, 0x00, // Physical Minimum (0)
// 0x46, 0xFF, 0x03, // Physical Maximum (1023)
// 0x75, 0x10, // Report Size (16)
// 0x95, 0x04, // Report Count (4)
// 0x81, 0x02, // Input (Data,Var,Abs,No Wrap,Linear,Preferred State,No Null Position)
// 0x0A, 0x21, 0x26, // Usage (0x2621)
// 0x15, 0x00, // Logical Minimum (0)
// 0x26, 0xFF, 0x00, // Logical Maximum (255)
// 0x35, 0x00, // Physical Minimum (0)
// 0x46, 0xFF, 0x00, // Physical Maximum (255)
// 0x75, 0x08, // Report Size (8)
// 0x95, 0x08, // Report Count (8)
// 0x91, 0x02, // Output (Data,Var,Abs,No Wrap,Linear,Preferred State,No Null Position,Non-volatile)
// 0x0A, 0x21, 0x26, // Usage (0x2621)
// 0x15, 0x00, // Logical Minimum (0)
// 0x26, 0xFF, 0x00, // Logical Maximum (255)
// 0x75, 0x08, // Report Size (8)
// 0x95, 0x08, // Report Count (8)
// 0xB1, 0x02, // Feature (Data,Var,Abs,No Wrap,Linear,Preferred State,No Null Position,Non-volatile)
// 0xC0, // End Collection
#pragma pack(push, 1)
struct skateboard_input_report
{
// 13 buttons, value range 0 to 1, 13 bits + 3 bits padding (2 bytes total)
u16 buttons{};
// d-pad, value range 0 to 7 (8 directions), 4 bits + 4 bits padding (1 byte total)
u8 d_pad{};
// 4 axis (X, Y, Z, RZ), value range 0 to 255, 1 byte each (4 bytes total)
u8 axis_x{};
u8 axis_y{};
u8 axis_z{};
u8 axis_rz{};
// 12 axis (0x20 - 0x2B), value range 0 to 255, 1 byte each (12 bytes total)
// These 12 values match the pressure sensitivity values of the buttons (CELL_PAD_BTN_OFFSET_PRESS)
u8 pressure_right{}; // value for CELL_PAD_BTN_OFFSET_PRESS_RIGHT -> always 0 ?
u8 pressure_left{}; // value for CELL_PAD_BTN_OFFSET_PRESS_LEFT -> always 0 ?
u8 pressure_up{}; // value for CELL_PAD_BTN_OFFSET_PRESS_UP -> always 0 ?
u8 pressure_down{}; // value for CELL_PAD_BTN_OFFSET_PRESS_DOWN -> always 0 ?
u8 pressure_triangle{}; // value for CELL_PAD_BTN_OFFSET_PRESS_TRIANGLE -> infrared nose
u8 pressure_circle{}; // value for CELL_PAD_BTN_OFFSET_PRESS_CIRCLE -> infrared tail
u8 pressure_cross{}; // value for CELL_PAD_BTN_OFFSET_PRESS_CROSS -> infrared left
u8 pressure_square{}; // value for CELL_PAD_BTN_OFFSET_PRESS_SQUARE -> infrared right
u8 pressure_l1{}; // value for CELL_PAD_BTN_OFFSET_PRESS_L1 -> tilt left (probably)
u8 pressure_r1{}; // value for CELL_PAD_BTN_OFFSET_PRESS_R1 -> tilt right (probably)
u8 pressure_l2{}; // value for CELL_PAD_BTN_OFFSET_PRESS_L2 -> always 0 ?
u8 pressure_r2{}; // value for CELL_PAD_BTN_OFFSET_PRESS_R2 -> always 0 ?
// 4 axis (0x2C - 0x2F), value range 0 to 1023, 2 bytes each (8 bytes total)
std::array<u16, 4> large_axes{};
};
#pragma pack(pop)
struct skateboard_output_report
{
// 8 axis (0x2621), value range 0 to 255, 1 byte each (8 bytes total)
std::array<u8, 8> data{};
};
struct skateboard_feature_report
{
// 8 axis (0x2621), value range 0 to 255, 1 byte each (8 bytes total)
std::array<u8, 8> data{};
};
}
class skateboard_device : public HidDevice
{
public:
bool skateboard_is_on = false;
reports::skateboard_input_report report{};
};
class skateboard_pad_handler final : public hid_pad_handler<skateboard_device>
{
enum skateboard_key_codes
{
none = 0,
left,
right,
up,
down,
cross,
square,
circle,
triangle,
start,
select,
ps,
ir_nose,
ir_tail,
ir_left,
ir_right,
tilt_left,
tilt_right,
};
public:
skateboard_pad_handler();
~skateboard_pad_handler();
void SetPadData(const std::string& padId, u8 player_id, u8 large_motor, u8 small_motor, s32 r, s32 g, s32 b, bool player_led, bool battery_led, u32 battery_led_brightness) override;
void init_config(cfg_pad* cfg) override;
private:
DataStatus get_data(skateboard_device* device) override;
void check_add_device(hid_device* hidDevice, std::string_view path, std::wstring_view wide_serial) override;
int send_output_report(skateboard_device* device) override;
PadHandlerBase::connection update_connection(const std::shared_ptr<PadDevice>& device) override;
std::unordered_map<u64, u16> get_button_values(const std::shared_ptr<PadDevice>& device) override;
pad_preview_values get_preview_values(const std::unordered_map<u64, u16>& data) override;
void get_extended_info(const pad_ensemble& binding) override;
void apply_pad_data(const pad_ensemble& binding) override;
};
| 7,835
|
C++
|
.h
| 174
| 42.770115
| 182
| 0.602878
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,617
|
basic_keyboard_handler.h
|
RPCS3_rpcs3/rpcs3/Input/basic_keyboard_handler.h
|
#pragma once
#include "util/types.hpp"
#include "Emu/Io/KeyboardHandler.h"
#include <QKeyEvent>
#include <QWindow>
class basic_keyboard_handler final : public KeyboardHandlerBase, public QObject
{
using KeyboardHandlerBase::KeyboardHandlerBase;
public:
void Init(keyboard_consumer& consumer, const u32 max_connect) override;
void SetTargetWindow(QWindow* target);
bool eventFilter(QObject* watched, QEvent* event) override;
void keyPressEvent(QKeyEvent* event);
void keyReleaseEvent(QKeyEvent* event);
static s32 getUnmodifiedKey(QKeyEvent* event);
private:
void LoadSettings(Keyboard& keyboard);
QWindow* m_target = nullptr;
};
| 645
|
C++
|
.h
| 19
| 32.105263
| 79
| 0.815832
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,618
|
sdl_pad_handler.h
|
RPCS3_rpcs3/rpcs3/Input/sdl_pad_handler.h
|
#pragma once
#ifdef HAVE_SDL2
#include "Emu/Io/PadHandler.h"
#include "SDL.h"
class SDLDevice : public PadDevice
{
public:
struct touch_point
{
int index = 0;
int x = 0;
int y = 0;
};
struct touchpad
{
int index = 0;
std::vector<touch_point> fingers;
};
struct sdl_info
{
SDL_GameController* game_controller = nullptr;
SDL_GameControllerType type = SDL_GameControllerType::SDL_CONTROLLER_TYPE_UNKNOWN;
SDL_Joystick* joystick = nullptr;
SDL_JoystickPowerLevel power_level = SDL_JoystickPowerLevel::SDL_JOYSTICK_POWER_UNKNOWN;
SDL_JoystickPowerLevel last_power_level = SDL_JoystickPowerLevel::SDL_JOYSTICK_POWER_UNKNOWN;
std::string name;
std::string path;
std::string serial;
u16 vid = 0;
u16 pid = 0;
u16 product_version = 0;
u16 firmware_version = 0;
bool is_virtual_device = false;
bool has_led = false;
bool has_rumble = false;
bool has_rumble_triggers = false;
bool has_accel = false;
bool has_gyro = false;
float data_rate_accel = 0.0f;
float data_rate_gyro = 0.0f;
std::set<SDL_GameControllerButton> button_ids;
std::set<SDL_GameControllerAxis> axis_ids;
std::vector<touchpad> touchpads;
};
sdl_info sdl{};
std::array<float, 3> values_accel{};
std::array<float, 3> values_gyro{};
bool led_needs_update = true;
bool led_is_on = true;
bool led_is_blinking = false;
steady_clock::time_point led_timestamp{};
};
class sdl_pad_handler : public PadHandlerBase
{
enum SDLKeyCodes
{
None = 0,
A,
B,
X,
Y,
Left,
Right,
Up,
Down,
LB,
RB,
LS,
RS,
Start,
Back,
Guide,
Misc1,
Paddle1,
Paddle2,
Paddle3,
Paddle4,
Touchpad,
Touch_L,
Touch_R,
Touch_U,
Touch_D,
LT,
RT,
LSXNeg,
LSXPos,
LSYNeg,
LSYPos,
RSXNeg,
RSXPos,
RSYNeg,
RSYPos
};
public:
sdl_pad_handler();
~sdl_pad_handler();
SDLDevice::sdl_info get_sdl_info(int i);
bool Init() override;
void process() override;
void init_config(cfg_pad* cfg) override;
std::vector<pad_list_entry> list_devices() override;
void SetPadData(const std::string& padId, u8 player_id, u8 large_motor, u8 small_motor, s32 r, s32 g, s32 b, bool player_led, bool battery_led, u32 battery_led_brightness) override;
u32 get_battery_level(const std::string& padId) override;
void get_motion_sensors(const std::string& pad_id, const motion_callback& callback, const motion_fail_callback& fail_callback, motion_preview_values preview_values, const std::array<AnalogSensor, 4>& sensors) override;
connection get_next_button_press(const std::string& padId, const pad_callback& callback, const pad_fail_callback& fail_callback, gui_call_type call_type, const std::vector<std::string>& buttons) override;
private:
// pseudo 'controller id' to keep track of unique controllers
std::map<std::string, std::shared_ptr<SDLDevice>> m_controllers;
void enumerate_devices();
std::shared_ptr<SDLDevice> get_device_by_game_controller(SDL_GameController* game_controller) const;
std::shared_ptr<PadDevice> get_device(const std::string& device) override;
PadHandlerBase::connection update_connection(const std::shared_ptr<PadDevice>& device) override;
void get_extended_info(const pad_ensemble& binding) override;
void apply_pad_data(const pad_ensemble& binding) override;
bool get_is_left_trigger(const std::shared_ptr<PadDevice>& device, u64 keyCode) override;
bool get_is_right_trigger(const std::shared_ptr<PadDevice>& device, u64 keyCode) override;
bool get_is_left_stick(const std::shared_ptr<PadDevice>& device, u64 keyCode) override;
bool get_is_right_stick(const std::shared_ptr<PadDevice>& device, u64 keyCode) override;
bool get_is_touch_pad_motion(const std::shared_ptr<PadDevice>& device, u64 keyCode) override;
std::unordered_map<u64, u16> get_button_values(const std::shared_ptr<PadDevice>& device) override;
pad_preview_values get_preview_values(const std::unordered_map<u64, u16>& data) override;
u32 get_battery_color(SDL_JoystickPowerLevel power_level, u32 brightness) const;
void set_rumble(SDLDevice* dev, u8 speed_large, u8 speed_small);
static std::string button_to_string(SDL_GameControllerButton button);
static std::string axis_to_string(SDL_GameControllerAxis axis);
static SDLKeyCodes get_button_code(SDL_GameControllerButton button);
};
#endif
| 4,282
|
C++
|
.h
| 128
| 30.828125
| 219
| 0.75194
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,619
|
gui_pad_thread.h
|
RPCS3_rpcs3/rpcs3/Input/gui_pad_thread.h
|
#pragma once
#include "util/types.hpp"
#include "util/atomic.hpp"
#include "Emu/Io/pad_types.h"
#include "Emu/Io/pad_config.h"
#include "Emu/Io/pad_config_types.h"
#include "Utilities/Timer.h"
#include <thread>
class PadHandlerBase;
class gui_settings;
class gui_pad_thread
{
public:
gui_pad_thread();
virtual ~gui_pad_thread();
void update_settings(const std::shared_ptr<gui_settings>& settings);
static std::shared_ptr<PadHandlerBase> GetHandler(pad_handler type);
static void InitPadConfig(cfg_pad& cfg, pad_handler type, std::shared_ptr<PadHandlerBase>& handler);
protected:
bool init();
void run();
void process_input();
enum class mouse_button
{
none,
left,
right,
middle
};
enum class mouse_wheel
{
none,
vertical,
horizontal
};
void send_key_event(u32 key, bool pressed);
void send_mouse_button_event(mouse_button btn, bool pressed);
void send_mouse_wheel_event(mouse_wheel wheel, int delta);
void send_mouse_move_event(int delta_x, int delta_y);
#ifdef __linux__
int m_uinput_fd = -1;
void emit_event(int type, int code, int val);
#endif
std::shared_ptr<PadHandlerBase> m_handler;
std::shared_ptr<Pad> m_pad;
std::unique_ptr<std::thread> m_thread;
atomic_t<bool> m_terminate = false;
atomic_t<bool> m_allow_global_input = false;
std::array<bool, static_cast<u32>(pad_button::pad_button_max_enum)> m_last_button_state{};
steady_clock::time_point m_timestamp;
steady_clock::time_point m_initial_timestamp;
Timer m_input_timer;
static constexpr u64 auto_repeat_ms_interval_default = 200;
pad_button m_last_auto_repeat_button = pad_button::pad_button_max_enum;
std::map<pad_button, u64> m_auto_repeat_buttons = {
{ pad_button::dpad_up, auto_repeat_ms_interval_default },
{ pad_button::dpad_down, auto_repeat_ms_interval_default },
{ pad_button::dpad_left, auto_repeat_ms_interval_default },
{ pad_button::dpad_right, auto_repeat_ms_interval_default },
{ pad_button::rs_up, 1 }, // used for wheel scrolling by default
{ pad_button::rs_down, 1 }, // used for wheel scrolling by default
{ pad_button::rs_left, 1 }, // used for wheel scrolling by default
{ pad_button::rs_right, 1 } // used for wheel scrolling by default
};
// Mouse movement should just work without delays
std::map<pad_button, u64> m_mouse_move_buttons = {
{ pad_button::ls_up, 1 },
{ pad_button::ls_down, 1 },
{ pad_button::ls_left, 1 },
{ pad_button::ls_right, 1 }
};
pad_button m_mouse_boost_button = pad_button::L2;
bool m_boost_mouse = false;
float m_mouse_delta_x = 0.0f;
float m_mouse_delta_y = 0.0f;
#ifdef __APPLE__
float m_mouse_abs_x = 0.0f;
float m_mouse_abs_y = 0.0f;
#endif
};
| 2,661
|
C++
|
.h
| 80
| 31.0375
| 101
| 0.722981
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,620
|
raw_mouse_handler.h
|
RPCS3_rpcs3/rpcs3/Input/raw_mouse_handler.h
|
#pragma once
#include "Emu/Io/MouseHandler.h"
#include "Emu/RSX/display.h"
#include "Utilities/Config.h"
#include "Utilities/mutex.h"
#include "Utilities/Thread.h"
#ifdef _WIN32
#include <windows.h>
#endif
static const std::map<std::string, int> raw_mouse_button_map
{
{ "", 0 },
#ifdef _WIN32
{ "Button 1", RI_MOUSE_BUTTON_1_UP },
{ "Button 2", RI_MOUSE_BUTTON_2_UP },
{ "Button 3", RI_MOUSE_BUTTON_3_UP },
{ "Button 4", RI_MOUSE_BUTTON_4_UP },
{ "Button 5", RI_MOUSE_BUTTON_5_UP },
#endif
};
class raw_mouse_handler;
class raw_mouse
{
public:
raw_mouse() {}
raw_mouse(u32 index, const std::string& device_name, void* handle, raw_mouse_handler* handler);
virtual ~raw_mouse();
void update_window_handle();
display_handle_t window_handle() const { return m_window_handle; }
void center_cursor();
#ifdef _WIN32
void update_values(const RAWMOUSE& state);
#endif
const std::string& device_name() const { return m_device_name; }
u32 index() const { return m_index; }
void set_index(u32 index);
void request_reload() { reload_requested = true; }
private:
void reload_config();
static std::pair<int, int> get_mouse_button(const cfg::string& button);
u32 m_index = 0;
std::string m_device_name;
void* m_handle{};
display_handle_t m_window_handle{};
int m_window_width{};
int m_window_height{};
int m_window_width_old{};
int m_window_height_old{};
int m_pos_x{};
int m_pos_y{};
float m_mouse_acceleration = 1.0f;
raw_mouse_handler* m_handler{};
std::map<u8, std::pair<int, int>> m_buttons;
bool reload_requested = false;
};
class raw_mouse_handler final : public MouseHandlerBase
{
public:
using MouseHandlerBase::MouseHandlerBase;
virtual ~raw_mouse_handler();
void Init(const u32 max_connect) override;
void SetIsForGui(bool value)
{
m_is_for_gui = value;
}
const std::map<void*, raw_mouse>& get_mice() const { return m_raw_mice; };
void set_mouse_press_callback(std::function<void(const std::string&, s32, bool)> cb)
{
m_mouse_press_callback = std::move(cb);
}
void mouse_press_callback(const std::string& device_name, s32 cell_code, bool pressed)
{
if (m_mouse_press_callback)
{
m_mouse_press_callback(device_name, cell_code, pressed);
}
}
void update_devices();
#ifdef _WIN32
void handle_native_event(const MSG& msg);
#endif
shared_mutex m_raw_mutex;
private:
u32 get_now_connect(std::set<u32>& connected_mice);
std::map<void*, raw_mouse> enumerate_devices(u32 max_connect);
#ifdef _WIN32
void register_raw_input_devices();
void unregister_raw_input_devices() const;
bool m_registered_raw_input_devices = false;
#endif
bool m_is_for_gui = false;
std::map<void*, raw_mouse> m_raw_mice;
std::function<void(const std::string&, s32, bool)> m_mouse_press_callback;
std::unique_ptr<named_thread<std::function<void()>>> m_thread;
};
| 2,819
|
C++
|
.h
| 95
| 27.663158
| 96
| 0.721378
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,621
|
ds4_pad_handler.h
|
RPCS3_rpcs3/rpcs3/Input/ds4_pad_handler.h
|
#pragma once
#include "hid_pad_handler.h"
#include <unordered_map>
namespace reports
{
constexpr u32 DS4_ACC_RES_PER_G = 8192;
constexpr u32 DS4_GYRO_RES_PER_DEG_S = 86; // technically this could be 1024, but keeping it at 86 keeps us within 16 bits of precision
constexpr u32 DS4_FEATURE_REPORT_USB_CALIBRATION_SIZE = 37;
constexpr u32 DS4_FEATURE_REPORT_BLUETOOTH_CALIBRATION_SIZE = 41;
//constexpr u32 DS4_FEATURE_REPORT_PAIRING_INFO_SIZE = 16;
//constexpr u32 DS4_FEATURE_REPORT_0x81_SIZE = 7;
constexpr u32 DS4_FEATURE_REPORT_FIRMWARE_INFO_SIZE = 49;
constexpr u32 DS4_INPUT_REPORT_USB_SIZE = 64;
constexpr u32 DS4_INPUT_REPORT_BLUETOOTH_SIZE = 78;
constexpr u32 DS4_OUTPUT_REPORT_USB_SIZE = 32;
constexpr u32 DS4_OUTPUT_REPORT_BLUETOOTH_SIZE = 78;
constexpr u32 DS4_TOUCHPAD_WIDTH = 1920;
constexpr u32 DS4_TOUCHPAD_HEIGHT = 942;
constexpr u32 DS4_TOUCH_POINT_INACTIVE = 0x80;
struct ds4_touch_point
{
u8 contact;
u8 x_lo;
u8 x_hi : 4;
u8 y_lo : 4;
u8 y_hi;
};
static_assert(sizeof(ds4_touch_point) == 4);
struct ds4_touch_report
{
u8 timestamp;
std::array<ds4_touch_point, 2> points;
};
static_assert(sizeof(ds4_touch_report) == 9);
struct ds4_input_report_common
{
u8 x;
u8 y;
u8 rx;
u8 ry;
u8 buttons[3];
u8 z;
u8 rz;
le_t<u16, 1> sensor_timestamp;
u8 sensor_temperature;
le_t<u16, 1> gyro[3];
le_t<u16, 1> accel[3];
u8 reserved2[5];
u8 status[2];
u8 reserved3;
};
static_assert(sizeof(ds4_input_report_common) == 32);
struct ds4_input_report_usb
{
u8 report_id;
ds4_input_report_common common;
u8 num_touch_reports;
std::array<ds4_touch_report, 3> touch_reports;
u8 reserved[3];
};
static_assert(sizeof(ds4_input_report_usb) == DS4_INPUT_REPORT_USB_SIZE);
struct ds4_input_report_bt
{
u8 report_id;
u8 reserved[2];
ds4_input_report_common common;
u8 num_touch_reports;
std::array<ds4_touch_report, 4> touch_reports;
u8 reserved2[2];
u8 crc32[4];
};
static_assert(sizeof(ds4_input_report_bt) == DS4_INPUT_REPORT_BLUETOOTH_SIZE);
struct ds4_output_report_common
{
u8 valid_flag0;
u8 valid_flag1;
u8 reserved;
u8 motor_right;
u8 motor_left;
u8 lightbar_red;
u8 lightbar_green;
u8 lightbar_blue;
u8 lightbar_blink_on;
u8 lightbar_blink_off;
};
static_assert(sizeof(ds4_output_report_common) == 10);
struct ds4_output_report_usb
{
u8 report_id;
ds4_output_report_common common;
u8 reserved[21];
};
static_assert(sizeof(ds4_output_report_usb) == DS4_OUTPUT_REPORT_USB_SIZE);
struct ds4_output_report_bt
{
u8 report_id;
u8 hw_control;
u8 audio_control;
ds4_output_report_common common;
u8 reserved[61];
u8 crc32[4];
};
static_assert(sizeof(ds4_output_report_bt) == DS4_OUTPUT_REPORT_BLUETOOTH_SIZE);
}
class DS4Device : public HidDevice
{
public:
bool bt_controller{false};
bool has_calib_data{false};
std::array<CalibData, CalibIndex::COUNT> calib_data{};
reports::ds4_input_report_usb report_usb{};
reports::ds4_input_report_bt report_bt{};
};
class ds4_pad_handler final : public hid_pad_handler<DS4Device>
{
// These are all the possible buttons on a standard DS4 controller
// The touchpad is restricted to its button for now (or forever?)
enum DS4KeyCodes
{
None = 0,
Triangle,
Circle,
Cross,
Square,
Left,
Right,
Up,
Down,
R1,
//R2But,
R3,
L1,
//L2But,
L3,
Share,
Options,
PSButton,
TouchPad,
Touch_L,
Touch_R,
Touch_U,
Touch_D,
L2,
R2,
LSXNeg,
LSXPos,
LSYNeg,
LSYPos,
RSXNeg,
RSXPos,
RSYNeg,
RSYPos
};
public:
ds4_pad_handler();
~ds4_pad_handler();
void SetPadData(const std::string& padId, u8 player_id, u8 large_motor, u8 small_motor, s32 r, s32 g, s32 b, bool player_led, bool battery_led, u32 battery_led_brightness) override;
u32 get_battery_level(const std::string& padId) override;
void init_config(cfg_pad* cfg) override;
private:
// This function gets us usuable buffer from the rawbuffer of padData
bool GetCalibrationData(DS4Device* ds4Device) const;
// Copies data into padData if status is NewData, otherwise buffer is untouched
DataStatus get_data(DS4Device* ds4Device) override;
int send_output_report(DS4Device* device) override;
void check_add_device(hid_device* hidDevice, std::string_view path, std::wstring_view serial) override;
bool get_is_left_trigger(const std::shared_ptr<PadDevice>& device, u64 keyCode) override;
bool get_is_right_trigger(const std::shared_ptr<PadDevice>& device, u64 keyCode) override;
bool get_is_left_stick(const std::shared_ptr<PadDevice>& device, u64 keyCode) override;
bool get_is_right_stick(const std::shared_ptr<PadDevice>& device, u64 keyCode) override;
bool get_is_touch_pad_motion(const std::shared_ptr<PadDevice>& device, u64 keyCode) override;
PadHandlerBase::connection update_connection(const std::shared_ptr<PadDevice>& device) override;
void get_extended_info(const pad_ensemble& binding) override;
void apply_pad_data(const pad_ensemble& binding) override;
std::unordered_map<u64, u16> get_button_values(const std::shared_ptr<PadDevice>& device) override;
pad_preview_values get_preview_values(const std::unordered_map<u64, u16>& data) override;
};
| 5,192
|
C++
|
.h
| 177
| 26.813559
| 182
| 0.742439
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,622
|
dualsense_pad_handler.h
|
RPCS3_rpcs3/rpcs3/Input/dualsense_pad_handler.h
|
#pragma once
#include "hid_pad_handler.h"
#include <unordered_map>
namespace reports
{
constexpr u32 DUALSENSE_ACC_RES_PER_G = 8192;
constexpr u32 DUALSENSE_GYRO_RES_PER_DEG_S = 86; // technically this could be 1024, but keeping it at 86 keeps us within 16 bits of precision
constexpr u32 DUALSENSE_CALIBRATION_REPORT_SIZE = 41;
constexpr u32 DUALSENSE_FIRMWARE_REPORT_SIZE = 64;
constexpr u32 DUALSENSE_PAIRING_REPORT_SIZE = 20;
constexpr u32 DUALSENSE_BLUETOOTH_REPORT_SIZE = 78;
constexpr u32 DUALSENSE_USB_REPORT_SIZE = 63; // 64 in hid, because of the report ID being added
constexpr u32 DUALSENSE_COMMON_REPORT_SIZE = 47;
constexpr u32 DUALSENSE_USB_INPUT_REPORT_SIZE = 64;
constexpr u32 DUALSENSE_BLUETOOTH_INPUT_REPORT_SIZE = 78;
constexpr u32 DUALSENSE_INPUT_REPORT_GYRO_X_OFFSET = 15;
constexpr u32 DUALSENSE_TOUCHPAD_WIDTH = 1920;
constexpr u32 DUALSENSE_TOUCHPAD_HEIGHT = 1080;
constexpr u32 DUALSENSE_TOUCH_POINT_INACTIVE = 0x80;
enum
{
VALID_FLAG_0_COMPATIBLE_VIBRATION = 0x01,
VALID_FLAG_0_HAPTICS_SELECT = 0x02,
VALID_FLAG_0_SET_LEFT_TRIGGER_MOTOR = 0x04,
VALID_FLAG_0_SET_RIGHT_TRIGGER_MOTOR = 0x08,
VALID_FLAG_0_SET_AUDIO_VOLUME = 0x10,
VALID_FLAG_0_TOGGLE_AUDIO = 0x20,
VALID_FLAG_0_SET_MICROPHONE_VOLUME = 0x40,
VALID_FLAG_0_TOGGLE_MICROPHONE = 0x80,
VALID_FLAG_1_TOGGLE_MIC_BUTTON_LED = 0x01,
VALID_FLAG_1_POWER_SAVE_CONTROL_ENABLE = 0x02,
VALID_FLAG_1_LIGHTBAR_CONTROL_ENABLE = 0x04,
VALID_FLAG_1_RELEASE_LEDS = 0x08,
VALID_FLAG_1_PLAYER_INDICATOR_CONTROL_ENABLE = 0x10,
VALID_FLAG_1_EFFECT_POWER = 0x40,
VALID_FLAG_2_SET_PLAYER_LED_BRIGHTNESS = 0x01,
VALID_FLAG_2_LIGHTBAR_SETUP_CONTROL_ENABLE = 0x02,
VALID_FLAG_2_IMPROVED_RUMBLE_EMULATION = 0x04,
AUDIO_BIT_FORCE_INTERNAL_MIC = 0x01,
AUDIO_BIT_FORCE_EXTERNAL_MIC = 0x02,
AUDIO_BIT_PAD_EXTERNAL_MIC = 0x04,
AUDIO_BIT_PAD_INTERNAL_MIC = 0x08,
AUDIO_BIT_DISABLE_EXTERNAL_SPEAKERS = 0x10,
AUDIO_BIT_ENABLE_INTERNAL_SPEAKERS = 0x20,
POWER_SAVE_CONTROL_MIC_MUTE = 0x10,
POWER_SAVE_CONTROL_AUDIO_MUTE = 0x40,
LIGHTBAR_SETUP_LIGHT_ON = 0x01,
LIGHTBAR_SETUP_LIGHT_OFF = 0x02,
MIC_BUTTON_LED_ON = 0x01,
MIC_BUTTON_LED_PULSE = 0x02,
};
struct dualsense_touch_point
{
u8 contact;
u8 x_lo;
u8 x_hi : 4;
u8 y_lo : 4;
u8 y_hi;
};
static_assert(sizeof(dualsense_touch_point) == 4);
struct dualsense_input_report_common
{
u8 x;
u8 y;
u8 rx;
u8 ry;
u8 z;
u8 rz;
u8 seq_number;
u8 buttons[4];
u8 reserved[4];
le_t<u16, 1> gyro[3];
le_t<u16, 1> accel[3];
le_t<u32, 1> sensor_timestamp;
u8 reserved2;
std::array<dualsense_touch_point, 2> points;
u8 reserved3[12];
u8 status;
u8 reserved4[10];
};
struct dualsense_input_report_usb
{
u8 report_id;
dualsense_input_report_common common;
};
static_assert(sizeof(dualsense_input_report_usb) == DUALSENSE_USB_INPUT_REPORT_SIZE);
struct dualsense_input_report_bt
{
u8 report_id;
u8 something;
dualsense_input_report_common common;
u8 reserved[9];
u8 crc32[4];
};
static_assert(sizeof(dualsense_input_report_bt) == DUALSENSE_BLUETOOTH_INPUT_REPORT_SIZE);
struct dualsense_output_report_common
{
u8 valid_flag_0;
u8 valid_flag_1;
u8 motor_right;
u8 motor_left;
u8 headphone_volume;
u8 speaker_volume;
u8 microphone_volume;
u8 audio_enable_bits;
u8 mute_button_led;
u8 power_save_control;
u8 right_trigger_effect[11];
u8 left_trigger_effect[11];
u8 reserved[6];
u8 valid_flag_2;
u8 effect_strength_1 : 4; // 0-7 (one for motors, the other for trigger motors, not sure which is which)
u8 effect_strength_2 : 4; // 0-7 (one for motors, the other for trigger motors, not sure which is which)
u8 reserved2;
u8 lightbar_setup;
u8 led_brightness;
u8 player_leds;
u8 lightbar_r;
u8 lightbar_g;
u8 lightbar_b;
};
static_assert(sizeof(dualsense_output_report_common) == DUALSENSE_COMMON_REPORT_SIZE);
struct dualsense_output_report_bt
{
u8 report_id; // 0x31
u8 seq_tag;
u8 tag;
dualsense_output_report_common common;
u8 reserved[24];
u8 crc32[4];
};
static_assert(sizeof(dualsense_output_report_bt) == DUALSENSE_BLUETOOTH_REPORT_SIZE);
struct dualsense_output_report_usb
{
u8 report_id; // 0x02
dualsense_output_report_common common;
u8 reserved[15];
};
static_assert(sizeof(dualsense_output_report_usb) == DUALSENSE_USB_REPORT_SIZE);
}
class DualSenseDevice : public HidDevice
{
public:
enum class DualSenseDataMode
{
Simple,
Enhanced
};
enum class DualSenseFeatureSet
{
Normal,
Edge
};
bool bt_controller{false};
u8 bt_sequence{0};
bool has_calib_data{false};
std::array<CalibData, CalibIndex::COUNT> calib_data{};
reports::dualsense_input_report_common report{}; // No need to have separate reports for usb and bluetooth
DualSenseDataMode data_mode{DualSenseDataMode::Simple};
DualSenseFeatureSet feature_set{DualSenseFeatureSet::Normal};
bool init_lightbar{true};
bool update_lightbar{true};
bool update_player_leds{true};
bool release_leds{false};
// Controls for lightbar pulse. This seems somewhat hacky for now, as I haven't found out a nicer way.
bool lightbar_on{false};
bool lightbar_on_old{false};
steady_clock::time_point last_lightbar_time;
};
class dualsense_pad_handler final : public hid_pad_handler<DualSenseDevice>
{
enum DualSenseKeyCodes
{
None = 0,
Triangle,
Circle,
Cross,
Square,
Left,
Right,
Up,
Down,
R1,
R3,
L1,
L3,
Share,
Options,
PSButton,
Mic,
TouchPad,
Touch_L,
Touch_R,
Touch_U,
Touch_D,
L2,
R2,
LSXNeg,
LSXPos,
LSYNeg,
LSYPos,
RSXNeg,
RSXPos,
RSYNeg,
RSYPos,
EdgeFnL,
EdgeFnR,
EdgeLB,
EdgeRB,
};
public:
dualsense_pad_handler();
~dualsense_pad_handler();
void SetPadData(const std::string& padId, u8 player_id, u8 large_motor, u8 small_motor, s32 r, s32 g, s32 b, bool player_led, bool battery_led, u32 battery_led_brightness) override;
u32 get_battery_level(const std::string& padId) override;
void init_config(cfg_pad* cfg) override;
private:
bool get_calibration_data(DualSenseDevice* dev) const;
DataStatus get_data(DualSenseDevice* device) override;
void check_add_device(hid_device* hidDevice, std::string_view path, std::wstring_view wide_serial) override;
int send_output_report(DualSenseDevice* device) override;
bool get_is_left_trigger(const std::shared_ptr<PadDevice>& device, u64 keyCode) override;
bool get_is_right_trigger(const std::shared_ptr<PadDevice>& device, u64 keyCode) override;
bool get_is_left_stick(const std::shared_ptr<PadDevice>& device, u64 keyCode) override;
bool get_is_right_stick(const std::shared_ptr<PadDevice>& device, u64 keyCode) override;
bool get_is_touch_pad_motion(const std::shared_ptr<PadDevice>& device, u64 keyCode) override;
PadHandlerBase::connection update_connection(const std::shared_ptr<PadDevice>& device) override;
std::unordered_map<u64, u16> get_button_values(const std::shared_ptr<PadDevice>& device) override;
pad_preview_values get_preview_values(const std::unordered_map<u64, u16>& data) override;
void get_extended_info(const pad_ensemble& binding) override;
void apply_pad_data(const pad_ensemble& binding) override;
};
| 7,571
|
C++
|
.h
| 232
| 30.008621
| 182
| 0.710357
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,623
|
keyboard_pad_handler.h
|
RPCS3_rpcs3/rpcs3/Input/keyboard_pad_handler.h
|
#pragma once
#include "util/types.hpp"
#include "Emu/Io/PadHandler.h"
#include <QWindow>
#include <QKeyEvent>
#include <string>
#include <vector>
#include <unordered_map>
enum mouse
{
move_left = 0x05555550,
move_right = 0x05555551,
move_up = 0x05555552,
move_down = 0x05555553,
wheel_up = 0x05555554,
wheel_down = 0x05555555,
wheel_left = 0x05555556,
wheel_right = 0x05555557
};
// Unique button names for the config files and our pad settings dialog
const std::unordered_map<u32, std::string> mouse_list =
{
{ Qt::NoButton , "" },
{ Qt::LeftButton , "Mouse Left" },
{ Qt::RightButton , "Mouse Right" },
{ Qt::MiddleButton , "Mouse Middle" },
{ Qt::BackButton , "Mouse Back" },
{ Qt::ForwardButton , "Mouse Fwd" },
{ Qt::TaskButton , "Mouse Task" },
{ Qt::ExtraButton4 , "Mouse 4" },
{ Qt::ExtraButton5 , "Mouse 5" },
{ Qt::ExtraButton6 , "Mouse 6" },
{ Qt::ExtraButton7 , "Mouse 7" },
{ Qt::ExtraButton8 , "Mouse 8" },
{ Qt::ExtraButton9 , "Mouse 9" },
{ Qt::ExtraButton10 , "Mouse 10" },
{ Qt::ExtraButton11 , "Mouse 11" },
{ Qt::ExtraButton12 , "Mouse 12" },
{ Qt::ExtraButton13 , "Mouse 13" },
{ Qt::ExtraButton14 , "Mouse 14" },
{ Qt::ExtraButton15 , "Mouse 15" },
{ Qt::ExtraButton16 , "Mouse 16" },
{ Qt::ExtraButton17 , "Mouse 17" },
{ Qt::ExtraButton18 , "Mouse 18" },
{ Qt::ExtraButton19 , "Mouse 19" },
{ Qt::ExtraButton20 , "Mouse 20" },
{ Qt::ExtraButton21 , "Mouse 21" },
{ Qt::ExtraButton22 , "Mouse 22" },
{ Qt::ExtraButton23 , "Mouse 23" },
{ Qt::ExtraButton24 , "Mouse 24" },
{ mouse::move_left , "Mouse MLeft" },
{ mouse::move_right , "Mouse MRight" },
{ mouse::move_up , "Mouse MUp" },
{ mouse::move_down , "Mouse MDown" },
{ mouse::wheel_up , "Wheel Up" },
{ mouse::wheel_down , "Wheel Down" },
{ mouse::wheel_left , "Wheel Left" },
{ mouse::wheel_right , "Wheel Right" },
};
class keyboard_pad_handler final : public QObject, public PadHandlerBase
{
public:
bool Init() override;
keyboard_pad_handler();
void SetTargetWindow(QWindow* target);
void processKeyEvent(QKeyEvent* event, bool pressed);
void keyPressEvent(QKeyEvent* event);
void keyReleaseEvent(QKeyEvent* event);
void mousePressEvent(QMouseEvent* event);
void mouseReleaseEvent(QMouseEvent* event);
void mouseMoveEvent(QMouseEvent* event);
void mouseWheelEvent(QWheelEvent* event);
bool eventFilter(QObject* target, QEvent* ev) override;
void init_config(cfg_pad* cfg) override;
std::vector<pad_list_entry> list_devices() override;
connection get_next_button_press(const std::string& /*padId*/, const pad_callback& /*callback*/, const pad_fail_callback& /*fail_callback*/, gui_call_type /*call_type*/, const std::vector<std::string>& /*buttons*/) override { return connection::connected; }
bool bindPadToDevice(std::shared_ptr<Pad> pad) override;
void process() override;
static std::string GetMouseName(const QMouseEvent* event);
static std::string GetMouseName(u32 button);
static QStringList GetKeyNames(const QKeyEvent* keyEvent);
static std::string GetKeyName(const QKeyEvent* keyEvent, bool with_modifiers);
static std::string GetKeyName(const u32& keyCode);
static std::set<u32> GetKeyCodes(const cfg::string& cfg_string);
static u32 GetKeyCode(const QString& keyName);
static int native_scan_code_from_string(const std::string& key);
static std::string native_scan_code_to_string(int native_scan_code);
protected:
void Key(const u32 code, bool pressed, u16 value = 255);
private:
QWindow* m_target = nullptr;
mouse_movement_mode m_mouse_movement_mode = mouse_movement_mode::relative;
bool m_keys_released = false;
bool m_mouse_move_used = false;
bool m_mouse_wheel_used = false;
bool get_mouse_lock_state() const;
void release_all_keys();
std::vector<Pad> m_pads_internal; // Accumulates input until the next poll. Only used for user input!
// Button Movements
steady_clock::time_point m_button_time;
f32 m_analog_lerp_factor = 1.0f;
f32 m_trigger_lerp_factor = 1.0f;
bool m_analog_limiter_toggle_mode = false;
bool m_pressure_intensity_toggle_mode = false;
u32 m_pressure_intensity_deadzone = 0;
// Stick Movements
steady_clock::time_point m_stick_time;
f32 m_l_stick_lerp_factor = 1.0f;
f32 m_r_stick_lerp_factor = 1.0f;
u32 m_l_stick_multiplier = 100;
u32 m_r_stick_multiplier = 100;
static constexpr usz max_sticks = 4;
std::array<u8, max_sticks> m_stick_min{ 0, 0, 0, 0 };
std::array<u8, max_sticks> m_stick_max{ 128, 128, 128, 128 };
std::array<u8, max_sticks> m_stick_val{ 128, 128, 128, 128 };
// Mouse Movements
steady_clock::time_point m_last_mouse_move_left;
steady_clock::time_point m_last_mouse_move_right;
steady_clock::time_point m_last_mouse_move_up;
steady_clock::time_point m_last_mouse_move_down;
int m_deadzone_x = 60;
int m_deadzone_y = 60;
double m_multi_x = 2;
double m_multi_y = 2.5;
// Mousewheel
steady_clock::time_point m_last_wheel_move_up;
steady_clock::time_point m_last_wheel_move_down;
steady_clock::time_point m_last_wheel_move_left;
steady_clock::time_point m_last_wheel_move_right;
};
| 5,249
|
C++
|
.h
| 130
| 38.376923
| 258
| 0.688701
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,624
|
evdev_joystick_handler.h
|
RPCS3_rpcs3/rpcs3/Input/evdev_joystick_handler.h
|
#pragma once
#ifdef HAVE_LIBEVDEV
#include "util/types.hpp"
#include "Utilities/File.h"
#include "Emu/Io/PadHandler.h"
#include <libevdev/libevdev.h>
#include <memory>
#include <unordered_map>
#include <array>
#include <vector>
#include <thread>
#include <ctime>
struct positive_axis : cfg::node
{
const std::string cfg_name = fs::get_config_dir() + "/evdev_positive_axis.yml";
cfg::_bool abs_x{ this, "ABS_X", false };
cfg::_bool abs_y{ this, "ABS_Y", false };
cfg::_bool abs_z{ this, "ABS_Z", false };
cfg::_bool abs_rx{ this, "ABS_RX", false };
cfg::_bool abs_ry{ this, "ABS_RY", false };
cfg::_bool abs_rz{ this, "ABS_RZ", false };
cfg::_bool abs_throttle{ this, "ABS_THROTTLE", false };
cfg::_bool abs_rudder{ this, "ABS_RUDDER", false };
cfg::_bool abs_wheel{ this, "ABS_WHEEL", false };
cfg::_bool abs_gas{ this, "ABS_GAS", false };
cfg::_bool abs_brake{ this, "ABS_BRAKE", false };
cfg::_bool abs_hat0x{ this, "ABS_HAT0X", false };
cfg::_bool abs_hat0y{ this, "ABS_HAT0Y", false };
cfg::_bool abs_hat1x{ this, "ABS_HAT1X", false };
cfg::_bool abs_hat1y{ this, "ABS_HAT1Y", false };
cfg::_bool abs_hat2x{ this, "ABS_HAT2X", false };
cfg::_bool abs_hat2y{ this, "ABS_HAT2Y", false };
cfg::_bool abs_hat3x{ this, "ABS_HAT3X", false };
cfg::_bool abs_hat3y{ this, "ABS_HAT3Y", false };
cfg::_bool abs_pressure{ this, "ABS_PRESSURE", false };
cfg::_bool abs_distance{ this, "ABS_DISTANCE", false };
cfg::_bool abs_tilt_x{ this, "ABS_TILT_X", false };
cfg::_bool abs_tilt_y{ this, "ABS_TILT_Y", false };
cfg::_bool abs_tool_width{ this, "ABS_TOOL_WIDTH", false };
cfg::_bool abs_volume{ this, "ABS_VOLUME", false };
cfg::_bool abs_misc{ this, "ABS_MISC", false };
cfg::_bool abs_mt_slot{ this, "ABS_MT_SLOT", false };
cfg::_bool abs_mt_touch_major{ this, "ABS_MT_TOUCH_MAJOR", false };
cfg::_bool abs_mt_touch_minor{ this, "ABS_MT_TOUCH_MINOR", false };
cfg::_bool abs_mt_width_major{ this, "ABS_MT_WIDTH_MAJOR", false };
cfg::_bool abs_mt_width_minor{ this, "ABS_MT_WIDTH_MINOR", false };
cfg::_bool abs_mt_orientation{ this, "ABS_MT_ORIENTATION", false };
cfg::_bool abs_mt_position_x{ this, "ABS_MT_POSITION_X", false };
cfg::_bool abs_mt_position_y{ this, "ABS_MT_POSITION_Y", false };
cfg::_bool abs_mt_tool_type{ this, "ABS_MT_TOOL_TYPE", false };
cfg::_bool abs_mt_blob_id{ this, "ABS_MT_BLOB_ID", false };
cfg::_bool abs_mt_tracking_id{ this, "ABS_MT_TRACKING_ID", false };
cfg::_bool abs_mt_pressure{ this, "ABS_MT_PRESSURE", false };
cfg::_bool abs_mt_distance{ this, "ABS_MT_DISTANCE", false };
cfg::_bool abs_mt_tool_x{ this, "ABS_MT_TOOL_X", false };
cfg::_bool abs_mt_tool_y{ this, "ABS_MT_TOOL_Y", false };
bool load()
{
if (fs::file cfg_file{ cfg_name, fs::read })
{
return from_string(cfg_file.to_string());
}
return false;
}
void save()
{
fs::pending_file file(cfg_name);
if (file.file)
{
file.file.write(to_string());
file.commit();
}
}
bool exist()
{
return fs::is_file(cfg_name);
}
};
class evdev_joystick_handler final : public PadHandlerBase
{
static constexpr u32 NO_BUTTON = u32{umax}; // Some event code that doesn't exist in evdev (code type is U16)
// Unique button names for the config files and our pad settings dialog
const std::unordered_map<u32, std::string> button_list =
{
{ NO_BUTTON , "" },
// Xbox One S Controller returns some buttons as key when connected through bluetooth
{ KEY_BACK , "Back Key" },
{ KEY_HOMEPAGE , "Homepage Key"},
// Wii/Wii U Controller drivers use the following few keys
{ KEY_UP , "Up Key" },
{ KEY_LEFT , "Left Key" },
{ KEY_RIGHT , "Right Key" },
{ KEY_DOWN , "Down Key" },
{ KEY_NEXT , "Next Key" },
{ KEY_PREVIOUS , "Previous Key"},
//{ BTN_MISC , "Misc" }, same as BTN_0
{ BTN_0 , "0" },
{ BTN_1 , "1" },
{ BTN_2 , "2" },
{ BTN_3 , "3" },
{ BTN_4 , "4" },
{ BTN_5 , "5" },
{ BTN_6 , "6" },
{ BTN_7 , "7" },
{ BTN_8 , "8" },
{ BTN_9 , "9" },
{ 0x10a , "0x10a" },
{ 0x10b , "0x10b" },
{ 0x10c , "0x10c" },
{ 0x10d , "0x10d" },
{ 0x10e , "0x10e" },
{ 0x10f , "0x10f" },
//{ BTN_MOUSE , "Mouse" }, same as BTN_LEFT
{ BTN_LEFT , "Left" },
{ BTN_RIGHT , "Right" },
{ BTN_MIDDLE , "Middle" },
{ BTN_SIDE , "Side" },
{ BTN_EXTRA , "Extra" },
{ BTN_FORWARD , "Forward" },
{ BTN_BACK , "Back" },
{ BTN_TASK , "Task" },
{ 0x118 , "0x118" },
{ 0x119 , "0x119" },
{ 0x11a , "0x11a" },
{ 0x11b , "0x11b" },
{ 0x11c , "0x11c" },
{ 0x11d , "0x11d" },
{ 0x11e , "0x11e" },
{ 0x11f , "0x11f" },
//{ BTN_JOYSTICK , "Joystick" }, same as BTN_TRIGGER
{ BTN_TRIGGER , "Trigger" },
{ BTN_THUMB , "Thumb" },
{ BTN_THUMB2 , "Thumb 2" },
{ BTN_TOP , "Top" },
{ BTN_TOP2 , "Top 2" },
{ BTN_PINKIE , "Pinkie" },
{ BTN_BASE , "Base" },
{ BTN_BASE2 , "Base 2" },
{ BTN_BASE3 , "Base 3" },
{ BTN_BASE4 , "Base 4" },
{ BTN_BASE5 , "Base 5" },
{ BTN_BASE6 , "Base 6" },
{ 0x12c , "0x12c" },
{ 0x12d , "0x12d" },
{ 0x12e , "0x12e" },
{ BTN_DEAD , "Dead" },
//{ BTN_GAMEPAD , "Gamepad" }, same as BTN_A
//{ BTN_SOUTH , "South" }, same as BTN_A
{ BTN_A , "A" },
//{ BTN_EAST , "South" }, same as BTN_B
{ BTN_B , "B" },
{ BTN_C , "C" },
//{ BTN_NORTH , "North" }, same as BTN_X
{ BTN_X , "X" },
//{ BTN_WEST , "West" }, same as BTN_Y
{ BTN_Y , "Y" },
{ BTN_Z , "Z" },
{ BTN_TL , "TL" },
{ BTN_TR , "TR" },
{ BTN_TL2 , "TL 2" },
{ BTN_TR2 , "TR 2" },
{ BTN_SELECT , "Select" },
{ BTN_START , "Start" },
{ BTN_MODE , "Mode" },
{ BTN_THUMBL , "Thumb L" },
{ BTN_THUMBR , "Thumb R" },
{ 0x13f , "0x13f" },
//{ BTN_DIGI , "Digi" }, same as BTN_TOOL_PEN
{ BTN_TOOL_PEN , "Pen" },
{ BTN_TOOL_RUBBER , "Rubber" },
{ BTN_TOOL_BRUSH , "Brush" },
{ BTN_TOOL_PENCIL , "Pencil" },
{ BTN_TOOL_AIRBRUSH , "Airbrush" },
{ BTN_TOOL_FINGER , "Finger" },
{ BTN_TOOL_MOUSE , "Mouse" },
{ BTN_TOOL_LENS , "Lense" },
{ BTN_TOOL_QUINTTAP , "Quinttap" },
{ 0x149 , "0x149" },
{ BTN_TOUCH , "Touch" },
{ BTN_STYLUS , "Stylus" },
{ BTN_STYLUS2 , "Stylus 2" },
{ BTN_TOOL_DOUBLETAP , "Doubletap" },
{ BTN_TOOL_TRIPLETAP , "Tripletap" },
{ BTN_TOOL_QUADTAP , "Quadtap" },
//{ BTN_WHEEL , "Wheel" }, same as BTN_GEAR_DOWN
{ BTN_GEAR_DOWN , "Gear Up" },
{ BTN_GEAR_UP , "Gear Down" },
{ BTN_DPAD_UP , "D-Pad Up" },
{ BTN_DPAD_DOWN , "D-Pad Down" },
{ BTN_DPAD_LEFT , "D-Pad Left" },
{ BTN_DPAD_RIGHT , "D-Pad Right" },
{ BTN_TRIGGER_HAPPY , "Happy" },
{ BTN_TRIGGER_HAPPY1 , "Happy 1" },
{ BTN_TRIGGER_HAPPY2 , "Happy 2" },
{ BTN_TRIGGER_HAPPY3 , "Happy 3" },
{ BTN_TRIGGER_HAPPY4 , "Happy 4" },
{ BTN_TRIGGER_HAPPY5 , "Happy 5" },
{ BTN_TRIGGER_HAPPY6 , "Happy 6" },
{ BTN_TRIGGER_HAPPY7 , "Happy 7" },
{ BTN_TRIGGER_HAPPY8 , "Happy 8" },
{ BTN_TRIGGER_HAPPY9 , "Happy 9" },
{ BTN_TRIGGER_HAPPY10 , "Happy 10" },
{ BTN_TRIGGER_HAPPY11 , "Happy 11" },
{ BTN_TRIGGER_HAPPY12 , "Happy 12" },
{ BTN_TRIGGER_HAPPY13 , "Happy 13" },
{ BTN_TRIGGER_HAPPY14 , "Happy 14" },
{ BTN_TRIGGER_HAPPY15 , "Happy 15" },
{ BTN_TRIGGER_HAPPY16 , "Happy 16" },
{ BTN_TRIGGER_HAPPY17 , "Happy 17" },
{ BTN_TRIGGER_HAPPY18 , "Happy 18" },
{ BTN_TRIGGER_HAPPY19 , "Happy 19" },
{ BTN_TRIGGER_HAPPY20 , "Happy 20" },
{ BTN_TRIGGER_HAPPY21 , "Happy 21" },
{ BTN_TRIGGER_HAPPY22 , "Happy 22" },
{ BTN_TRIGGER_HAPPY23 , "Happy 23" },
{ BTN_TRIGGER_HAPPY24 , "Happy 24" },
{ BTN_TRIGGER_HAPPY25 , "Happy 25" },
{ BTN_TRIGGER_HAPPY26 , "Happy 26" },
{ BTN_TRIGGER_HAPPY27 , "Happy 27" },
{ BTN_TRIGGER_HAPPY28 , "Happy 28" },
{ BTN_TRIGGER_HAPPY29 , "Happy 29" },
{ BTN_TRIGGER_HAPPY30 , "Happy 30" },
{ BTN_TRIGGER_HAPPY31 , "Happy 31" },
{ BTN_TRIGGER_HAPPY32 , "Happy 32" },
{ BTN_TRIGGER_HAPPY33 , "Happy 33" },
{ BTN_TRIGGER_HAPPY34 , "Happy 34" },
{ BTN_TRIGGER_HAPPY35 , "Happy 35" },
{ BTN_TRIGGER_HAPPY36 , "Happy 36" },
{ BTN_TRIGGER_HAPPY37 , "Happy 37" },
{ BTN_TRIGGER_HAPPY38 , "Happy 38" },
{ BTN_TRIGGER_HAPPY39 , "Happy 39" },
{ BTN_TRIGGER_HAPPY40 , "Happy 40" }
};
// Unique positive axis names for the config files and our pad settings dialog
const std::unordered_map<u32, std::string> axis_list =
{
{ ABS_X , "LX+" },
{ ABS_Y , "LY+" },
{ ABS_Z , "LZ+" },
{ ABS_RX , "RX+" },
{ ABS_RY , "RY+" },
{ ABS_RZ , "RZ+" },
{ ABS_THROTTLE , "Throttle+" },
{ ABS_RUDDER , "Rudder+" },
{ ABS_WHEEL , "Wheel+" },
{ ABS_GAS , "Gas+" },
{ ABS_BRAKE , "Brake+" },
{ ABS_HAT0X , "Hat0 X+" },
{ ABS_HAT0Y , "Hat0 Y+" },
{ ABS_HAT1X , "Hat1 X+" },
{ ABS_HAT1Y , "Hat1 Y+" },
{ ABS_HAT2X , "Hat2 X+" },
{ ABS_HAT2Y , "Hat2 Y+" },
{ ABS_HAT3X , "Hat3 X+" },
{ ABS_HAT3Y , "Hat3 Y+" },
{ ABS_PRESSURE , "Pressure+" },
{ ABS_DISTANCE , "Distance+" },
{ ABS_TILT_X , "Tilt X+" },
{ ABS_TILT_Y , "Tilt Y+" },
{ ABS_TOOL_WIDTH , "Width+" },
{ ABS_VOLUME , "Volume+" },
{ ABS_MISC , "Misc+" },
{ ABS_MT_SLOT , "Slot+" },
{ ABS_MT_TOUCH_MAJOR , "MT TMaj+" },
{ ABS_MT_TOUCH_MINOR , "MT TMin+" },
{ ABS_MT_WIDTH_MAJOR , "MT WMaj+" },
{ ABS_MT_WIDTH_MINOR , "MT WMin+" },
{ ABS_MT_ORIENTATION , "MT Orient+" },
{ ABS_MT_POSITION_X , "MT PosX+" },
{ ABS_MT_POSITION_Y , "MT PosY+" },
{ ABS_MT_TOOL_TYPE , "MT TType+" },
{ ABS_MT_BLOB_ID , "MT Blob ID+" },
{ ABS_MT_TRACKING_ID , "MT Track ID+" },
{ ABS_MT_PRESSURE , "MT Pressure+" },
{ ABS_MT_DISTANCE , "MT Distance+" },
{ ABS_MT_TOOL_X , "MT Tool X+" },
{ ABS_MT_TOOL_Y , "MT Tool Y+" },
};
// Unique negative axis names for the config files and our pad settings dialog
const std::unordered_map<u32, std::string> rev_axis_list =
{
{ ABS_X , "LX-" },
{ ABS_Y , "LY-" },
{ ABS_Z , "LZ-" },
{ ABS_RX , "RX-" },
{ ABS_RY , "RY-" },
{ ABS_RZ , "RZ-" },
{ ABS_THROTTLE , "Throttle-" },
{ ABS_RUDDER , "Rudder-" },
{ ABS_WHEEL , "Wheel-" },
{ ABS_GAS , "Gas-" },
{ ABS_BRAKE , "Brake-" },
{ ABS_HAT0X , "Hat0 X-" },
{ ABS_HAT0Y , "Hat0 Y-" },
{ ABS_HAT1X , "Hat1 X-" },
{ ABS_HAT1Y , "Hat1 Y-" },
{ ABS_HAT2X , "Hat2 X-" },
{ ABS_HAT2Y , "Hat2 Y-" },
{ ABS_HAT3X , "Hat3 X-" },
{ ABS_HAT3Y , "Hat3 Y-" },
{ ABS_PRESSURE , "Pressure-" },
{ ABS_DISTANCE , "Distance-" },
{ ABS_TILT_X , "Tilt X-" },
{ ABS_TILT_Y , "Tilt Y-" },
{ ABS_TOOL_WIDTH , "Width-" },
{ ABS_VOLUME , "Volume-" },
{ ABS_MISC , "Misc-" },
{ ABS_MT_SLOT , "Slot-" },
{ ABS_MT_TOUCH_MAJOR , "MT TMaj-" },
{ ABS_MT_TOUCH_MINOR , "MT TMin-" },
{ ABS_MT_WIDTH_MAJOR , "MT WMaj-" },
{ ABS_MT_WIDTH_MINOR , "MT WMin-" },
{ ABS_MT_ORIENTATION , "MT Orient-" },
{ ABS_MT_POSITION_X , "MT PosX-" },
{ ABS_MT_POSITION_Y , "MT PosY-" },
{ ABS_MT_TOOL_TYPE , "MT TType-" },
{ ABS_MT_BLOB_ID , "MT Blob ID-" },
{ ABS_MT_TRACKING_ID , "MT Track ID-" },
{ ABS_MT_PRESSURE , "MT Pressure-" },
{ ABS_MT_DISTANCE , "MT Distance-" },
{ ABS_MT_TOOL_X , "MT Tool X-" },
{ ABS_MT_TOOL_Y , "MT Tool Y-" },
};
// Unique motion axis names for the config files and our pad settings dialog
const std::unordered_map<u32, std::string> motion_axis_list =
{
{ ABS_X , "X" },
{ ABS_Y , "Y" },
{ ABS_Z , "Z" },
{ ABS_RX , "RX" },
{ ABS_RY , "RY" },
{ ABS_RZ , "RZ" },
};
struct EvdevButton
{
u32 code = 0; // key code of our button or axis
int dir = 0; // dir is -1 in case of a button, 0 in case of a regular axis and 1 in case of a reverse axis
int type = 0; // EV_KEY or EV_ABS
};
struct evdev_sensor : public EvdevButton
{
bool mirrored = false;
s32 shift = 0;
};
struct input_event_wrapper
{
int type{}; // EV_KEY or EV_ABS
bool is_initialized{};
};
struct key_event_wrapper : public input_event_wrapper
{
key_event_wrapper() { type = EV_KEY; }
u16 value{};
};
struct axis_event_wrapper : public input_event_wrapper
{
axis_event_wrapper() { type = EV_ABS; }
std::map<bool, u16> values{}; // direction (negative = true)
bool is_trigger{};
int min{};
int max{};
int flat{};
};
struct EvdevDevice : public PadDevice
{
libevdev* device{ nullptr };
std::string path;
std::vector<EvdevButton> all_buttons;
std::set<u32> trigger_left{};
std::set<u32> trigger_right{};
std::array<std::set<u32>, 4> axis_left{};
std::array<std::set<u32>, 4> axis_right{};
std::array<evdev_sensor, 4> axis_motion{};
std::map<u32, std::shared_ptr<input_event_wrapper>> events_by_code;
int cur_dir = 0;
int cur_type = 0;
int effect_id = -1;
bool has_rumble = false;
bool has_motion = false;
};
public:
evdev_joystick_handler();
~evdev_joystick_handler();
void init_config(cfg_pad* cfg) override;
bool Init() override;
std::vector<pad_list_entry> list_devices() override;
bool bindPadToDevice(std::shared_ptr<Pad> pad) override;
connection get_next_button_press(const std::string& padId, const pad_callback& callback, const pad_fail_callback& fail_callback, gui_call_type call_type, const std::vector<std::string>& buttons) override;
void get_motion_sensors(const std::string& padId, const motion_callback& callback, const motion_fail_callback& fail_callback, motion_preview_values preview_values, const std::array<AnalogSensor, 4>& sensors) override;
std::unordered_map<u32, std::string> get_motion_axis_list() const override;
void SetPadData(const std::string& padId, u8 player_id, u8 large_motor, u8 small_motor, s32 r, s32 g, s32 b, bool player_led, bool battery_led, u32 battery_led_brightness) override;
private:
void close_devices();
std::shared_ptr<EvdevDevice> get_evdev_device(const std::string& device);
std::string get_device_name(const libevdev* dev);
bool update_device(const std::shared_ptr<PadDevice>& device);
std::shared_ptr<evdev_joystick_handler::EvdevDevice> add_device(const std::string& device, bool in_settings = false);
std::shared_ptr<evdev_joystick_handler::EvdevDevice> add_motion_device(const std::string& device, bool in_settings);
std::unordered_map<u64, std::pair<u16, bool>> GetButtonValues(const std::shared_ptr<EvdevDevice>& device);
void SetRumble(EvdevDevice* device, u8 large, u8 small);
positive_axis m_pos_axis_config;
std::set<u32> m_positive_axis;
std::set<std::string> m_blacklist;
std::unordered_map<std::string, u16> m_min_button_values;
std::unordered_map<std::string, std::shared_ptr<evdev_joystick_handler::EvdevDevice>> m_settings_added;
std::unordered_map<std::string, std::shared_ptr<evdev_joystick_handler::EvdevDevice>> m_motion_settings_added;
std::shared_ptr<EvdevDevice> m_dev;
bool check_button_set(const std::set<u32>& indices, const u32 code);
bool check_button_sets(const std::array<std::set<u32>, 4>& sets, const u32 code);
void apply_input_events(const std::shared_ptr<Pad>& pad);
u16 get_sensor_value(const libevdev* dev, const AnalogSensor& sensor, const input_event& evt) const;
protected:
PadHandlerBase::connection update_connection(const std::shared_ptr<PadDevice>& device) override;
void get_mapping(const pad_ensemble& binding) override;
void get_extended_info(const pad_ensemble& binding) override;
void apply_pad_data(const pad_ensemble& binding) override;
bool get_is_left_trigger(const std::shared_ptr<PadDevice>& device, u64 keyCode) override;
bool get_is_right_trigger(const std::shared_ptr<PadDevice>& device, u64 keyCode) override;
bool get_is_left_stick(const std::shared_ptr<PadDevice>& device, u64 keyCode) override;
bool get_is_right_stick(const std::shared_ptr<PadDevice>& device, u64 keyCode) override;
};
#endif
| 18,239
|
C++
|
.h
| 422
| 40.542654
| 218
| 0.522008
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,625
|
evdev_gun_handler.h
|
RPCS3_rpcs3/rpcs3/Input/evdev_gun_handler.h
|
#pragma once
#ifdef HAVE_LIBEVDEV
#include <array>
#include <map>
#include "Utilities/mutex.h"
enum class gun_button
{
btn_left,
btn_right,
btn_middle,
btn_1,
btn_2,
btn_3,
btn_4,
btn_5,
btn_6,
btn_7,
btn_8
};
class evdev_gun_handler
{
public:
evdev_gun_handler();
~evdev_gun_handler();
bool init();
bool is_init() const;
u32 get_num_guns() const;
int get_button(u32 gunno, gun_button button) const;
int get_axis_x(u32 gunno) const;
int get_axis_y(u32 gunno) const;
int get_axis_x_max(u32 gunno) const;
int get_axis_y_max(u32 gunno) const;
void poll(u32 index);
shared_mutex mutex;
private:
atomic_t<bool> m_is_init{false};
struct udev* m_udev = nullptr;
struct evdev_axis
{
int value = 0;
int min = 0;
int max = 0;
};
struct evdev_gun
{
struct libevdev* device = nullptr;
std::map<int, int> buttons;
std::map<int, evdev_axis> axis;
};
std::vector<evdev_gun> m_devices;
};
#endif
| 936
|
C++
|
.h
| 52
| 15.923077
| 52
| 0.708716
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,626
|
xinput_pad_handler.h
|
RPCS3_rpcs3/rpcs3/Input/xinput_pad_handler.h
|
#pragma once
#include "Emu/Io/PadHandler.h"
#include <unordered_map>
#ifndef NOMINMAX
#define NOMINMAX
#endif
#include <Windows.h>
#include <Xinput.h>
#include <chrono>
// ScpToolkit defined structure for pressure sensitive button query
struct SCP_EXTN
{
float SCP_UP;
float SCP_RIGHT;
float SCP_DOWN;
float SCP_LEFT;
float SCP_LX;
float SCP_LY;
float SCP_L1;
float SCP_L2;
float SCP_L3;
float SCP_RX;
float SCP_RY;
float SCP_R1;
float SCP_R2;
float SCP_R3;
float SCP_T;
float SCP_C;
float SCP_X;
float SCP_S;
float SCP_SELECT;
float SCP_START;
float SCP_PS;
};
struct SCP_DS3_ACCEL
{
unsigned short SCP_ACCEL_X;
unsigned short SCP_ACCEL_Z;
unsigned short SCP_ACCEL_Y;
unsigned short SCP_GYRO;
};
class xinput_pad_handler final : public PadHandlerBase
{
// These are all the possible buttons on a standard xbox 360 or xbox one controller
enum XInputKeyCodes
{
None = 0,
A,
B,
X,
Y,
Left,
Right,
Up,
Down,
LB,
RB,
LS,
RS,
Start,
Back,
Guide,
LT,
RT,
LT_Pos,
LT_Neg,
RT_Pos,
RT_Neg,
LSXNeg,
LSXPos,
LSYNeg,
LSYPos,
RSXNeg,
RSXPos,
RSYNeg,
RSYPos
};
using PadButtonValues = std::unordered_map<u64, u16>;
struct XInputDevice : public PadDevice
{
u32 deviceNumber{ 0 };
bool is_scp_device{ false };
DWORD state{ ERROR_NOT_CONNECTED }; // holds internal controller state change
SCP_EXTN state_scp{};
XINPUT_STATE state_base{};
};
public:
xinput_pad_handler();
~xinput_pad_handler();
bool Init() override;
std::vector<pad_list_entry> list_devices() override;
void SetPadData(const std::string& padId, u8 player_id, u8 large_motor, u8 small_motor, s32 r, s32 g, s32 b, bool player_led, bool battery_led, u32 battery_led_brightness) override;
u32 get_battery_level(const std::string& padId) override;
void init_config(cfg_pad* cfg) override;
private:
typedef DWORD (WINAPI * PFN_XINPUTGETEXTENDED)(DWORD, SCP_EXTN *);
typedef DWORD (WINAPI * PFN_XINPUTGETCUSTOMDATA)(DWORD, DWORD, void *);
typedef DWORD (WINAPI * PFN_XINPUTGETSTATE)(DWORD, XINPUT_STATE *);
typedef DWORD (WINAPI * PFN_XINPUTSETSTATE)(DWORD, XINPUT_VIBRATION *);
typedef DWORD (WINAPI * PFN_XINPUTGETBATTERYINFORMATION)(DWORD, BYTE, XINPUT_BATTERY_INFORMATION *);
int GetDeviceNumber(const std::string& padId);
static PadButtonValues get_button_values_base(const XINPUT_STATE& state, trigger_recognition_mode trigger_mode);
static PadButtonValues get_button_values_scp(const SCP_EXTN& state, trigger_recognition_mode trigger_mode);
HMODULE library{ nullptr };
PFN_XINPUTGETEXTENDED xinputGetExtended{ nullptr };
PFN_XINPUTGETCUSTOMDATA xinputGetCustomData{ nullptr };
PFN_XINPUTGETSTATE xinputGetState{ nullptr };
PFN_XINPUTSETSTATE xinputSetState{ nullptr };
PFN_XINPUTGETBATTERYINFORMATION xinputGetBatteryInformation{ nullptr };
std::shared_ptr<PadDevice> get_device(const std::string& device) override;
bool get_is_left_trigger(const std::shared_ptr<PadDevice>& device, u64 keyCode) override;
bool get_is_right_trigger(const std::shared_ptr<PadDevice>& device, u64 keyCode) override;
bool get_is_left_stick(const std::shared_ptr<PadDevice>& device, u64 keyCode) override;
bool get_is_right_stick(const std::shared_ptr<PadDevice>& device, u64 keyCode) override;
PadHandlerBase::connection update_connection(const std::shared_ptr<PadDevice>& device) override;
void get_extended_info(const pad_ensemble& binding) override;
void apply_pad_data(const pad_ensemble& binding) override;
std::unordered_map<u64, u16> get_button_values(const std::shared_ptr<PadDevice>& device) override;
pad_preview_values get_preview_values(const std::unordered_map<u64, u16>& data) override;
};
| 3,693
|
C++
|
.h
| 120
| 28.441667
| 182
| 0.764308
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,627
|
hid_pad_handler.h
|
RPCS3_rpcs3/rpcs3/Input/hid_pad_handler.h
|
#pragma once
#include "Emu/Io/PadHandler.h"
#include "Utilities/CRC.h"
#include "Utilities/Thread.h"
#include "hidapi.h"
struct CalibData
{
s16 bias = 0;
s32 sens_numer = 0;
s32 sens_denom = 0;
};
enum CalibIndex
{
// gyro
PITCH = 0,
YAW,
ROLL,
// accel
X,
Y,
Z,
COUNT
};
class HidDevice : public PadDevice
{
public:
void close();
hid_device* hidDevice{nullptr};
std::string path;
bool enable_player_leds{false};
u8 led_delay_on{0};
u8 led_delay_off{0};
u8 battery_level{0};
u8 last_battery_level{0};
u8 cable_state{0};
};
struct id_pair
{
u16 m_vid = 0;
u16 m_pid = 0;
};
template <class Device>
class hid_pad_handler : public PadHandlerBase
{
public:
hid_pad_handler(pad_handler type, std::vector<id_pair> ids);
~hid_pad_handler();
bool Init() override;
void process() override;
std::vector<pad_list_entry> list_devices() override;
protected:
enum class DataStatus
{
NewData,
NoNewData,
ReadError,
};
CRCPP::CRC::Table<u32, 32> crcTable{CRCPP::CRC::CRC_32()};
std::vector<id_pair> m_ids;
// pseudo 'controller id' to keep track of unique controllers
std::map<std::string, std::shared_ptr<Device>> m_controllers;
std::set<std::string> m_last_enumerated_devices;
std::set<std::string> m_new_enumerated_devices;
std::map<std::string, std::wstring> m_enumerated_serials;
std::mutex m_enumeration_mutex;
std::unique_ptr<named_thread<std::function<void()>>> m_enumeration_thread;
void enumerate_devices();
void update_devices();
std::shared_ptr<Device> get_hid_device(const std::string& padId);
virtual void check_add_device(hid_device* hidDevice, std::string_view path, std::wstring_view serial) = 0;
virtual int send_output_report(Device* device) = 0;
virtual DataStatus get_data(Device* device) = 0;
static s16 apply_calibration(s32 raw_value, const CalibData& calib_data)
{
const s32 biased = raw_value - calib_data.bias;
const s32 quot = calib_data.sens_numer / calib_data.sens_denom;
const s32 rem = calib_data.sens_numer % calib_data.sens_denom;
const s32 output = (quot * biased) + ((rem * biased) / calib_data.sens_denom);
return static_cast<s16>(std::clamp<s32>(output, s16{smin}, s16{smax}));
}
static s16 read_s16(const void* buf)
{
return *static_cast<const s16*>(buf);
}
static u32 read_u32(const void* buf)
{
return *static_cast<const u32*>(buf);
}
static u32 get_battery_color(u8 battery_level, u32 brightness);
private:
std::shared_ptr<PadDevice> get_device(const std::string& device) override;
};
| 2,516
|
C++
|
.h
| 92
| 25.26087
| 107
| 0.72803
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,628
|
product_info.h
|
RPCS3_rpcs3/rpcs3/Input/product_info.h
|
#pragma once
#include <vector>
#include "Emu/Io/pad_types.h"
namespace input
{
enum class product_type
{
playstation_3_controller,
red_octane_gh_guitar,
red_octane_gh_drum_kit,
dance_dance_revolution_mat,
dj_hero_turntable,
harmonix_rockband_guitar,
harmonix_rockband_drum_kit,
harmonix_rockband_drum_kit_2,
rock_revolution_drum_kit,
ps_move_navigation,
ride_skateboard,
guncon_3,
top_shot_elite,
top_shot_fearmaster,
udraw_gametablet,
};
enum vendor_id
{
sony_corp = 0x054C, // Sony Corp.
namco = 0x0B9A, // Namco
sony_cea = 0x12BA, // Sony Computer Entertainment America
konami_de = 0x1CCF, // Konami Digital Entertainment
bda = 0x20D6, // Bensussen Deutsch & Associates
};
enum product_id
{
red_octane_gh_guitar = 0x0100, // RedOctane Guitar (Guitar Hero 4 Guitar Controller)
red_octane_gh_drum_kit = 0x0120, // RedOctane Drum Kit (Guitar Hero 4 Drum Controller)
dj_hero_turntable = 0x0140, // DJ Hero Turntable Controller
harmonix_rockband_guitar = 0x0200, // Harmonix Guitar (Rock Band II Guitar Controller)
harmonix_rockband_drum_kit = 0x0210, // Harmonix Drum Kit (Rock Band II Drum Controller)
harmonix_rockband_drum_kit_2 = 0x0218, // Harmonix Pro-Drum Kit (Rock Band III Pro-Drum Controller)
playstation_3_controller = 0x0268, // PlayStation 3 Controller
rock_revolution_drum_kit = 0x0300, // Rock Revolution Drum Controller
ps_move_navigation = 0x042F, // PlayStation Move navigation controller
dance_dance_revolution_mat = 0x1010, // Dance Dance Revolution Dance Mat Controller
ride_skateboard = 0x0400, // Tony Hawk RIDE Skateboard Controller
top_shot_elite = 0x04A0, // Top Shot Elite Controller
top_shot_fearmaster = 0x04A1, // Top Shot Fearmaster Controller
guncon_3 = 0x0800, // GunCon 3 Controller
udraw_gametablet = 0xCB17, // uDraw GameTablet Controller
};
struct product_info
{
product_type type;
u16 class_id;
u16 vendor_id;
u16 product_id;
u32 pclass_profile; // See CELL_PAD_PCLASS_PROFILE flags
u32 capabilites; // See CELL_PAD_CAPABILITY flags
};
product_info get_product_info(product_type type);
product_type get_product_by_vid_pid(u16 vid, u16 pid);
std::vector<product_info> get_products_by_class(int class_id);
}
| 2,376
|
C++
|
.h
| 62
| 35.66129
| 101
| 0.710139
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,629
|
basic_mouse_handler.h
|
RPCS3_rpcs3/rpcs3/Input/basic_mouse_handler.h
|
#pragma once
#include "util/types.hpp"
#include "Emu/Io/MouseHandler.h"
#include <QWindow>
#include <QMouseEvent>
#include <QWheelEvent>
namespace cfg
{
class string;
}
class basic_mouse_handler final : public MouseHandlerBase, public QObject
{
using MouseHandlerBase::MouseHandlerBase;
public:
void Init(const u32 max_connect) override;
void SetTargetWindow(QWindow* target);
void MouseButtonDown(QMouseEvent* event);
void MouseButtonUp(QMouseEvent* event);
void MouseScroll(QWheelEvent* event);
void MouseMove(QMouseEvent* event);
bool eventFilter(QObject* obj, QEvent* ev) override;
private:
void reload_config();
bool get_mouse_lock_state() const;
static int get_mouse_button(const cfg::string& button);
QWindow* m_target = nullptr;
std::map<u8, int> m_buttons;
};
| 791
|
C++
|
.h
| 28
| 26.464286
| 73
| 0.793377
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,630
|
unzip.h
|
RPCS3_rpcs3/rpcs3/Crypto/unzip.h
|
#pragma once
std::vector<u8> unzip(const void* src, usz size);
template <typename T>
inline std::vector<u8> unzip(const T& src)
{
return unzip(src.data(), src.size());
}
bool unzip(const void* src, usz size, fs::file& out);
template <typename T>
inline bool unzip(const std::vector<u8>& src, fs::file& out)
{
return unzip(src.data(), src.size(), out);
}
bool zip(const void* src, usz size, fs::file& out, bool multi_thread_it = false);
template <typename T>
inline bool zip(const T& src, fs::file& out)
{
return zip(src.data(), src.size(), out);
}
| 557
|
C++
|
.h
| 19
| 27.842105
| 81
| 0.703008
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,631
|
unself.h
|
RPCS3_rpcs3/rpcs3/Crypto/unself.h
|
#pragma once
#include "key_vault.h"
#include "zlib.h"
#include "util/types.hpp"
#include "Utilities/File.h"
#include "util/logs.hpp"
#include "unedat.h"
LOG_CHANNEL(self_log, "SELF");
// SCE-specific definitions for e_type:
enum
{
ET_SCE_EXEC = 0xFE00, // SCE Executable - PRX2
ET_SCE_RELEXEC = 0xFE04, // SCE Relocatable Executable - PRX2
ET_SCE_STUBLIB = 0xFE0C, // SCE SDK Stubs
ET_SCE_DYNEXEC = 0xFE10, // SCE EXEC_ASLR (PS4 Executable with ASLR)
ET_SCE_DYNAMIC = 0xFE18, // ?
ET_SCE_IOPRELEXEC = 0xFF80, // SCE IOP Relocatable Executable
ET_SCE_IOPRELEXEC2 = 0xFF81, // SCE IOP Relocatable Executable Version 2
ET_SCE_EERELEXEC = 0xFF90, // SCE EE Relocatable Executable
ET_SCE_EERELEXEC2 = 0xFF91, // SCE EE Relocatable Executable Version 2
ET_SCE_PSPRELEXEC = 0xFFA0, // SCE PSP Relocatable Executable
ET_SCE_PPURELEXEC = 0xFFA4, // SCE PPU Relocatable Executable
ET_SCE_ARMRELEXEC = 0xFFA5, // ?SCE ARM Relocatable Executable (PS Vita System Software earlier or equal 0.931.010)
ET_SCE_PSPOVERLAY = 0xFFA8, // ?
};
enum
{
ELFOSABI_CELL_LV2 = 102 // CELL LV2
};
enum
{
PT_SCE_RELA = 0x60000000,
PT_SCE_LICINFO_1 = 0x60000001,
PT_SCE_LICINFO_2 = 0x60000002,
PT_SCE_DYNLIBDATA = 0x61000000,
PT_SCE_PROCPARAM = 0x61000001,
PT_SCE_UNK_61000010 = 0x61000010,
PT_SCE_COMMENT = 0x6FFFFF00,
PT_SCE_LIBVERSION = 0x6FFFFF01,
PT_SCE_UNK_70000001 = 0x70000001,
PT_SCE_IOPMOD = 0x70000080,
PT_SCE_EEMOD = 0x70000090,
PT_SCE_PSPRELA = 0x700000A0,
PT_SCE_PSPRELA2 = 0x700000A1,
PT_SCE_PPURELA = 0x700000A4,
PT_SCE_SEGSYM = 0x700000A8,
};
enum
{
PF_SPU_X = 0x00100000,
PF_SPU_W = 0x00200000,
PF_SPU_R = 0x00400000,
PF_RSX_X = 0x01000000,
PF_RSX_W = 0x02000000,
PF_RSX_R = 0x04000000,
};
enum
{
SHT_SCE_RELA = 0x60000000,
SHT_SCE_NID = 0x61000001,
SHT_SCE_IOPMOD = 0x70000080,
SHT_SCE_EEMOD = 0x70000090,
SHT_SCE_PSPRELA = 0x700000A0,
SHT_SCE_PPURELA = 0x700000A4,
};
struct program_identification_header
{
u64 program_authority_id;
u32 program_vendor_id;
u32 program_type;
u64 program_sceversion;
u64 padding;
void Load(const fs::file& f);
void Show() const;
};
struct segment_ext_header
{
u64 offset; // Offset to data
u64 size; // Size of data
u32 compression; // 1 = plain, 2 = zlib
u32 unknown; // Always 0, as far as I know.
u64 encryption; // 0 = unrequested, 1 = completed, 2 = requested
void Load(const fs::file& f);
void Show() const;
};
struct version_header
{
u32 subheader_type; // 1 - sceversion
u32 present; // 0 = false, 1 = true
u32 size; // usually 0x10
u32 unknown4;
void Load(const fs::file& f);
void Show() const;
};
struct supplemental_header
{
u32 type; // 1=PS3 plaintext_capability; 2=PS3 ELF digest; 3=PS3 NPDRM, 4=PS Vita ELF digest; 5=PS Vita NPDRM; 6=PS Vita boot param; 7=PS Vita shared secret
u32 size;
u64 next; // 1 if another Supplemental Header element follows else 0
union
{
// type 1, 0x30 bytes
struct // 0x20 bytes of data
{
u32 ctrl_flag1;
u32 unknown1;
u32 unknown2;
u32 unknown3;
u32 unknown4;
u32 unknown5;
u32 unknown6;
u32 unknown7;
} PS3_plaintext_capability_header;
// type 2, 0x40 bytes
struct // 0x30 bytes of data
{
u8 constant[0x14]; // same for every PS3/PS Vita SELF, hardcoded in make_fself.exe: 627CB1808AB938E32C8C091708726A579E2586E4
u8 elf_digest[0x14]; // SHA-1. Hash F2C552BF716ED24759CBE8A0A9A6DB9965F3811C is blacklisted by appldr
u64 required_system_version; // filled on Sony authentication server, contains decimal PS3_SYSTEM_VER value from PARAM.SFO
} PS3_elf_digest_header_40;
// type 2, 0x30 bytes
struct // 0x20 bytes of data
{
u8 constant_or_elf_digest[0x14];
u8 padding[0xC];
} PS3_elf_digest_header_30;
// type 3, 0x90 bytes
struct // 0x80 bytes of data
{
NPD_HEADER npd;
} PS3_npdrm_header;
};
void Load(const fs::file& f);
void Show() const;
};
struct MetadataInfo
{
u8 key[0x10];
u8 key_pad[0x10];
u8 iv[0x10];
u8 iv_pad[0x10];
void Load(u8* in);
void Show() const;
};
struct MetadataHeader
{
u64 signature_input_length;
u32 unknown1;
u32 section_count;
u32 key_count;
u32 opt_header_size;
u32 unknown2;
u32 unknown3;
void Load(u8* in);
void Show() const;
};
struct MetadataSectionHeader
{
u64 data_offset;
u64 data_size;
u32 type;
u32 program_idx;
u32 hashed;
u32 sha1_idx;
u32 encrypted;
u32 key_idx;
u32 iv_idx;
u32 compressed;
void Load(u8* in);
void Show() const;
};
struct SectionHash
{
u8 sha1[20];
u8 padding[12];
u8 hmac_key[64];
void Load(const fs::file& f);
};
struct CapabilitiesInfo
{
u32 type;
u32 capabilities_size;
u32 next;
u32 unknown1;
u64 unknown2;
u64 unknown3;
u64 flags;
u32 unknown4;
u32 unknown5;
void Load(const fs::file& f);
};
struct Signature
{
u8 r[21];
u8 s[21];
u8 padding[6];
void Load(const fs::file& f);
};
struct SelfSection
{
u8* data;
u64 size;
u64 offset;
void Load(const fs::file& f);
};
struct Elf32_Ehdr
{
//u8 e_ident[16]; // ELF identification
u32 e_magic;
u8 e_class;
u8 e_data;
u8 e_curver;
u8 e_os_abi;
u64 e_abi_ver;
u16 e_type; // object file type
u16 e_machine; // machine type
u32 e_version; // object file version
u32 e_entry; // entry point address
u32 e_phoff; // program header offset
u32 e_shoff; // section header offset
u32 e_flags; // processor-specific flags
u16 e_ehsize; // ELF header size
u16 e_phentsize; // size of program header entry
u16 e_phnum; // number of program header entries
u16 e_shentsize; // size of section header entry
u16 e_shnum; // number of section header entries
u16 e_shstrndx; // section name string table index
void Load(const fs::file& f);
static void Show() {}
bool IsLittleEndian() const { return e_data == 1; }
bool CheckMagic() const { return e_magic == 0x7F454C46; }
u32 GetEntry() const { return e_entry; }
};
struct Elf32_Shdr
{
u32 sh_name; // section name
u32 sh_type; // section type
u32 sh_flags; // section attributes
u32 sh_addr; // virtual address in memory
u32 sh_offset; // offset in file
u32 sh_size; // size of section
u32 sh_link; // link to other section
u32 sh_info; // miscellaneous information
u32 sh_addralign; // address alignment boundary
u32 sh_entsize; // size of entries, if section has table
void Load(const fs::file& f);
void LoadLE(const fs::file& f);
static void Show() {}
};
struct Elf32_Phdr
{
u32 p_type; // Segment type
u32 p_offset; // Segment file offset
u32 p_vaddr; // Segment virtual address
u32 p_paddr; // Segment physical address
u32 p_filesz; // Segment size in file
u32 p_memsz; // Segment size in memory
u32 p_flags; // Segment flags
u32 p_align; // Segment alignment
void Load(const fs::file& f);
void LoadLE(const fs::file& f);
static void Show() {}
};
struct Elf64_Ehdr
{
//u8 e_ident[16]; // ELF identification
u32 e_magic;
u8 e_class;
u8 e_data;
u8 e_curver;
u8 e_os_abi;
u64 e_abi_ver;
u16 e_type; // object file type
u16 e_machine; // machine type
u32 e_version; // object file version
u64 e_entry; // entry point address
u64 e_phoff; // program header offset
u64 e_shoff; // section header offset
u32 e_flags; // processor-specific flags
u16 e_ehsize; // ELF header size
u16 e_phentsize; // size of program header entry
u16 e_phnum; // number of program header entries
u16 e_shentsize; // size of section header entry
u16 e_shnum; // number of section header entries
u16 e_shstrndx; // section name string table index
void Load(const fs::file& f);
static void Show() {}
bool CheckMagic() const { return e_magic == 0x7F454C46; }
u64 GetEntry() const { return e_entry; }
};
struct Elf64_Shdr
{
u32 sh_name; // section name
u32 sh_type; // section type
u64 sh_flags; // section attributes
u64 sh_addr; // virtual address in memory
u64 sh_offset; // offset in file
u64 sh_size; // size of section
u32 sh_link; // link to other section
u32 sh_info; // miscellaneous information
u64 sh_addralign; // address alignment boundary
u64 sh_entsize; // size of entries, if section has table
void Load(const fs::file& f);
static void Show(){}
};
struct Elf64_Phdr
{
u32 p_type; // Segment type
u32 p_flags; // Segment flags
u64 p_offset; // Segment file offset
u64 p_vaddr; // Segment virtual address
u64 p_paddr; // Segment physical address
u64 p_filesz; // Segment size in file
u64 p_memsz; // Segment size in memory
u64 p_align; // Segment alignment
void Load(const fs::file& f);
static void Show(){}
};
struct SceHeader
{
u32 se_magic;
u32 se_hver;
u16 se_flags;
u16 se_type;
u32 se_meta;
u64 se_hsize;
u64 se_esize;
void Load(const fs::file& f);
static void Show(){}
bool CheckMagic() const { return se_magic == 0x53434500; }
};
struct ext_hdr
{
u64 ext_hdr_version;
u64 program_identification_hdr_offset;
u64 ehdr_offset;
u64 phdr_offset;
u64 shdr_offset;
u64 segment_ext_hdr_offset;
u64 version_hdr_offset;
u64 supplemental_hdr_offset;
u64 supplemental_hdr_size;
u64 padding;
void Load(const fs::file& f);
static void Show(){}
};
struct SelfAdditionalInfo
{
bool valid = false;
std::vector<supplemental_header> supplemental_hdr;
program_identification_header prog_id_hdr;
};
class SCEDecrypter
{
protected:
// Main SELF file stream.
const fs::file& sce_f;
// SCE headers.
SceHeader sce_hdr{};
// Metadata structs.
MetadataInfo meta_info{};
MetadataHeader meta_hdr{};
std::vector<MetadataSectionHeader> meta_shdr{};
// Internal data buffers.
std::unique_ptr<u8[]> data_keys{};
u32 data_keys_length{};
std::unique_ptr<u8[]> data_buf{};
u32 data_buf_length{};
public:
SCEDecrypter(const fs::file& s);
std::vector<fs::file> MakeFile();
bool LoadHeaders();
bool LoadMetadata(const u8 erk[32], const u8 riv[16]);
bool DecryptData();
};
class SELFDecrypter
{
// Main SELF file stream.
const fs::file& self_f;
// SCE, SELF and APP headers.
SceHeader sce_hdr{};
ext_hdr m_ext_hdr{};
program_identification_header m_prog_id_hdr{};
// ELF64 header and program header/section header arrays.
Elf64_Ehdr elf64_hdr{};
std::vector<Elf64_Shdr> shdr64_arr{};
std::vector<Elf64_Phdr> phdr64_arr{};
// ELF32 header and program header/section header arrays.
Elf32_Ehdr elf32_hdr{};
std::vector<Elf32_Shdr> shdr32_arr{};
std::vector<Elf32_Phdr> phdr32_arr{};
// Decryption info structs.
std::vector<segment_ext_header> m_seg_ext_hdr{};
version_header m_version_hdr{};
std::vector<supplemental_header> m_supplemental_hdr_arr{};
// Metadata structs.
MetadataInfo meta_info{};
MetadataHeader meta_hdr{};
std::vector<MetadataSectionHeader> meta_shdr{};
// Internal data buffers.
std::unique_ptr<u8[]> data_keys{};
u32 data_keys_length{};
std::unique_ptr<u8[]> data_buf{};
u32 data_buf_length{};
// Main key vault instance.
KeyVault key_v{};
public:
SELFDecrypter(const fs::file& s);
fs::file MakeElf(bool isElf32);
bool LoadHeaders(bool isElf32, SelfAdditionalInfo* out_info = nullptr);
void ShowHeaders(bool isElf32);
bool LoadMetadata(u8* klic_key);
bool DecryptData();
bool DecryptNPDRM(u8 *metadata, u32 metadata_size);
const NPD_HEADER* GetNPDHeader() const;
static bool GetKeyFromRap(const char *content_id, u8 *npdrm_key);
private:
template<typename EHdr, typename SHdr, typename PHdr>
void WriteElf(fs::file& e, EHdr ehdr, SHdr shdr, PHdr phdr)
{
// Set initial offset.
u32 data_buf_offset = 0;
// Write ELF header.
WriteEhdr(e, ehdr);
// Write program headers.
for (u32 i = 0; i < ehdr.e_phnum; ++i)
{
WritePhdr(e, phdr[i]);
}
for (unsigned int i = 0; i < meta_hdr.section_count; i++)
{
// PHDR type.
if (meta_shdr[i].type == 2)
{
// Decompress if necessary.
if (meta_shdr[i].compressed == 2)
{
const auto filesz = phdr[meta_shdr[i].program_idx].p_filesz;
// Create a pointer to a buffer for decompression.
std::unique_ptr<u8[]> decomp_buf(new u8[filesz]);
// Create a buffer separate from data_buf to uncompress.
std::unique_ptr<u8[]> zlib_buf(new u8[data_buf_length]);
memcpy(zlib_buf.get(), data_buf.get(), data_buf_length);
uLongf decomp_buf_length = ::narrow<uLongf>(filesz);
// Use zlib uncompress on the new buffer.
// decomp_buf_length changes inside the call to uncompress
const int rv = uncompress(decomp_buf.get(), &decomp_buf_length, zlib_buf.get() + data_buf_offset, data_buf_length);
// Check for errors (TODO: Probably safe to remove this once these changes have passed testing.)
switch (rv)
{
case Z_MEM_ERROR: self_log.error("MakeELF encountered a Z_MEM_ERROR!"); break;
case Z_BUF_ERROR: self_log.error("MakeELF encountered a Z_BUF_ERROR!"); break;
case Z_DATA_ERROR: self_log.error("MakeELF encountered a Z_DATA_ERROR!"); break;
default: break;
}
// Seek to the program header data offset and write the data.
e.seek(phdr[meta_shdr[i].program_idx].p_offset);
e.write(decomp_buf.get(), filesz);
}
else
{
// Seek to the program header data offset and write the data.
e.seek(phdr[meta_shdr[i].program_idx].p_offset);
e.write(data_buf.get() + data_buf_offset, meta_shdr[i].data_size);
}
// Advance the data buffer offset by data size.
data_buf_offset += ::narrow<u32>(meta_shdr[i].data_size);
}
}
// Write section headers.
if (m_ext_hdr.shdr_offset != 0)
{
e.seek(ehdr.e_shoff);
for (u32 i = 0; i < ehdr.e_shnum; ++i)
{
WriteShdr(e, shdr[i]);
}
}
}
};
fs::file decrypt_self(fs::file elf_or_self, u8* klic_key = nullptr, SelfAdditionalInfo* additional_info = nullptr, bool require_encrypted = false);
bool verify_npdrm_self_headers(const fs::file& self, u8* klic_key = nullptr, NPD_HEADER* npd_out = nullptr);
bool get_npdrm_self_header(const fs::file& self, NPD_HEADER& npd);
u128 get_default_self_klic();
| 14,770
|
C++
|
.h
| 484
| 26.960744
| 158
| 0.670089
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,632
|
utils.h
|
RPCS3_rpcs3/rpcs3/Crypto/utils.h
|
#pragma once
// Copyright (C) 2014 Hykem <hykem@hotmail.com>
// Licensed under the terms of the GNU GPL, version 2.0 or later versions.
// http://www.gnu.org/licenses/gpl-2.0.txt
#include "util/types.hpp"
#include "util/asm.hpp"
#include <stdlib.h>
enum { CRYPTO_MAX_PATH = 4096 };
char* extract_file_name(const char* file_path, char real_file_name[CRYPTO_MAX_PATH]);
std::string sha256_get_hash(const char* data, usz size, bool lower_case);
// Hex string conversion auxiliary functions.
u64 hex_to_u64(const char* hex_str);
void hex_to_bytes(unsigned char *data, const char *hex_str, unsigned int str_length);
// Crypto functions (AES128-CBC, AES128-ECB, SHA1-HMAC and AES-CMAC).
void aescbc128_decrypt(unsigned char *key, unsigned char *iv, unsigned char *in, unsigned char *out, usz len);
void aescbc128_encrypt(unsigned char *key, unsigned char *iv, unsigned char *in, unsigned char *out, usz len);
void aesecb128_encrypt(unsigned char *key, unsigned char *in, unsigned char *out);
bool hmac_hash_compare(unsigned char *key, int key_len, unsigned char *in, usz in_len, unsigned char *hash, usz hash_len);
void hmac_hash_forge(unsigned char *key, int key_len, unsigned char *in, usz in_len, unsigned char *hash);
bool cmac_hash_compare(unsigned char *key, int key_len, unsigned char *in, usz in_len, unsigned char *hash, usz hash_len);
void cmac_hash_forge(unsigned char *key, int key_len, unsigned char *in, usz in_len, unsigned char *hash);
void mbedtls_zeroize(void *v, size_t n);
// SC passphrase crypto
int vtrm_decrypt(int type, u8* iv, u8* input, u8* output);
int vtrm_decrypt_master(s64 laid, s64 paid, u8* iv, u8* input, u8* output);
int vtrm_decrypt_with_portability(int type, u8* iv, u8* input, u8* output);
| 1,774
|
C++
|
.h
| 26
| 65.461538
| 123
| 0.732639
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,633
|
md5.h
|
RPCS3_rpcs3/rpcs3/Crypto/md5.h
|
/**
* \file md5.h
*
* \brief MD5 message digest algorithm (hash function)
*
* \warning MD5 is considered a weak message digest and its use constitutes a
* security risk. We recommend considering stronger message
* digests instead.
*/
/*
* Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
* SPDX-License-Identifier: GPL-2.0
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
* This file is part of mbed TLS (https://tls.mbed.org)
*/
#ifndef MBEDTLS_MD5_H
#define MBEDTLS_MD5_H
#include <stddef.h>
#include <stdint.h>
/* MBEDTLS_ERR_MD5_HW_ACCEL_FAILED is deprecated and should not be used. */
#define MBEDTLS_ERR_MD5_HW_ACCEL_FAILED -0x002F /**< MD5 hardware accelerator failed */
#ifdef __cplusplus
extern "C" {
#endif
#if !defined(MBEDTLS_MD5_ALT)
// Regular implementation
//
/**
* \brief MD5 context structure
*
* \warning MD5 is considered a weak message digest and its use
* constitutes a security risk. We recommend considering
* stronger message digests instead.
*
*/
typedef struct mbedtls_md5_context
{
uint32_t total[2]; /*!< number of bytes processed */
uint32_t state[4]; /*!< intermediate digest state */
unsigned char buffer[64]; /*!< data block being processed */
}
mbedtls_md5_context;
#else /* MBEDTLS_MD5_ALT */
#include "md5_alt.h"
#endif /* MBEDTLS_MD5_ALT */
/**
* \brief Initialize MD5 context
*
* \param ctx MD5 context to be initialized
*
* \warning MD5 is considered a weak message digest and its use
* constitutes a security risk. We recommend considering
* stronger message digests instead.
*
*/
void mbedtls_md5_init( mbedtls_md5_context *ctx );
/**
* \brief Clear MD5 context
*
* \param ctx MD5 context to be cleared
*
* \warning MD5 is considered a weak message digest and its use
* constitutes a security risk. We recommend considering
* stronger message digests instead.
*
*/
void mbedtls_md5_free( mbedtls_md5_context *ctx );
/**
* \brief Clone (the state of) an MD5 context
*
* \param dst The destination context
* \param src The context to be cloned
*
* \warning MD5 is considered a weak message digest and its use
* constitutes a security risk. We recommend considering
* stronger message digests instead.
*
*/
void mbedtls_md5_clone( mbedtls_md5_context *dst,
const mbedtls_md5_context *src );
/**
* \brief MD5 context setup
*
* \param ctx context to be initialized
*
* \return 0 if successful
*
* \warning MD5 is considered a weak message digest and its use
* constitutes a security risk. We recommend considering
* stronger message digests instead.
*
*/
int mbedtls_md5_starts_ret( mbedtls_md5_context *ctx );
/**
* \brief MD5 process buffer
*
* \param ctx MD5 context
* \param input buffer holding the data
* \param ilen length of the input data
*
* \return 0 if successful
*
* \warning MD5 is considered a weak message digest and its use
* constitutes a security risk. We recommend considering
* stronger message digests instead.
*
*/
int mbedtls_md5_update_ret( mbedtls_md5_context *ctx,
const unsigned char *input,
size_t ilen );
/**
* \brief MD5 final digest
*
* \param ctx MD5 context
* \param output MD5 checksum result
*
* \return 0 if successful
*
* \warning MD5 is considered a weak message digest and its use
* constitutes a security risk. We recommend considering
* stronger message digests instead.
*
*/
int mbedtls_md5_finish_ret( mbedtls_md5_context *ctx,
unsigned char output[16] );
/**
* \brief MD5 process data block (internal use only)
*
* \param ctx MD5 context
* \param data buffer holding one block of data
*
* \return 0 if successful
*
* \warning MD5 is considered a weak message digest and its use
* constitutes a security risk. We recommend considering
* stronger message digests instead.
*
*/
int mbedtls_internal_md5_process( mbedtls_md5_context *ctx,
const unsigned char data[64] );
#if !defined(MBEDTLS_DEPRECATED_REMOVED)
#if defined(MBEDTLS_DEPRECATED_WARNING)
#define MBEDTLS_DEPRECATED __attribute__((deprecated))
#else
#define MBEDTLS_DEPRECATED
#endif
/**
* \brief MD5 context setup
*
* \deprecated Superseded by mbedtls_md5_starts_ret() in 2.7.0
*
* \param ctx context to be initialized
*
* \warning MD5 is considered a weak message digest and its use
* constitutes a security risk. We recommend considering
* stronger message digests instead.
*
*/
MBEDTLS_DEPRECATED void mbedtls_md5_starts( mbedtls_md5_context *ctx );
/**
* \brief MD5 process buffer
*
* \deprecated Superseded by mbedtls_md5_update_ret() in 2.7.0
*
* \param ctx MD5 context
* \param input buffer holding the data
* \param ilen length of the input data
*
* \warning MD5 is considered a weak message digest and its use
* constitutes a security risk. We recommend considering
* stronger message digests instead.
*
*/
MBEDTLS_DEPRECATED void mbedtls_md5_update( mbedtls_md5_context *ctx,
const unsigned char *input,
size_t ilen );
/**
* \brief MD5 final digest
*
* \deprecated Superseded by mbedtls_md5_finish_ret() in 2.7.0
*
* \param ctx MD5 context
* \param output MD5 checksum result
*
* \warning MD5 is considered a weak message digest and its use
* constitutes a security risk. We recommend considering
* stronger message digests instead.
*
*/
MBEDTLS_DEPRECATED void mbedtls_md5_finish( mbedtls_md5_context *ctx,
unsigned char output[16] );
/**
* \brief MD5 process data block (internal use only)
*
* \deprecated Superseded by mbedtls_internal_md5_process() in 2.7.0
*
* \param ctx MD5 context
* \param data buffer holding one block of data
*
* \warning MD5 is considered a weak message digest and its use
* constitutes a security risk. We recommend considering
* stronger message digests instead.
*
*/
MBEDTLS_DEPRECATED void mbedtls_md5_process( mbedtls_md5_context *ctx,
const unsigned char data[64] );
#undef MBEDTLS_DEPRECATED
#endif /* !MBEDTLS_DEPRECATED_REMOVED */
/**
* \brief Output = MD5( input buffer )
*
* \param input buffer holding the data
* \param ilen length of the input data
* \param output MD5 checksum result
*
* \return 0 if successful
*
* \warning MD5 is considered a weak message digest and its use
* constitutes a security risk. We recommend considering
* stronger message digests instead.
*
*/
int mbedtls_md5_ret( const unsigned char *input,
size_t ilen,
unsigned char output[16] );
#if !defined(MBEDTLS_DEPRECATED_REMOVED)
#if defined(MBEDTLS_DEPRECATED_WARNING)
#define MBEDTLS_DEPRECATED __attribute__((deprecated))
#else
#define MBEDTLS_DEPRECATED
#endif
/**
* \brief Output = MD5( input buffer )
*
* \deprecated Superseded by mbedtls_md5_ret() in 2.7.0
*
* \param input buffer holding the data
* \param ilen length of the input data
* \param output MD5 checksum result
*
* \warning MD5 is considered a weak message digest and its use
* constitutes a security risk. We recommend considering
* stronger message digests instead.
*
*/
MBEDTLS_DEPRECATED void mbedtls_md5( const unsigned char *input,
size_t ilen,
unsigned char output[16] );
#undef MBEDTLS_DEPRECATED
#endif /* !MBEDTLS_DEPRECATED_REMOVED */
#if defined(MBEDTLS_SELF_TEST)
/**
* \brief Checkup routine
*
* \return 0 if successful, or 1 if the test failed
*
* \warning MD5 is considered a weak message digest and its use
* constitutes a security risk. We recommend considering
* stronger message digests instead.
*
*/
int mbedtls_md5_self_test( int verbose );
#endif /* MBEDTLS_SELF_TEST */
#ifdef __cplusplus
}
#endif
#endif /* mbedtls_md5.h */
| 9,602
|
C++
|
.h
| 281
| 30.800712
| 106
| 0.636686
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| true
| false
| false
| false
| false
| false
| false
|
5,634
|
aesni.h
|
RPCS3_rpcs3/rpcs3/Crypto/aesni.h
|
#pragma once
#define POLARSSL_HAVE_ASM
/**
* \file aesni.h
*
* \brief AES-NI for hardware AES acceleration on some Intel processors
*
* Copyright (C) 2013, Brainspark B.V.
*
* This file is part of PolarSSL (http://www.polarssl.org)
* Lead Maintainer: Paul Bakker <polarssl_maintainer at polarssl.org>
*
* All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include "aes.h"
#define POLARSSL_AESNI_AES 0x02000000u
#define POLARSSL_AESNI_CLMUL 0x00000002u
#ifdef __cplusplus
extern "C" {
#endif
/**
* \brief AES-NI features detection routine
*
* \param what The feature to detect
* (POLARSSL_AESNI_AES or POLARSSL_AESNI_CLMUL)
*
* \return 1 if CPU has support for the feature, 0 otherwise
*/
int aesni_supports( unsigned int what );
/**
* \brief AES-NI AES-ECB block en(de)cryption
*
* \param ctx AES context
* \param mode AES_ENCRYPT or AES_DECRYPT
* \param input 16-byte input block
* \param output 16-byte output block
*
* \return 0 on success (cannot fail)
*/
int aesni_crypt_ecb( aes_context *ctx,
int mode,
const unsigned char input[16],
unsigned char output[16] );
/**
* \brief GCM multiplication: c = a * b in GF(2^128)
*
* \param c Result
* \param a First operand
* \param b Second operand
*
* \note Both operands and result are bit strings interpreted as
* elements of GF(2^128) as per the GCM spec.
*/
void aesni_gcm_mult( unsigned char c[16],
const unsigned char a[16],
const unsigned char b[16] );
/**
* \brief Compute decryption round keys from encryption round keys
*
* \param invkey Round keys for the equivalent inverse cipher
* \param fwdkey Original round keys (for encryption)
* \param nr Number of rounds (that is, number of round keys minus one)
*/
void aesni_inverse_key( unsigned char *invkey,
const unsigned char *fwdkey, int nr );
/**
* \brief Perform key expansion (for encryption)
*
* \param rk Destination buffer where the round keys are written
* \param key Encryption key
* \param bits Key size in bits (must be 128, 192 or 256)
*
* \return 0 if successful, or POLARSSL_ERR_AES_INVALID_KEY_LENGTH
*/
int aesni_setkey_enc( unsigned char *rk,
const unsigned char *key,
size_t bits );
#ifdef __cplusplus
}
#endif
| 3,270
|
C++
|
.h
| 94
| 31.170213
| 78
| 0.655194
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,635
|
ec.h
|
RPCS3_rpcs3/rpcs3/Crypto/ec.h
|
#pragma once
// Copyright (C) 2014 Hykem <hykem@hotmail.com>
// Licensed under the terms of the GNU GPL, version 2.0 or later versions.
// http://www.gnu.org/licenses/gpl-2.0.txt
#include "util/types.hpp"
void ecdsa_set_curve(const u8* p, const u8* a, const u8* b, const u8* N, const u8* Gx, const u8* Gy);
void ecdsa_set_pub(const u8* Q);
void ecdsa_set_priv(const u8* k);
bool ecdsa_verify(u8* hash, u8* R, u8* S);
| 426
|
C++
|
.h
| 9
| 46
| 101
| 0.698068
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,636
|
unedat.h
|
RPCS3_rpcs3/rpcs3/Crypto/unedat.h
|
#pragma once
#include <array>
#include "utils.h"
#include "Utilities/File.h"
constexpr u32 SDAT_FLAG = 0x01000000;
constexpr u32 EDAT_COMPRESSED_FLAG = 0x00000001;
constexpr u32 EDAT_FLAG_0x02 = 0x00000002;
constexpr u32 EDAT_ENCRYPTED_KEY_FLAG = 0x00000008;
constexpr u32 EDAT_FLAG_0x10 = 0x00000010;
constexpr u32 EDAT_FLAG_0x20 = 0x00000020;
constexpr u32 EDAT_DEBUG_DATA_FLAG = 0x80000000;
struct loaded_npdrm_keys
{
atomic_t<u128> dec_keys[16]{};
atomic_t<u64> dec_keys_pos = 0;
u128 one_time_key{}; // For savestates
atomic_t<u32> npdrm_fds{0};
void install_decryption_key(u128 key)
{
dec_keys_pos.atomic_op([&](u64& pos) { dec_keys[pos++ % std::size(dec_keys)] = key; });
}
// TODO: Check if correct for ELF files usage
u128 last_key(usz backwards = 0) const
{
backwards++;
const usz pos = dec_keys_pos;
return pos >= backwards ? dec_keys[(pos - backwards) % std::size(dec_keys)].load() : u128{};
}
SAVESTATE_INIT_POS(2);
loaded_npdrm_keys() = default;
loaded_npdrm_keys(utils::serial& ar);
void save(utils::serial& ar);
};
struct NPD_HEADER
{
u32 magic;
s32 version;
s32 license;
s32 type;
char content_id[0x30];
u8 digest[0x10];
u8 title_hash[0x10];
u8 dev_hash[0x10];
s64 activate_time;
s64 expire_time;
};
struct EDAT_HEADER
{
s32 flags;
s32 block_size;
u64 file_size;
};
// Decrypts full file, or null/empty file
extern fs::file DecryptEDAT(const fs::file& input, const std::string& input_file_name, int mode, u8 *custom_klic);
extern void read_npd_edat_header(const fs::file* input, NPD_HEADER& NPD, EDAT_HEADER& EDAT);
extern bool VerifyEDATHeaderWithKLicense(const fs::file& input, const std::string& input_file_name, const u8* custom_klic, NPD_HEADER *npd_out = nullptr);
u128 GetEdatRifKeyFromRapFile(const fs::file& rap_file);
struct EDATADecrypter final : fs::file_base
{
// file stream
fs::file m_edata_file;
const fs::file& edata_file;
std::string m_file_name;
bool m_is_key_final = true;
u64 file_size{0};
u32 total_blocks{0};
u64 pos{0};
NPD_HEADER npdHeader{};
EDAT_HEADER edatHeader{};
u128 dec_key{};
public:
EDATADecrypter(fs::file&& input, u128 dec_key = {}, std::string file_name = {}, bool is_key_final = true) noexcept
: m_edata_file(std::move(input))
, edata_file(m_edata_file)
, m_file_name(std::move(file_name))
, m_is_key_final(is_key_final)
, dec_key(dec_key)
{
}
EDATADecrypter(const fs::file& input, u128 dec_key = {}, std::string file_name = {}, bool is_key_final = true) noexcept
: m_edata_file(fs::file{})
, edata_file(input)
, m_file_name(std::move(file_name))
, m_is_key_final(is_key_final)
, dec_key(dec_key)
{
}
// false if invalid
bool ReadHeader();
u64 ReadData(u64 pos, u8* data, u64 size);
fs::stat_t get_stat() override
{
fs::stat_t stats = edata_file.get_stat();
stats.is_writable = false; // TODO
stats.size = file_size;
return stats;
}
bool trunc(u64) override
{
return false;
}
u64 read(void* buffer, u64 size) override
{
const u64 bytesRead = ReadData(pos, static_cast<u8*>(buffer), size);
pos += bytesRead;
return bytesRead;
}
u64 read_at(u64 offset, void* buffer, u64 size) override
{
return ReadData(offset, static_cast<u8*>(buffer), size);
}
u64 write(const void*, u64) override
{
return 0;
}
u64 seek(s64 offset, fs::seek_mode whence) override
{
const s64 new_pos =
whence == fs::seek_set ? offset :
whence == fs::seek_cur ? offset + pos :
whence == fs::seek_end ? offset + size() : -1;
if (new_pos < 0)
{
fs::g_tls_error = fs::error::inval;
return -1;
}
pos = new_pos;
return pos;
}
u64 size() override { return file_size; }
fs::file_id get_id() override
{
fs::file_id id = edata_file.get_id();
id.type.insert(0, "EDATADecrypter: "sv);
return id;
}
u128 get_key() const
{
return dec_key;
}
};
| 3,840
|
C++
|
.h
| 141
| 24.914894
| 154
| 0.698828
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,637
|
sha1.h
|
RPCS3_rpcs3/rpcs3/Crypto/sha1.h
|
#pragma once
/**
* \file sha1.h
*
* \brief SHA-1 cryptographic hash function
*
* Copyright (C) 2006-2013, Brainspark B.V.
*
* This file is part of PolarSSL (http://www.polarssl.org)
* Lead Maintainer: Paul Bakker <polarssl_maintainer at polarssl.org>
*
* All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include <string.h>
#ifdef _MSC_VER
#include <basetsd.h>
typedef UINT32 uint32_t;
#else
#include <inttypes.h>
#endif
#define POLARSSL_ERR_SHA1_FILE_IO_ERROR -0x0076 /**< Read/write error in file. */
// Regular implementation
//
/**
* \brief SHA-1 context structure
*/
typedef struct
{
uint32_t total[2]; /*!< number of bytes processed */
uint32_t state[5]; /*!< intermediate digest state */
unsigned char buffer[64]; /*!< data block being processed */
unsigned char ipad[64]; /*!< HMAC: inner padding */
unsigned char opad[64]; /*!< HMAC: outer padding */
}
sha1_context;
#ifdef __cplusplus
extern "C" {
#endif
/**
* \brief SHA-1 context setup
*
* \param ctx context to be initialized
*/
void sha1_starts( sha1_context *ctx );
/**
* \brief SHA-1 process buffer
*
* \param ctx SHA-1 context
* \param input buffer holding the data
* \param ilen length of the input data
*/
void sha1_update( sha1_context *ctx, const unsigned char *input, size_t ilen );
/**
* \brief SHA-1 final digest
*
* \param ctx SHA-1 context
* \param output SHA-1 checksum result
*/
void sha1_finish( sha1_context *ctx, unsigned char output[20] );
/* Internal use */
void sha1_process( sha1_context *ctx, const unsigned char data[64] );
#ifdef __cplusplus
}
#endif
#ifdef __cplusplus
extern "C" {
#endif
/**
* \brief Output = SHA-1( input buffer )
*
* \param input buffer holding the data
* \param ilen length of the input data
* \param output SHA-1 checksum result
*/
void sha1( const unsigned char *input, size_t ilen, unsigned char output[20] );
/**
* \brief Output = SHA-1( file contents )
*
* \param path input file name
* \param output SHA-1 checksum result
*
* \return 0 if successful, or POLARSSL_ERR_SHA1_FILE_IO_ERROR
*/
int sha1_file( const char *path, unsigned char output[20] );
/**
* \brief SHA-1 HMAC context setup
*
* \param ctx HMAC context to be initialized
* \param key HMAC secret key
* \param keylen length of the HMAC key
*/
void sha1_hmac_starts( sha1_context *ctx, const unsigned char *key, size_t keylen );
/**
* \brief SHA-1 HMAC process buffer
*
* \param ctx HMAC context
* \param input buffer holding the data
* \param ilen length of the input data
*/
void sha1_hmac_update( sha1_context *ctx, const unsigned char *input, size_t ilen );
/**
* \brief SHA-1 HMAC final digest
*
* \param ctx HMAC context
* \param output SHA-1 HMAC checksum result
*/
void sha1_hmac_finish( sha1_context *ctx, unsigned char output[20] );
/**
* \brief SHA-1 HMAC context reset
*
* \param ctx HMAC context to be reset
*/
void sha1_hmac_reset( sha1_context *ctx );
/**
* \brief Output = HMAC-SHA-1( hmac key, input buffer )
*
* \param key HMAC secret key
* \param keylen length of the HMAC key
* \param input buffer holding the data
* \param ilen length of the input data
* \param output HMAC-SHA-1 result
*/
void sha1_hmac( const unsigned char *key, size_t keylen,
const unsigned char *input, size_t ilen,
unsigned char output[20] );
#ifdef __cplusplus
}
#endif
| 4,520
|
C++
|
.h
| 142
| 28.577465
| 98
| 0.645756
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| true
| false
| false
| false
| false
| false
| false
|
5,639
|
sha256.h
|
RPCS3_rpcs3/rpcs3/Crypto/sha256.h
|
/**
* \file sha256.h
*
* \brief This file contains SHA-224 and SHA-256 definitions and functions.
*
* The Secure Hash Algorithms 224 and 256 (SHA-224 and SHA-256) cryptographic
* hash functions are defined in <em>FIPS 180-4: Secure Hash Standard (SHS)</em>.
*/
/*
* Copyright (C) 2006-2018, Arm Limited (or its affiliates), All Rights Reserved
* SPDX-License-Identifier: GPL-2.0
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
* This file is part of Mbed TLS (https://tls.mbed.org)
*/
#ifndef MBEDTLS_SHA256_H
#define MBEDTLS_SHA256_H
#include <stddef.h>
#include <stdint.h>
/* MBEDTLS_ERR_SHA256_HW_ACCEL_FAILED is deprecated and should not be used. */
#define MBEDTLS_ERR_SHA256_HW_ACCEL_FAILED -0x0037 /**< SHA-256 hardware accelerator failed */
#define MBEDTLS_ERR_SHA256_BAD_INPUT_DATA -0x0074 /**< SHA-256 input data was malformed. */
#ifdef __cplusplus
extern "C" {
#endif
#if !defined(MBEDTLS_SHA256_ALT)
// Regular implementation
//
/**
* \brief The SHA-256 context structure.
*
* The structure is used both for SHA-256 and for SHA-224
* checksum calculations. The choice between these two is
* made in the call to mbedtls_sha256_starts_ret().
*/
typedef struct mbedtls_sha256_context
{
uint32_t total[2]; /*!< The number of Bytes processed. */
uint32_t state[8]; /*!< The intermediate digest state. */
unsigned char buffer[64]; /*!< The data block being processed. */
int is224; /*!< Determines which function to use:
0: Use SHA-256, or 1: Use SHA-224. */
}
mbedtls_sha256_context;
#else /* MBEDTLS_SHA256_ALT */
#include "sha256_alt.h"
#endif /* MBEDTLS_SHA256_ALT */
/**
* \brief This function initializes a SHA-256 context.
*
* \param ctx The SHA-256 context to initialize. This must not be \c NULL.
*/
void mbedtls_sha256_init( mbedtls_sha256_context *ctx );
/**
* \brief This function clears a SHA-256 context.
*
* \param ctx The SHA-256 context to clear. This may be \c NULL, in which
* case this function returns immediately. If it is not \c NULL,
* it must point to an initialized SHA-256 context.
*/
void mbedtls_sha256_free( mbedtls_sha256_context *ctx );
/**
* \brief This function clones the state of a SHA-256 context.
*
* \param dst The destination context. This must be initialized.
* \param src The context to clone. This must be initialized.
*/
void mbedtls_sha256_clone( mbedtls_sha256_context *dst,
const mbedtls_sha256_context *src );
/**
* \brief This function starts a SHA-224 or SHA-256 checksum
* calculation.
*
* \param ctx The context to use. This must be initialized.
* \param is224 This determines which function to use. This must be
* either \c 0 for SHA-256, or \c 1 for SHA-224.
*
* \return \c 0 on success.
* \return A negative error code on failure.
*/
int mbedtls_sha256_starts_ret( mbedtls_sha256_context *ctx, int is224 );
/**
* \brief This function feeds an input buffer into an ongoing
* SHA-256 checksum calculation.
*
* \param ctx The SHA-256 context. This must be initialized
* and have a hash operation started.
* \param input The buffer holding the data. This must be a readable
* buffer of length \p ilen Bytes.
* \param ilen The length of the input data in Bytes.
*
* \return \c 0 on success.
* \return A negative error code on failure.
*/
int mbedtls_sha256_update_ret( mbedtls_sha256_context *ctx,
const unsigned char *input,
size_t ilen );
/**
* \brief This function finishes the SHA-256 operation, and writes
* the result to the output buffer.
*
* \param ctx The SHA-256 context. This must be initialized
* and have a hash operation started.
* \param output The SHA-224 or SHA-256 checksum result.
* This must be a writable buffer of length \c 32 Bytes.
*
* \return \c 0 on success.
* \return A negative error code on failure.
*/
int mbedtls_sha256_finish_ret( mbedtls_sha256_context *ctx,
unsigned char output[32] );
/**
* \brief This function processes a single data block within
* the ongoing SHA-256 computation. This function is for
* internal use only.
*
* \param ctx The SHA-256 context. This must be initialized.
* \param data The buffer holding one block of data. This must
* be a readable buffer of length \c 64 Bytes.
*
* \return \c 0 on success.
* \return A negative error code on failure.
*/
int mbedtls_internal_sha256_process( mbedtls_sha256_context *ctx,
const unsigned char data[64] );
#if !defined(MBEDTLS_DEPRECATED_REMOVED)
#if defined(MBEDTLS_DEPRECATED_WARNING)
#define MBEDTLS_DEPRECATED __attribute__((deprecated))
#else
#define MBEDTLS_DEPRECATED
#endif
/**
* \brief This function starts a SHA-224 or SHA-256 checksum
* calculation.
*
* \deprecated Superseded by mbedtls_sha256_starts_ret() in 2.7.0.
*
* \param ctx The context to use. This must be initialized.
* \param is224 Determines which function to use. This must be
* either \c 0 for SHA-256, or \c 1 for SHA-224.
*/
MBEDTLS_DEPRECATED void mbedtls_sha256_starts( mbedtls_sha256_context *ctx,
int is224 );
/**
* \brief This function feeds an input buffer into an ongoing
* SHA-256 checksum calculation.
*
* \deprecated Superseded by mbedtls_sha256_update_ret() in 2.7.0.
*
* \param ctx The SHA-256 context to use. This must be
* initialized and have a hash operation started.
* \param input The buffer holding the data. This must be a readable
* buffer of length \p ilen Bytes.
* \param ilen The length of the input data in Bytes.
*/
MBEDTLS_DEPRECATED void mbedtls_sha256_update( mbedtls_sha256_context *ctx,
const unsigned char *input,
size_t ilen );
/**
* \brief This function finishes the SHA-256 operation, and writes
* the result to the output buffer.
*
* \deprecated Superseded by mbedtls_sha256_finish_ret() in 2.7.0.
*
* \param ctx The SHA-256 context. This must be initialized and
* have a hash operation started.
* \param output The SHA-224 or SHA-256 checksum result. This must be
* a writable buffer of length \c 32 Bytes.
*/
MBEDTLS_DEPRECATED void mbedtls_sha256_finish( mbedtls_sha256_context *ctx,
unsigned char output[32] );
/**
* \brief This function processes a single data block within
* the ongoing SHA-256 computation. This function is for
* internal use only.
*
* \deprecated Superseded by mbedtls_internal_sha256_process() in 2.7.0.
*
* \param ctx The SHA-256 context. This must be initialized.
* \param data The buffer holding one block of data. This must be
* a readable buffer of size \c 64 Bytes.
*/
MBEDTLS_DEPRECATED void mbedtls_sha256_process( mbedtls_sha256_context *ctx,
const unsigned char data[64] );
#undef MBEDTLS_DEPRECATED
#endif /* !MBEDTLS_DEPRECATED_REMOVED */
/**
* \brief This function calculates the SHA-224 or SHA-256
* checksum of a buffer.
*
* The function allocates the context, performs the
* calculation, and frees the context.
*
* The SHA-256 result is calculated as
* output = SHA-256(input buffer).
*
* \param input The buffer holding the data. This must be a readable
* buffer of length \p ilen Bytes.
* \param ilen The length of the input data in Bytes.
* \param output The SHA-224 or SHA-256 checksum result. This must
* be a writable buffer of length \c 32 Bytes.
* \param is224 Determines which function to use. This must be
* either \c 0 for SHA-256, or \c 1 for SHA-224.
*/
int mbedtls_sha256_ret( const unsigned char *input,
size_t ilen,
unsigned char output[32],
int is224 );
#if !defined(MBEDTLS_DEPRECATED_REMOVED)
#if defined(MBEDTLS_DEPRECATED_WARNING)
#define MBEDTLS_DEPRECATED __attribute__((deprecated))
#else
#define MBEDTLS_DEPRECATED
#endif
/**
* \brief This function calculates the SHA-224 or SHA-256 checksum
* of a buffer.
*
* The function allocates the context, performs the
* calculation, and frees the context.
*
* The SHA-256 result is calculated as
* output = SHA-256(input buffer).
*
* \deprecated Superseded by mbedtls_sha256_ret() in 2.7.0.
*
* \param input The buffer holding the data. This must be a readable
* buffer of length \p ilen Bytes.
* \param ilen The length of the input data in Bytes.
* \param output The SHA-224 or SHA-256 checksum result. This must be
* a writable buffer of length \c 32 Bytes.
* \param is224 Determines which function to use. This must be either
* \c 0 for SHA-256, or \c 1 for SHA-224.
*/
MBEDTLS_DEPRECATED void mbedtls_sha256( const unsigned char *input,
size_t ilen,
unsigned char output[32],
int is224 );
#undef MBEDTLS_DEPRECATED
#endif /* !MBEDTLS_DEPRECATED_REMOVED */
#ifdef __cplusplus
}
#endif
#endif /* mbedtls_sha256.h */
| 10,897
|
C++
|
.h
| 257
| 38.175097
| 110
| 0.622174
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| true
| false
| false
| false
| false
| false
| false
|
5,640
|
lz.h
|
RPCS3_rpcs3/rpcs3/Crypto/lz.h
|
#pragma once
// Copyright (C) 2014 Hykem <hykem@hotmail.com>
// Licensed under the terms of the GNU GPL, version 2.0 or later versions.
// http://www.gnu.org/licenses/gpl-2.0.txt
// Reverse-engineered custom Lempel–Ziv–Markov based compression.
#include <string.h>
void decode_range(unsigned int *range, unsigned int *code, unsigned char **src);
int decode_bit(unsigned int *range, unsigned int *code, int *index, unsigned char **src, unsigned char *c);
int decode_number(unsigned char *ptr, int index, int *bit_flag, unsigned int *range, unsigned int *code, unsigned char **src);
int decode_word(unsigned char *ptr, int index, int *bit_flag, unsigned int *range, unsigned int *code, unsigned char **src);
int decompress(unsigned char *out, unsigned char *in, unsigned int size);
| 794
|
C++
|
.h
| 11
| 70.454545
| 126
| 0.748387
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,641
|
decrypt_binaries.h
|
RPCS3_rpcs3/rpcs3/Crypto/decrypt_binaries.h
|
#pragma once
class decrypt_binaries_t
{
std::vector<u128> m_klics;
std::vector<std::string> m_modules;
usz m_index = 0;
public:
decrypt_binaries_t(std::vector<std::string> modules) noexcept
: m_modules(std::move(modules))
{
}
usz decrypt(std::string_view klic_input = {});
bool done() const
{
return m_index >= m_modules.size();
}
const std::string& operator[](usz index) const
{
return ::at32(m_modules, index);
}
};
| 499
|
C++
|
.h
| 21
| 18.904762
| 65
| 0.613108
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,642
|
unpkg.h
|
RPCS3_rpcs3/rpcs3/Crypto/unpkg.h
|
#pragma once
#include "Loader/PSF.h"
#include "util/endian.hpp"
#include "util/types.hpp"
#include "Utilities/File.h"
#include <sstream>
#include <iomanip>
#include <span>
#include <deque>
// Constants
enum : u32
{
PKG_HEADER_SIZE = 0xC0, // sizeof(pkg_header) + sizeof(pkg_unk_checksum)
PKG_HEADER_SIZE2 = 0x280,
PKG_MAX_FILENAME_SIZE = 256,
};
enum : u16
{
PKG_RELEASE_TYPE_RELEASE = 0x8000,
PKG_RELEASE_TYPE_DEBUG = 0x0000,
PKG_PLATFORM_TYPE_PS3 = 0x0001,
PKG_PLATFORM_TYPE_PSP_PSVITA = 0x0002,
};
enum : u32
{
PKG_FILE_ENTRY_NPDRM = 1,
PKG_FILE_ENTRY_NPDRMEDAT = 2,
PKG_FILE_ENTRY_REGULAR = 3,
PKG_FILE_ENTRY_FOLDER = 4,
PKG_FILE_ENTRY_UNK0 = 5,
PKG_FILE_ENTRY_UNK1 = 6,
PKG_FILE_ENTRY_SDAT = 9,
PKG_FILE_ENTRY_OVERWRITE = 0x80000000,
PKG_FILE_ENTRY_PSP = 0x10000000,
PKG_FILE_ENTRY_KNOWN_BITS = 0xff | PKG_FILE_ENTRY_PSP | PKG_FILE_ENTRY_OVERWRITE,
};
enum : u32
{
PKG_CONTENT_TYPE_UNKNOWN_1 = 0x01, // ?
PKG_CONTENT_TYPE_UNKNOWN_2 = 0x02, // ?
PKG_CONTENT_TYPE_UNKNOWN_3 = 0x03, // ?
PKG_CONTENT_TYPE_GAME_DATA = 0x04, // GameData (also patches)
PKG_CONTENT_TYPE_GAME_EXEC = 0x05, // GameExec
PKG_CONTENT_TYPE_PS1_EMU = 0x06, // PS1emu
PKG_CONTENT_TYPE_PC_ENGINE = 0x07, // PSP & PCEngine
PKG_CONTENT_TYPE_UNKNOWN_4 = 0x08, // ?
PKG_CONTENT_TYPE_THEME = 0x09, // Theme
PKG_CONTENT_TYPE_WIDGET = 0x0A, // Widget
PKG_CONTENT_TYPE_LICENSE = 0x0B, // License
PKG_CONTENT_TYPE_VSH_MODULE = 0x0C, // VSHModule
PKG_CONTENT_TYPE_PSN_AVATAR = 0x0D, // PSN Avatar
PKG_CONTENT_TYPE_PSP_GO = 0x0E, // PSPgo
PKG_CONTENT_TYPE_MINIS = 0x0F, // Minis
PKG_CONTENT_TYPE_NEOGEO = 0x10, // NEOGEO
PKG_CONTENT_TYPE_VMC = 0x11, // VMC
PKG_CONTENT_TYPE_PS2_CLASSIC = 0x12, // ?PS2Classic? Seen on PS2 classic
PKG_CONTENT_TYPE_UNKNOWN_5 = 0x13, // ?
PKG_CONTENT_TYPE_PSP_REMASTERED = 0x14, // ?
PKG_CONTENT_TYPE_PSP2_GD = 0x15, // PSVita Game Data
PKG_CONTENT_TYPE_PSP2_AC = 0x16, // PSVita Additional Content
PKG_CONTENT_TYPE_PSP2_LA = 0x17, // PSVita LiveArea
PKG_CONTENT_TYPE_PSM_1 = 0x18, // PSVita PSM ?
PKG_CONTENT_TYPE_WT = 0x19, // Web TV ?
PKG_CONTENT_TYPE_UNKNOWN_6 = 0x1A, // ?
PKG_CONTENT_TYPE_UNKNOWN_7 = 0x1B, // ?
PKG_CONTENT_TYPE_UNKNOWN_8 = 0x1C, // ?
PKG_CONTENT_TYPE_PSM_2 = 0x1D, // PSVita PSM ?
PKG_CONTENT_TYPE_UNKNOWN_9 = 0x1E, // ?
PKG_CONTENT_TYPE_PSP2_THEME = 0x1F, // PSVita Theme
};
// Structs
struct PKGHeader
{
le_t<u32> pkg_magic; // Magic (0x7f504b47) (" PKG")
be_t<u16> pkg_type; // Release type (Retail:0x8000, Debug:0x0000)
be_t<u16> pkg_platform; // Platform type (PS3:0x0001, PSP:0x0002)
be_t<u32> meta_offset; // Metadata offset. Usually 0xC0 for PS3, usually 0x280 for PSP and PSVita
be_t<u32> meta_count; // Metadata item count
be_t<u32> meta_size; // Metadata size.
be_t<u32> file_count; // Number of files
be_t<u64> pkg_size; // PKG size in bytes
be_t<u64> data_offset; // Encrypted data offset
be_t<u64> data_size; // Encrypted data size in bytes
char title_id[48]; // Title ID
be_t<u64> qa_digest[2]; // This should be the hash of "files + attribs"
be_t<u128> klicensee; // Nonce
// + some stuff
};
// Extended header in PSP and PSVita packages
struct PKGExtHeader
{
le_t<u32> magic; // 0x7F657874 (" ext")
be_t<u32> unknown_1; // Maybe version. always 1
be_t<u32> ext_hdr_size; // Extended header size. ex: 0x40
be_t<u32> ext_data_size; // ex: 0x180
be_t<u32> main_and_ext_headers_hmac_offset; // ex: 0x100
be_t<u32> metadata_header_hmac_offset; // ex: 0x360, 0x390, 0x490
be_t<u64> tail_offset; // tail size seams to be always 0x1A0
be_t<u32> padding1;
be_t<u32> pkg_key_id; // Id of the AES key used for decryption. PSP = 0x1, PSVita = 0xC0000002, PSM = 0xC0000004
be_t<u32> full_header_hmac_offset; // ex: none (old pkg): 0, 0x930
u8 padding2[20];
};
struct PKGEntry
{
be_t<u32> name_offset; // File name offset
be_t<u32> name_size; // File name size
be_t<u64> file_offset; // File offset
be_t<u64> file_size; // File size
be_t<u32> type; // File type
be_t<u32> pad; // Padding (zeros)
};
// https://www.psdevwiki.com/ps3/PKG_files#PKG_Metadata
struct PKGMetaData
{
private:
static std::string to_hex_string(u8 buf[], usz size)
{
std::stringstream sstream;
for (usz i = 0; i < size; i++)
{
sstream << std::hex << std::setw(2) << std::setfill('0') << static_cast<int>(buf[i]);
}
return sstream.str();
}
static std::string to_hex_string(u8 buf[], usz size, usz dotpos)
{
std::string result = to_hex_string(buf, size);
if (result.size() > dotpos)
{
result.insert(dotpos, 1, '.');
}
return result;
}
public:
be_t<u32> drm_type{ 0 };
be_t<u32> content_type{ 0 };
be_t<u32> package_type{ 0 };
be_t<u64> package_size{ 0 };
u8 qa_digest[24]{ 0 };
be_t<u64> unk_0x9{ 0 };
be_t<u64> unk_0xB{ 0 };
struct package_revision
{
struct package_revision_data
{
u8 make_package_npdrm_ver[2]{ 0 };
u8 version[2]{ 0 };
} data{};
std::string make_package_npdrm_ver;
std::string version;
void interpret_data()
{
make_package_npdrm_ver = to_hex_string(data.make_package_npdrm_ver, sizeof(data.make_package_npdrm_ver));
version = to_hex_string(data.version, sizeof(data.version), 2);
}
std::string to_string() const
{
return fmt::format("make package npdrm version: %s, version: %s", make_package_npdrm_ver, version);
}
} package_revision;
struct software_revision
{
struct software_revision_data
{
u8 unk[1]{ 0 };
u8 firmware_version[3]{ 0 };
u8 version[2]{ 0 };
u8 app_version[2]{ 0 };
} data{};
std::string unk; // maybe hardware id
std::string firmware_version;
std::string version;
std::string app_version;
void interpret_data()
{
unk = to_hex_string(data.unk, sizeof(data.unk));
firmware_version = to_hex_string(data.firmware_version, sizeof(data.firmware_version), 2);
version = to_hex_string(data.version, sizeof(data.version), 2);
app_version = to_hex_string(data.app_version, sizeof(data.app_version), 2);
}
std::string to_string() const
{
return fmt::format("unk: %s, firmware version: %s, version: %s, app version: %s",
unk, firmware_version, version, app_version);
}
} software_revision;
std::string title_id;
std::string install_dir;
// PSVita stuff
struct vita_item_info // size is 0x28 (40)
{
be_t<u32> offset{ 0 };
be_t<u32> size{ 0 };
u8 sha256[32]{ 0 };
std::string to_string() const
{
return fmt::format("offset: 0x%x, size: 0x%x, sha256: 0x%x", offset, size, sha256);
}
} item_info;
struct vita_sfo_info // size is 0x38 (56)
{
be_t<u32> param_offset{ 0 };
be_t<u16> param_size{ 0 };
be_t<u32> unk_1{ 0 }; // seen values: 0x00000001-0x00000018, 0x0000001b-0x0000001c
be_t<u32> psp2_system_ver{ 0 }; // BCD encoded
u8 unk_2[8]{ 0 };
u8 param_digest[32]{ 0 }; // SHA256 of param_data. Called ParamDigest: This is sha256 digest of param.sfo.
std::string to_string() const
{
return fmt::format("param_offset: 0x%x, param_size: 0x%x, unk_1: 0x%x, psp2_system_ver: 0x%x, unk_2: 0x%x, param_digest: 0x%x",
param_offset, param_size, unk_1, psp2_system_ver, unk_2, param_digest);
}
} sfo_info;
struct vita_unknown_data_info // size is 0x48 (72)
{
be_t<u32> unknown_data_offset{ 0 };
be_t<u16> unknown_data_size{ 0 }; // ex: 0x320
u8 unk[32]{ 0 };
u8 unknown_data_sha256[32]{ 0 };
std::string to_string() const
{
return fmt::format("unknown_data_offset: 0x%x, unknown_data_size: 0x%x, unk: 0x%x, unknown_data_sha256: 0x%x",
unknown_data_offset, unknown_data_size, unk, unknown_data_sha256);
}
} unknown_data_info;
struct vita_entirety_info // size is 0x38 (56)
{
be_t<u32> entirety_data_offset{ 0 }; // located just before SFO
be_t<u32> entirety_data_size{ 0 }; // ex: 0xA0, C0, 0x100, 0x120, 0x160
be_t<u16> flags{ 0 }; // ex: EE 00, FE 10, FE 78, FE F8, FF 10, FF 90, FF D0, flags indicating which digests it embeds
be_t<u16> unk_1{ 0 }; // always 00 00
be_t<u32> unk_2{ 0 }; // ex: 1, 0
u8 unk_3[8]{ 0 };
u8 entirety_digest[32]{ 0 };
std::string to_string() const
{
return fmt::format("entirety_data_offset: 0x%x, entirety_data_size: 0x%x, flags: 0x%x, unk_1: 0x%x, unk_2: 0x%x, unk_3: 0x%x, entirety_digest: 0x%x",
entirety_data_offset, entirety_data_size, flags, unk_1, unk_2, unk_3, entirety_digest);
}
} entirety_info;
struct vita_version_info // size is 0x28 (40)
{
be_t<u32> publishing_tools_version{ 0 };
be_t<u32> psf_builder_version{ 0 };
u8 padding[32]{ 0 };
std::string to_string() const
{
return fmt::format("publishing_tools_version: 0x%x, psf_builder_version: 0x%x, padding: 0x%x",
publishing_tools_version, psf_builder_version, padding);
}
} version_info;
struct vita_self_info // size is 0x38 (56)
{
be_t<u32> self_info_offset{ 0 }; // offset to the first self_info_data_element
be_t<u32> self_info_size{ 0 }; // usually 0x10 or 0x20
u8 unk[16]{ 0 };
u8 self_sha256[32]{ 0 };
std::string to_string() const
{
return fmt::format("self_info_offset: 0x%x, self_info_size: 0x%x, unk: 0x%x, self_sha256: 0x%x",
self_info_offset, self_info_size, unk, self_sha256);
}
} self_info;
};
struct package_install_result
{
enum class error_type
{
no_error,
app_version,
other
} error = error_type::no_error;
struct version
{
std::string expected;
std::string found;
} version;
};
class package_reader
{
struct thread_key
{
const usz unique_num = umax;
};
struct install_entry
{
typename std::map<std::string, install_entry*>::value_type* weak_reference{};
std::string name;
u64 file_offset{};
u64 file_size{};
u32 type{};
u32 pad{};
// Check if the entry is the same one registered in entries to install
bool is_dominating() const
{
return weak_reference->second == this;
}
};
public:
package_reader(const std::string& path);
~package_reader();
enum result
{
not_started,
started,
success,
aborted,
aborted_dirty,
error,
error_dirty
};
bool is_valid() const { return m_is_valid; }
package_install_result check_target_app_version() const;
static package_install_result extract_data(std::deque<package_reader>& readers, std::deque<std::string>& bootable_paths);
psf::registry get_psf() const { return m_psf; }
result get_result() const { return m_result; };
int get_progress(int maximum = 100) const;
void abort_extract();
private:
bool read_header();
bool read_metadata();
bool read_param_sfo();
bool decrypt_data();
void archive_seek(s64 new_offset, const fs::seek_mode damode = fs::seek_set);
u64 archive_read(void* data_ptr, u64 num_bytes);
bool set_install_path();
bool fill_data(std::map<std::string, install_entry*>& all_install_entries);
std::span<const char> archive_read_block(u64 offset, void* data_ptr, u64 num_bytes);
std::span<const char> decrypt(u64 offset, u64 size, const uchar* key, thread_key thread_data_key = {0});
void extract_worker(thread_key thread_data_key);
std::deque<install_entry> m_install_entries;
std::string m_install_path;
atomic_t<bool> m_aborted = false;
atomic_t<usz> m_num_failures = 0;
atomic_t<usz> m_entry_indexer = 0;
atomic_t<usz> m_written_bytes = 0;
bool m_was_null = false;
static constexpr usz BUF_SIZE = 8192 * 1024; // 8 MB
bool m_is_valid = false;
result m_result = result::not_started;
std::string m_path{};
std::string m_install_dir{};
fs::file m_file{};
std::vector<std::unique_ptr<u128[]>> m_bufs{};
std::array<uchar, 16> m_dec_key{};
PKGHeader m_header{};
PKGMetaData m_metadata{};
psf::registry m_psf{};
// Expose bootable file installed (if installed such)
std::string m_bootable_file_path;
};
| 12,153
|
C++
|
.h
| 352
| 32.045455
| 152
| 0.653561
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,643
|
key_vault.h
|
RPCS3_rpcs3/rpcs3/Crypto/key_vault.h
|
#pragma once
#include "util/types.hpp"
#include <string>
#include <vector>
#include <memory>
enum SELF_KEY_TYPE
{
KEY_LV0 = 1,
KEY_LV1,
KEY_LV2,
KEY_APP,
KEY_ISO,
KEY_LDR,
KEY_UNK7,
KEY_NPDRM
};
struct SELF_KEY
{
u64 version_start{};
u64 version_end{};
u16 revision{};
u32 self_type{};
u8 erk[0x20]{};
u8 riv[0x10]{};
u8 pub[0x28]{};
u8 priv[0x15]{};
u32 curve_type{};
SELF_KEY(u64 ver_start, u64 ver_end, u16 rev, u32 type, const std::string& e, const std::string& r, const std::string& pb, const std::string& pr, u32 ct);
};
constexpr u32 PASSPHRASE_KEY_LEN = 16;
constexpr u32 PASSPHRASE_OUT_LEN = 4096;
constexpr u8 SC_ISO_SERIES_KEY_1[PASSPHRASE_KEY_LEN] = {
0xD4, 0x13, 0xB8, 0x96, 0x63, 0xE1, 0xFE, 0x9F, 0x75, 0x14, 0x3D, 0x3B, 0xB4, 0x56, 0x52, 0x74 // D413B89663E1FE9F75143D3BB4565274
};
constexpr u8 SC_ISO_SERIES_KEY_2[PASSPHRASE_KEY_LEN] = {
0xFA, 0x72, 0xCE, 0xEF, 0x59, 0xB4, 0xD2, 0x98, 0x9F, 0x11, 0x19, 0x13, 0x28, 0x7F, 0x51, 0xC7 // FA72CEEF59B4D2989F111913287F51C7
};
constexpr u8 SC_KEY_FOR_MASTER_1[PASSPHRASE_KEY_LEN] = {
0xDA, 0xA4, 0xB9, 0xF2, 0xBC, 0x70, 0xB2, 0x80, 0xA7, 0xB3, 0x40, 0xFA, 0x0D, 0x04, 0xBA, 0x14 // DAA4B9F2BC70B280A7B340FA0D04BA14
};
constexpr u8 SC_KEY_FOR_MASTER_2[PASSPHRASE_KEY_LEN] = {
0x29, 0xC1, 0x94, 0xFF, 0xEC, 0x1F, 0xD1, 0x4D, 0x4A, 0xAE, 0x00, 0x6C, 0x32, 0xB3, 0x59, 0x90 // 29C194FFEC1FD14D4AAE006C32B35990
};
constexpr u8 SC_ISO_SERIES_INTERNAL_KEY_1[PASSPHRASE_KEY_LEN] = {
0x73, 0x63, 0x6B, 0x65, 0x79, 0x5F, 0x73, 0x65, 0x72, 0x69, 0x65, 0x73, 0x6B, 0x65, 0x79, 0x00 // 73636B65795F7365726965736B657900
};
constexpr u8 SC_ISO_SERIES_INTERNAL_KEY_2[PASSPHRASE_KEY_LEN] = {
0x73, 0x63, 0x6B, 0x65, 0x79, 0x5F, 0x73, 0x65, 0x72, 0x69, 0x65, 0x73, 0x6B, 0x65, 0x79, 0x32 // 73636B65795F7365726965736B657932
};
constexpr u8 SC_ISO_SERIES_INTERNAL_KEY_3[PASSPHRASE_KEY_LEN] = {
0x73, 0x63, 0x6B, 0x65, 0x79, 0x5F, 0x66, 0x6F, 0x72, 0x5F, 0x6D, 0x61, 0x73, 0x74, 0x65, 0x72 // 73636B65795F666F725F6D6173746572
};
constexpr u8 PKG_AES_KEY_IDU[0x10] = {
0x5d, 0xb9, 0x11, 0xe6, 0xb7, 0xe5, 0x0a, 0x7d, 0x32, 0x15, 0x38, 0xfd, 0x7c, 0x66, 0xf1, 0x7b
};
constexpr u8 PKG_AES_KEY[0x10] = {
0x2e, 0x7b, 0x71, 0xd7, 0xc9, 0xc9, 0xa1, 0x4e, 0xa3, 0x22, 0x1f, 0x18, 0x88, 0x28, 0xb8, 0xf8
};
constexpr u8 PKG_AES_KEY2[0x10] = {
0x07, 0xf2, 0xc6, 0x82, 0x90, 0xb5, 0x0d, 0x2c, 0x33, 0x81, 0x8d, 0x70, 0x9b, 0x60, 0xe6, 0x2b
};
constexpr u8 PKG_AES_KEY_VITA_1[0x10] = {
0xE3, 0x1A, 0x70, 0xC9, 0xCE, 0x1D, 0xD7, 0x2B, 0xF3, 0xC0, 0x62, 0x29, 0x63, 0xF2, 0xEC, 0xCB
};
constexpr u8 PKG_AES_KEY_VITA_2[0x10] = {
0x42, 0x3A, 0xCA, 0x3A, 0x2B, 0xD5, 0x64, 0x9F, 0x96, 0x86, 0xAB, 0xAD, 0x6F, 0xD8, 0x80, 0x1F
};
constexpr u8 PKG_AES_KEY_VITA_3[0x10] = {
0xAF, 0x07, 0xFD, 0x59, 0x65, 0x25, 0x27, 0xBA, 0xF1, 0x33, 0x89, 0x66, 0x8B, 0x17, 0xD9, 0xEA
};
constexpr u8 NP_IDPS[0x10] = {
0x5E, 0x06, 0xE0, 0x4F, 0xD9, 0x4A, 0x71, 0xBF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01
};
constexpr u8 NP_KLIC_FREE[0x10] = {
0x72, 0xF9, 0x90, 0x78, 0x8F, 0x9C, 0xFF, 0x74, 0x57, 0x25, 0xF0, 0x8E, 0x4C, 0x12, 0x83, 0x87
};
constexpr u8 NP_OMAC_KEY_2[0x10] = {
0x6B, 0xA5, 0x29, 0x76, 0xEF, 0xDA, 0x16, 0xEF, 0x3C, 0x33, 0x9F, 0xB2, 0x97, 0x1E, 0x25, 0x6B
};
constexpr u8 NP_OMAC_KEY_3[0x10] = {
0x9B, 0x51, 0x5F, 0xEA, 0xCF, 0x75, 0x06, 0x49, 0x81, 0xAA, 0x60, 0x4D, 0x91, 0xA5, 0x4E, 0x97
};
constexpr u8 NP_KLIC_KEY[0x10] = {
0xF2, 0xFB, 0xCA, 0x7A, 0x75, 0xB0, 0x4E, 0xDC, 0x13, 0x90, 0x63, 0x8C, 0xCD, 0xFD, 0xD1, 0xEE
};
constexpr u8 NP_RIF_KEY[0x10] = {
0xDA, 0x7D, 0x4B, 0x5E, 0x49, 0x9A, 0x4F, 0x53, 0xB1, 0xC1, 0xA1, 0x4A, 0x74, 0x84, 0x44, 0x3B
};
// PSP Minis
constexpr u8 NP_PSP_KEY_1[0x10] = {
0x2A, 0x6A, 0xFB, 0xCF, 0x43, 0xD1, 0x57, 0x9F, 0x7D, 0x73, 0x87, 0x41, 0xA1, 0x3B, 0xD4, 0x2E
};
// PSP Remasters
constexpr u8 NP_PSP_KEY_2[0x10] = {
0x0D, 0xB8, 0x57, 0x32, 0x36, 0x6C, 0xD7, 0x34, 0xFC, 0x87, 0x9E, 0x74, 0x33, 0x43, 0xBB, 0x4F
};
constexpr u8 NP_PSX_KEY[0x10] = {
0x52, 0xC0, 0xB5, 0xCA, 0x76, 0xD6, 0x13, 0x4B, 0xB4, 0x5F, 0xC6, 0x6C, 0xA6, 0x37, 0xF2, 0xC1
};
constexpr u8 RAP_KEY[0x10] = {
0x86, 0x9F, 0x77, 0x45, 0xC1, 0x3F, 0xD8, 0x90, 0xCC, 0xF2, 0x91, 0x88, 0xE3, 0xCC, 0x3E, 0xDF
};
constexpr u8 RAP_PBOX[0x10] = {
0x0C, 0x03, 0x06, 0x04, 0x01, 0x0B, 0x0F, 0x08, 0x02, 0x07, 0x00, 0x05, 0x0A, 0x0E, 0x0D, 0x09
};
constexpr u8 RAP_E1[0x10] = {
0xA9, 0x3E, 0x1F, 0xD6, 0x7C, 0x55, 0xA3, 0x29, 0xB7, 0x5F, 0xDD, 0xA6, 0x2A, 0x95, 0xC7, 0xA5
};
constexpr u8 RAP_E2[0x10] = {
0x67, 0xD4, 0x5D, 0xA3, 0x29, 0x6D, 0x00, 0x6A, 0x4E, 0x7C, 0x53, 0x7B, 0xF5, 0x53, 0x8C, 0x74
};
constexpr u8 SDAT_KEY[0x10] = {
0x0D, 0x65, 0x5E, 0xF8, 0xE6, 0x74, 0xA9, 0x8A, 0xB8, 0x50, 0x5C, 0xFA, 0x7D, 0x01, 0x29, 0x33
};
constexpr u8 EDAT_KEY_0[0x10] = {
0xBE, 0x95, 0x9C, 0xA8, 0x30, 0x8D, 0xEF, 0xA2, 0xE5, 0xE1, 0x80, 0xC6, 0x37, 0x12, 0xA9, 0xAE
};
constexpr u8 EDAT_HASH_0[0x10] = {
0xEF, 0xFE, 0x5B, 0xD1, 0x65, 0x2E, 0xEB, 0xC1, 0x19, 0x18, 0xCF, 0x7C, 0x04, 0xD4, 0xF0, 0x11
};
constexpr u8 EDAT_KEY_1[0x10] = {
0x4C, 0xA9, 0xC1, 0x4B, 0x01, 0xC9, 0x53, 0x09, 0x96, 0x9B, 0xEC, 0x68, 0xAA, 0x0B, 0xC0, 0x81
};
constexpr u8 EDAT_HASH_1[0x10] = {
0x3D, 0x92, 0x69, 0x9B, 0x70, 0x5B, 0x07, 0x38, 0x54, 0xD8, 0xFC, 0xC6, 0xC7, 0x67, 0x27, 0x47
};
constexpr u8 EDAT_IV[0x10] = {
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
};
constexpr u8 VSH_CURVE_P[0x14] = {
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x01, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF
};
constexpr u8 VSH_CURVE_A[0x14] = {
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x01, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFC
};
constexpr u8 VSH_CURVE_B[0x14] = {
0xA6, 0x8B, 0xED, 0xC3, 0x34, 0x18, 0x02, 0x9C, 0x1D, 0x3C, 0xE3, 0x3B, 0x9A, 0x32, 0x1F, 0xCC, 0xBB, 0x9E, 0x0F, 0x0B
};
constexpr u8 VSH_CURVE_N[0x15] = {
0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFE, 0xFF, 0xFF, 0xB5, 0xAE, 0x3C, 0x52, 0x3E, 0x63, 0x94, 0x4F, 0x21, 0x27
};
constexpr u8 VSH_CURVE_GX[0x14] = {
0x12, 0x8E, 0xC4, 0x25, 0x64, 0x87, 0xFD, 0x8F, 0xDF, 0x64, 0xE2, 0x43, 0x7B, 0xC0, 0xA1, 0xF6, 0xD5, 0xAF, 0xDE, 0x2C
};
constexpr u8 VSH_CURVE_GY[0x14] = {
0x59, 0x58, 0x55, 0x7E, 0xB1, 0xDB, 0x00, 0x12, 0x60, 0x42, 0x55, 0x24, 0xDB, 0xC3, 0x79, 0xD5, 0xAC, 0x5F, 0x4A, 0xDF
};
constexpr u8 VSH_PUB[0x28] = {
0x62, 0x27, 0xB0, 0x0A, 0x02, 0x85, 0x6F, 0xB0, 0x41, 0x08, 0x87, 0x67, 0x19, 0xE0, 0xA0, 0x18, 0x32, 0x91, 0xEE, 0xB9,
0x6E, 0x73, 0x6A, 0xBF, 0x81, 0xF7, 0x0E, 0xE9, 0x16, 0x1B, 0x0D, 0xDE, 0xB0, 0x26, 0x76, 0x1A, 0xFF, 0x7B, 0xC8, 0x5B
};
constexpr u8 SCEPKG_RIV[0x10] = {
0x4A, 0xCE, 0xF0, 0x12, 0x24, 0xFB, 0xEE, 0xDF, 0x82, 0x45, 0xF8, 0xFF, 0x10, 0x21, 0x1E, 0x6E
};
constexpr u8 SCEPKG_ERK[0x20] = {
0xA9, 0x78, 0x18, 0xBD, 0x19, 0x3A, 0x67, 0xA1, 0x6F, 0xE8, 0x3A, 0x85, 0x5E, 0x1B, 0xE9, 0xFB, 0x56, 0x40, 0x93, 0x8D,
0x4D, 0xBC, 0xB2, 0xCB, 0x52, 0xC5, 0xA2, 0xF8, 0xB0, 0x2B, 0x10, 0x31
};
constexpr u8 PUP_KEY[0x40] = {
0xF4, 0x91, 0xAD, 0x94, 0xC6, 0x81, 0x10, 0x96, 0x91, 0x5F, 0xD5, 0xD2, 0x44, 0x81, 0xAE, 0xDC, 0xED, 0xED, 0xBE, 0x6B,
0xE5, 0x13, 0x72, 0x4D, 0xD8, 0xF7, 0xB6, 0x91, 0xE8, 0x8A, 0x38, 0xF4, 0xB5, 0x16, 0x2B, 0xFB, 0xEC, 0xBE, 0x3A, 0x62,
0x18, 0x5D, 0xD7, 0xC9, 0x4D, 0xA2, 0x22, 0x5A, 0xDA, 0x3F, 0xBF, 0xCE, 0x55, 0x5B, 0x9E, 0xA9, 0x64, 0x98, 0x29, 0xEB,
0x30, 0xCE, 0x83, 0x66
};
// name; location; notes
constexpr s64 PAID_01 = 0x0003CD28CB47D3C1L; // spu_token_processor.self; CoreOS; Only for 2E - 083.007
constexpr s64 PAID_02 = 0x1010000001000001L; // vsh / games / utilities; /dev_flash/, cell_root/target/images; only for 2E - 080.006
constexpr s64 PAID_03 = 0x1010000001000003L; // retail games and their updates
constexpr s64 PAID_04 = 0x1010000002000003L;
constexpr s64 PAID_05 = 0x1020000401000001L; // ps2emu; /dev_flash/ps2emu; CEX DEX DECR ?
constexpr s64 PAID_06 = 0x1050000003000001L; // lv2_kernel.self; CoreOS; same for CEX DEX DECR
constexpr s64 PAID_07 = 0x1070000001000002L; // onicore_child.self; /dev_flash/vsh/module; same for CEX DEX DECR
constexpr s64 PAID_08 = 0x1070000002000002L; // mcore.self; /dev_flash/vsh/module; same for CEX DEX DECR
constexpr s64 PAID_09 = 0x1070000003000002L; // mgvideo.self; /dev_flash/vsh/module; same for CEX DEX DECR
constexpr s64 PAID_10 = 0x1070000004000002L; // swagner / swreset; /dev_flash/vsh/module; DTCP-IP DRM modules
constexpr s64 PAID_11 = 0x107000000E000001L; // vtrm_server.fself; lv1
constexpr s64 PAID_12 = 0x107000000F000001L; // update_manager_server.fself; lv1
constexpr s64 PAID_13 = 0x1070000010000001L; // sc_manager_server.fself; lv1
constexpr s64 PAID_14 = 0x1070000011000001L; // secure_rtc_server.fself; lv1
constexpr s64 PAID_15 = 0x1070000012000001L; // spm_server.fself; lv1
constexpr s64 PAID_16 = 0x1070000013000001L; // sb_manager_server.fself; lv1
constexpr s64 PAID_17 = 0x1070000014000001L; // framework.fself; lv1
constexpr s64 PAID_18 = 0x1070000015000001L; // lv2_loader.fself; lv1
constexpr s64 PAID_19 = 0x1070000016000001L; // profile_loader.fself; lv1
constexpr s64 PAID_20 = 0x1070000017000001L; // ss_init.fself; lv1
constexpr s64 PAID_21 = 0x1070000018000001L; // individual_info_mgr_server.fself; lv1
constexpr s64 PAID_22 = 0x1070000019000001L; // app_info_manager_server.fself; lv1
constexpr s64 PAID_23 = 0x107000001A000001L; // ss_sc_init_pu.fself; JIG lv1 proc
constexpr s64 PAID_24 = 0x107000001C000001L; // updater_frontend.fself; lv1
constexpr s64 PAID_25 = 0x107000001D000001L; // sysmgr_ss.fself; lv1
constexpr s64 PAID_26 = 0x107000001F000001L; // sb_iso_spu_module.self; CoreOS; same for CEX DEX DECR
constexpr s64 PAID_27 = 0x1070000020000001L; // sc_iso.self / sc_iso_factory.self; CoreOS / [2.43 JIG PUP]; same for CEX DEX DECR
constexpr s64 PAID_28 = 0x1070000021000001L; // spp_verifier.self; CoreOS; same for CEX DEX DECR
constexpr s64 PAID_29 = 0x1070000022000001L; // spu_pkg_rvk_verifier.self; CoreOS; same for CEX DEX DECR
constexpr s64 PAID_30 = 0x1070000023000001L; // spu_token_processor.self; CoreOS; same for CEX DEX DECR
constexpr s64 PAID_31 = 0x1070000024000001L; // sv_iso_spu_module.self; CoreOS; same for CEX DEX DECR
constexpr s64 PAID_32 = 0x1070000025000001L; // aim_spu_module.self; CoreOS; same for CEX DEX DECR
constexpr s64 PAID_33 = 0x1070000026000001L; // ss_sc_init.self; [2.43 JIG PUP]
constexpr s64 PAID_34 = 0x1070000027000001L; // dispatcher.fself; lv1;
constexpr s64 PAID_35 = 0x1070000028000001L; // factory_data_mngr_server.fself; JIG lv1 proc
constexpr s64 PAID_36 = 0x1070000029000001L; // fdm_spu_module.self; [2.43 JIG PUP]
constexpr s64 PAID_37 = 0x107000002A000001L;
constexpr s64 PAID_38 = 0x1070000031000001L;
constexpr s64 PAID_39 = 0x1070000032000001L; // ss_server1.fself; lv1
constexpr s64 PAID_40 = 0x1070000033000001L; // ss_server2.fself; lv1
constexpr s64 PAID_41 = 0x1070000034000001L; // ss_server3.fself; lv1
constexpr s64 PAID_42 = 0x1070000037000001L; // mc_iso_spu_module.self; CoreOS; same for CEX DEX DECR
constexpr s64 PAID_43 = 0x1070000039000001L; // bdp_bdmv.self; /dev_flash/bdplayer
constexpr s64 PAID_44 = 0x107000003A000001L; // bdj.self; /dev_flash/bdplayer
constexpr s64 PAID_45 = 0x1070000040000001L; // sys/external modules; /dev_flash/sys/external; same for CEX DEX DECR (incl. liblv2dbg_for_cex.sprx + liblv2dbg_for_dex.sprx)
constexpr s64 PAID_46 = 0x1070000041000001L; // ps1emu; /dev_flash/ps1emu; CEX DEX DECR ?
constexpr s64 PAID_47 = 0x1070000043000001L; // me_iso_spu_module.self; CoreOS; same for CEX DEX DECR
constexpr s64 PAID_48 = 0x1070000044000001L; // (related to usb dongle)
constexpr s64 PAID_49 = 0x1070000045000001L; // USB Dongle Authenticator; ss_server1.fself; same for CEX DEX DECR
constexpr s64 PAID_50 = 0x1070000046000001L; // spu_mode_auth.self; [2.43 JIG PUP]
constexpr s64 PAID_51 = 0x1070000047000001L; // otheros.self; otheros.self
constexpr s64 PAID_52 = 0x1070000048000001L; // ftpd; cell_root/target/images; DECR
constexpr s64 PAID_53 = 0x107000004C000001L; // spu_utoken_processor.self; CoreOS (since FW 2.40)
constexpr s64 PAID_54 = 0x107000004E000001L; // (syscall 878)
constexpr s64 PAID_55 = 0x107000004F000001L;
constexpr s64 PAID_56 = 0x1070000050000001L;
constexpr s64 PAID_57 = 0x1070000051000001L;
constexpr s64 PAID_58 = 0x1070000052000001L; // sys/internal CEX + vsh/module modules CEX; /dev_flash/sys/internal + /dev_flash/vsh/module; Differs between CEX (this authid) and DECR
constexpr s64 PAID_59 = 0x1070000054000001L; // (syscall 21)
constexpr s64 PAID_60 = 0x1070000055000001L; // manu_info_spu_module.self; CoreOS (since FW 3.50)
constexpr s64 PAID_61 = 0x1070000058000001L; // me_iso_for_ps2emu.self; CoreOS (since FW 3.70)
constexpr s64 PAID_62 = 0x1070000059000001L; // sv_iso_for_ps2emu.self; CoreOS (since FW 3.70)
constexpr s64 PAID_63 = 0x1070000300000001L; // Lv2diag.self; BD-remarry toolkit
constexpr s64 PAID_64 = 0x10700003FC000001L; // emer_init.self; CoreOS (since FW 2.00)
constexpr s64 PAID_65 = 0x10700003FD000001L; // ps3swu; PUP root; same for CEX DEX DECR
constexpr s64 PAID_66 = 0x10700003FD000001L; // PS3ToolUpdater; cell_root/target/images; Only DECR
constexpr s64 PAID_67 = 0x10700003FD000001L; // manufacturing_updater_for_reset.self; BD-remarry toolkit
constexpr s64 PAID_68 = 0x10700003FE000001L; // sys_agent.self DECR; /dev_flash/sys/internal; DECR
constexpr s64 PAID_69 = 0x10700003FF000001L; // db_backup, mkfs, mkfs_085, mount_hdd, registry_backup, set_monitor, most sys/internal modules DECR + most vsh/module modules DECR; /dev_flash/sys/internal + /dev_flash/vsh/module + cell_root/target/images; Differs between DECR (this authid) and CEX
constexpr s64 PAID_70 = 0x1070000400000001L; // vsh / games / utilities; /dev_flash/, cell_root/target/images; only for 081.003 - 083.007
constexpr s64 PAID_71 = 0x1070000409000001L; // psp_emulator.self; /dev_flash/pspemu/psp_emulator.self; CEX DEX DECR ?
constexpr s64 PAID_72 = 0x107000040A000001L; // psp_translator.self; /dev_flash/pspemu/psp_translator.self; CEX DEX DECR ?
constexpr s64 PAID_73 = 0x107000040B000001L; // emulator_api.sprx and other .sprx; /dev_flash/pspemu/release/; CEX DEX DECR ?
constexpr s64 PAID_74 = 0x107000040C000001L; // emulator_drm.sprx; /dev_flash/pspemu/release/emulator_drm.sprx; CEX DEX DECR ?
constexpr s64 PAID_75 = 0x107000040C000001L; // libchnnlsv.sprx; /dev_flash/sys/internal/; CEX DEX DECR ?
constexpr s64 PAID_76 = 0x107000040D000001L; // ?psp related?; ?/dev_flash/pspemu/release/?; CEX DEX DECR ?
constexpr s64 PAID_77 = 0x1070000500000001L; // cellftp; cell_root/target/images/; DECR
constexpr s64 PAID_78 = 0x1070000501000001L; // hdd_copy.self; CoreOS (since FW 3.10)
constexpr s64 PAID_79 = 0x10700005FC000001L; // sys_audio; /dev_flash/sys/internal; CEX
constexpr s64 PAID_80 = 0x10700005FD000001L; // sys_init_osd; /dev_flash/sys/internal; CEX
constexpr s64 PAID_81 = 0x10700005FF000001L; // vsh.self; /dev_flash/vsh/; CEX
constexpr s64 PAID_82 = 0x1070001002000001L; // PvrRecSvr.sprx; BCJB95006\USRDIR\v320; CEX
constexpr s64 PAID_83 = 0x1070200056000001L; // cachemgr.self; WebMAF apps/USRDIR
constexpr s64 PAID_84 = 0x1070200057000001L; // EBOOT.BIN.self + .sprx files; WebMAF apps/USRDIR/prx/ps3; Demen_prx.ppu.sprx + WebMAF sprx files
constexpr s64 PAID_85 = 0x1FF0000001000001L; // lv0; CoreOS; same for CEX DEX DECR
constexpr s64 PAID_86 = 0x1FF0000002000001L; // lv1.self; CoreOS; same for CEX DEX DECR
constexpr s64 PAID_87 = 0x1FF0000008000001L; // lv1ldr; CoreOS; same for CEX DEX DECR
constexpr s64 PAID_88 = 0x1FF0000009000001L; // lv2ldr; CoreOS; same for CEX DEX DECR
constexpr s64 PAID_89 = 0x1FF000000A000001L; // isoldr; CoreOS; same for CEX DEX DECR
constexpr s64 PAID_90 = 0x1FF000000B000001L; // rvkldr; CoreOS; same for CEX DEX DECR
constexpr s64 PAID_91 = 0x1FF000000C000001L; // appldr; CoreOS; same for CEX DEX DECR
constexpr s64 LAID_1 = 0x1070000001000001L; // (= HV processes / SCE_CELLOS_PME); flash and vflash
constexpr s64 LAID_2 = 0x1070000002000001L; // (= GameOS / PS3_LPAR); flash and vflash
constexpr s64 LAID_3 = 0x1020000003000001L; // (= PS2_LPAR / PS2_GX_LPAR / PS2_SW_LPAR / PS2_NE_LPAR); (used in ps3vflashc region inside vflash in NOR consoles, and ps3db region)... dev_flash and dev_hdd0 regions
constexpr s64 LAID_4 = 0x1080000004000001L; // (= LINUX_LPAR); (used in ps3vflashf region inside vflash in NOR consoles)... otheros bootloader region
class KeyVault
{
std::vector<SELF_KEY> sk_LV0_arr{};
std::vector<SELF_KEY> sk_LV1_arr{};
std::vector<SELF_KEY> sk_LV2_arr{};
std::vector<SELF_KEY> sk_APP_arr{};
std::vector<SELF_KEY> sk_ISO_arr{};
std::vector<SELF_KEY> sk_LDR_arr{};
std::vector<SELF_KEY> sk_UNK7_arr{};
std::vector<SELF_KEY> sk_NPDRM_arr{};
std::unique_ptr<u8[]> klicensee_key{};
public:
KeyVault();
SELF_KEY FindSelfKey(u32 type, u16 revision, u64 version);
void SetKlicenseeKey(u8* key);
u8* GetKlicenseeKey() const;
private:
void LoadSelfLV0Keys();
void LoadSelfLDRKeys();
void LoadSelfLV1Keys();
void LoadSelfLV2Keys();
void LoadSelfISOKeys();
void LoadSelfAPPKeys();
void LoadSelfUNK7Keys();
void LoadSelfNPDRMKeys();
SELF_KEY GetSelfLV0Key() const;
SELF_KEY GetSelfLDRKey() const;
SELF_KEY GetSelfLV1Key(u64 version) const;
SELF_KEY GetSelfLV2Key(u64 version) const;
SELF_KEY GetSelfISOKey(u16 revision, u64 version) const;
SELF_KEY GetSelfAPPKey(u16 revision) const;
SELF_KEY GetSelfUNK7Key(u64 version) const;
SELF_KEY GetSelfNPDRMKey(u16 revision) const;
};
// RAP to RIF function.
void rap_to_rif(unsigned char* rap, unsigned char* rif);
| 17,623
|
C++
|
.h
| 296
| 57.885135
| 296
| 0.733225
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,644
|
to_endian.hpp
|
RPCS3_rpcs3/rpcs3/util/to_endian.hpp
|
#pragma once
#include "util/types.hpp"
#include "util/endian.hpp"
union v128;
// Type converter: converts native endianness arithmetic/enum types to appropriate se_t<> type
template <typename T, bool Se, typename = void>
struct to_se
{
template <typename T2, typename = void>
struct to_se_
{
using type = T2;
};
template <typename T2>
struct to_se_<T2, std::enable_if_t<std::is_arithmetic_v<T2> || std::is_enum_v<T2>>>
{
using type = std::conditional_t<(sizeof(T2) > 1), se_t<T2, Se>, T2>;
};
// Convert arithmetic and enum types
using type = typename to_se_<T>::type;
};
template <bool Se>
struct to_se<v128, Se>
{
using type = se_t<v128, Se, 16>;
};
template <bool Se>
struct to_se<u128, Se>
{
using type = se_t<u128, Se>;
};
template <bool Se>
struct to_se<s128, Se>
{
using type = se_t<s128, Se>;
};
template <typename T, bool Se>
struct to_se<const T, Se, std::enable_if_t<!std::is_array_v<T>>>
{
// Move const qualifier
using type = const typename to_se<T, Se>::type;
};
template <typename T, bool Se>
struct to_se<volatile T, Se, std::enable_if_t<!std::is_array_v<T> && !std::is_const_v<T>>>
{
// Move volatile qualifier
using type = volatile typename to_se<T, Se>::type;
};
template <typename T, bool Se>
struct to_se<T[], Se>
{
// Move array qualifier
using type = typename to_se<T, Se>::type[];
};
template <typename T, bool Se, usz N>
struct to_se<T[N], Se>
{
// Move array qualifier
using type = typename to_se<T, Se>::type[N];
};
// BE/LE aliases for to_se<>
template <typename T>
using to_be_t = typename to_se<T, std::endian::little == std::endian::native>::type;
template <typename T>
using to_le_t = typename to_se<T, std::endian::big == std::endian::native>::type;
| 1,721
|
C++
|
.h
| 65
| 24.892308
| 94
| 0.688375
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
5,645
|
bless.hpp
|
RPCS3_rpcs3/rpcs3/util/bless.hpp
|
#pragma once
namespace utils
{
// Hack. Pointer cast util to workaround UB. Use with extreme care.
template <typename T, typename U>
[[nodiscard]] T* bless(U* ptr)
{
#ifdef _MSC_VER
return (T*)ptr;
#elif defined(ARCH_X64)
T* result;
__asm__("movq %1, %0;" : "=r" (result) : "r" (ptr) : "memory");
return result;
#elif defined(ARCH_ARM64)
T* result;
__asm__("mov %0, %1" : "=r" (result) : "r" (ptr) : "memory");
return result;
#endif
}
}
| 478
|
C++
|
.h
| 20
| 20.85
| 69
| 0.598684
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,646
|
endian.hpp
|
RPCS3_rpcs3/rpcs3/util/endian.hpp
|
#pragma once // No BOM and only basic ASCII in this header, or a neko will die
#include "util/types.hpp"
#ifndef _MSC_VER
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Weffc++"
#endif
namespace stx
{
template <typename T, usz Align = alignof(T), usz Size = sizeof(T)>
struct se_storage
{
struct type8
{
alignas(Align > alignof(T) ? alignof(T) : Align) uchar data[sizeof(T)];
};
struct type64
{
alignas(8) u64 data[sizeof(T) < 8 ? 1 : sizeof(T) / 8];
};
using type = std::conditional_t<(Align >= 8 && sizeof(T) % 8 == 0), type64, type8>;
// Possibly unoptimized generic byteswap for unaligned data
static constexpr type swap(const type& src) noexcept;
};
template <typename T>
struct se_storage<T, 2, 2>
{
using type = u16;
static constexpr u16 swap(u16 src) noexcept
{
#if __cpp_lib_byteswap >= 202110L
return std::byteswap(src);
#elif defined(__GNUG__)
return __builtin_bswap16(src);
#else
if (std::is_constant_evaluated())
{
return (src >> 8) | (src << 8);
}
return _byteswap_ushort(src);
#endif
}
};
template <typename T>
struct se_storage<T, 4, 4>
{
using type = u32;
static constexpr u32 swap(u32 src) noexcept
{
#if __cpp_lib_byteswap >= 202110L
return std::byteswap(src);
#elif defined(__GNUG__)
return __builtin_bswap32(src);
#else
if (std::is_constant_evaluated())
{
const u32 v0 = ((src << 8) & 0xff00ff00) | ((src >> 8) & 0x00ff00ff);
return (v0 << 16) | (v0 >> 16);
}
return _byteswap_ulong(src);
#endif
}
};
template <typename T>
struct se_storage<T, 8, 8>
{
using type = u64;
static constexpr u64 swap(u64 src) noexcept
{
#if __cpp_lib_byteswap >= 202110L
return std::byteswap(src);
#elif defined(__GNUG__)
return __builtin_bswap64(src);
#else
if (std::is_constant_evaluated())
{
const u64 v0 = ((src << 8) & 0xff00ff00ff00ff00) | ((src >> 8) & 0x00ff00ff00ff00ff);
const u64 v1 = ((v0 << 16) & 0xffff0000ffff0000) | ((v0 >> 16) & 0x0000ffff0000ffff);
return (v1 << 32) | (v1 >> 32);
}
return _byteswap_uint64(src);
#endif
}
};
template <typename T, usz Align, usz Size>
constexpr typename se_storage<T, Align, Size>::type se_storage<T, Align, Size>::swap(const type& src) noexcept
{
// Try to keep u16/u32/u64 optimizations at the cost of more bitcasts
if constexpr (sizeof(T) == 1)
{
return src;
}
else if constexpr (sizeof(T) == 2)
{
return std::bit_cast<type>(se_storage<u16>::swap(std::bit_cast<u16>(src)));
}
else if constexpr (sizeof(T) == 4)
{
return std::bit_cast<type>(se_storage<u32>::swap(std::bit_cast<u32>(src)));
}
else if constexpr (sizeof(T) == 8)
{
return std::bit_cast<type>(se_storage<u64>::swap(std::bit_cast<u64>(src)));
}
else if constexpr (sizeof(T) % 8 == 0)
{
type64 tmp = std::bit_cast<type64>(src);
type64 dst{};
// Swap u64 blocks
for (usz i = 0; i < sizeof(T) / 8; i++)
{
dst.data[i] = se_storage<u64>::swap(tmp.data[sizeof(T) / 8 - 1 - i]);
}
return std::bit_cast<type>(dst);
}
else
{
type dst{};
// Swap by moving every byte
for (usz i = 0; i < sizeof(T); i++)
{
dst.data[i] = src.data[sizeof(T) - 1 - i];
}
return dst;
}
}
// Endianness support template
template <typename T, bool Swap, usz Align = alignof(T)>
class alignas(Align) se_t
{
using type = std::remove_cv_t<T>;
using stype = typename se_storage<type, Align>::type;
using storage = se_storage<type, Align>;
stype m_data;
static_assert(!std::is_pointer_v<type>, "se_t<> error: invalid type (pointer)");
static_assert(!std::is_reference_v<type>, "se_t<> error: invalid type (reference)");
static_assert(!std::is_array_v<type>, "se_t<> error: invalid type (array)");
static_assert(sizeof(type) == alignof(type), "se_t<> error: unexpected alignment");
static constexpr stype to_data(type value) noexcept
{
if constexpr (Swap)
{
return storage::swap(std::bit_cast<stype>(value));
}
else
{
return std::bit_cast<stype>(value);
}
}
static constexpr auto int_or_enum()
{
if constexpr (std::is_enum_v<type>)
{
return std::underlying_type_t<type>{};
}
else
{
return type{};
}
}
using under = decltype(int_or_enum());
public:
ENABLE_BITWISE_SERIALIZATION;
se_t() noexcept = default;
constexpr se_t(type value) noexcept
: m_data(to_data(value))
{
}
constexpr type value() const noexcept
{
if constexpr (Swap)
{
return std::bit_cast<type>(storage::swap(m_data));
}
else
{
return std::bit_cast<type>(m_data);
}
}
constexpr type get() const noexcept
{
return value();
}
constexpr se_t& operator=(type value) noexcept
{
m_data = to_data(value);
return *this;
}
constexpr operator type() const noexcept
{
return value();
}
#ifdef _MSC_VER
explicit constexpr operator bool() const noexcept
{
static_assert(!type{});
static_assert(!std::is_floating_point_v<type>);
return !!std::bit_cast<type>(m_data);
}
#endif
constexpr auto operator~() const noexcept
{
if constexpr ((std::is_integral_v<T> || std::is_enum_v<T>) && std::is_convertible_v<T, int>)
{
// Return se_t of integral type if possible. Promotion to int is omitted on purpose (a compromise).
return std::bit_cast<se_t<under, Swap>>(static_cast<under>(~std::bit_cast<under>(m_data)));
}
else
{
return ~value();
}
}
private:
// Compatible bit pattern cast
template <typename To, typename Test = int, typename T2>
static constexpr To right_arg_cast(const T2& rhs) noexcept
{
return std::bit_cast<To>(static_cast<se_t<To, Swap>>(rhs));
}
template <typename To, typename Test = int, typename R, usz Align2>
static constexpr To right_arg_cast(const se_t<R, Swap, Align2>& rhs) noexcept
{
if constexpr ((std::is_integral_v<R> || std::is_enum_v<R>) && std::is_convertible_v<R, Test> && sizeof(R) == sizeof(T))
{
// Optimization: allow to reuse bit pattern of any se_t with bit-compatible type
return std::bit_cast<To>(rhs);
}
else
{
return std::bit_cast<To>(static_cast<se_t<To, Swap>>(rhs.value()));
}
}
public:
template <typename T2, typename = decltype(+std::declval<const T2&>())>
constexpr bool operator==(const T2& rhs) const noexcept
{
using R = std::common_type_t<T2>;
if constexpr ((std::is_integral_v<T> || std::is_enum_v<T>) && (std::is_integral_v<R> || std::is_enum_v<R>))
{
if constexpr (sizeof(T) >= sizeof(R))
{
if constexpr (std::is_convertible_v<T, int> && std::is_convertible_v<R, int>)
{
return std::bit_cast<under>(m_data) == right_arg_cast<under>(rhs);
}
else
{
// Compare with strict type on the right side (possibly scoped enum)
return std::bit_cast<type>(m_data) == right_arg_cast<type, type>(rhs);
}
}
}
// Keep outside of if constexpr to make sure it fails on invalid comparison
return value() == rhs;
}
private:
template <typename T2>
static constexpr bool check_args_for_bitwise_op()
{
using R = std::common_type_t<T2>;
if constexpr ((std::is_integral_v<T> || std::is_enum_v<T>) && (std::is_integral_v<R> || std::is_enum_v<R>))
{
if constexpr (std::is_convertible_v<T, int> && std::is_convertible_v<R, int> && sizeof(T) >= sizeof(R))
{
return true;
}
}
return false;
}
public:
template <typename T2>
constexpr auto operator&(const T2& rhs) const noexcept
{
if constexpr (check_args_for_bitwise_op<T2>())
{
return std::bit_cast<se_t<under, Swap>>(static_cast<under>(std::bit_cast<under>(m_data) & right_arg_cast<under>(rhs)));
}
else
{
return value() & rhs;
}
}
template <typename T2>
constexpr auto operator|(const T2& rhs) const noexcept
{
if constexpr (check_args_for_bitwise_op<T2>())
{
return std::bit_cast<se_t<under, Swap>>(static_cast<under>(std::bit_cast<under>(m_data) | right_arg_cast<under>(rhs)));
}
else
{
return value() | rhs;
}
}
template <typename T2>
constexpr auto operator^(const T2& rhs) const noexcept
{
if constexpr (check_args_for_bitwise_op<T2>())
{
return std::bit_cast<se_t<under, Swap>>(static_cast<under>(std::bit_cast<under>(m_data) ^ right_arg_cast<under>(rhs)));
}
else
{
return value() ^ rhs;
}
}
template <typename T1>
constexpr se_t& operator+=(const T1& rhs)
{
*this = value() + rhs;
return *this;
}
template <typename T1>
constexpr se_t& operator-=(const T1& rhs)
{
*this = value() - rhs;
return *this;
}
template <typename T1>
constexpr se_t& operator*=(const T1& rhs)
{
*this = value() * rhs;
return *this;
}
template <typename T1>
constexpr se_t& operator/=(const T1& rhs)
{
*this = value() / rhs;
return *this;
}
template <typename T1>
constexpr se_t& operator%=(const T1& rhs)
{
*this = value() % rhs;
return *this;
}
template <typename T1>
constexpr se_t& operator&=(const T1& rhs)
{
if constexpr (std::is_integral_v<T>)
{
m_data = std::bit_cast<stype, type>(static_cast<type>(std::bit_cast<type>(m_data) & right_arg_cast<type>(rhs)));
return *this;
}
*this = value() & rhs;
return *this;
}
template <typename T1>
constexpr se_t& operator|=(const T1& rhs)
{
if constexpr (std::is_integral_v<T>)
{
m_data = std::bit_cast<stype, type>(static_cast<type>(std::bit_cast<type>(m_data) | right_arg_cast<type>(rhs)));
return *this;
}
*this = value() | rhs;
return *this;
}
template <typename T1>
constexpr se_t& operator^=(const T1& rhs)
{
if constexpr (std::is_integral_v<T>)
{
m_data = std::bit_cast<stype, type>(static_cast<type>(std::bit_cast<type>(m_data) ^ right_arg_cast<type>(rhs)));
return *this;
}
*this = value() ^ rhs;
return *this;
}
template <typename T1>
constexpr se_t& operator<<=(const T1& rhs)
{
*this = value() << rhs;
return *this;
}
template <typename T1>
constexpr se_t& operator>>=(const T1& rhs)
{
*this = value() >> rhs;
return *this;
}
constexpr se_t& operator++()
{
T value = *this;
*this = ++value;
return *this;
}
constexpr se_t& operator--()
{
T value = *this;
*this = --value;
return *this;
}
constexpr T operator++(int)
{
T value = *this;
T result = value++;
*this = value;
return result;
}
constexpr T operator--(int)
{
T value = *this;
T result = value--;
*this = value;
return result;
}
};
}
// Specializations
template <typename T, bool Swap, usz Align, typename T2, bool Swap2, usz Align2>
struct std::common_type<stx::se_t<T, Swap, Align>, stx::se_t<T2, Swap2, Align2>> : std::common_type<T, T2> {};
template <typename T, bool Swap, usz Align, typename T2>
struct std::common_type<stx::se_t<T, Swap, Align>, T2> : std::common_type<T, std::common_type_t<T2>> {};
template <typename T, typename T2, bool Swap2, usz Align2>
struct std::common_type<T, stx::se_t<T2, Swap2, Align2>> : std::common_type<std::common_type_t<T>, T2> {};
#ifndef _MSC_VER
#pragma GCC diagnostic pop
#endif
| 11,195
|
C++
|
.h
| 418
| 23.244019
| 123
| 0.638902
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
5,647
|
video_sink.h
|
RPCS3_rpcs3/rpcs3/util/video_sink.h
|
#pragma once
#include "util/types.hpp"
#include "util/atomic.hpp"
#include "Utilities/mutex.h"
#include <deque>
#include <cmath>
namespace utils
{
class video_sink
{
public:
video_sink() = default;
virtual ~video_sink() = default;
virtual void stop(bool flush = true) = 0;
virtual void pause(bool flush = true) = 0;
virtual void resume() = 0;
bool add_frame(std::vector<u8>& frame, u32 pitch, u32 width, u32 height, s32 pixel_format, usz timestamp_ms)
{
// Do not allow new frames while flushing or paused
if (m_flush || m_paused)
return false;
std::lock_guard lock(m_video_mtx);
m_frames_to_encode.emplace_back(timestamp_ms, pitch, width, height, pixel_format, std::move(frame));
return true;
}
bool add_audio_samples(const u8* buf, u32 sample_count, u16 channels, usz timestamp_us)
{
// Do not allow new samples while flushing or paused
if (m_flush || m_paused || !buf || !sample_count || !channels)
return false;
std::vector<u8> sample(buf, buf + sample_count * channels * sizeof(f32));
std::lock_guard lock(m_audio_mtx);
m_samples_to_encode.emplace_back(timestamp_us, sample_count, channels, std::move(sample));
return true;
}
s64 get_pts(usz timestamp_ms) const
{
return static_cast<s64>(std::round((timestamp_ms * m_framerate) / 1000.0));
}
s64 get_audio_pts(usz timestamp_us) const
{
static constexpr f64 us_per_sec = 1000000.0;
const f64 us_per_block = us_per_sec / (m_sample_rate / static_cast<f64>(m_samples_per_block));
return static_cast<s64>(std::round(timestamp_us / us_per_block));
}
usz get_timestamp_ms(s64 pts) const
{
return static_cast<usz>(std::round((pts * 1000) / static_cast<f64>(m_framerate)));
}
usz get_audio_timestamp_us(s64 pts) const
{
static constexpr f64 us_per_sec = 1000000.0;
const f64 us_per_block = us_per_sec / (m_sample_rate / static_cast<f64>(m_samples_per_block));
return static_cast<usz>(pts * us_per_block);
}
atomic_t<bool> has_error{false};
struct encoder_frame
{
encoder_frame() = default;
encoder_frame(usz timestamp_ms, u32 pitch, u32 width, u32 height, s32 av_pixel_format, std::vector<u8>&& data)
: timestamp_ms(timestamp_ms), pitch(pitch), width(width), height(height), av_pixel_format(av_pixel_format), data(std::move(data))
{}
s64 pts = -1; // Optional
usz timestamp_ms = 0;
u32 pitch = 0;
u32 width = 0;
u32 height = 0;
s32 av_pixel_format = 0; // NOTE: Make sure this is a valid AVPixelFormat
std::vector<u8> data;
};
struct encoder_sample
{
encoder_sample() = default;
encoder_sample(usz timestamp_us, u32 sample_count, u16 channels, std::vector<u8>&& data)
: timestamp_us(timestamp_us), sample_count(sample_count), channels(channels), data(std::move(data))
{
}
usz timestamp_us = 0;
u32 sample_count = 0;
u16 channels = 0;
std::vector<u8> data;
};
// These two variables should only be set once before we start encoding, so we don't need mutexes or atomics.
bool use_internal_audio = false; // True if we want to fetch samples from cellAudio
bool use_internal_video = false; // True if we want to fetch frames from rsx
protected:
shared_mutex m_video_mtx;
std::deque<encoder_frame> m_frames_to_encode;
shared_mutex m_audio_mtx;
std::deque<encoder_sample> m_samples_to_encode;
atomic_t<bool> m_paused = false;
atomic_t<bool> m_flush = false;
u32 m_framerate = 30;
u32 m_sample_rate = 48000;
static constexpr u32 m_samples_per_block = 256;
};
}
| 3,535
|
C++
|
.h
| 97
| 33.020619
| 133
| 0.694355
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,648
|
serialization.hpp
|
RPCS3_rpcs3/rpcs3/util/serialization.hpp
|
#pragma once
#include "util/types.hpp"
#include <vector>
namespace utils
{
template <typename T>
concept FastRandomAccess = requires (T& obj)
{
std::data(obj)[std::size(obj)];
};
template <typename T>
concept Reservable = requires (T& obj)
{
obj.reserve(std::size(obj));
};
template <typename T>
concept Bitcopy = (std::is_arithmetic_v<T>) || (std::is_enum_v<T>) || Integral<T> || requires ()
{
std::enable_if_t<std::conjunction_v<typename T::enable_bitcopy>>();
};
template <typename T>
concept TupleAlike = requires ()
{
std::tuple_size<std::remove_cv_t<T>>::value;
};
template <typename T>
concept ListAlike = requires (T& obj) { obj.insert(obj.end(), std::declval<typename T::value_type>()); };
struct serial;
struct serialization_file_handler
{
serialization_file_handler() = default;
virtual ~serialization_file_handler() = default;
// Handle read/write operations
virtual bool handle_file_op(serial& ar, usz pos, usz size, const void* data = nullptr) = 0;
// Obtain data size (targets to be only higher than 'recommended' and thus may not be accurate)
virtual usz get_size(const utils::serial& /*ar*/, usz /*recommended*/) const
{
return 0;
}
// Skip reading some (compressed) data
virtual void skip_until(utils::serial& /*ar*/)
{
}
// Detect empty stream (TODO: Clean this, instead perhaps use a magic static representing empty stream)
virtual bool is_null() const
{
return false;
}
virtual void finalize_block(utils::serial& /*ar*/)
{
}
virtual bool is_valid() const
{
return true;
}
virtual void finalize(utils::serial&) = 0;
};
struct serial
{
private:
bool m_is_writing = true;
bool m_expect_little_data = false;
public:
std::vector<u8> data;
usz data_offset = 0;
usz pos = 0;
usz m_max_data = umax;
std::unique_ptr<serialization_file_handler> m_file_handler;
serial() noexcept = default;
serial(const serial&) = delete;
serial& operator=(const serial&) = delete;
explicit serial(serial&&) noexcept = default;
serial& operator=(serial&&) noexcept = default;
~serial() noexcept = default;
// Checks if this instance is currently used for serialization
bool is_writing() const
{
return m_is_writing;
}
void set_expect_little_data(bool value)
{
m_expect_little_data = value;
}
// Return true if small amounts of both input and output memory are expected (performance hint)
bool expect_little_data() const
{
return m_expect_little_data;
}
// Reserve memory for serialization
void reserve(usz size)
{
data.reserve(data.size() + size);
}
template <typename Func> requires (std::is_convertible_v<std::invoke_result_t<Func>, const void*>)
bool raw_serialize(Func&& memory_provider, usz size)
{
if (!size)
{
return true;
}
if (m_file_handler && m_file_handler->is_null())
{
// Instead of doing nothing at all, increase pos so it would be possible to estimate memory requirements
pos += size;
return true;
}
// Overflow check
ensure(~pos >= size - 1);
if (is_writing())
{
ensure(pos <= data_offset + data.size());
const auto ptr = reinterpret_cast<const u8*>(memory_provider());
if (pos != data_offset + data.size())
{
data.insert(data.begin() + pos - data_offset, ptr, ptr + size);
pos += size;
return true;
}
// Seems to be much faster than data.begin() + pos on MSVC
data.insert(data.end(), ptr, ptr + size);
pos += size;
return true;
}
if (data.empty() || pos < data_offset || pos + (size - 1) > (data.size() - 1) + data_offset)
{
// Load from file
ensure(m_file_handler);
ensure(m_file_handler->handle_file_op(*this, pos, size, nullptr));
ensure(!data.empty() && pos >= data_offset && pos + (size - 1) <= (data.size() - 1) + data_offset);
}
std::memcpy(const_cast<void*>(static_cast<const void*>(memory_provider())), data.data() + (pos - data_offset), size);
pos += size;
return true;
}
bool raw_serialize(const void* ptr, usz size)
{
return raw_serialize(FN(ptr), size);
}
template <typename T> requires Integral<T>
bool serialize_vle(T&& value)
{
for (auto i = value;;)
{
const auto i_old = std::exchange(i, i >> 7);
const u8 to_write = static_cast<u8>((static_cast<u8>(i_old) % 0x80) | (i ? 0x80 : 0));
raw_serialize(&to_write, 1);
if (!i)
{
break;
}
}
return true;
}
template <typename T> requires Integral<T>
bool deserialize_vle(T& value)
{
value = {};
for (u32 i = 0;; i += 7)
{
u8 byte_data = 0;
if (!raw_serialize(&byte_data, 1))
{
return false;
}
value |= static_cast<T>(byte_data % 0x80) << i;
if (!(byte_data & 0x80))
{
break;
}
}
return true;
}
// (De)serialization function
template <typename T>
bool serialize(T& obj)
{
// Fallback to global overload
return ::serialize(*this, obj);
}
// Enabled for fundamental types, enumerations and if specified explicitly that type can be saved in pure bitwise manner
template <typename T> requires Bitcopy<T>
bool serialize(T& obj)
{
return raw_serialize(std::addressof(obj), sizeof(obj));
}
// std::vector, std::basic_string
// Discourage using std::pair/tuple with vectors because it eliminates the possibility of bitwise optimization
template <typename T> requires FastRandomAccess<T> && ListAlike<T> && (!TupleAlike<typename T::value_type>)
bool serialize(T& obj)
{
if (is_writing())
{
serialize_vle(obj.size());
if constexpr (Bitcopy<typename std::remove_reference_t<T>::value_type>)
{
raw_serialize(obj.data(), sizeof(obj[0]) * obj.size());
}
else
{
for (auto&& value : obj)
{
if (!serialize(value))
{
return false;
}
}
}
return true;
}
obj.clear();
if (m_file_handler && m_file_handler->is_null())
{
return true;
}
usz size = 0;
if (!deserialize_vle(size))
{
return false;
}
if constexpr (Bitcopy<typename T::value_type>)
{
if (!raw_serialize([&](){ obj.resize(size); return obj.data(); }, sizeof(obj[0]) * size))
{
obj.clear();
return false;
}
}
else
{
// TODO: Postpone resizing to after file bounds checks
obj.resize(size);
for (auto&& value : obj)
{
if (!serialize(value))
{
obj.clear();
return false;
}
}
}
return true;
}
// C-array, std::array, std::span (span must be supplied with size and address, this function does not modify it)
template <typename T> requires FastRandomAccess<T> && (!ListAlike<T>) && (!Bitcopy<T>)
bool serialize(T& obj)
{
if constexpr (Bitcopy<std::remove_reference_t<decltype(std::declval<T>()[0])>>)
{
return raw_serialize(std::data(obj), sizeof(obj[0]) * std::size(obj));
}
else
{
for (auto&& value : obj)
{
if (!serialize(value))
{
return false;
}
}
return true;
}
}
// std::deque, std::list, std::(unordered_)set, std::(unordered_)map, std::(unordered_)multiset, std::(unordered_)multimap
template <typename T> requires (!FastRandomAccess<T>) && ListAlike<T>
bool serialize(T& obj)
{
if (is_writing())
{
serialize_vle(obj.size());
for (auto&& value : obj)
{
if (!serialize(value))
{
return false;
}
}
return true;
}
obj.clear();
if (m_file_handler && m_file_handler->is_null())
{
return true;
}
usz size = 0;
if (!deserialize_vle(size))
{
return false;
}
if constexpr (Reservable<T>)
{
obj.reserve(size);
}
for (usz i = 0; i < size; i++)
{
obj.insert(obj.end(), static_cast<typename T::value_type>(*this));
if (!is_valid())
{
obj.clear();
return false;
}
}
return true;
}
template <typename T> requires requires (T& obj) { (obj.*(&T::operator()))(std::declval<stx::exact_t<utils::serial&>>()); }
bool serialize(T& obj)
{
obj(*this);
return is_valid();
}
template <usz i = 0, typename T>
bool serialize_tuple(T& obj)
{
const bool res = serialize(std::get<i>(obj));
constexpr usz next_i = std::min<usz>(i + 1, std::tuple_size_v<T> - 1);
if constexpr (next_i == i)
{
return res;
}
else
{
return res && serialize_tuple<next_i>(obj);
}
}
// std::pair, std::tuple
template <typename T> requires TupleAlike<T> && (!FastRandomAccess<T>)
bool serialize(T& obj)
{
return serialize_tuple(obj);
}
// Wrapper for serialize(T&), allows to pass multiple objects at once
template <typename... Args> requires (sizeof...(Args) != 0)
bool operator()(Args&&... args) noexcept
{
return ((AUDIT(!std::is_const_v<std::remove_reference_t<Args>> || is_writing())
, serialize(const_cast<std::remove_cvref_t<Args>&>(static_cast<const Args&>(args)))), ...);
}
// Code style utility, for when utils::serial is a pointer for example
template <typename... Args> requires (sizeof...(Args) > 1 || !(std::is_convertible_v<Args&&, Args&> && ...))
bool serialize(Args&&... args)
{
return this->operator()(std::forward<Args>(args)...);
}
// Convert serialization manager to deserializion manager
// If no arg is provided reuse saved buffer
void set_reading_state(std::vector<u8>&& _data = std::vector<u8>{}, bool expect_little_data = false)
{
if (!_data.empty())
{
data = std::move(_data);
}
m_is_writing = false;
m_expect_little_data = expect_little_data;
m_max_data = umax;
pos = 0;
data_offset = 0;
}
// Reset to empty serialization manager
void clear()
{
data.clear();
m_is_writing = true;
pos = 0;
data_offset = 0;
m_file_handler.reset();
}
usz seek_end(usz backwards = 0)
{
ensure(data.size() + data_offset >= backwards);
pos = data.size() + data_offset - backwards;
return pos;
}
usz seek_pos(usz val, bool cleanup = false)
{
const usz old_pos = std::exchange(pos, val);
if (cleanup || data.empty())
{
// Relocate future data
if (m_file_handler)
{
m_file_handler->skip_until(*this);
}
breathe();
}
return old_pos;
}
usz pad_from_end(usz forwards)
{
ensure(is_writing());
pos = data.size() + data_offset;
data.resize(data.size() + forwards);
return pos;
}
// Allow for memory saving operations: if writing, flush to file if too large. If reading, discard memory (not implemented).
// Execute only if past memory is known to not going be reused
void breathe(bool forced = false)
{
if (!forced && (!m_file_handler || (data.size() < 0x100'0000 && pos >= data_offset)))
{
// Let's not do anything if less than 16MB
return;
}
ensure(m_file_handler);
ensure(m_file_handler->handle_file_op(*this, 0, umax, nullptr));
}
template <typename T> requires (std::is_copy_constructible_v<std::remove_const_t<T>>) && (std::is_constructible_v<std::remove_const_t<T>> || Bitcopy<std::remove_const_t<T>> ||
std::is_constructible_v<std::remove_const_t<T>, stx::exact_t<serial&>> || TupleAlike<std::remove_const_t<T>>)
operator T() noexcept
{
AUDIT(!is_writing());
using type = std::remove_const_t<T>;
if constexpr (Bitcopy<T>)
{
u8 buf[sizeof(type)]{};
ensure(raw_serialize(buf, sizeof(buf)));
return std::bit_cast<type>(buf);
}
else if constexpr (std::is_constructible_v<type, stx::exact_t<serial&>>)
{
return type(stx::exact_t<serial&>(*this));
}
else if constexpr (std::is_constructible_v<type>)
{
type value{};
ensure(serialize(value));
return value;
}
else if constexpr (TupleAlike<T>)
{
static_assert(std::tuple_size_v<type> == 2, "Unimplemented tuple serialization!");
auto first = operator std::remove_cvref_t<decltype(std::get<0>(std::declval<type&>()))>();
return type{ std::move(first)
, operator std::remove_cvref_t<decltype(std::get<1>(std::declval<type&>()))> };
}
}
// Code style utility wrapper for operator T()
template <typename T>
T pop()
{
return this->operator T();
}
void swap_handler(serial& ar)
{
std::swap(ar.m_file_handler, this->m_file_handler);
}
usz get_size(usz recommended = umax) const
{
recommended = std::min<usz>(recommended, m_max_data);
return std::min<usz>(m_max_data, m_file_handler ? m_file_handler->get_size(*this, recommended) : (data.empty() ? 0 : data_offset + data.size()));
}
template <typename T> requires (Bitcopy<T>)
usz predict_object_size(const T&)
{
return sizeof(T);
}
template <typename T> requires FastRandomAccess<T> && (!ListAlike<T>) && (!Bitcopy<T>)
usz predict_object_size(const T& obj)
{
return std::size(obj) * sizeof(obj[0]);
}
template <typename T> requires (std::is_copy_constructible_v<std::remove_reference_t<T>> && std::is_constructible_v<std::remove_reference_t<T>>)
usz try_read(T&& obj)
{
if (is_writing())
{
return 0;
}
const usz end_pos = pos + predict_object_size(std::forward<T>(obj));
const usz size = get_size(end_pos);
if (size >= end_pos)
{
serialize(std::forward<T>(obj));
return 0;
}
return end_pos - size;
}
template <typename T> requires (std::is_copy_constructible_v<T> && std::is_constructible_v<T> && Bitcopy<T>)
std::pair<bool, T> try_read()
{
if (is_writing())
{
return {};
}
const usz end_pos = pos + sizeof(T);
const usz size = get_size(end_pos);
using type = std::remove_const_t<T>;
if (size >= end_pos)
{
return {true, this->operator type()};
}
return {};
}
void patch_raw_data(usz pos, const void* data, usz size)
{
if (m_file_handler && m_file_handler->is_null())
{
return;
}
if (!size)
{
return;
}
std::memcpy(&::at32(this->data, pos - data_offset + size - 1) - (size - 1), data, size);
}
// Returns true if valid, can be invalidated by setting pos to umax
// Used when an invalid state is encountered somewhere in a place we can't check success code such as constructor)
bool is_valid() const
{
// TODO
return true;
}
};
}
| 14,225
|
C++
|
.h
| 512
| 23.75
| 177
| 0.635616
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
5,649
|
typeindices.hpp
|
RPCS3_rpcs3/rpcs3/util/typeindices.hpp
|
#pragma once
#include "util/types.hpp"
#include "util/shared_ptr.hpp"
#include <string_view>
#ifndef _MSC_VER
#define ATTR_PURE __attribute__((pure))
#else
#define ATTR_PURE /* nothing available */
#endif
namespace stx
{
template <typename Info>
class type_counter;
// Type information for given Info type, also serving as tag
template <typename Info>
class type_info final : public Info
{
// Current type id (starts from 0)
u32 type = umax;
u32 size = 1;
u32 align = 1;
u32 begin = 0;
double order{};
// Next typeinfo in linked list
type_info* next = nullptr;
// Auxiliary pointer to base type
const type_info* base = nullptr;
type_info(Info info, u32 size, u32 align, double order, const type_info* base = nullptr) noexcept;
friend type_counter<Info>;
public:
constexpr type_info() noexcept
: Info()
{
}
ATTR_PURE u32 index() const
{
return type;
}
ATTR_PURE u32 pos() const
{
return begin;
}
ATTR_PURE u32 end() const
{
return begin + size;
}
ATTR_PURE double init_pos() const
{
return order;
}
};
// Class for automatic type registration for given Info type
template <typename Info>
class type_counter final
{
// Dummy first element to simplify list filling logic
type_info<Info> first{};
// Linked list built at global initialization time
type_info<Info>* next = &first;
friend type_info<Info>;
public:
constexpr type_counter() noexcept = default;
u32 count() const
{
return next->index() + 1;
}
u32 align() const
{
return first.align;
}
u32 size() const
{
// Get on first use
static const u32 sz = [&]()
{
u32 result = 0;
for (auto* ptr = first.next; ptr; ptr = ptr->next)
{
result = ((result + ptr->align - 1) & (u32{0} - ptr->align));
ptr->begin = result;
result = result + ptr->size;
}
return result;
}();
return sz;
}
class const_iterator
{
const type_info<Info>* ptr;
public:
const_iterator(const type_info<Info>* ptr)
: ptr(ptr)
{
}
const type_info<Info>& operator*() const
{
return *ptr;
}
const type_info<Info>* operator->() const
{
return ptr;
}
const_iterator& operator++()
{
ptr = ptr->next;
return *this;
}
const_iterator operator++(int)
{
const_iterator r = ptr;
ptr = ptr->next;
return r;
}
bool operator==(const const_iterator& r) const
{
return ptr == r.ptr;
}
};
const_iterator begin() const
{
return first.next;
}
const_iterator end() const
{
return nullptr;
}
// Global type info instance
template <typename T>
static const type_info<Info> type;
// Helper for dynamic types
template <typename T, typename As>
static const type_info<Info> dyn_type;
};
// Global typecounter instance
template <typename Info>
auto& typelist()
{
static type_counter<Info> typelist_v;
return typelist_v;
}
// Helper for dynamic types
template <typename Info>
auto& dyn_typelist()
{
static type_counter<Info> typelist_v;
return typelist_v;
}
template <typename T> requires requires () { T::savestate_init_pos + 0.; }
constexpr double get_savestate_init_pos()
{
return T::savestate_init_pos;
}
template <typename T> requires (!(requires () { T::savestate_init_pos + 0.; }))
constexpr double get_savestate_init_pos()
{
return {};
}
template <typename Info> template <typename T>
const type_info<Info> type_counter<Info>::type{Info::template make_typeinfo<T>(), sizeof(T), alignof(T), get_savestate_init_pos<T>()};
template <typename Info> template <typename T, typename As>
const type_info<Info> type_counter<Info>::dyn_type{Info::template make_typeinfo<As>(), sizeof(As), alignof(As), get_savestate_init_pos<T>(), &type_counter<Info>::template type<T>};
template <typename Info>
type_info<Info>::type_info(Info info, u32 _size, u32 _align, double order, const type_info<Info>* cbase) noexcept
: Info(info)
{
auto& tl = typelist<Info>();
// Update type info
this->size = _size > this->size ? _size : this->size;
this->align = _align > this->align ? _align : this->align;
this->base = cbase;
this->order = order;
// Update global max alignment
tl.first.align = _align > tl.first.align ? _align : tl.first.align;
auto& dl = dyn_typelist<Info>();
if (cbase)
{
dl.next->next = this;
dl.next = this;
// Update base max size/align for dynamic types
for (auto ptr = tl.first.next; ptr; ptr = ptr->next)
{
if (cbase == ptr)
{
ptr->size = _size > ptr->size ? _size : ptr->size;
ptr->align = _align > ptr->align ? _align : ptr->align;
this->type = ptr->type;
}
}
return;
}
// Update type index
this->type = tl.next->type + 1;
// Update base max size/align for dynamic types
for (auto ptr = dl.first.next; ptr; ptr = ptr->next)
{
if (ptr->base == this)
{
this->size = ptr->size > this->size ? ptr->size : this->size;
this->align = ptr->align > this->align ? ptr->align : this->align;
ptr->type = this->type;
}
}
// Update linked list
tl.next->next = this;
tl.next = this;
}
// Type index accessor
template <typename Info, typename T, typename As = T>
ATTR_PURE inline u32 typeindex() noexcept
{
static_assert(sizeof(T) > 0);
if constexpr (std::is_same_v<T, As>)
{
return type_counter<Info>::template type<T>.index();
}
else
{
static_assert(sizeof(As) > 0);
static_assert(PtrSame<T, As>);
return type_counter<Info>::template dyn_type<T, As>.index();
}
}
// Type global offset
template <typename Info, typename T>
ATTR_PURE inline u32 typeoffset() noexcept
{
static_assert(sizeof(T) > 0);
return type_counter<Info>::template type<T>.pos();
}
// Type info accessor
template <typename Info, typename T, typename As = T>
ATTR_PURE inline const Info& typedata() noexcept
{
static_assert(sizeof(T) > 0 && sizeof(As) > 0);
static_assert(PtrSame<T, As>); // TODO
return type_counter<Info>::template dyn_type<T, As>;
}
}
#undef ATTR_PURE
| 6,091
|
C++
|
.h
| 239
| 22.138075
| 181
| 0.662351
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
5,650
|
vm.hpp
|
RPCS3_rpcs3/rpcs3/util/vm.hpp
|
#pragma once
#include "util/types.hpp"
#include "util/atomic.hpp"
#include <string>
namespace utils
{
#ifdef _WIN32
using native_handle = void*;
#else
using native_handle = int;
#endif
// Obtain system page size
long get_page_size();
// System page size
inline const long c_page_size = get_page_size();
// Memory protection type
enum class protection
{
rw, // Read + write (default)
ro, // Read only
no, // No access
wx, // Read + write + execute
rx, // Read + execute
};
/**
* Reserve `size` bytes of virtual memory and returns it.
* The memory should be committed before usage.
*/
void* memory_reserve(usz size, void* use_addr = nullptr, bool is_memory_mapping = false);
/**
* Commit `size` bytes of virtual memory starting at pointer.
* That is, bake reserved memory with physical memory.
* pointer should belong to a range of reserved memory.
*/
void memory_commit(void* pointer, usz size, protection prot = protection::rw);
// Decommit all memory committed via commit_page_memory.
void memory_decommit(void* pointer, usz size);
// Decommit all memory and commit it again.
void memory_reset(void* pointer, usz size, protection prot = protection::rw);
// Free memory after reserved by memory_reserve, should specify original size
void memory_release(void* pointer, usz size);
// Set memory protection
void memory_protect(void* pointer, usz size, protection prot);
// Lock pages in memory
bool memory_lock(void* pointer, usz size);
// Map file descriptor
void* memory_map_fd(native_handle fd, usz size, protection prot);
// Shared memory handle
class shm
{
#ifdef _WIN32
void* m_handle{};
#else
int m_file{};
#endif
u32 m_flags{};
u64 m_size{};
atomic_t<void*> m_ptr{nullptr};
std::string m_storage;
public:
explicit shm(u64 size, u32 flags = 0);
// Construct with specified path as sparse file storage
shm(u64 size, const std::string& storage);
shm(const shm&) = delete;
shm& operator=(const shm&) = delete;
~shm();
// Map shared memory
u8* map(void* ptr, protection prot = protection::rw, bool cow = false) const;
// Attempt to map shared memory fix fixed pointer
u8* try_map(void* ptr, protection prot = protection::rw, bool cow = false) const;
// Map shared memory over reserved memory region, which is unsafe (non-atomic) under Win32
std::pair<u8*, std::string> map_critical(void* ptr, protection prot = protection::rw, bool cow = false);
// Map shared memory into its own storage (not mapped by default)
u8* map_self(protection prot = protection::rw);
// Unmap shared memory
void unmap(void* ptr) const;
// Unmap shared memory, undoing map_critical
void unmap_critical(void* ptr);
// Unmap shared memory, undoing map_self()
void unmap_self();
// Get memory mapped by map_self()
u8* get() const
{
return static_cast<u8*>(+m_ptr);
}
u64 size() const
{
return m_size;
}
// Flags are unspecified, consider it userdata
u32 flags() const
{
return m_flags;
}
// Another userdata
u64 info = 0;
};
}
| 3,065
|
C++
|
.h
| 98
| 28.581633
| 106
| 0.714237
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
5,651
|
console.h
|
RPCS3_rpcs3/rpcs3/util/console.h
|
#pragma once
#include <string_view>
namespace utils
{
enum console_stream
{
std_out = 0x01,
std_err = 0x02,
std_in = 0x04,
};
void attach_console(int stream, bool open_console);
void output_stderr(std::string_view str, bool with_endline = false);
}
| 265
|
C++
|
.h
| 13
| 18.230769
| 69
| 0.725806
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,652
|
fixed_typemap.hpp
|
RPCS3_rpcs3/rpcs3/util/fixed_typemap.hpp
|
#pragma once
// Backported from auto_typemap.hpp as a more simple alternative
#include "util/types.hpp"
#include "util/typeindices.hpp"
#include <utility>
#include <type_traits>
#include <algorithm>
enum class thread_state : u32;
extern thread_local std::string_view g_tls_serialize_name;
namespace utils
{
struct serial;
}
namespace stx
{
struct launch_retainer{};
extern u16 serial_breathe_and_tag(utils::serial& ar, std::string_view name, bool tag_bit);
// Simplified typemap with exactly one object of each used type, non-moveable. Initialized on init(). Destroyed on clear().
template <typename Tag /*Tag should be unique*/, u32 Size = 0, u32 Align = (Size ? 64 : __STDCPP_DEFAULT_NEW_ALIGNMENT__)>
class alignas(Align) manual_typemap
{
static constexpr std::string_view parse_type(std::string_view pretty_name)
{
#ifdef _MSC_VER
const auto pos = pretty_name.find("::typeinfo::make_typeinfo<");
const auto end = pretty_name.rfind(">(void)");
return pretty_name.substr(pos + 26, end - pos - 26);
#else
const auto pos = pretty_name.find("T = ");
if (pos + 1)
{
pretty_name.remove_prefix(pos + 4);
auto end = pretty_name.find("; Tag =");
if (end + 1)
{
return pretty_name.substr(0, end);
}
end = pretty_name.find(", Tag =");
if (end + 1)
{
return pretty_name.substr(0, end);
}
if (!pretty_name.empty() && pretty_name.back() == ']')
{
pretty_name.remove_suffix(1);
}
return pretty_name;
}
return {};
#endif
}
// Save default constructor and destructor and optional joining operation
struct typeinfo
{
bool(*create)(uchar* ptr, manual_typemap&, utils::serial*, std::string_view) noexcept = nullptr;
void(*thread_op)(void* ptr, thread_state) noexcept = nullptr;
void(*save)(void* ptr, utils::serial&) noexcept = nullptr;
bool(*saveable)(bool) noexcept = nullptr;
void(*destroy)(void* ptr) noexcept = nullptr;
bool is_trivial_and_nonsavable = false;
std::string_view name;
template <typename T>
static bool call_ctor(uchar* ptr, manual_typemap& _this, utils::serial* ar, std::string_view name) noexcept
{
if (ar)
{
if constexpr (std::is_constructible_v<T, exact_t<manual_typemap&>, exact_t<utils::serial&>>)
{
g_tls_serialize_name = name;
new (ptr) T(exact_t<manual_typemap&>(_this), exact_t<utils::serial&>(*ar));
return true;
}
if constexpr (std::is_constructible_v<T, exact_t<const launch_retainer&>, exact_t<utils::serial&>>)
{
g_tls_serialize_name = name;
new (ptr) T(exact_t<const launch_retainer&>(launch_retainer{}), exact_t<utils::serial&>(*ar));
return true;
}
if constexpr (std::is_constructible_v<T, exact_t<utils::serial&>>)
{
g_tls_serialize_name = name;
new (ptr) T(exact_t<utils::serial&>(*ar));
return true;
}
}
// Allow passing reference to "this"
if constexpr (std::is_constructible_v<T, exact_t<manual_typemap&>>)
{
new (ptr) T(exact_t<manual_typemap&>(_this));
return true;
}
if constexpr (std::is_constructible_v<T, exact_t<const launch_retainer&>>)
{
new (ptr) T(exact_t<const launch_retainer&>(launch_retainer{}));
return true;
}
// Call default constructor only if available
if constexpr (std::is_default_constructible_v<T>)
{
new (ptr) T();
return true;
}
return false;
}
template <typename T>
static void call_dtor(void* ptr) noexcept
{
auto* obj = std::launder(static_cast<T*>(ptr));
obj->~T();
std::memset(ptr, 0xCC, sizeof(T)); // Set to trap values
}
template <typename T>
static void call_thread_op(void* ptr, thread_state state) noexcept
{
// Abort and/or join (expected thread_state::aborting or thread_state::finished)
*std::launder(static_cast<T*>(ptr)) = state;
}
template <typename T> requires requires (T& a) { a.save(std::declval<stx::exact_t<utils::serial&>>()); }
static void call_save(void* ptr, utils::serial& ar) noexcept
{
std::launder(static_cast<T*>(ptr))->save(stx::exact_t<utils::serial&>(ar));
}
template <typename T> requires requires (const T&) { T::saveable(true); }
static bool call_saveable(bool is_writing) noexcept
{
return T::saveable(is_writing);
}
template <typename T>
static typeinfo make_typeinfo()
{
static_assert(!std::is_copy_assignable_v<T> && !std::is_copy_constructible_v<T>, "Please make sure the object cannot be accidentally copied.");
typeinfo r{};
r.create = &call_ctor<T>;
r.destroy = &call_dtor<T>;
if constexpr (std::is_assignable_v<T&, thread_state>)
{
r.thread_op = &call_thread_op<T>;
}
if constexpr (!!(requires (T& a) { a.save(std::declval<stx::exact_t<utils::serial&>>()); }))
{
r.save = &call_save<T>;
}
if constexpr (!!(requires (const T&) { T::saveable(true); }))
{
r.saveable = &call_saveable<T>;
}
r.is_trivial_and_nonsavable = std::is_trivially_default_constructible_v<T> && !r.save;
#ifdef _MSC_VER
constexpr std::string_view name = parse_type(__FUNCSIG__);
#else
constexpr std::string_view name = parse_type(__PRETTY_FUNCTION__);
#endif
r.name = name;
return r;
}
};
// Objects
union
{
uchar* m_list = nullptr;
mutable uchar m_data[Size ? Size : 1];
};
// Indicates whether object is created at given index
std::array<bool, (Size ? Size / Align : 65536)> m_init{};
// Creation order for each object (used to reverse destruction order)
void** m_order = nullptr;
// Helper for destroying in reverse order
const typeinfo** m_info = nullptr;
public:
manual_typemap() noexcept = default;
manual_typemap(const manual_typemap&) = delete;
manual_typemap& operator=(const manual_typemap&) = delete;
~manual_typemap()
{
ensure(!m_info);
}
void reset()
{
if (is_init())
{
clear();
}
m_order = new void*[stx::typelist<typeinfo>().count() + 1];
m_info = new const typeinfo*[stx::typelist<typeinfo>().count() + 1];
ensure(m_init.size() > stx::typelist<typeinfo>().count());
if constexpr (Size == 0)
{
if (stx::typelist<typeinfo>().align() > __STDCPP_DEFAULT_NEW_ALIGNMENT__)
{
m_list = static_cast<uchar*>(::operator new(usz{stx::typelist<typeinfo>().size()}, std::align_val_t{stx::typelist<typeinfo>().align()}));
}
else
{
m_list = new uchar[stx::typelist<typeinfo>().size()];
}
}
else
{
ensure(Size >= stx::typelist<typeinfo>().size());
ensure(Align >= stx::typelist<typeinfo>().align());
}
// Set to trap values
std::memset(Size == 0 ? m_list : m_data, 0xCC, stx::typelist<typeinfo>().size());
*m_order++ = nullptr;
*m_info++ = nullptr;
}
void init(bool reset = true, utils::serial* ar = nullptr, std::function<void()> func = {})
{
if (reset)
{
this->reset();
}
// Use unique_ptr to reduce header dependencies in this commonly used header
const usz type_count = stx::typelist<typeinfo>().count();
const auto order = std::make_unique<std::pair<double, const type_info<typeinfo>*>[]>(type_count);
usz pos = 0;
for (const auto& type : stx::typelist<typeinfo>())
{
order[pos++] = {type.init_pos(), std::addressof(type)};
}
std::stable_sort(order.get(), order.get() + type_count, [](auto& a, auto& b)
{
if (a.second->is_trivial_and_nonsavable && !b.second->is_trivial_and_nonsavable)
{
return true;
}
return a.first < b.first;
});
const auto info_before = m_info;
for (pos = 0; pos < type_count; pos++)
{
const auto& type = *order[pos].second;
const u32 id = type.index();
uchar* data = (Size ? +m_data : m_list) + type.pos();
// Allocate initialization order id
if (m_init[id])
{
continue;
}
const bool saveable = !type.saveable || type.saveable(false);
if (type.create(data, *this, saveable ? ar : nullptr, type.name))
{
*m_order++ = data;
*m_info++ = &type;
m_init[id] = true;
if (ar && saveable && type.save)
{
serial_breathe_and_tag(*ar, type.name, false);
}
}
}
if (func)
{
func();
}
// Launch threads
for (auto it = m_info; it != info_before; it--)
{
if (auto op = (*std::prev(it))->thread_op)
{
op(*std::prev(m_order, m_info - it + 1), thread_state{});
}
}
g_tls_serialize_name = {};
}
void clear()
{
if (!is_init())
{
return;
}
// Get actual number of created objects
u32 _max = 0;
for (const auto& type : stx::typelist<typeinfo>())
{
if (m_init[type.index()])
{
// Skip object if not created
_max++;
}
}
// Destroy objects in reverse order
for (; _max; _max--)
{
auto* info = *--m_info;
const u32 type_index = static_cast<const type_info<typeinfo>*>(info)->index();
info->destroy(*--m_order);
// Set init to false. We don't want other fxo to use this fxo in their destructor.
m_init[type_index] = false;
}
// Pointers should be restored to their positions
m_info--;
m_order--;
delete[] m_info;
delete[] m_order;
if constexpr (Size == 0)
{
if (stx::typelist<typeinfo>().align() > __STDCPP_DEFAULT_NEW_ALIGNMENT__)
{
::operator delete[](m_list, std::align_val_t{stx::typelist<typeinfo>().align()});
}
else
{
delete[] m_list;
}
}
m_init.fill(false);
m_info = nullptr;
m_order = nullptr;
if constexpr (Size == 0)
{
m_list = nullptr;
}
}
template <typename T> requires (std::is_same_v<T&, utils::serial&>)
void save(T& ar)
{
if (!is_init())
{
return;
}
// Get actual number of created objects
u32 _max = 0;
for (const auto& type : stx::typelist<typeinfo>())
{
if (m_init[type.index()])
{
// Skip object if not created
_max++;
}
}
// Save data in forward order
for (u32 i = _max; i; i--)
{
const auto info = (*std::prev(m_info, i));
if (auto save = info->save)
{
save(*std::prev(m_order, i), ar);
serial_breathe_and_tag(ar, info->name, false);
}
}
}
// Check if object is not initialized but shall be initialized first (to use in initializing other objects)
template <typename T> requires (!std::is_constructible_v<T, exact_t<utils::serial&>> && (std::is_constructible_v<T, exact_t<manual_typemap&>> || std::is_default_constructible_v<T>))
void need() noexcept
{
if (!m_init[stx::typeindex<typeinfo, std::decay_t<T>>()])
{
if constexpr (std::is_constructible_v<T, exact_t<manual_typemap&>>)
{
init<T>(exact_t<manual_typemap&>(*this));
return;
}
if constexpr (std::is_default_constructible_v<T>)
{
init<T>();
return;
}
}
}
// Explicitly initialize object of type T possibly with dynamic type As and arguments
template <typename T, typename As = T, typename... Args> requires (std::is_constructible_v<std::decay_t<As>, Args&&...>)
As* init(Args&&... args) noexcept
{
if (m_init[stx::typeindex<typeinfo, std::decay_t<T>, std::decay_t<As>>()])
{
// Already exists, recreation is not supported (may be added later)
return nullptr;
}
m_init[stx::typeindex<typeinfo, std::decay_t<T>, std::decay_t<As>>()] = true;
As* obj = nullptr;
const auto type_info = &stx::typedata<typeinfo, std::decay_t<T>, std::decay_t<As>>();
g_tls_serialize_name = get_name<T, As>();
if constexpr (Size != 0)
{
obj = new (m_data + stx::typeoffset<typeinfo, std::decay_t<T>>()) std::decay_t<As>(std::forward<Args>(args)...);
}
else
{
obj = new (m_list + stx::typeoffset<typeinfo, std::decay_t<T>>()) std::decay_t<As>(std::forward<Args>(args)...);
}
if constexpr ((std::is_same_v<std::remove_cvref_t<Args>, utils::serial> || ...))
{
ensure(type_info->save);
serial_breathe_and_tag(std::get<0>(std::tie(args...)), get_name<T, As>(), false);
}
if constexpr ((std::is_same_v<std::remove_cvref_t<Args>, utils::serial*> || ...))
{
ensure(type_info->save);
utils::serial* ar = std::get<0>(std::tie(args...));
if (ar)
{
serial_breathe_and_tag(*ar, get_name<T, As>(), false);
}
}
g_tls_serialize_name = {};
*m_order++ = obj;
*m_info++ = type_info;
return obj;
}
// CTAD adaptor for init (see init description), accepts template not type
template <template <class...> typename Template, typename... Args>
auto init(Args&&... args) noexcept
{
// Deduce the type from given template and its arguments
using T = decltype(Template(std::forward<Args>(args)...));
return init<T>(std::forward<Args>(args)...);
}
template <typename T>
bool is_init() const noexcept
{
return m_init[stx::typeindex<typeinfo, std::decay_t<T>>()];
}
bool is_init() const noexcept
{
return m_info != nullptr;
}
// Obtain object pointer (may be uninitialized memory)
template <typename T>
T& get() const noexcept
{
if constexpr (Size != 0)
{
return *std::launder(reinterpret_cast<T*>(m_data + stx::typeoffset<typeinfo, std::decay_t<T>>()));
}
else
{
return *std::launder(reinterpret_cast<T*>(m_list + stx::typeoffset<typeinfo, std::decay_t<T>>()));
}
}
template <typename T, typename As = T>
static std::string_view get_name() noexcept
{
return stx::typedata<typeinfo, std::decay_t<T>, std::decay_t<As>>().name;
}
// Obtain object pointer if initialized
template <typename T>
T* try_get() const noexcept
{
if (is_init<T>())
{
[[likely]] return std::addressof(get<T>());
}
[[unlikely]] return nullptr;
}
class iterator
{
const typeinfo** m_info;
void** m_ptr;
public:
iterator(const typeinfo** _info, void** _ptr)
: m_info(_info)
, m_ptr(_ptr)
{
}
std::pair<const typeinfo&, void*> operator*() const
{
return {*m_info[-1], m_ptr[-1]};
}
iterator& operator++()
{
m_info--;
m_ptr--;
if (!m_info[-1])
{
m_info = nullptr;
m_ptr = nullptr;
}
return *this;
}
bool operator!=(const iterator& rhs) const
{
return m_info != rhs.m_info || m_ptr != rhs.m_ptr;
}
};
iterator begin() noexcept
{
return iterator{m_info, m_order};
}
iterator end() noexcept
{
return iterator{nullptr, nullptr};
}
};
}
| 14,453
|
C++
|
.h
| 485
| 25.371134
| 183
| 0.62224
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,653
|
auto_typemap.hpp
|
RPCS3_rpcs3/rpcs3/util/auto_typemap.hpp
|
#pragma once
#include "util/types.hpp"
#include "util/typeindices.hpp"
#include <utility>
#include <type_traits>
namespace stx
{
// Simplified typemap with exactly one object of each used type, non-moveable.
template <typename Tag /*Tag should be unique*/, u32 Size = 0, u32 Align = (Size ? 64 : __STDCPP_DEFAULT_NEW_ALIGNMENT__)>
class alignas(Align) auto_typemap
{
// Save default constructor and destructor
struct typeinfo
{
bool(*create)(uchar* ptr, auto_typemap&) noexcept = nullptr;
void(*destroy)(void* ptr) noexcept = nullptr;
template <typename T>
static bool call_ctor(uchar* ptr, auto_typemap& _this) noexcept
{
{
// Allow passing reference to "this"
if constexpr (std::is_constructible_v<T, auto_typemap&>)
{
new (ptr) T(_this);
return true;
}
// Call default constructor only if available
if constexpr (std::is_default_constructible_v<T>)
{
new (ptr) T();
return true;
}
}
return false;
}
template <typename T>
static void call_dtor(void* ptr) noexcept
{
std::launder(static_cast<T*>(ptr))->~T();
std::memset(ptr, 0xCC, sizeof(T)); // Set to trap values
}
template <typename T>
static typeinfo make_typeinfo()
{
typeinfo r;
r.create = &call_ctor<T>;
r.destroy = &call_dtor<T>;
return r;
}
};
// Objects
union
{
uchar* m_list;
mutable uchar m_data[Size ? Size : 1];
};
// Creation order for each object (used to reverse destruction order)
void** m_order;
// Helper for destroying in reverse order
const typeinfo** m_info;
// Indicates whether object is created at given index
bool* m_init;
public:
auto_typemap() noexcept
: m_order(new void*[stx::typelist<typeinfo>().count()])
, m_info(new const typeinfo*[stx::typelist<typeinfo>().count()])
, m_init(new bool[stx::typelist<typeinfo>().count()]{})
{
if constexpr (Size == 0)
{
if (stx::typelist<typeinfo>().align() > __STDCPP_DEFAULT_NEW_ALIGNMENT__)
{
m_list = static_cast<uchar*>(::operator new(usz{stx::typelist<typeinfo>().size()}, std::align_val_t{stx::typelist<typeinfo>().align()}));
}
else
{
m_list = new uchar[stx::typelist<typeinfo>().size()];
}
}
else
{
ensure(Size >= stx::typelist<typeinfo>().size());
ensure(Align >= stx::typelist<typeinfo>().align());
}
// Set to trap values
std::memset(Size == 0 ? m_list : m_data, 0xCC, stx::typelist<typeinfo>().size());
for (const auto& type : stx::typelist<typeinfo>())
{
const u32 id = type.index();
uchar* data = (Size ? +m_data : m_list) + type.pos();
// Allocate initialization order id
if (type.create(data, *this))
{
*m_order++ = data;
*m_info++ = &type;
m_init[id] = true;
}
}
}
auto_typemap(const auto_typemap&) = delete;
auto_typemap& operator=(const auto_typemap&) = delete;
~auto_typemap()
{
// Get actual number of created objects
u32 _max = 0;
for (const auto& type : stx::typelist<typeinfo>())
{
if (m_init[type.index()])
{
// Skip object if not created
_max++;
}
}
// Destroy objects in reverse order
for (; _max; _max--)
{
auto* info = *--m_info;
const u32 type_index = static_cast<const type_info<typeinfo>*>(info)->index();
info->destroy(*--m_order);
// Set init to false. We don't want other fxo to use this fxo in their destructor.
m_init[type_index] = false;
}
// Pointers should be restored to their positions
delete[] m_init;
delete[] m_info;
delete[] m_order;
if constexpr (Size == 0)
{
if (stx::typelist<typeinfo>().align() > __STDCPP_DEFAULT_NEW_ALIGNMENT__)
{
::operator delete[](m_list, std::align_val_t{stx::typelist<typeinfo>().align()});
}
else
{
delete[] m_list;
}
}
}
// Check if object is not initialized but shall be initialized first (to use in initializing other objects)
template <typename T>
void need() noexcept
{
if (!m_init[stx::typeindex<typeinfo, std::decay_t<T>>()])
{
if constexpr (std::is_constructible_v<T, auto_typemap&>)
{
init<T>(*this);
return;
}
if constexpr (std::is_default_constructible_v<T>)
{
init<T>();
return;
}
}
}
// Explicitly initialize object of type T possibly with dynamic type As and arguments
template <typename T, typename As = T, typename... Args>
As* init(Args&&... args) noexcept
{
if (std::exchange(m_init[stx::typeindex<typeinfo, std::decay_t<T>, std::decay_t<As>>()], true))
{
// Already exists, recreation is not supported (may be added later)
return nullptr;
}
As* obj = nullptr;
if constexpr (Size != 0)
{
obj = new (m_data + stx::typeoffset<typeinfo, std::decay_t<T>>()) std::decay_t<As>(std::forward<Args>(args)...);
}
else
{
obj = new (m_list + stx::typeoffset<typeinfo, std::decay_t<T>>()) std::decay_t<As>(std::forward<Args>(args)...);
}
*m_order++ = obj;
*m_info++ = &stx::typedata<typeinfo, std::decay_t<T>, std::decay_t<As>>();
return obj;
}
// CTAD adaptor for init (see init description), accepts template not type
template <template <class...> typename Template, typename... Args>
auto init(Args&&... args) noexcept
{
// Deduce the type from given template and its arguments
using T = decltype(Template(std::forward<Args>(args)...));
return init<T>(std::forward<Args>(args)...);
}
template <typename T>
bool is_init() const noexcept
{
return m_init[stx::typeindex<typeinfo, std::decay_t<T>>()];
}
// Obtain object reference
template <typename T>
T& get() const noexcept
{
if constexpr (Size != 0)
{
return *std::launder(reinterpret_cast<T*>(m_data + stx::typeoffset<typeinfo, std::decay_t<T>>()));
}
else
{
return *std::launder(reinterpret_cast<T*>(m_list + stx::typeoffset<typeinfo, std::decay_t<T>>()));
}
}
// Obtain object pointer if initialized
template <typename T>
T* try_get() const noexcept
{
if (is_init<T>())
{
[[likely]] return &get<T>();
}
[[unlikely]] return nullptr;
}
};
}
using stx::auto_typemap;
| 6,222
|
C++
|
.h
| 217
| 24.442396
| 142
| 0.630591
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
5,654
|
logs.hpp
|
RPCS3_rpcs3/rpcs3/util/logs.hpp
|
#pragma once // No BOM and only basic ASCII in this header, or a neko will die
#include <map>
#include <memory>
#include <string>
#include <vector>
#include <initializer_list>
#include "util/atomic.hpp"
#include "Utilities/StrFmt.h"
namespace logs
{
enum class level : unsigned char
{
always = 0, // Highest log severity (cannot be disabled)
fatal = 1,
error = 2,
todo = 3,
success = 4,
warning = 5,
notice = 6,
trace = 7, // Lowest severity (usually disabled)
};
struct channel;
// Message information
struct message
{
// Default constructor
consteval message() = default;
// Cannot be moved because it relies on its location
message(const message&) = delete;
message& operator =(const message&) = delete;
// Send log message to the given channel with severity
template <typename... Args>
void operator()(const const_str& fmt, const Args&... args) const;
operator level() const
{
return level(uchar(reinterpret_cast<uptr>(this) & 7));
}
const channel* operator->() const
{
return reinterpret_cast<const channel*>(reinterpret_cast<uptr>(this) & -16);
}
inline explicit operator bool() const;
private:
// Send log message to global logger instance
void broadcast(const char*, const fmt_type_info*, ...) const;
friend struct channel;
};
struct stored_message
{
const message& m;
u64 stamp;
std::string prefix;
std::string text;
};
class listener
{
// Next listener (linked list)
atomic_t<listener*> m_next{};
friend struct message;
public:
constexpr listener() = default;
virtual ~listener();
// Process log message
virtual void log(u64 stamp, const message& msg, const std::string& prefix, const std::string& text) = 0;
// Flush contents (file writer)
virtual void sync();
// Close file handle after flushing to disk (hazardous)
virtual void close_prematurely();
// Add new listener
static void add(listener*);
// Special purpose
void broadcast(const stored_message&) const;
// Flush log to disk
static void sync_all();
// Close file handle after flushing to disk (hazardous)
static void close_all_prematurely();
};
struct alignas(16) channel : private message
{
// Channel prefix (added to every log message)
const char* const name;
// The lowest logging level enabled for this channel (used for early filtering)
atomic_t<level> enabled;
// Initialize channel
consteval channel(const char* name) noexcept
: message{}
, name(name)
, enabled(level::notice)
{
}
// Special access to "always visible" channel which shouldn't be used
const message& always() const
{
return *this;
}
#define GEN_LOG_METHOD(_sev)\
const message _sev{};\
GEN_LOG_METHOD(fatal)
GEN_LOG_METHOD(error)
GEN_LOG_METHOD(todo)
GEN_LOG_METHOD(success)
GEN_LOG_METHOD(warning)
GEN_LOG_METHOD(notice)
GEN_LOG_METHOD(trace)
#undef GEN_LOG_METHOD
};
inline logs::message::operator bool() const
{
// Test if enabled
return *this <= (*this)->enabled.observe();
}
template <typename... Args>
FORCE_INLINE SAFE_BUFFERS(void) message::operator()(const const_str& fmt, const Args&... args) const
{
if (operator bool()) [[unlikely]]
{
if constexpr (sizeof...(Args) > 0)
{
broadcast(fmt, fmt::type_info_v<Args...>, u64{fmt_unveil<Args>::get(args)}...);
}
else
{
broadcast(fmt, nullptr);
}
}
}
struct registerer
{
registerer(channel& _ch);
};
// Log level control: set all channels to level::notice
void reset();
// Log level control: set all channels to level::always
void silence();
// Log level control: register channel if necessary, set channel level
void set_level(const std::string&, level);
// Log level control: get channel level
level get_level(const std::string&);
// Log level control: set specific channels to level::fatal
void set_channel_levels(const std::map<std::string, logs::level, std::less<>>& map);
// Get all registered log channels
std::vector<std::string> get_channels();
// Helper: no additional name specified
consteval const char* make_channel_name(const char* name, const char* alt = nullptr)
{
return alt ? alt : name;
}
// Called in main()
std::unique_ptr<logs::listener> make_file_listener(const std::string& path, u64 max_size);
// Called in main()
void set_init(std::initializer_list<stored_message>);
}
#define LOG_CHANNEL(ch, ...) inline constinit ::logs::channel ch(::logs::make_channel_name(#ch, ##__VA_ARGS__)); \
namespace logs { inline ::logs::registerer reg_##ch{ch}; }
LOG_CHANNEL(rsx_log, "RSX");
| 4,586
|
C++
|
.h
| 155
| 26.709677
| 114
| 0.707706
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
5,655
|
fence.hpp
|
RPCS3_rpcs3/rpcs3/util/fence.hpp
|
#pragma once
#include "util/types.hpp"
#ifdef _M_X64
#ifdef _MSC_VER
extern "C" void _mm_lfence();
#else
#include <immintrin.h>
#endif
#endif
namespace utils
{
inline void lfence()
{
#ifdef _M_X64
_mm_lfence();
#elif defined(ARCH_X64)
__builtin_ia32_lfence();
#elif defined(ARCH_ARM64)
// TODO
__asm__ volatile("isb");
#else
#error "Missing lfence() implementation"
#endif
}
}
| 391
|
C++
|
.h
| 25
| 14.08
| 40
| 0.716253
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
5,656
|
types.hpp
|
RPCS3_rpcs3/rpcs3/util/types.hpp
|
#pragma once // No BOM and only basic ASCII in this header, or a neko will die
#include <cstdint>
#include <cstddef>
#include <cstring>
#include <type_traits>
#include <utility>
#include <chrono>
#include <array>
#include <tuple>
#include <compare>
#include <memory>
#include <bit>
#include <string>
#include <source_location>
#if defined(__SSE2__) || defined(_M_X64) || defined(_M_AMD64) || defined(__x86_64__) || defined(__amd64__)
#define ARCH_X64 1
#elif defined(__aarch64__) || defined(__arm64__) || defined(_M_ARM64)
#define ARCH_ARM64 1
// v8.4a+ gives us atomic 16 byte ld/st
// See Arm C Language Extensions Documentation
// Currently there is no feature macro for LSE2 specifically so we define it ourself
// Unfortunately the __ARM_ARCH integer macro isn't universally defined so we use this hack instead
#if defined(__ARM_ARCH_8_4__) || defined(__ARM_ARCH_8_5__) || defined(__ARM_ARCH_8_6__) || defined(__ARM_ARCH_9__)
#define ARM_FEATURE_LSE2 1
#endif
#endif
using std::chrono::steady_clock;
using namespace std::literals;
#ifndef __has_builtin
#define __has_builtin(x) 0
#endif
#ifdef _MSC_VER
#define SAFE_BUFFERS(...) __declspec(safebuffers) __VA_ARGS__
#define NEVER_INLINE __declspec(noinline)
#define FORCE_INLINE __forceinline
#else // not _MSC_VER
#ifdef __clang__
#define SAFE_BUFFERS(...) __attribute__((no_stack_protector)) __VA_ARGS__
#else
#define SAFE_BUFFERS(...) __VA_ARGS__ __attribute__((__optimize__("no-stack-protector")))
#endif
#define NEVER_INLINE __attribute__((noinline)) inline
#define FORCE_INLINE __attribute__((always_inline)) inline
#endif // _MSC_VER
#define CHECK_SIZE(type, size) static_assert(sizeof(type) == size, "Invalid " #type " type size")
#define CHECK_ALIGN(type, align) static_assert(alignof(type) == align, "Invalid " #type " type alignment")
#define CHECK_MAX_SIZE(type, size) static_assert(sizeof(type) <= size, #type " type size is too big")
#define CHECK_SIZE_ALIGN(type, size, align) CHECK_SIZE(type, size); CHECK_ALIGN(type, align)
#define DECLARE(...) decltype(__VA_ARGS__) __VA_ARGS__
#define STR_CASE(...) case __VA_ARGS__: return #__VA_ARGS__
#if defined(_DEBUG) || defined(_AUDIT)
#define AUDIT(...) (static_cast<void>(ensure(__VA_ARGS__)))
#else
#define AUDIT(...) (static_cast<std::void_t<decltype((__VA_ARGS__))>>(0))
#endif
namespace utils
{
template <typename F>
struct fn_helper
{
F f;
fn_helper(F&& f)
: f(std::forward<F>(f))
{
}
template <typename... Args>
auto operator()(Args&&... args) const
{
if constexpr (sizeof...(Args) == 0)
return f(0, 0, 0, 0);
else if constexpr (sizeof...(Args) == 1)
return f(std::forward<Args>(args)..., 0, 0, 0);
else if constexpr (sizeof...(Args) == 2)
return f(std::forward<Args>(args)..., 0, 0);
else if constexpr (sizeof...(Args) == 3)
return f(std::forward<Args>(args)..., 0);
else if constexpr (sizeof...(Args) == 4)
return f(std::forward<Args>(args)...);
else
static_assert(sizeof...(Args) <= 4);
}
};
template <typename F>
fn_helper(F&& f) -> fn_helper<F>;
}
// Shorter lambda.
#define FN(...) \
::utils::fn_helper([&]( \
[[maybe_unused]] auto&& x, \
[[maybe_unused]] auto&& y, \
[[maybe_unused]] auto&& z, \
[[maybe_unused]] auto&& w){ return (__VA_ARGS__); })
#if __cpp_lib_bit_cast < 201806L
namespace std
{
template <typename To, typename From>
[[nodiscard]] constexpr To bit_cast(const From& from) noexcept
{
return __builtin_bit_cast(To, from);
}
}
#endif
#if defined(__INTELLISENSE__) || (defined (__clang__) && (__clang_major__ <= 16))
#define consteval constexpr
#define constinit
#endif
using schar = signed char;
using uchar = unsigned char;
using ushort = unsigned short;
using uint = unsigned int;
using ulong = unsigned long;
using ullong = unsigned long long;
using llong = long long;
using uptr = std::uintptr_t;
using u8 = std::uint8_t;
using u16 = std::uint16_t;
using u32 = std::uint32_t;
using u64 = std::uint64_t;
using usz = std::size_t;
using s8 = std::int8_t;
using s16 = std::int16_t;
using s32 = std::int32_t;
using s64 = std::int64_t;
using ssz = std::make_signed_t<std::size_t>;
// Get integral type from type size
template <usz N>
struct get_int_impl
{
};
template <>
struct get_int_impl<sizeof(u8)>
{
using utype = u8;
};
template <>
struct get_int_impl<sizeof(u16)>
{
using utype = u16;
};
template <>
struct get_int_impl<sizeof(u32)>
{
using utype = u32;
};
template <>
struct get_int_impl<sizeof(u64)>
{
using utype = u64;
};
template <usz N>
using get_uint_t = typename get_int_impl<N>::utype;
template <typename T>
std::remove_cvref_t<T> as_rvalue(T&& obj)
{
return std::forward<T>(obj);
}
template <typename T, usz Align>
class atomic_t;
namespace stx
{
template <typename T, bool Se, usz Align>
class se_t;
template <typename T>
struct lazy;
template <typename T>
struct generator;
}
using stx::se_t;
// se_t<> with native endianness
template <typename T, usz Align = alignof(T)>
using nse_t = se_t<T, false, Align>;
template <typename T, usz Align = alignof(T)>
using be_t = se_t<T, std::endian::little == std::endian::native, Align>;
template <typename T, usz Align = alignof(T)>
using le_t = se_t<T, std::endian::big == std::endian::native, Align>;
template <typename T, usz Align = alignof(T)>
using atomic_be_t = atomic_t<be_t<T>, Align>;
template <typename T, usz Align = alignof(T)>
using atomic_le_t = atomic_t<le_t<T>, Align>;
// Bool type equivalent
class b8
{
u8 m_value;
public:
b8() = default;
using enable_bitcopy = std::true_type;
constexpr b8(bool value) noexcept
: m_value(value)
{
}
constexpr operator bool() const noexcept
{
return m_value != 0;
}
constexpr bool set(bool value) noexcept
{
m_value = value;
return value;
}
};
#if defined(ARCH_X64) && !defined(_MSC_VER)
using __m128i = long long __attribute__((vector_size(16)));
using __m128d = double __attribute__((vector_size(16)));
using __m128 = float __attribute__((vector_size(16)));
#endif
#ifndef _MSC_VER
using u128 = __uint128_t;
using s128 = __int128_t;
#else
extern "C"
{
union __m128;
union __m128i;
struct __m128d;
uchar _addcarry_u64(uchar, u64, u64, u64*);
uchar _subborrow_u64(uchar, u64, u64, u64*);
u64 __shiftleft128(u64, u64, uchar);
u64 __shiftright128(u64, u64, uchar);
u64 _umul128(u64, u64, u64*);
}
// Unsigned 128-bit integer implementation (TODO)
struct alignas(16) u128
{
u64 lo, hi;
u128() noexcept = default;
template <typename T, std::enable_if_t<std::is_unsigned_v<T>, u64> = 0>
constexpr u128(T arg) noexcept
: lo(arg)
, hi(0)
{
}
template <typename T, std::enable_if_t<std::is_signed_v<T>, s64> = 0>
constexpr u128(T arg) noexcept
: lo(s64{arg})
, hi(s64{arg} >> 63)
{
}
constexpr explicit operator bool() const noexcept
{
return !!(lo | hi);
}
constexpr explicit operator u64() const noexcept
{
return lo;
}
constexpr explicit operator s64() const noexcept
{
return lo;
}
constexpr friend u128 operator+(const u128& l, const u128& r)
{
u128 value = l;
value += r;
return value;
}
constexpr friend u128 operator-(const u128& l, const u128& r)
{
u128 value = l;
value -= r;
return value;
}
constexpr friend u128 operator*(const u128& l, const u128& r)
{
u128 value = l;
value *= r;
return value;
}
constexpr u128 operator+() const
{
return *this;
}
constexpr u128 operator-() const
{
u128 value{};
value -= *this;
return value;
}
constexpr u128& operator++()
{
*this += 1;
return *this;
}
constexpr u128 operator++(int)
{
u128 value = *this;
*this += 1;
return value;
}
constexpr u128& operator--()
{
*this -= 1;
return *this;
}
constexpr u128 operator--(int)
{
u128 value = *this;
*this -= 1;
return value;
}
constexpr u128 operator<<(u128 shift_value) const
{
u128 value = *this;
value <<= shift_value;
return value;
}
constexpr u128 operator>>(u128 shift_value) const
{
u128 value = *this;
value >>= shift_value;
return value;
}
constexpr u128 operator~() const
{
u128 value{};
value.lo = ~lo;
value.hi = ~hi;
return value;
}
constexpr friend u128 operator&(const u128& l, const u128& r)
{
u128 value{};
value.lo = l.lo & r.lo;
value.hi = l.hi & r.hi;
return value;
}
constexpr friend u128 operator|(const u128& l, const u128& r)
{
u128 value{};
value.lo = l.lo | r.lo;
value.hi = l.hi | r.hi;
return value;
}
constexpr friend u128 operator^(const u128& l, const u128& r)
{
u128 value{};
value.lo = l.lo ^ r.lo;
value.hi = l.hi ^ r.hi;
return value;
}
constexpr u128& operator+=(const u128& r)
{
if (std::is_constant_evaluated())
{
lo += r.lo;
hi += r.hi + (lo < r.lo);
}
else
{
_addcarry_u64(_addcarry_u64(0, r.lo, lo, &lo), r.hi, hi, &hi);
}
return *this;
}
constexpr u128& operator-=(const u128& r)
{
if (std::is_constant_evaluated())
{
hi -= r.hi + (lo < r.lo);
lo -= r.lo;
}
else
{
_subborrow_u64(_subborrow_u64(0, lo, r.lo, &lo), hi, r.hi, &hi);
}
return *this;
}
constexpr u128& operator*=(const u128& r)
{
const u64 _hi = r.hi * lo + r.lo * hi;
if (std::is_constant_evaluated())
{
hi = (lo >> 32) * (r.lo >> 32) + (((lo >> 32) * (r.lo & 0xffffffff)) >> 32) + (((r.lo >> 32) * (lo & 0xffffffff)) >> 32);
lo = lo * r.lo;
}
else
{
lo = _umul128(lo, r.lo, &hi);
}
hi += _hi;
return *this;
}
constexpr u128& operator<<=(const u128& r)
{
if (std::is_constant_evaluated())
{
if (r.hi == 0 && r.lo < 64)
{
hi = (hi << r.lo) | (lo >> (64 - r.lo));
lo = (lo << r.lo);
return *this;
}
else if (r.hi == 0 && r.lo < 128)
{
hi = (lo << (r.lo - 64));
lo = 0;
return *this;
}
}
const u64 v0 = lo << (r.lo & 63);
const u64 v1 = __shiftleft128(lo, hi, static_cast<uchar>(r.lo));
lo = (r.lo & 64) ? 0 : v0;
hi = (r.lo & 64) ? v0 : v1;
return *this;
}
constexpr u128& operator>>=(const u128& r)
{
if (std::is_constant_evaluated())
{
if (r.hi == 0 && r.lo < 64)
{
lo = (lo >> r.lo) | (hi << (64 - r.lo));
hi = (hi >> r.lo);
return *this;
}
else if (r.hi == 0 && r.lo < 128)
{
lo = (hi >> (r.lo - 64));
hi = 0;
return *this;
}
}
const u64 v0 = hi >> (r.lo & 63);
const u64 v1 = __shiftright128(lo, hi, static_cast<uchar>(r.lo));
lo = (r.lo & 64) ? v0 : v1;
hi = (r.lo & 64) ? 0 : v0;
return *this;
}
constexpr u128& operator&=(const u128& r)
{
lo &= r.lo;
hi &= r.hi;
return *this;
}
constexpr u128& operator|=(const u128& r)
{
lo |= r.lo;
hi |= r.hi;
return *this;
}
constexpr u128& operator^=(const u128& r)
{
lo ^= r.lo;
hi ^= r.hi;
return *this;
}
};
// Signed 128-bit integer implementation
struct s128 : u128
{
using u128::u128;
constexpr s128 operator>>(u128 shift_value) const
{
s128 value = *this;
value >>= shift_value;
return value;
}
constexpr s128& operator>>=(const u128& r)
{
if (std::is_constant_evaluated())
{
if (r.hi == 0 && r.lo < 64)
{
lo = (lo >> r.lo) | (hi << (64 - r.lo));
hi = (static_cast<s64>(hi) >> r.lo);
return *this;
}
else if (r.hi == 0 && r.lo < 128)
{
s64 _lo = static_cast<s64>(hi) >> (r.lo - 64);
lo = _lo;
hi = _lo >> 63;
return *this;
}
}
const u64 v0 = static_cast<s64>(hi) >> (r.lo & 63);
const u64 v1 = __shiftright128(lo, hi, static_cast<uchar>(r.lo));
lo = (r.lo & 64) ? v0 : v1;
hi = (r.lo & 64) ? static_cast<s64>(hi) >> 63 : v0;
return *this;
}
};
#endif
// Optimization for u64*u64=u128
constexpr u128 u128_from_mul(u64 a, u64 b)
{
#ifdef _MSC_VER
if (!std::is_constant_evaluated())
{
u64 hi;
u128 result = _umul128(a, b, &hi);
result.hi = hi;
return result;
}
#endif
return u128{a} * b;
}
template <>
struct get_int_impl<16>
{
using utype = u128;
using stype = s128;
};
enum class f16 : u16{};
using f32 = float;
using f64 = double;
template <typename T>
concept UnsignedInt = std::is_unsigned_v<std::common_type_t<T>> || std::is_same_v<std::common_type_t<T>, u128>;
template <typename T>
concept SignedInt = (std::is_signed_v<std::common_type_t<T>> && std::is_integral_v<std::common_type_t<T>>) || std::is_same_v<std::common_type_t<T>, s128>;
template <typename T>
concept FPInt = std::is_floating_point_v<std::common_type_t<T>> || std::is_same_v<std::common_type_t<T>, f16>;
template <typename T>
concept Integral = std::is_integral_v<std::common_type_t<T>> || std::is_same_v<std::common_type_t<T>, u128> || std::is_same_v<std::common_type_t<T>, s128>;
template <typename T>
constexpr T min_v;
template <UnsignedInt T>
constexpr std::common_type_t<T> min_v<T> = 0;
template <SignedInt T>
constexpr std::common_type_t<T> min_v<T> = static_cast<std::common_type_t<T>>(-1) << (sizeof(std::common_type_t<T>) * 8 - 1);
template <>
constexpr inline f16 min_v<f16>{0xfbffu};
template <>
constexpr inline f32 min_v<f32> = std::bit_cast<f32, u32>(0xff'7fffffu);
template <>
constexpr inline f64 min_v<f64> = std::bit_cast<f64, u64>(0xffe'7ffff'ffffffffu);
template <FPInt T>
constexpr std::common_type_t<T> min_v<T> = min_v<std::common_type_t<T>>;
template <typename T>
constexpr T max_v;
template <UnsignedInt T>
constexpr std::common_type_t<T> max_v<T> = -1;
template <SignedInt T>
constexpr std::common_type_t<T> max_v<T> = static_cast<std::common_type_t<T>>(~min_v<T>);
template <>
constexpr inline f16 max_v<f16>{0x7bffu};
template <>
constexpr inline f32 max_v<f32> = std::bit_cast<f32, u32>(0x7f'7fffffu);
template <>
constexpr inline f64 max_v<f64> = std::bit_cast<f64, u64>(0x7fe'fffff'ffffffffu);
template <FPInt T>
constexpr std::common_type_t<T> max_v<T> = max_v<std::common_type_t<T>>;
// Return magic value for any unsigned type
constexpr struct umax_impl_t
{
template <UnsignedInt T>
constexpr bool operator==(const T& rhs) const
{
return rhs == max_v<T>;
}
template <UnsignedInt T>
constexpr std::strong_ordering operator<=>(const T& rhs) const
{
return rhs == max_v<T> ? std::strong_ordering::equal : std::strong_ordering::greater;
}
template <UnsignedInt T>
constexpr operator T() const
{
return max_v<T>;
}
} umax;
constexpr struct smin_impl_t
{
template <SignedInt T>
constexpr bool operator==(const T& rhs) const
{
return rhs == min_v<T>;
}
template <SignedInt T>
constexpr std::strong_ordering operator<=>(const T& rhs) const
{
return rhs == min_v<T> ? std::strong_ordering::equal : std::strong_ordering::less;
}
template <SignedInt T>
constexpr operator T() const
{
return min_v<T>;
}
} smin;
constexpr struct smax_impl_t
{
template <SignedInt T>
constexpr bool operator==(const T& rhs) const
{
return rhs == max_v<T>;
}
template <SignedInt T>
constexpr std::strong_ordering operator<=>(const T& rhs) const
{
return rhs == max_v<T> ? std::strong_ordering::equal : std::strong_ordering::greater;
}
template <SignedInt T>
constexpr operator T() const
{
return max_v<T>;
}
} smax;
// Compare signed or unsigned type with its max value
constexpr struct amax_impl_t
{
template <typename T> requires SignedInt<T> || UnsignedInt<T>
constexpr bool operator ==(const T& rhs) const
{
return rhs == max_v<T>;
}
template <typename T> requires SignedInt<T> || UnsignedInt<T>
constexpr std::strong_ordering operator <=>(const T& rhs) const
{
return max_v<T> <=> rhs;
}
template <typename T> requires SignedInt<T> || UnsignedInt<T>
constexpr operator T() const
{
return max_v<T>;
}
} amax;
// Compare signed or unsigned type with its minimal value (like zero or INT_MIN)
constexpr struct amin_impl_t
{
template <typename T> requires SignedInt<T> || UnsignedInt<T>
constexpr bool operator ==(const T& rhs) const
{
return rhs == min_v<T>;
}
template <typename T> requires SignedInt<T> || UnsignedInt<T>
constexpr std::strong_ordering operator <=>(const T& rhs) const
{
return min_v<T> <=> rhs;
}
template <typename T> requires SignedInt<T> || UnsignedInt<T>
constexpr operator T() const
{
return min_v<T>;
}
} amin;
template <typename T, typename T2>
inline u32 offset32(T T2::*const mptr)
{
#ifdef _MSC_VER
return std::bit_cast<u32>(mptr);
#elif __GNUG__
return std::bit_cast<usz>(mptr);
#else
static_assert(sizeof(mptr) == 0, "Unsupported pointer-to-member size");
#endif
}
template <typename T>
struct offset32_array
{
static_assert(std::is_array_v<T>, "Invalid pointer-to-member type (array expected)");
template <typename Arg>
static inline u32 index32(const Arg& arg)
{
return u32{sizeof(std::remove_extent_t<T>)} * static_cast<u32>(arg);
}
};
template <typename T, usz N>
struct offset32_array<std::array<T, N>>
{
template <typename Arg>
static inline u32 index32(const Arg& arg)
{
return u32{sizeof(T)} * static_cast<u32>(arg);
}
};
template <typename Arg>
struct offset32_detail;
template <typename T, typename T2, typename Arg, typename... Args>
inline u32 offset32(T T2::*const mptr, const Arg& arg, const Args&... args)
{
return offset32_detail<Arg>::offset32(mptr, arg, args...);
}
template <typename Arg>
struct offset32_detail
{
template <typename T, typename T2, typename... Args>
static inline u32 offset32(T T2::*const mptr, const Arg& arg, const Args&... args)
{
return ::offset32(mptr, args...) + offset32_array<T>::index32(arg);
}
};
template <typename T3, typename T4>
struct offset32_detail<T3 T4::*>
{
template <typename T, typename T2, typename... Args>
static inline u32 offset32(T T2::*const mptr, T3 T4::*const mptr2, const Args&... args)
{
return ::offset32(mptr) + ::offset32(mptr2, args...);
}
};
// Convert 0-2-byte string to u16 value like reinterpret_cast does
constexpr u16 operator""_u16(const char* s, usz /*length*/)
{
char buf[2]{s[0], s[1]};
return std::bit_cast<u16>(buf);
}
// Convert 3-4-byte string to u32 value like reinterpret_cast does
constexpr u32 operator""_u32(const char* s, usz /*length*/)
{
char buf[4]{s[0], s[1], s[2], s[3]};
return std::bit_cast<u32>(buf);
}
// Convert 5-8-byte string to u64 value like reinterpret_cast does
constexpr u64 operator""_u64(const char* s, usz len)
{
char buf[8]{s[0], s[1], s[2], s[3], s[4], (len < 6 ? '\0' : s[5]), (len < 7 ? '\0' : s[6]), (len < 8 ? '\0' : s[7])};
return std::bit_cast<u64>(buf);
}
#if !defined(__INTELLISENSE__) && !__has_builtin(__builtin_COLUMN) && !defined(_MSC_VER)
constexpr unsigned __builtin_COLUMN()
{
return -1;
}
#endif
template <usz Size = umax>
struct const_str_t
{
static constexpr usz size = Size;
char8_t chars[Size + 1]{};
constexpr const_str_t(const char(&a)[Size + 1])
{
for (usz i = 0; i <= Size; i++)
chars[i] = a[i];
}
constexpr const_str_t(const char8_t(&a)[Size + 1])
{
for (usz i = 0; i <= Size; i++)
chars[i] = a[i];
}
operator const char*() const
{
return reinterpret_cast<const char*>(chars);
}
constexpr operator const char8_t*() const
{
return chars;
}
};
template <>
struct const_str_t<umax>
{
const usz size;
union
{
const char8_t* chars;
const char* chars2;
};
constexpr const_str_t()
: size(0)
, chars(nullptr)
{
}
template <usz N>
constexpr const_str_t(const char8_t(&a)[N])
: size(N - 1)
, chars(+a)
{
}
template <usz N>
constexpr const_str_t(const char(&a)[N])
: size(N - 1)
, chars2(+a)
{
}
constexpr operator const char*() const
{
return std::launder(chars2);
}
constexpr operator const char8_t*() const
{
return chars;
}
};
template <usz Size>
const_str_t(const char(&a)[Size]) -> const_str_t<Size - 1>;
template <usz Size>
const_str_t(const char8_t(&a)[Size]) -> const_str_t<Size - 1>;
using const_str = const_str_t<>;
namespace fmt
{
[[noreturn]] void raw_verify_error(std::source_location loc, const char8_t* msg, usz object);
[[noreturn]] void raw_range_error(std::source_location loc, std::string_view index, usz container_size);
[[noreturn]] void raw_range_error(std::source_location loc, usz index, usz container_size);
}
// No full implementation to ease on header weight
template <typename T>
std::conditional_t<std::is_integral_v<std::remove_cvref_t<T>>, usz, std::string_view> format_object_simplified(const T& obj)
{
using type = std::remove_cvref_t<T>;
if constexpr (std::is_integral_v<type> || std::is_same_v<std::string, type> || std::is_same_v<std::string_view, type>)
{
return obj;
}
else if constexpr (std::is_array_v<type> && std::is_constructible_v<std::string_view, type>)
{
return { obj, std::size(obj) - 1 };
}
else
{
return std::string_view{};
}
}
template <typename T>
constexpr decltype(auto) ensure(T&& arg, const_str msg = const_str(), std::source_location src_loc = std::source_location::current()) noexcept
{
if (std::forward<T>(arg)) [[likely]]
{
return std::forward<T>(arg);
}
fmt::raw_verify_error(src_loc, msg, 0);
}
template <typename T, typename F> requires (std::is_invocable_v<F, T&&>)
constexpr decltype(auto) ensure(T&& arg, F&& pred, const_str msg = const_str(), std::source_location src_loc = std::source_location::current()) noexcept
{
if (std::forward<F>(pred)(std::forward<T>(arg))) [[likely]]
{
return std::forward<T>(arg);
}
fmt::raw_verify_error(src_loc, msg, 0);
}
// narrow() function details
template <typename From, typename To = void, typename = void>
struct narrow_impl
{
// Temporarily (diagnostic)
static_assert(std::is_void_v<To>, "narrow_impl<> specialization not found");
// Returns true if value cannot be represented in type To
static constexpr bool test(const From&)
{
// Unspecialized cases (including cast to void) always considered narrowing
return true;
}
};
// Unsigned to unsigned narrowing
template <typename From, typename To>
struct narrow_impl<From, To, std::enable_if_t<std::is_unsigned_v<From> && std::is_unsigned_v<To>>>
{
static constexpr bool test(const From& value)
{
return sizeof(To) < sizeof(From) && static_cast<To>(value) != value;
}
};
// Signed to signed narrowing
template <typename From, typename To>
struct narrow_impl<From, To, std::enable_if_t<std::is_signed_v<From> && std::is_signed_v<To>>>
{
static constexpr bool test(const From& value)
{
return sizeof(To) < sizeof(From) && static_cast<To>(value) != value;
}
};
// Unsigned to signed narrowing
template <typename From, typename To>
struct narrow_impl<From, To, std::enable_if_t<std::is_unsigned_v<From> && std::is_signed_v<To>>>
{
static constexpr bool test(const From& value)
{
return sizeof(To) <= sizeof(From) && value > (static_cast<std::make_unsigned_t<To>>(-1) >> 1);
}
};
// Signed to unsigned narrowing (I)
template <typename From, typename To>
struct narrow_impl<From, To, std::enable_if_t<std::is_signed_v<From> && std::is_unsigned_v<To> && sizeof(To) >= sizeof(From)>>
{
static constexpr bool test(const From& value)
{
return value < static_cast<From>(0);
}
};
// Signed to unsigned narrowing (II)
template <typename From, typename To>
struct narrow_impl<From, To, std::enable_if_t<std::is_signed_v<From> && std::is_unsigned_v<To> && sizeof(To) < sizeof(From)>>
{
static constexpr bool test(const From& value)
{
return static_cast<std::make_unsigned_t<From>>(value) > static_cast<To>(-1);
}
};
// Simple type enabled (TODO: allow for To as well)
template <typename From, typename To>
struct narrow_impl<From, To, std::enable_if_t<!std::is_same_v<std::common_type_t<From>, From>>>
: narrow_impl<std::common_type_t<From>, To>
{
};
template <typename To = void, typename From, typename = decltype(static_cast<To>(std::declval<From>()))>
[[nodiscard]] constexpr To narrow(const From& value, std::source_location src_loc = std::source_location::current())
{
// Narrow check
if (narrow_impl<From, To>::test(value)) [[unlikely]]
{
fmt::raw_verify_error(src_loc, u8"Narrowing error", +value);
}
return static_cast<To>(value);
}
// Returns u32 size() for container
template <typename CT> requires requires (const CT& x) { std::size(x); }
[[nodiscard]] constexpr u32 size32(const CT& container, std::source_location src_loc = std::source_location::current())
{
// TODO: Support std::array
constexpr bool is_const = std::is_array_v<std::remove_cvref_t<CT>>;
if constexpr (is_const)
{
constexpr usz Size = sizeof(container) / sizeof(container[0]);
return std::conditional_t<is_const, u32, usz>{Size};
}
else
{
return narrow<u32>(container.size(), src_loc);
}
}
template <typename CT, typename T> requires requires (CT&& x) { std::size(x); std::data(x); } || requires (CT&& x) { std::size(x); x.front(); }
[[nodiscard]] constexpr auto& at32(CT&& container, T&& index, std::source_location src_loc = std::source_location::current())
{
// Make sure the index is within u32 range
const std::make_unsigned_t<std::common_type_t<T>> idx = index;
const u32 csz = ::size32(container, src_loc);
if (csz <= idx) [[unlikely]]
fmt::raw_range_error(src_loc, format_object_simplified(index), csz);
auto it = std::begin(std::forward<CT>(container));
std::advance(it, idx);
return *it;
}
template <typename CT, typename T> requires requires (CT&& x, T&& y) { x.count(y); x.find(y); }
[[nodiscard]] constexpr auto& at32(CT&& container, T&& index, std::source_location src_loc = std::source_location::current())
{
// Associative container
const auto found = container.find(std::forward<T>(index));
usz csv = umax;
if constexpr ((requires () { container.size(); }))
csv = container.size();
if (found == container.end()) [[unlikely]]
fmt::raw_range_error(src_loc, format_object_simplified(index), csv);
return found->second;
}
// Simplified hash algorithm. May be used in std::unordered_(map|set).
template <typename T, usz Shift = 0>
struct value_hash
{
usz operator()(T value) const
{
return static_cast<usz>(value) >> Shift;
}
};
template <typename... T>
struct fill_array_t
{
std::tuple<T...> args;
template <typename V, usz Num>
constexpr std::unwrap_reference_t<V> get() const
{
return std::get<Num>(args);
}
template <typename U, usz N, usz... M, usz... Idx>
constexpr std::array<U, N> fill(std::index_sequence<M...>, std::index_sequence<Idx...>) const
{
return{(static_cast<void>(Idx), U(get<T, M>()...))...};
}
template <typename U, usz N>
constexpr operator std::array<U, N>() const
{
return fill<U, N>(std::make_index_sequence<sizeof...(T)>(), std::make_index_sequence<N>());
}
};
template <typename... T>
constexpr auto fill_array(const T&... args)
{
return fill_array_t<T...>{{args...}};
}
template <typename X, typename Y>
concept PtrCastable = requires(const volatile X* x, const volatile Y* y)
{
static_cast<const volatile Y*>(x);
static_cast<const volatile X*>(y);
};
template <typename X, typename Y> requires PtrCastable<X, Y>
consteval bool is_same_ptr()
{
if constexpr (std::is_void_v<X> || std::is_void_v<Y> || std::is_same_v<std::remove_cv_t<X>, std::remove_cv_t<Y>>)
{
return true;
}
else if constexpr (sizeof(X) == sizeof(Y))
{
return true;
}
else
{
bool result = false;
if constexpr (sizeof(X) < sizeof(Y))
{
std::allocator<Y> a{};
Y* ptr = a.allocate(1);
result = static_cast<X*>(ptr) == static_cast<void*>(ptr);
a.deallocate(ptr, 1);
}
else
{
std::allocator<X> a{};
X* ptr = a.allocate(1);
result = static_cast<Y*>(ptr) == static_cast<void*>(ptr);
a.deallocate(ptr, 1);
}
return result;
}
}
template <typename X, typename Y> requires PtrCastable<X, Y>
constexpr bool is_same_ptr(const volatile Y* ptr)
{
return static_cast<const volatile X*>(ptr) == static_cast<const volatile void*>(ptr);
}
template <typename X, typename Y>
concept PtrSame = (is_same_ptr<X, Y>());
namespace stx
{
template <typename T>
struct exact_t
{
static_assert(std::is_reference_v<T> || std::is_convertible_v<T, const T&>);
T obj;
explicit exact_t(T&& _obj) : obj(std::forward<T>(_obj)) {}
exact_t& operator=(const exact_t&) = delete;
template <typename U> requires (std::is_same_v<U&, T>)
operator U&() const noexcept { return obj; };
template <typename U> requires (std::is_same_v<const U&, T>)
operator const U&() const noexcept { return obj; };
template <typename U> requires (std::is_same_v<U, T> && std::is_copy_constructible_v<T>)
operator U() const noexcept { return obj; };
};
template <typename T>
stx::exact_t<T&> make_exact(T&& obj) noexcept
{
return stx::exact_t<T&>(static_cast<T&>(obj));
}
}
// Read object of type T from raw pointer, array, string, vector, or any contiguous container
template <typename T, typename U>
constexpr T read_from_ptr(U&& array, usz pos = 0)
{
// TODO: ensure array element types are trivial
static_assert(sizeof(T) % sizeof(array[0]) == 0);
std::decay_t<decltype(array[0])> buf[sizeof(T) / sizeof(array[0])];
if (!std::is_constant_evaluated())
std::memcpy(+buf, &array[pos], sizeof(buf));
else
for (usz i = 0; i < pos; buf[i] = array[pos + i], i++);
return std::bit_cast<T>(buf);
}
template <typename T, typename U>
constexpr void write_to_ptr(U&& array, usz pos, const T& value)
{
static_assert(sizeof(T) % sizeof(array[0]) == 0);
if (!std::is_constant_evaluated())
std::memcpy(&array[pos], &value, sizeof(value));
else
ensure(!"Unimplemented");
}
template <typename T, typename U>
constexpr void write_to_ptr(U&& array, const T& value)
{
static_assert(sizeof(T) % sizeof(array[0]) == 0);
if (!std::is_constant_evaluated())
std::memcpy(&array[0], &value, sizeof(value));
else
ensure(!"Unimplemented");
}
constexpr struct aref_tag_t{} aref_tag{};
template <typename T, typename U>
class aref final
{
U* m_ptr;
static_assert(sizeof(std::decay_t<T>) % sizeof(U) == 0);
public:
aref() = delete;
constexpr aref(const aref&) = default;
explicit constexpr aref(aref_tag_t, U* ptr)
: m_ptr(ptr)
{
}
constexpr T value() const
{
return read_from_ptr<T>(m_ptr);
}
constexpr operator T() const
{
return read_from_ptr<T>(m_ptr);
}
aref& operator=(const aref&) = delete;
constexpr aref& operator=(const T& value) const
{
write_to_ptr<T>(m_ptr, value);
return *this;
}
template <typename MT, typename T2> requires (std::is_convertible_v<const volatile T*, const volatile T2*>) && PtrSame<T, T2>
aref<MT, U> ref(MT T2::*const mptr) const
{
return aref<MT, U>(aref_tag, m_ptr + offset32(mptr) / sizeof(U));
}
template <typename MT, typename T2, typename ET = std::remove_extent_t<MT>> requires (std::is_convertible_v<const volatile T*, const volatile T2*>) && PtrSame<T, T2>
aref<ET, U> ref(MT T2::*const mptr, usz index) const
{
return aref<ET, U>(aref_tag, m_ptr + offset32(mptr) / sizeof(U) + sizeof(ET) / sizeof(U) * index);
}
};
template <typename T, typename U>
class aref<T[], U>
{
U* m_ptr;
static_assert(sizeof(std::decay_t<T>) % sizeof(U) == 0);
public:
aref() = delete;
constexpr aref(const aref&) = default;
explicit constexpr aref(aref_tag_t, U* ptr)
: m_ptr(ptr)
{
}
aref& operator=(const aref&) = delete;
constexpr aref<T, U> operator[](usz index) const
{
return aref<T, U>(aref_tag, m_ptr + index * (sizeof(T) / sizeof(U)));
}
};
template <typename T, typename U, std::size_t N>
class aref<T[N], U>
{
U* m_ptr;
static_assert(sizeof(std::decay_t<T>) % sizeof(U) == 0);
public:
aref() = delete;
constexpr aref(const aref&) = default;
explicit constexpr aref(aref_tag_t, U* ptr)
: m_ptr(ptr)
{
}
aref& operator=(const aref&) = delete;
constexpr aref<T, U> operator[](usz index) const
{
return aref<T, U>(aref_tag, m_ptr + index * (sizeof(T) / sizeof(U)));
}
};
// Reference object of type T, see read_from_ptr
template <typename T, typename U>
constexpr auto ref_ptr(U&& array, usz pos = 0) -> aref<T, std::decay_t<decltype(array[0])>>
{
return aref<T, std::decay_t<decltype(array[0])>>(aref_tag, &array[pos]);
}
namespace utils
{
struct serial;
}
template <typename T>
extern bool serialize(utils::serial& ar, T& obj);
#define USING_SERIALIZATION_VERSION(name) []()\
{\
extern void using_##name##_serialization();\
using_##name##_serialization();\
}()
#define GET_OR_USE_SERIALIZATION_VERSION(cond, name) [&]()\
{\
extern void using_##name##_serialization();\
extern s32 get_##name##_serialization_version();\
return (static_cast<bool>(cond) ? (using_##name##_serialization(), 0) : get_##name##_serialization_version());\
}()
#define GET_SERIALIZATION_VERSION(name) []()\
{\
extern s32 get_##name##_serialization_version();\
return get_##name##_serialization_version();\
}()
#define ENABLE_BITWISE_SERIALIZATION using enable_bitcopy = std::true_type;
#define SAVESTATE_INIT_POS(...) static constexpr double savestate_init_pos = (__VA_ARGS__)
#define UNUSED(expr) do { (void)(expr); } while (0)
| 32,566
|
C++
|
.h
| 1,168
| 25.722603
| 166
| 0.672656
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
5,657
|
slow_mutex.hpp
|
RPCS3_rpcs3/rpcs3/util/slow_mutex.hpp
|
#pragma once
#include "util/types.hpp"
#include "util/atomic.hpp"
#include "Utilities/StrFmt.h"
// Pessimistic mutex for slow operation, does not spin wait, occupies only one byte
class slow_mutex
{
atomic_t<u8> m_value{0};
public:
constexpr slow_mutex() noexcept = default;
void lock() noexcept
{
// Two-stage locking: increment, then wait
while (true)
{
const u8 prev = m_value.fetch_op([](u8& val)
{
if ((val & 0x7f) == 0x7f) [[unlikely]]
return;
val++;
});
if ((prev & 0x7f) == 0x7f) [[unlikely]]
{
// Keep trying until counter can be incremented
m_value.wait(0x7f, 0x7f);
}
else if (prev == 0)
{
// Locked
return;
}
else
{
// Normal waiting
break;
}
}
// Wait for signal bit
m_value.wait(0, 0x80);
m_value &= ~0x80;
}
bool try_lock() noexcept
{
return m_value.compare_and_swap_test(0, 1);
}
void unlock() noexcept
{
const u8 prev = m_value.fetch_op([](u8& val)
{
if (val) [[likely]]
val--;
});
if (prev == 0) [[unlikely]]
{
fmt::throw_exception("I tried to unlock unlocked mutex.");
}
// Set signal and notify
if (prev & 0x7f)
{
m_value |= 0x80;
m_value.notify_one(0x80);
}
if ((prev & 0x7f) == 0x7f) [[unlikely]]
{
// Overflow notify: value can be incremented
m_value.notify_one(0x7f);
}
}
bool is_free() const noexcept
{
return !m_value;
}
void lock_unlock() noexcept
{
if (m_value)
{
lock();
unlock();
}
}
};
| 1,499
|
C++
|
.h
| 81
| 15.259259
| 83
| 0.616809
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
5,658
|
media_utils.h
|
RPCS3_rpcs3/rpcs3/util/media_utils.h
|
#pragma once
#include "Utilities/StrUtil.h"
#include "Utilities/Thread.h"
#include "util/video_provider.h"
#include "Emu/Cell/Modules/cellMusic.h"
#include <unordered_map>
#include <deque>
#include <mutex>
#include <thread>
namespace utils
{
std::string av_error_to_string(int error);
struct ffmpeg_codec
{
int codec_id{};
std::string name;
std::string long_name;
};
std::vector<ffmpeg_codec> list_ffmpeg_decoders();
std::vector<ffmpeg_codec> list_ffmpeg_encoders();
struct media_info
{
std::string path;
std::string sub_type; // The sub type if available (png, jpg...)
s32 audio_av_codec_id = 0; // 0 = AV_CODEC_ID_NONE
s32 video_av_codec_id = 0; // 0 = AV_CODEC_ID_NONE
s32 audio_bitrate_bps = 0; // Bit rate in bit/s
s32 video_bitrate_bps = 0; // Bit rate in bit/s
s32 sample_rate = 0; // Samples per second
s64 duration_us = 0; // in AV_TIME_BASE fractional seconds (= microseconds)
s32 width = 0; // Width if available
s32 height = 0; // Height if available
s32 orientation = 0; // Orientation if available (= CellSearchOrientation)
std::unordered_map<std::string, std::string> metadata;
// Convenience function for metadata
template <typename T>
T get_metadata(const std::string& key, const T& def) const;
};
std::pair<bool, media_info> get_media_info(const std::string& path, s32 av_media_type);
template <typename D>
void parse_metadata(D& dst, const utils::media_info& mi, const std::string& key, const std::string& def, usz max_length)
{
std::string value = mi.get_metadata<std::string>(key, def);
if (value.size() > max_length)
{
value.resize(max_length);
}
strcpy_trunc(dst, value);
};
class audio_decoder
{
public:
audio_decoder();
~audio_decoder();
void set_context(music_selection_context context);
void set_swap_endianness(bool swapped);
void clear();
void stop();
void decode();
u32 set_next_index(bool next);
shared_mutex m_mtx;
static constexpr s32 sample_rate = 48000;
std::vector<u8> data;
atomic_t<u64> m_size = 0;
atomic_t<u32> track_fully_decoded{0};
atomic_t<u32> track_fully_consumed{0};
atomic_t<bool> has_error{false};
std::deque<std::pair<u64, u64>> timestamps_ms;
private:
bool m_swap_endianness = false;
music_selection_context m_context{};
std::unique_ptr<named_thread<std::function<void()>>> m_thread;
};
class video_encoder : public utils::video_sink
{
public:
video_encoder();
~video_encoder();
struct frame_format
{
s32 av_pixel_format = 0; // NOTE: Make sure this is a valid AVPixelFormat
u32 width = 0;
u32 height = 0;
u32 pitch = 0;
std::string to_string() const
{
return fmt::format("{ av_pixel_format=%d, width=%d, height=%d, pitch=%d }", av_pixel_format, width, height, pitch);
}
};
std::string path() const;
s64 last_video_pts() const;
void set_path(const std::string& path);
void set_framerate(u32 framerate);
void set_video_bitrate(u32 bitrate);
void set_output_format(frame_format format);
void set_video_codec(s32 codec_id);
void set_max_b_frames(s32 max_b_frames);
void set_gop_size(s32 gop_size);
void set_sample_rate(u32 sample_rate);
void set_audio_channels(u32 channels);
void set_audio_bitrate(u32 bitrate);
void set_audio_codec(s32 codec_id);
void pause(bool flush = true) override;
void stop(bool flush = true) override;
void resume() override;
void encode();
private:
std::string m_path;
s64 m_last_audio_pts = 0;
s64 m_last_video_pts = 0;
// Thread control
std::unique_ptr<named_thread<std::function<void()>>> m_thread;
atomic_t<bool> m_running = false;
// Video parameters
u32 m_video_bitrate_bps = 0;
s32 m_video_codec_id = 12; // AV_CODEC_ID_MPEG4
s32 m_max_b_frames = 2;
s32 m_gop_size = 12;
frame_format m_out_format{};
// Audio parameters
u32 m_channels = 2;
u32 m_audio_bitrate_bps = 320000;
s32 m_audio_codec_id = 86018; // AV_CODEC_ID_AAC
};
}
| 3,947
|
C++
|
.h
| 125
| 28.688
| 121
| 0.700632
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,659
|
init_mutex.hpp
|
RPCS3_rpcs3/rpcs3/util/init_mutex.hpp
|
#pragma once
#include "util/atomic.hpp"
namespace stx
{
// Mutex designed to support 3 categories of concurrent access to protected resource (initialization, finalization and normal use) while holding the "init" state bit
class init_mutex
{
// Set after initialization and removed before finalization
static constexpr u32 c_init_bit = 0x8000'0000;
// Contains "reader" count and init bit
atomic_t<u32> m_state = 0;
public:
constexpr init_mutex() noexcept = default;
class init_lock final
{
init_mutex* _this;
template <typename Func, typename... Args>
void invoke_callback(int invoke_count, Func&& func, Args&&... args) const
{
std::invoke(func, invoke_count, *this, std::forward<Args>(args)...);
}
public:
template <typename Forced, typename... FAndArgs>
explicit init_lock(init_mutex& mtx, Forced&&, FAndArgs&&... args) noexcept
: _this(&mtx)
{
bool invoked_func = false;
while (true)
{
auto [val, ok] = _this->m_state.fetch_op([](u32& value)
{
if (value == 0)
{
value = 1;
return true;
}
if constexpr (Forced()())
{
if (value & c_init_bit)
{
value -= c_init_bit - 1;
return true;
}
}
return false;
});
if (val == 0)
{
// Success: obtained "init lock"
break;
}
if (val & c_init_bit)
{
if constexpr (Forced()())
{
// Forced reset
val -= c_init_bit - 1;
while (val != 1)
{
if constexpr (sizeof...(FAndArgs))
{
if (!invoked_func)
{
invoke_callback(0, std::forward<FAndArgs>(args)...);
invoked_func = true;
}
}
// Wait for other users to finish their work
_this->m_state.wait(val);
val = _this->m_state;
}
}
// Failure
_this = nullptr;
break;
}
if constexpr (sizeof...(FAndArgs))
{
if (!invoked_func)
{
invoke_callback(0, std::forward<FAndArgs>(args)...);
invoked_func = true;
}
}
_this->m_state.wait(val);
}
// Finalization of wait callback
if constexpr (sizeof...(FAndArgs))
{
if (invoked_func)
{
invoke_callback(1, std::forward<FAndArgs>(args)...);
}
}
}
init_lock(const init_lock&) = delete;
init_lock(init_lock&& lock) noexcept
: _this(std::exchange(lock._this, nullptr))
{
}
init_lock& operator=(const init_lock&) = delete;
~init_lock()
{
if (_this)
{
// Set initialized state and remove "init lock"
_this->m_state += c_init_bit - 1;
_this->m_state.notify_all();
}
}
explicit operator bool() const& noexcept
{
return _this != nullptr;
}
explicit operator bool() && = delete;
void force_lock(init_mutex* mtx)
{
_this = mtx;
}
void cancel() & noexcept
{
if (_this)
{
// Abandon "init lock"
_this->m_state -= 1;
_this->m_state.notify_all();
_this = nullptr;
}
}
init_mutex* get_mutex()
{
return _this;
}
};
// Obtain exclusive lock to initialize protected resource. Waits for ongoing initialization or finalization. Fails if already initialized.
template <typename... FAndArgs>
[[nodiscard]] init_lock init(FAndArgs&&... args) noexcept
{
return init_lock(*this, std::false_type{}, std::forward<FAndArgs>(args)...);
}
// Same as init, but never fails, and executes provided `on_reset` function if already initialized.
template <typename F, typename... Args>
[[nodiscard]] init_lock init_always(F on_reset, Args&&... args) noexcept
{
init_lock lock(*this, std::true_type{});
if (!lock)
{
lock.force_lock(this);
std::invoke(std::forward<F>(on_reset), std::forward<Args>(args)...);
}
return lock;
}
class reset_lock final
{
init_lock _lock;
public:
explicit reset_lock(init_lock&& lock) noexcept
: _lock(std::move(lock))
{
}
reset_lock(const reset_lock&) = delete;
reset_lock& operator=(const reset_lock&) = delete;
~reset_lock()
{
if (_lock)
{
// Set uninitialized state and remove "init lock"
_lock.cancel();
}
}
explicit operator bool() const& noexcept
{
return !!_lock;
}
explicit operator bool() && = delete;
void set_init() & noexcept
{
if (_lock)
{
// Set initialized state (TODO?)
_lock.get_mutex()->m_state |= c_init_bit;
_lock.get_mutex()->m_state.notify_all();
}
}
};
// Obtain exclusive lock to finalize protected resource. Waits for ongoing use. Fails if not initialized.
template <typename F, typename... Args>
[[nodiscard]] reset_lock reset(F on_reset, Args&&... args) noexcept
{
init_lock lock(*this, std::true_type{}, std::forward<F>(on_reset), std::forward<Args>(args)...);
if (!lock)
{
lock.force_lock(this);
}
else
{
lock.cancel();
}
return reset_lock(std::move(lock));
}
[[nodiscard]] reset_lock reset() noexcept
{
init_lock lock(*this, std::true_type{});
if (!lock)
{
lock.force_lock(this);
}
else
{
lock.cancel();
}
return reset_lock(std::move(lock));
}
class access_lock final
{
init_mutex* _this;
public:
explicit access_lock(init_mutex& mtx) noexcept
: _this(&mtx)
{
auto [val, ok] = _this->m_state.fetch_op([](u32& value)
{
if (value & c_init_bit)
{
// Add "access lock"
value += 1;
return true;
}
return false;
});
if (!ok)
{
_this = nullptr;
return;
}
}
access_lock(const access_lock&) = delete;
access_lock& operator=(const access_lock&) = delete;
~access_lock()
{
if (_this)
{
// TODO: check condition
if (--_this->m_state <= 1)
{
_this->m_state.notify_all();
}
}
}
explicit operator bool() const& noexcept
{
return _this != nullptr;
}
explicit operator bool() && = delete;
};
// Obtain shared lock to use protected resource. Fails if not initialized.
[[nodiscard]] access_lock access() noexcept
{
return access_lock(*this);
}
// Simple state test. Hard to use, easy to misuse.
bool volatile_is_initialized() const noexcept
{
return (m_state & c_init_bit) != 0;
}
// Wait for access()
void wait_for_initialized() const noexcept
{
const u32 state = m_state;
if (state & c_init_bit)
{
return;
}
m_state.wait(state);
}
};
using init_lock = init_mutex::init_lock;
using reset_lock = init_mutex::reset_lock;
using access_lock = init_mutex::access_lock;
}
| 6,711
|
C++
|
.h
| 280
| 18.921429
| 166
| 0.594883
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,660
|
video_provider.h
|
RPCS3_rpcs3/rpcs3/util/video_provider.h
|
#pragma once
#include "video_sink.h"
enum class recording_mode
{
stopped = 0,
rpcs3,
cell
};
namespace utils
{
class video_provider
{
public:
video_provider() = default;
~video_provider();
bool set_video_sink(std::shared_ptr<video_sink> sink, recording_mode type);
void set_pause_time_us(usz pause_time_us);
bool can_consume_frame();
void present_frame(std::vector<u8>& data, u32 pitch, u32 width, u32 height, bool is_bgra);
void present_samples(u8* buf, u32 sample_count, u16 channels);
private:
recording_mode check_mode();
recording_mode m_type = recording_mode::stopped;
std::shared_ptr<video_sink> m_video_sink;
shared_mutex m_video_mutex{};
shared_mutex m_audio_mutex{};
atomic_t<bool> m_active{false};
atomic_t<usz> m_start_time_us{umax};
s64 m_last_video_pts_incoming = -1;
s64 m_last_audio_pts_incoming = -1;
usz m_pause_time_us = 0;
};
} // namespace utils
| 918
|
C++
|
.h
| 33
| 25.272727
| 92
| 0.72032
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,661
|
dyn_lib.hpp
|
RPCS3_rpcs3/rpcs3/util/dyn_lib.hpp
|
#pragma once
#include <string>
namespace utils
{
class dynamic_library
{
void* m_handle = nullptr;
public:
dynamic_library() = default;
dynamic_library(const std::string& path);
dynamic_library(const dynamic_library&) = delete;
dynamic_library(dynamic_library&& other) noexcept
: m_handle(other.m_handle)
{
other.m_handle = nullptr;
}
dynamic_library& operator=(const dynamic_library&) = delete;
dynamic_library& operator=(dynamic_library&& other) noexcept
{
std::swap(m_handle, other.m_handle);
return *this;
}
~dynamic_library();
bool load(const std::string& path);
void close();
private:
void* get_impl(const std::string& name) const;
public:
template <typename Type = void>
Type* get(const std::string& name) const
{
Type* result;
*reinterpret_cast<void**>(&result) = get_impl(name);
return result;
}
template <typename Type>
bool get(Type*& function, const std::string& name) const
{
*reinterpret_cast<void**>(&function) = get_impl(name);
return function != nullptr;
}
bool loaded() const;
explicit operator bool() const;
};
// (assume the lib is always loaded)
void* get_proc_address(const char* lib, const char* name);
template <typename F>
struct dynamic_import
{
static_assert(sizeof(F) == 0, "Invalid function type");
};
template <typename R, typename... Args>
struct dynamic_import<R(Args...)>
{
atomic_t<uptr> ptr;
const char* const lib;
const char* const name;
// Constant initialization
constexpr dynamic_import(const char* lib, const char* name) noexcept
: ptr(-1)
, lib(lib)
, name(name)
{
}
void init() noexcept
{
ptr.release(reinterpret_cast<uptr>(get_proc_address(lib, name)));
}
operator bool() noexcept
{
if (ptr == umax) [[unlikely]]
{
init();
}
return ptr != 0;
}
// Caller
R operator()(Args... args) noexcept
{
if (ptr == umax) [[unlikely]]
{
init();
}
return reinterpret_cast<R (*)(Args...)>(ptr.load())(args...);
}
};
}
#define DYNAMIC_IMPORT(lib, name, ...) inline constinit utils::dynamic_import<__VA_ARGS__> name(lib, #name);
#define DYNAMIC_IMPORT_RENAME(lib, declare_name, lib_func_name, ...) inline constinit utils::dynamic_import<__VA_ARGS__> declare_name(lib, lib_func_name);
| 2,316
|
C++
|
.h
| 89
| 22.707865
| 154
| 0.675897
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
5,662
|
asm.hpp
|
RPCS3_rpcs3/rpcs3/util/asm.hpp
|
#pragma once
#include "util/types.hpp"
#include "util/tsc.hpp"
#include "util/atomic.hpp"
#include <functional>
extern bool g_use_rtm;
extern u64 g_rtm_tx_limit1;
#ifdef _M_X64
#ifdef _MSC_VER
extern "C"
{
u32 _xbegin();
void _xend();
void _mm_pause();
void _mm_prefetch(const char*, int);
void _m_prefetchw(const volatile void*);
uchar _rotl8(uchar, uchar);
ushort _rotl16(ushort, uchar);
u64 __popcnt64(u64);
s64 __mulh(s64, s64);
u64 __umulh(u64, u64);
s64 _div128(s64, s64, s64, s64*);
u64 _udiv128(u64, u64, u64, u64*);
void __debugbreak();
}
#include <intrin.h>
#else
#include <immintrin.h>
#endif
#endif
namespace utils
{
// Transaction helper (result = pair of success and op result, or just bool)
template <typename F, typename R = std::invoke_result_t<F>>
inline auto tx_start(F op)
{
#if defined(ARCH_X64)
uint status = -1;
for (auto stamp0 = get_tsc(), stamp1 = stamp0; g_use_rtm && stamp1 - stamp0 <= g_rtm_tx_limit1; stamp1 = get_tsc())
{
#ifndef _MSC_VER
__asm__ goto ("xbegin %l[retry];" ::: "memory" : retry);
#else
status = _xbegin();
if (status != _XBEGIN_STARTED) [[unlikely]]
{
goto retry;
}
#endif
if constexpr (std::is_void_v<R>)
{
std::invoke(op);
#ifndef _MSC_VER
__asm__ volatile ("xend;" ::: "memory");
#else
_xend();
#endif
return true;
}
else
{
auto result = std::invoke(op);
#ifndef _MSC_VER
__asm__ volatile ("xend;" ::: "memory");
#else
_xend();
#endif
return std::make_pair(true, std::move(result));
}
retry:
#ifndef _MSC_VER
__asm__ volatile ("movl %%eax, %0;" : "=r" (status) :: "memory");
#endif
if (!status) [[unlikely]]
{
break;
}
}
#else
static_cast<void>(op);
#endif
if constexpr (std::is_void_v<R>)
{
return false;
}
else
{
return std::make_pair(false, R());
}
};
// Try to prefetch to Level 2 cache since it's not split to data/code on most processors
template <typename T>
constexpr void prefetch_exec(T func)
{
if (std::is_constant_evaluated())
{
return;
}
const u64 value = reinterpret_cast<u64>(func);
const void* ptr = reinterpret_cast<const void*>(value);
#ifdef _M_X64
return _mm_prefetch(static_cast<const char*>(ptr), _MM_HINT_T1);
#else
return __builtin_prefetch(ptr, 0, 2);
#endif
}
// Try to prefetch to Level 1 cache
constexpr void prefetch_read(const void* ptr)
{
if (std::is_constant_evaluated())
{
return;
}
#ifdef _M_X64
return _mm_prefetch(static_cast<const char*>(ptr), _MM_HINT_T0);
#else
return __builtin_prefetch(ptr, 0, 3);
#endif
}
constexpr void prefetch_write(void* ptr)
{
if (std::is_constant_evaluated())
{
return;
}
#if defined(_M_X64) && !defined(__clang__)
return _m_prefetchw(ptr);
#else
return __builtin_prefetch(ptr, 1, 0);
#endif
}
constexpr u8 rol8(u8 x, u8 n)
{
if (std::is_constant_evaluated())
{
return (x << (n & 7)) | (x >> ((-n & 7)));
}
#ifdef _MSC_VER
return _rotl8(x, n);
#elif defined(__clang__)
return __builtin_rotateleft8(x, n);
#elif defined(ARCH_X64)
return __builtin_ia32_rolqi(x, n);
#else
return (x << (n & 7)) | (x >> ((-n & 7)));
#endif
}
constexpr u16 rol16(u16 x, u16 n)
{
if (std::is_constant_evaluated())
{
return (x << (n & 15)) | (x >> ((-n & 15)));
}
#ifdef _MSC_VER
return _rotl16(x, static_cast<uchar>(n));
#elif defined(__clang__)
return __builtin_rotateleft16(x, n);
#elif defined(ARCH_X64)
return __builtin_ia32_rolhi(x, n);
#else
return (x << (n & 15)) | (x >> ((-n & 15)));
#endif
}
constexpr u32 rol32(u32 x, u32 n)
{
if (std::is_constant_evaluated())
{
return (x << (n & 31)) | (x >> (((0 - n) & 31)));
}
#ifdef _MSC_VER
return _rotl(x, n);
#elif defined(__clang__)
return __builtin_rotateleft32(x, n);
#else
return (x << (n & 31)) | (x >> (((0 - n) & 31)));
#endif
}
constexpr u64 rol64(u64 x, u64 n)
{
if (std::is_constant_evaluated())
{
return (x << (n & 63)) | (x >> (((0 - n) & 63)));
}
#ifdef _MSC_VER
return _rotl64(x, static_cast<int>(n));
#elif defined(__clang__)
return __builtin_rotateleft64(x, n);
#else
return (x << (n & 63)) | (x >> (((0 - n) & 63)));
#endif
}
constexpr u32 popcnt64(u64 v)
{
#if !defined(_MSC_VER) || defined(__SSE4_2__)
if (std::is_constant_evaluated())
#endif
{
v = (v & 0xaaaaaaaaaaaaaaaa) / 2 + (v & 0x5555555555555555);
v = (v & 0xcccccccccccccccc) / 4 + (v & 0x3333333333333333);
v = (v & 0xf0f0f0f0f0f0f0f0) / 16 + (v & 0x0f0f0f0f0f0f0f0f);
v = (v & 0xff00ff00ff00ff00) / 256 + (v & 0x00ff00ff00ff00ff);
v = ((v & 0xffff0000ffff0000) >> 16) + (v & 0x0000ffff0000ffff);
return static_cast<u32>((v >> 32) + v);
}
#if !defined(_MSC_VER) || defined(__SSE4_2__)
#ifdef _MSC_VER
return static_cast<u32>(__popcnt64(v));
#else
return __builtin_popcountll(v);
#endif
#endif
}
constexpr u32 popcnt128(const u128& v)
{
#ifdef _MSC_VER
return popcnt64(v.lo) + popcnt64(v.hi);
#else
return popcnt64(v) + popcnt64(v >> 64);
#endif
}
constexpr u64 umulh64(u64 x, u64 y)
{
#ifdef _MSC_VER
if (std::is_constant_evaluated())
#endif
{
return static_cast<u64>((u128{x} * u128{y}) >> 64);
}
#ifdef _MSC_VER
return __umulh(x, y);
#endif
}
inline s64 mulh64(s64 x, s64 y)
{
#ifdef _MSC_VER
return __mulh(x, y);
#else
return (s128{x} * s128{y}) >> 64;
#endif
}
inline s64 div128(s64 high, s64 low, s64 divisor, s64* remainder = nullptr)
{
#ifdef _MSC_VER
s64 rem = 0;
s64 r = _div128(high, low, divisor, &rem);
if (remainder)
{
*remainder = rem;
}
#else
const s128 x = (u128{static_cast<u64>(high)} << 64) | u64(low);
const s128 r = x / divisor;
if (remainder)
{
*remainder = x % divisor;
}
#endif
return r;
}
inline u64 udiv128(u64 high, u64 low, u64 divisor, u64* remainder = nullptr)
{
#ifdef _MSC_VER
u64 rem = 0;
u64 r = _udiv128(high, low, divisor, &rem);
if (remainder)
{
*remainder = rem;
}
#else
const u128 x = (u128{high} << 64) | low;
const u128 r = x / divisor;
if (remainder)
{
*remainder = x % divisor;
}
#endif
return r;
}
#ifdef _MSC_VER
inline u128 operator/(u128 lhs, u64 rhs)
{
u64 rem = 0;
return _udiv128(lhs.hi, lhs.lo, rhs, &rem);
}
#endif
constexpr u32 ctz128(u128 arg)
{
#ifdef _MSC_VER
if (!arg.lo)
return std::countr_zero(arg.hi) + 64u;
else
return std::countr_zero(arg.lo);
#else
if (u64 lo = static_cast<u64>(arg))
return std::countr_zero<u64>(lo);
else
return std::countr_zero<u64>(arg >> 64) + 64;
#endif
}
constexpr u32 clz128(u128 arg)
{
#ifdef _MSC_VER
if (arg.hi)
return std::countl_zero(arg.hi);
else
return std::countl_zero(arg.lo) + 64;
#else
if (u64 hi = static_cast<u64>(arg >> 64))
return std::countl_zero<u64>(hi);
else
return std::countl_zero<u64>(arg) + 64;
#endif
}
inline void pause()
{
#if defined(ARCH_ARM64)
__asm__ volatile("yield");
#elif defined(_M_X64)
_mm_pause();
#elif defined(ARCH_X64)
__builtin_ia32_pause();
#else
#error "Missing utils::pause() implementation"
#endif
}
// Synchronization helper (cache-friendly busy waiting)
inline void busy_wait(usz cycles = 3000)
{
const u64 stop = get_tsc() + cycles;
do pause();
while (get_tsc() < stop);
}
// Align to power of 2
template <typename T, typename U, typename = std::enable_if_t<std::is_unsigned_v<T>>>
constexpr std::make_unsigned_t<std::common_type_t<T, U>> align(T value, U align)
{
return static_cast<std::make_unsigned_t<std::common_type_t<T, U>>>((value + (align - 1)) & (T{0} - align));
}
// General purpose aligned division, the result is rounded up not truncated
template <typename T, typename = std::enable_if_t<std::is_unsigned_v<T>>>
constexpr T aligned_div(T value, std::type_identity_t<T> align)
{
return static_cast<T>(value / align + T{!!(value % align)});
}
// General purpose aligned division, the result is rounded to nearest
template <typename T, typename = std::enable_if_t<std::is_integral_v<T>>>
constexpr T rounded_div(T value, std::type_identity_t<T> align)
{
if constexpr (std::is_unsigned_v<T>)
{
return static_cast<T>(value / align + T{(value % align) > (align / 2)});
}
return static_cast<T>(value / align + (value > 0 ? T{(value % align) > (align / 2)} : 0 - T{(value % align) < (align / 2)}));
}
// Multiplying by ratio, semi-resistant to overflows
template <UnsignedInt T>
constexpr T rational_mul(T value, std::type_identity_t<T> numerator, std::type_identity_t<T> denominator)
{
if constexpr (sizeof(T) <= sizeof(u64) / 2)
{
return static_cast<T>(value * u64{numerator} / u64{denominator});
}
#if is_u128_emulated
if constexpr (sizeof(T) <= sizeof(u128) / 2)
{
return static_cast<T>(u128_from_mul(value, numerator) / u64{denominator});
}
#endif
return static_cast<T>(value / denominator * numerator + (value % denominator) * numerator / denominator);
}
template <UnsignedInt T>
constexpr T add_saturate(T addend1, T addend2)
{
return static_cast<T>(~addend1) < addend2 ? T{umax} : static_cast<T>(addend1 + addend2);
}
template <UnsignedInt T>
constexpr T sub_saturate(T minuend, T subtrahend)
{
return minuend < subtrahend ? T{0} : static_cast<T>(minuend - subtrahend);
}
template <UnsignedInt T>
constexpr T mul_saturate(T factor1, T factor2)
{
return factor1 > 0 && T{umax} / factor1 < factor2 ? T{umax} : static_cast<T>(factor1 * factor2);
}
inline void trigger_write_page_fault(void* ptr)
{
#if defined(ARCH_X64) && !defined(_MSC_VER)
__asm__ volatile("lock orl $0, 0(%0)" :: "r" (ptr));
#elif defined(ARCH_ARM64)
u32 value = 0;
u32* u32_ptr = static_cast<u32*>(ptr);
__asm__ volatile("ldset %w0, %w0, %1" : "+r"(value), "=Q"(*u32_ptr) : "r"(value));
#else
*static_cast<atomic_t<u32> *>(ptr) += 0;
#endif
}
inline void trap()
{
#ifdef _M_X64
__debugbreak();
#elif defined(ARCH_X64)
__asm__ volatile("int3");
#elif defined(ARCH_ARM64)
__asm__ volatile("brk 0x42");
#else
#error "Missing utils::trap() implementation"
#endif
}
} // namespace utils
using utils::busy_wait;
#ifdef _MSC_VER
using utils::operator/;
#endif
| 10,106
|
C++
|
.h
| 414
| 21.934783
| 127
| 0.646357
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
5,663
|
sysinfo.hpp
|
RPCS3_rpcs3/rpcs3/util/sysinfo.hpp
|
#pragma once
#include "util/types.hpp"
#include <string>
namespace utils
{
bool has_ssse3();
bool has_sse41();
bool has_avx();
bool has_avx2();
bool has_rtm();
bool has_tsx_force_abort();
bool has_rtm_always_abort();
bool has_mpx();
bool has_avx512();
bool has_avx512_icl();
bool has_avx512_vnni();
bool has_avx10();
bool has_avx10_512();
u32 avx10_isa_version();
bool has_avx512_256();
bool has_avx512_icl_256();
bool has_xop();
bool has_clwb();
bool has_invariant_tsc();
bool has_fma3();
bool has_fma4();
bool has_fast_vperm2b();
bool has_erms();
bool has_fsrm();
bool has_waitx();
bool has_waitpkg();
bool has_appropriate_um_wait();
bool has_um_wait();
std::string get_cpu_brand();
std::string get_system_info();
std::string get_firmware_version();
std::string get_OS_version();
int get_maxfiles();
bool get_low_power_mode();
u64 get_total_memory();
u32 get_thread_count();
u32 get_cpu_family();
u32 get_cpu_model();
// A threshold of 0xFFFFFFFF means that the rep movsb is expected to be slow on this platform
u32 get_rep_movsb_threshold();
u64 _get_main_tid();
inline const u64 main_tid = _get_main_tid();
extern u64 s_tsc_freq;
inline ullong get_tsc_freq()
{
return s_tsc_freq;
}
}
| 1,283
|
C++
|
.h
| 53
| 21.415094
| 94
| 0.704142
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,664
|
serialization_ext.hpp
|
RPCS3_rpcs3/rpcs3/util/serialization_ext.hpp
|
#pragma once
#include "util/serialization.hpp"
#include "util/shared_ptr.hpp"
#include "Utilities/Thread.h"
#include <deque>
namespace fs
{
class file;
}
// Uncompressed file serialization handler
struct uncompressed_serialization_file_handler : utils::serialization_file_handler
{
const std::unique_ptr<fs::file> m_file_storage;
const std::add_pointer_t<const fs::file> m_file;
explicit uncompressed_serialization_file_handler(fs::file&& file) noexcept
: utils::serialization_file_handler()
, m_file_storage(std::make_unique<fs::file>(std::move(file)))
, m_file(m_file_storage.get())
{
}
explicit uncompressed_serialization_file_handler(const fs::file& file) noexcept
: utils::serialization_file_handler()
, m_file_storage(nullptr)
, m_file(std::addressof(file))
{
}
uncompressed_serialization_file_handler(const uncompressed_serialization_file_handler&) = delete;
uncompressed_serialization_file_handler& operator=(const uncompressed_serialization_file_handler&) = delete;
// Handle file read and write requests
bool handle_file_op(utils::serial& ar, usz pos, usz size, const void* data) override;
// Get available memory or file size
// Preferably memory size if is already greater/equal to recommended to avoid additional file ops
usz get_size(const utils::serial& ar, usz recommended) const override;
void finalize(utils::serial& ar) override;
};
template <typename File> requires (std::is_same_v<std::remove_cvref_t<File>, fs::file>)
inline std::unique_ptr<uncompressed_serialization_file_handler> make_uncompressed_serialization_file_handler(File&& file)
{
ensure(file);
return std::make_unique<uncompressed_serialization_file_handler>(std::forward<File>(file));
}
struct compressed_stream_data;
// Compressed file serialization handler
struct compressed_serialization_file_handler : utils::serialization_file_handler
{
explicit compressed_serialization_file_handler(fs::file&& file) noexcept
: utils::serialization_file_handler()
, m_file_storage(std::make_unique<fs::file>(std::move(file)))
, m_file(m_file_storage.get())
{
}
explicit compressed_serialization_file_handler(const fs::file& file) noexcept
: utils::serialization_file_handler()
, m_file_storage(nullptr)
, m_file(std::addressof(file))
{
}
compressed_serialization_file_handler(const compressed_serialization_file_handler&) = delete;
compressed_serialization_file_handler& operator=(const compressed_serialization_file_handler&) = delete;
// Handle file read and write requests
bool handle_file_op(utils::serial& ar, usz pos, usz size, const void* data) override;
// Get available memory or file size
// Preferably memory size if is already greater/equal to recommended to avoid additional file ops
usz get_size(const utils::serial& ar, usz recommended) const override;
void skip_until(utils::serial& ar) override;
bool is_valid() const override
{
return !m_errored;
}
void finalize(utils::serial& ar) override;
private:
const std::unique_ptr<fs::file> m_file_storage;
const std::add_pointer_t<const fs::file> m_file;
std::vector<u8> m_stream_data;
usz m_stream_data_index = 0;
usz m_file_read_index = 0;
atomic_t<usz> m_pending_bytes = 0;
atomic_t<bool> m_pending_signal = false;
bool m_write_inited = false;
bool m_read_inited = false;
bool m_errored = false;
std::shared_ptr<compressed_stream_data> m_stream;
std::unique_ptr<named_thread<std::function<void()>>> m_stream_data_prepare_thread;
std::unique_ptr<named_thread<std::function<void()>>> m_file_writer_thread;
usz read_at(utils::serial& ar, usz read_pos, void* data, usz size);
void initialize(utils::serial& ar);
void stream_data_prepare_thread_op();
void file_writer_thread_op();
void blocked_compressed_write(const std::vector<u8>& data);
};
template <typename File> requires (std::is_same_v<std::remove_cvref_t<File>, fs::file>)
inline std::unique_ptr<compressed_serialization_file_handler> make_compressed_serialization_file_handler(File&& file)
{
ensure(file);
return std::make_unique<compressed_serialization_file_handler>(std::forward<File>(file));
}
struct compressed_zstd_stream_data;
// Compressed file serialization handler
struct compressed_zstd_serialization_file_handler : utils::serialization_file_handler
{
explicit compressed_zstd_serialization_file_handler(fs::file&& file) noexcept
: utils::serialization_file_handler()
, m_file_storage(std::make_unique<fs::file>(std::move(file)))
, m_file(m_file_storage.get())
{
}
explicit compressed_zstd_serialization_file_handler(const fs::file& file) noexcept
: utils::serialization_file_handler()
, m_file_storage(nullptr)
, m_file(std::addressof(file))
{
}
compressed_zstd_serialization_file_handler(const compressed_zstd_serialization_file_handler&) = delete;
compressed_zstd_serialization_file_handler& operator=(const compressed_zstd_serialization_file_handler&) = delete;
// Handle file read and write requests
bool handle_file_op(utils::serial& ar, usz pos, usz size, const void* data) override;
// Get available memory or file size
// Preferably memory size if is already greater/equal to recommended to avoid additional file ops
usz get_size(const utils::serial& ar, usz recommended) const override;
void skip_until(utils::serial& ar) override;
bool is_valid() const override
{
return !m_errored;
}
void finalize(utils::serial& ar) override;
private:
const std::unique_ptr<fs::file> m_file_storage;
const std::add_pointer_t<const fs::file> m_file;
std::vector<u8> m_stream_data;
usz m_stream_data_index = 0;
usz m_file_read_index = 0;
atomic_t<usz> m_pending_bytes = 0;
atomic_t<bool> m_pending_signal = false;
bool m_write_inited = false;
bool m_read_inited = false;
atomic_t<bool> m_errored = false;
usz m_input_buffer_index = 0;
atomic_t<usz> m_output_buffer_index = 0;
atomic_t<usz> m_thread_buffer_index = 0;
struct compression_thread_context_t
{
atomic_ptr<std::vector<u8>> m_input;
atomic_ptr<std::vector<u8>> m_output;
bool notified = false;
std::unique_ptr<named_thread<std::function<void()>>> m_thread;
};
std::deque<compression_thread_context_t> m_compression_threads;
std::shared_ptr<compressed_zstd_stream_data> m_stream;
std::unique_ptr<named_thread<std::function<void()>>> m_file_writer_thread;
usz read_at(utils::serial& ar, usz read_pos, void* data, usz size);
void initialize(utils::serial& ar);
void stream_data_prepare_thread_op();
void file_writer_thread_op();
void blocked_compressed_write(const std::vector<u8>& data);
};
template <typename File> requires (std::is_same_v<std::remove_cvref_t<File>, fs::file>)
inline std::unique_ptr<compressed_zstd_serialization_file_handler> make_compressed_zstd_serialization_file_handler(File&& file)
{
ensure(file);
return std::make_unique<compressed_zstd_serialization_file_handler>(std::forward<File>(file));
}
// Null file serialization handler
struct null_serialization_file_handler : utils::serialization_file_handler
{
explicit null_serialization_file_handler() noexcept
{
}
// Handle file read and write requests
bool handle_file_op(utils::serial& ar, usz pos, usz size, const void* data) override;
void finalize(utils::serial& ar) override;
bool is_null() const override
{
return true;
}
};
inline std::unique_ptr<null_serialization_file_handler> make_null_serialization_file_handler()
{
return std::make_unique<null_serialization_file_handler>();
}
| 7,423
|
C++
|
.h
| 179
| 39.335196
| 127
| 0.763538
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,665
|
fnv_hash.hpp
|
RPCS3_rpcs3/rpcs3/util/fnv_hash.hpp
|
#pragma once
#include "util/types.hpp"
#include <cstring>
namespace rpcs3
{
constexpr usz fnv_seed = 14695981039346656037ull;
constexpr usz fnv_prime = 1099511628211ull;
template <typename T>
static usz hash_base(T value)
{
return static_cast<usz>(value);
}
template <typename T, typename = std::enable_if_t<std::is_integral_v<T>>>
static inline usz hash64(usz hash_value, T data)
{
hash_value ^= data;
hash_value *= fnv_prime;
return hash_value;
}
template <typename T, typename U>
static usz hash_struct_base(const T& value)
{
// FNV 64-bit
usz result = fnv_seed;
const uchar* bits = reinterpret_cast<const uchar*>(&value);
for (usz n = 0; n < (sizeof(T) / sizeof(U)); ++n)
{
U val{};
std::memcpy(&val, bits + (n * sizeof(U)), sizeof(U));
result = hash64(result, val);
}
return result;
}
template <typename T>
static usz hash_struct(const T& value)
{
static constexpr auto block_sz = sizeof(T);
if constexpr ((block_sz & 0x7) == 0)
{
return hash_struct_base<T, u64>(value);
}
if constexpr ((block_sz & 0x3) == 0)
{
return hash_struct_base<T, u32>(value);
}
if constexpr ((block_sz & 0x1) == 0)
{
return hash_struct_base<T, u16>(value);
}
return hash_struct_base<T, u8>(value);
}
}
| 1,339
|
C++
|
.h
| 52
| 21.75
| 75
| 0.645289
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
5,666
|
tsc.hpp
|
RPCS3_rpcs3/rpcs3/util/tsc.hpp
|
#pragma once
#include "util/types.hpp"
#ifdef _M_X64
#ifdef _MSC_VER
extern "C" u64 __rdtsc();
#else
#include <immintrin.h>
#endif
#endif
namespace utils
{
inline u64 get_tsc()
{
#if defined(ARCH_ARM64)
u64 r = 0;
__asm__ volatile("mrs %0, cntvct_el0" : "=r" (r));
return r;
#elif defined(_M_X64)
return __rdtsc();
#elif defined(ARCH_X64)
return __builtin_ia32_rdtsc();
#else
#error "Missing utils::get_tsc() implementation"
#endif
}
}
| 452
|
C++
|
.h
| 26
| 15.769231
| 52
| 0.690307
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
5,667
|
simd.hpp
|
RPCS3_rpcs3/rpcs3/util/simd.hpp
|
#pragma once
#include "util/types.hpp"
#include "util/v128.hpp"
#include "util/sysinfo.hpp"
#include "util/asm.hpp"
#include "Utilities/JIT.h"
#if defined(ARCH_X64)
#ifdef _MSC_VER
#include <intrin.h>
#else
#include <x86intrin.h>
#endif
#include <immintrin.h>
#include <emmintrin.h>
#endif
#if defined(ARCH_ARM64)
#include <arm_neon.h>
#endif
#include <cmath>
#include <math.h>
#include <cfenv>
#if defined(__clang__)
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wunused-parameter"
#elif defined(__GNUC__)
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunused-parameter"
#endif
namespace asmjit
{
struct vec_builder;
}
inline thread_local asmjit::vec_builder* g_vc = nullptr;
namespace asmjit
{
#if defined(ARCH_X64)
using gpr_type = x86::Gp;
using vec_type = x86::Xmm;
using mem_type = x86::Mem;
#else
struct gpr_type : Operand
{
gpr_type() = default;
gpr_type(u32)
{
}
};
struct vec_type : Operand
{
vec_type() = default;
vec_type(u32)
{
}
};
struct mem_type : Operand
{
};
#endif
struct mem_lazy : Operand
{
const Operand& eval(bool is_lv);
};
enum class arg_class : u32
{
reg_lv, // const auto x = gv_...(y, z);
reg_rv, // r = gv_...(y, z);
imm_lv,
imm_rv,
mem_lv,
mem_rv,
};
constexpr arg_class operator+(arg_class _base, u32 off)
{
return arg_class(u32(_base) + off);
}
template <typename... Args>
constexpr bool any_operand_v = (std::is_base_of_v<Operand, std::decay_t<Args>> || ...);
template <typename T, typename D = std::decay_t<T>>
constexpr arg_class arg_classify =
std::is_same_v<v128, D> ? arg_class::imm_lv + !std::is_reference_v<T> :
std::is_base_of_v<mem_type, D> ? arg_class::mem_lv :
std::is_base_of_v<mem_lazy, D> ? arg_class::mem_lv + !std::is_reference_v<T> :
std::is_reference_v<T> ? arg_class::reg_lv : arg_class::reg_rv;
struct vec_builder : native_asm
{
using base = native_asm;
bool fail_flag = false;
vec_builder(CodeHolder* ch)
: native_asm(ch)
{
if (!g_vc)
{
g_vc = this;
}
}
~vec_builder()
{
if (g_vc == this)
{
g_vc = nullptr;
}
}
u32 vec_allocated = 0xffffffff << 6;
vec_type vec_alloc()
{
if (!~vec_allocated)
{
fail_flag = true;
return vec_type{0};
}
const u32 idx = std::countr_one(vec_allocated);
vec_allocated |= vec_allocated + 1;
return vec_type{idx};
}
template <u32 Size>
std::array<vec_type, Size> vec_alloc()
{
std::array<vec_type, Size> r;
for (auto& x : r)
{
x = vec_alloc();
}
return r;
}
void vec_dealloc(vec_type vec)
{
vec_allocated &= ~(1u << vec.id());
}
void emit_consts()
{
// (TODO: sort in use order)
for (u32 sz = 1; sz <= 16; sz++)
{
for (auto& [key, _label] : consts[sz - 1])
{
base::align(AlignMode::kData, 1u << std::countr_zero<u32>(sz));
base::bind(_label);
base::embed(&key, sz);
}
}
}
std::unordered_map<v128, Label> consts[16]{};
#if defined(ARCH_X64)
std::unordered_map<v128, vec_type> const_allocs{};
template <typename T, u32 Size = sizeof(T)>
x86::Mem get_const(const T& data, u32 esize = Size)
{
static_assert(Size <= 16);
// Find existing const
v128 key{};
std::memcpy(&key, &data, Size);
if (Size == 16 && esize == 4 && key._u64[0] == key._u64[1] && key._u32[0] == key._u32[1])
{
x86::Mem r = get_const<u32>(key._u32[0]);
r.setBroadcast(x86::Mem::Broadcast::k1To4);
return r;
}
if (Size == 16 && esize == 8 && key._u64[0] == key._u64[1])
{
x86::Mem r = get_const<u64>(key._u64[0]);
r.setBroadcast(x86::Mem::Broadcast::k1To2);
return r;
}
auto& _label = consts[Size - 1][key];
if (!_label.isValid())
_label = base::newLabel();
return x86::Mem(_label, 0, Size);
}
#endif
};
struct free_on_exit
{
Operand x{};
free_on_exit() = default;
free_on_exit(const free_on_exit&) = delete;
free_on_exit& operator=(const free_on_exit&) = delete;
~free_on_exit()
{
if (x.isReg())
{
vec_type v;
v.copyFrom(x);
g_vc->vec_dealloc(v);
}
}
};
#if defined(ARCH_X64)
inline Operand arg_eval(v128& _c, u32 esize)
{
const auto found = g_vc->const_allocs.find(_c);
if (found != g_vc->const_allocs.end())
{
return found->second;
}
vec_type reg = g_vc->vec_alloc();
// TODO: PSHUFD style broadcast? Needs known const layout
if (utils::has_avx() && _c._u64[0] == _c._u64[1])
{
if (_c._u32[0] == _c._u32[1])
{
if (utils::has_avx2() && _c._u16[0] == _c._u16[1])
{
if (_c._u8[0] == _c._u8[1])
{
ensure(!g_vc->vpbroadcastb(reg, g_vc->get_const(_c._u8[0])));
}
else
{
ensure(!g_vc->vpbroadcastw(reg, g_vc->get_const(_c._u16[0])));
}
}
else
{
ensure(!g_vc->vbroadcastss(reg, g_vc->get_const(_c._u32[0])));
}
}
else
{
ensure(!g_vc->vbroadcastsd(reg, g_vc->get_const(_c._u32[0])));
}
}
else if (!_c._u)
{
ensure(!g_vc->pxor(reg, reg));
}
else if (!~_c._u)
{
ensure(!g_vc->pcmpeqd(reg, reg));
}
else
{
ensure(!g_vc->movaps(reg, g_vc->get_const(_c, esize)));
}
g_vc->const_allocs.emplace(_c, reg);
return reg;
}
inline Operand arg_eval(v128&& _c, u32 esize)
{
const auto found = g_vc->const_allocs.find(_c);
if (found != g_vc->const_allocs.end())
{
vec_type r = found->second;
g_vc->const_allocs.erase(found);
g_vc->vec_dealloc(r);
return r;
}
// Hack: assume can use mem op (TODO)
return g_vc->get_const(_c, esize);
}
template <typename T> requires(std::is_base_of_v<mem_lazy, std::decay_t<T>>)
inline decltype(auto) arg_eval(T&& mem, u32)
{
return mem.eval(std::is_reference_v<T>);
}
inline decltype(auto) arg_eval(const Operand& mem, u32)
{
return mem;
}
inline decltype(auto) arg_eval(Operand& mem, u32)
{
return mem;
}
inline decltype(auto) arg_eval(Operand&& mem, u32)
{
return std::move(mem);
}
inline void arg_free(const v128&)
{
}
inline void arg_free(const Operand& op)
{
if (op.isReg())
{
g_vc->vec_dealloc(vec_type{op.id()});
}
}
template <typename T>
inline bool arg_use_evex(const auto& op)
{
constexpr auto _class = arg_classify<T>;
if constexpr (_class == arg_class::imm_rv)
return g_vc->const_allocs.count(op) == 0;
else if constexpr (_class == arg_class::imm_lv)
return false;
else if (op.isMem())
{
// Check if broadcast is set, or if the offset immediate can use disp8*N encoding
mem_type mem{};
mem.copyFrom(op);
if (mem.hasBaseLabel())
return false;
if (mem.hasBroadcast())
return true;
if (!mem.hasOffset() || mem.offset() % mem.size() || u64(mem.offset() + 128) < 256 || u64(mem.offset() / mem.size() + 128) >= 256)
return false;
return true;
}
return false;
}
template <typename A, typename... Args>
vec_type unary_op(x86::Inst::Id op, x86::Inst::Id op2, A&& a, Args&&... args)
{
if constexpr (arg_classify<A> == arg_class::reg_rv)
{
if (op)
{
ensure(!g_vc->emit(op, a, std::forward<Args>(args)...));
}
else
{
ensure(!g_vc->emit(op2, a, a, std::forward<Args>(args)...));
}
return a;
}
else
{
vec_type r = g_vc->vec_alloc();
if (op)
{
if (op2 && utils::has_avx())
{
// Assume op2 is AVX (but could be PSHUFD as well for example)
ensure(!g_vc->emit(op2, r, arg_eval(std::forward<A>(a), 16), std::forward<Args>(args)...));
}
else
{
// TODO
ensure(!g_vc->emit(x86::Inst::Id::kIdMovaps, r, arg_eval(std::forward<A>(a), 16)));
ensure(!g_vc->emit(op, r, std::forward<Args>(args)...));
}
}
else
{
ensure(!g_vc->emit(op2, r, arg_eval(std::forward<A>(a), 16), std::forward<Args>(args)...));
}
return r;
}
}
template <typename D, typename S>
void store_op(x86::Inst::Id op, x86::Inst::Id evex_op, D&& d, S&& s)
{
static_assert(arg_classify<D> == arg_class::mem_lv);
mem_type dst;
dst.copyFrom(arg_eval(std::forward<D>(d), 16));
if (utils::has_avx512() && evex_op)
{
if (!dst.hasBaseLabel() && dst.hasOffset() && dst.offset() % dst.size() == 0 && u64(dst.offset() + 128) >= 256 && u64(dst.offset() / dst.size() + 128) < 256)
{
ensure(!g_vc->evex().emit(evex_op, dst, arg_eval(std::forward<S>(s), 16)));
return;
}
}
ensure(!g_vc->emit(op, dst, arg_eval(std::forward<S>(s), 16)));
}
template <typename A, typename B, typename... Args>
vec_type binary_op(u32 esize, x86::Inst::Id mov_op, x86::Inst::Id sse_op, x86::Inst::Id avx_op, x86::Inst::Id evex_op, A&& a, B&& b, Args&&... args)
{
free_on_exit e;
Operand src1{};
if constexpr (arg_classify<A> == arg_class::reg_rv)
{
// Use src1 as a destination
src1 = arg_eval(std::forward<A>(a), 16);
if (utils::has_avx512() && evex_op && arg_use_evex<B>(b))
{
ensure(!g_vc->evex().emit(evex_op, src1, src1, arg_eval(std::forward<B>(b), esize), std::forward<Args>(args)...));
return vec_type{src1.id()};
}
if constexpr (arg_classify<B> == arg_class::reg_rv)
{
e.x = b;
}
}
else if (utils::has_avx() && avx_op && (arg_classify<A> == arg_class::reg_lv || arg_classify<A> == arg_class::mem_lv))
{
Operand srca = arg_eval(std::forward<A>(a), 16);
if constexpr (arg_classify<A> == arg_class::reg_lv)
{
if constexpr (arg_classify<B> == arg_class::reg_rv)
{
// Use src2 as a destination
src1 = arg_eval(std::forward<B>(b), 16);
}
else
{
// Use new reg as a destination
src1 = g_vc->vec_alloc();
}
}
else
{
src1 = g_vc->vec_alloc();
if constexpr (arg_classify<B> == arg_class::reg_rv)
{
e.x = b;
}
}
if (utils::has_avx512() && evex_op && arg_use_evex<B>(b))
{
ensure(!g_vc->evex().emit(evex_op, src1, srca, arg_eval(std::forward<B>(b), esize), std::forward<Args>(args)...));
return vec_type{src1.id()};
}
ensure(!g_vc->emit(avx_op, src1, srca, arg_eval(std::forward<B>(b), 16), std::forward<Args>(args)...));
return vec_type{src1.id()};
}
else do
{
if constexpr (arg_classify<A> == arg_class::mem_rv)
{
if (a.isReg())
{
src1 = vec_type(a.id());
if constexpr (arg_classify<B> == arg_class::reg_rv)
{
e.x = b;
}
break;
}
}
if constexpr (arg_classify<A> == arg_class::imm_rv)
{
if (auto found = g_vc->const_allocs.find(a); found != g_vc->const_allocs.end())
{
src1 = found->second;
g_vc->const_allocs.erase(found);
if constexpr (arg_classify<B> == arg_class::reg_rv)
{
e.x = b;
}
break;
}
}
src1 = g_vc->vec_alloc();
if constexpr (arg_classify<B> == arg_class::reg_rv)
{
e.x = b;
}
if constexpr (arg_classify<A> == arg_class::imm_rv)
{
if (!a._u)
{
// All zeros
ensure(!g_vc->emit(x86::Inst::kIdPxor, src1, src1));
break;
}
else if (!~a._u)
{
// All ones
ensure(!g_vc->emit(x86::Inst::kIdPcmpeqd, src1, src1));
break;
}
}
// Fallback to arg copy
ensure(!g_vc->emit(mov_op, src1, arg_eval(std::forward<A>(a), 16)));
}
while (0);
if (utils::has_avx512() && evex_op && arg_use_evex<B>(b))
{
ensure(!g_vc->evex().emit(evex_op, src1, src1, arg_eval(std::forward<B>(b), esize), std::forward<Args>(args)...));
}
else if (sse_op)
{
ensure(!g_vc->emit(sse_op, src1, arg_eval(std::forward<B>(b), 16), std::forward<Args>(args)...));
}
else
{
ensure(!g_vc->emit(avx_op, src1, src1, arg_eval(std::forward<B>(b), 16), std::forward<Args>(args)...));
}
return vec_type{src1.id()};
}
#define FOR_X64(f, ...) do { using enum asmjit::x86::Inst::Id; return asmjit::f(__VA_ARGS__); } while (0)
#elif defined(ARCH_ARM64)
#define FOR_X64(...) do { fmt::throw_exception("Unimplemented for this architecture!"); } while (0)
#endif
}
inline v128 gv_select8(const v128& _cmp, const v128& _true, const v128& _false);
inline v128 gv_signselect8(const v128& bits, const v128& _true, const v128& _false);
inline v128 gv_select16(const v128& _cmp, const v128& _true, const v128& _false);
inline v128 gv_select32(const v128& _cmp, const v128& _true, const v128& _false);
inline v128 gv_selectfs(const v128& _cmp, const v128& _true, const v128& _false);
template <typename A, typename B> requires (asmjit::any_operand_v<A, B>)
inline asmjit::vec_type gv_gts32(A&&, B&&);
inline void gv_set_zeroing_denormals()
{
#if defined(ARCH_X64)
u32 cr = _mm_getcsr();
cr = (cr & ~_MM_FLUSH_ZERO_MASK) | _MM_FLUSH_ZERO_ON;
cr = (cr & ~_MM_DENORMALS_ZERO_MASK) | _MM_DENORMALS_ZERO_ON;
cr = (cr | _MM_MASK_INVALID);
_mm_setcsr(cr);
#elif defined(ARCH_ARM64)
u64 cr;
__asm__ volatile("mrs %0, FPCR" : "=r"(cr));
cr |= 0x1000000ull;
__asm__ volatile("msr FPCR, %0" :: "r"(cr));
#else
#error "Not implemented"
#endif
}
inline void gv_unset_zeroing_denormals()
{
#if defined(ARCH_X64)
u32 cr = _mm_getcsr();
cr = (cr & ~_MM_FLUSH_ZERO_MASK) | _MM_FLUSH_ZERO_OFF;
cr = (cr & ~_MM_DENORMALS_ZERO_MASK) | _MM_DENORMALS_ZERO_OFF;
cr = (cr | _MM_MASK_INVALID);
_mm_setcsr(cr);
#elif defined(ARCH_ARM64)
u64 cr;
__asm__ volatile("mrs %0, FPCR" : "=r"(cr));
cr &= ~0x1000000ull;
__asm__ volatile("msr FPCR, %0" :: "r"(cr));
#else
#error "Not implemented"
#endif
}
inline bool g_use_avx = utils::has_avx();
inline void gv_zeroupper()
{
#if defined(ARCH_X64)
if (!g_use_avx)
return;
#if defined(_M_X64) && defined(_MSC_VER)
_mm256_zeroupper();
#else
__asm__ volatile("vzeroupper;");
#endif
#endif
}
inline v128 gv_bcst8(u8 value)
{
#if defined(ARCH_X64)
return _mm_set1_epi8(value);
#elif defined(ARCH_ARM64)
return vdupq_n_s8(value);
#endif
}
inline v128 gv_bcst16(u16 value)
{
#if defined(ARCH_X64)
return _mm_set1_epi16(value);
#elif defined(ARCH_ARM64)
return vdupq_n_s16(value);
#endif
}
// Optimized broadcast using constant offset assumption
inline v128 gv_bcst16(const u16& value, auto mptr, auto... args)
{
#if defined(ARCH_X64)
const u32 offset = ::offset32(mptr, args...);
[[maybe_unused]] const __m128i* ptr = reinterpret_cast<__m128i*>(uptr(&value) - offset % 16);
#if !defined(__AVX2__)
if (offset % 16 == 0)
return _mm_shuffle_epi32(_mm_shufflelo_epi16(*ptr, 0), 0);
if (offset % 16 == 2)
return _mm_shuffle_epi32(_mm_shufflelo_epi16(*ptr, 0b01010101), 0);
if (offset % 16 == 4)
return _mm_shuffle_epi32(_mm_shufflelo_epi16(*ptr, 0b10101010), 0);
if (offset % 16 == 6)
return _mm_shuffle_epi32(_mm_shufflelo_epi16(*ptr, 0xff), 0);
if (offset % 16 == 8)
return _mm_shuffle_epi32(_mm_shufflehi_epi16(*ptr, 0), 0xff);
if (offset % 16 == 10)
return _mm_shuffle_epi32(_mm_shufflehi_epi16(*ptr, 0b01010101), 0xff);
if (offset % 16 == 12)
return _mm_shuffle_epi32(_mm_shufflehi_epi16(*ptr, 0b10101010), 0xff);
if (offset % 16 == 14)
return _mm_shuffle_epi32(_mm_shufflehi_epi16(*ptr, 0xff), 0xff);
#endif
return _mm_set1_epi16(value);
#else
static_cast<void>(mptr);
return gv_bcst16(value);
#endif
}
inline v128 gv_bcst32(u32 value)
{
#if defined(ARCH_X64)
return _mm_set1_epi32(value);
#elif defined(ARCH_ARM64)
return vdupq_n_s32(value);
#endif
}
// Optimized broadcast using constant offset assumption
inline v128 gv_bcst32(const u32& value, auto mptr, auto... args)
{
#if defined(ARCH_X64)
const u32 offset = ::offset32(mptr, args...);
[[maybe_unused]] const __m128i* ptr = reinterpret_cast<__m128i*>(uptr(&value) - offset % 16);
#if !defined(__AVX__)
if (offset % 16 == 0)
return _mm_shuffle_epi32(*ptr, 0);
if (offset % 16 == 4)
return _mm_shuffle_epi32(*ptr, 0b01010101);
if (offset % 16 == 8)
return _mm_shuffle_epi32(*ptr, 0b10101010);
if (offset % 16 == 12)
return _mm_shuffle_epi32(*ptr, 0xff);
#endif
return _mm_set1_epi32(value);
#else
static_cast<void>(mptr);
return gv_bcst32(value);
#endif
}
inline v128 gv_bcst64(u64 value)
{
#if defined(ARCH_X64)
return _mm_set1_epi64x(value);
#elif defined(ARCH_ARM64)
return vdupq_n_s64(value);
#endif
}
// Optimized broadcast using constant offset assumption
inline v128 gv_bcst64(const u64& value, auto mptr, auto... args)
{
#if defined(ARCH_X64)
const u32 offset = ::offset32(mptr, args...);
[[maybe_unused]] const __m128i* ptr = reinterpret_cast<__m128i*>(uptr(&value) - offset % 16);
#if !defined(__AVX__)
if (offset % 16 == 0)
return _mm_shuffle_epi32(*ptr, 0b00010001);
if (offset % 16 == 8)
return _mm_shuffle_epi32(*ptr, 0b10111011);
#endif
return _mm_set1_epi64x(value);
#else
static_cast<void>(mptr);
return gv_bcst64(value);
#endif
}
inline v128 gv_bcstfs(f32 value)
{
#if defined(ARCH_X64)
return _mm_set1_ps(value);
#elif defined(ARCH_ARM64)
return vdupq_n_f32(value);
#endif
}
inline v128 gv_and32(const v128& a, const v128& b)
{
#if defined(ARCH_X64)
return _mm_and_si128(a, b);
#elif defined(ARCH_ARM64)
return vandq_s32(a, b);
#endif
}
template <typename A, typename B> requires (asmjit::any_operand_v<A, B>)
inline auto gv_and32(A&& a, B&& b)
{
FOR_X64(binary_op, 4, kIdMovdqa, kIdPand, kIdVpand, kIdVpandd, std::forward<A>(a), std::forward<B>(b));
}
inline v128 gv_andfs(const v128& a, const v128& b)
{
#if defined(ARCH_X64)
return _mm_and_ps(a, b);
#elif defined(ARCH_ARM64)
return vandq_s32(a, b);
#endif
}
template <typename A, typename B> requires (asmjit::any_operand_v<A, B>)
inline auto gv_andfs(A&& a, B&& b)
{
FOR_X64(binary_op, 4, kIdMovaps, kIdAndps, kIdVandps, kIdVandps, std::forward<A>(a), std::forward<B>(b));
}
inline v128 gv_andn32(const v128& a, const v128& b)
{
#if defined(ARCH_X64)
return _mm_andnot_si128(a, b);
#elif defined(ARCH_ARM64)
return vbicq_s32(b, a);
#endif
}
template <typename A, typename B> requires (asmjit::any_operand_v<A, B>)
inline auto gv_andn32(A&& a, B&& b)
{
FOR_X64(binary_op, 4, kIdMovdqa, kIdPandn, kIdVpandn, kIdVpandnd, std::forward<A>(a), std::forward<B>(b));
}
inline v128 gv_andnfs(const v128& a, const v128& b)
{
#if defined(ARCH_X64)
return _mm_andnot_ps(a, b);
#elif defined(ARCH_ARM64)
return vbicq_s32(b, a);
#endif
}
template <typename A, typename B> requires (asmjit::any_operand_v<A, B>)
inline auto gv_andnfs(A&& a, B&& b)
{
FOR_X64(binary_op, 4, kIdMovaps, kIdAndnps, kIdVandnps, kIdVandnps, std::forward<A>(a), std::forward<B>(b));
}
inline v128 gv_or32(const v128& a, const v128& b)
{
#if defined(ARCH_X64)
return _mm_or_si128(a, b);
#elif defined(ARCH_ARM64)
return vorrq_s32(a, b);
#endif
}
template <typename A, typename B> requires (asmjit::any_operand_v<A, B>)
inline auto gv_or32(A&& a, B&& b)
{
FOR_X64(binary_op, 4, kIdMovdqa, kIdPor, kIdVpor, kIdVpord, std::forward<A>(a), std::forward<B>(b));
}
inline v128 gv_orfs(const v128& a, const v128& b)
{
#if defined(ARCH_X64)
return _mm_or_ps(a, b);
#elif defined(ARCH_ARM64)
return vorrq_s32(a, b);
#endif
}
template <typename A, typename B> requires (asmjit::any_operand_v<A, B>)
inline auto gv_orfs(A&& a, B&& b)
{
FOR_X64(binary_op, 4, kIdMovaps, kIdOrps, kIdVorps, kIdVorps, std::forward<A>(a), std::forward<B>(b));
}
inline v128 gv_xor32(const v128& a, const v128& b)
{
#if defined(ARCH_X64)
return _mm_xor_si128(a, b);
#elif defined(ARCH_ARM64)
return veorq_s32(a, b);
#endif
}
template <typename A, typename B> requires (asmjit::any_operand_v<A, B>)
inline auto gv_xor32(A&& a, B&& b)
{
FOR_X64(binary_op, 4, kIdMovdqa, kIdPxor, kIdVpxor, kIdVpxord, std::forward<A>(a), std::forward<B>(b));
}
inline v128 gv_xorfs(const v128& a, const v128& b)
{
#if defined(ARCH_X64)
return _mm_xor_ps(a, b);
#elif defined(ARCH_ARM64)
return veorq_s32(a, b);
#endif
}
template <typename A, typename B> requires (asmjit::any_operand_v<A, B>)
inline auto gv_xorfs(A&& a, B&& b)
{
FOR_X64(binary_op, 4, kIdMovaps, kIdXorps, kIdVxorps, kIdVxorps, std::forward<A>(a), std::forward<B>(b));
}
inline v128 gv_not32(const v128& a)
{
#if defined(ARCH_X64)
return _mm_xor_si128(a, _mm_set1_epi32(-1));
#elif defined(ARCH_ARM64)
return vmvnq_u32(a);
#endif
}
template <typename A> requires (asmjit::any_operand_v<A>)
inline auto gv_not32(A&& a)
{
#if defined(ARCH_X64)
asmjit::vec_type ones = g_vc->vec_alloc();
g_vc->pcmpeqd(ones, ones);
FOR_X64(binary_op, 4, kIdMovdqa, kIdPxor, kIdVpxor, kIdVpxord, std::move(ones), std::forward<A>(a));
#endif
}
inline v128 gv_notfs(const v128& a)
{
#if defined(ARCH_X64)
return _mm_xor_ps(a, _mm_castsi128_ps(_mm_set1_epi32(-1)));
#elif defined(ARCH_ARM64)
return vmvnq_u32(a);
#endif
}
template <typename A> requires (asmjit::any_operand_v<A>)
inline auto gv_notfs(A&& a)
{
#if defined(ARCH_X64)
asmjit::vec_type ones = g_vc->vec_alloc();
g_vc->pcmpeqd(ones, ones);
FOR_X64(binary_op, 4, kIdMovaps, kIdXorps, kIdVxorps, kIdVxorps, std::move(ones), std::forward<A>(a));
#endif
}
inline v128 gv_shl16(const v128& a, u32 count)
{
if (count >= 16)
return v128{};
#if defined(ARCH_X64)
return _mm_slli_epi16(a, count);
#elif defined(ARCH_ARM64)
return vshlq_s16(a, vdupq_n_s16(count));
#endif
}
template <typename A> requires (asmjit::any_operand_v<A>)
inline auto gv_shl16(A&& a, u32 count)
{
FOR_X64(unary_op, kIdPsllw, kIdVpsllw, std::forward<A>(a), count);
}
inline v128 gv_shl32(const v128& a, u32 count)
{
if (count >= 32)
return v128{};
#if defined(ARCH_X64)
return _mm_slli_epi32(a, count);
#elif defined(ARCH_ARM64)
return vshlq_s32(a, vdupq_n_s32(count));
#endif
}
template <typename A> requires (asmjit::any_operand_v<A>)
inline auto gv_shl32(A&& a, u32 count)
{
FOR_X64(unary_op, kIdPslld, kIdVpslld, std::forward<A>(a), count);
}
inline v128 gv_shl64(const v128& a, u32 count)
{
if (count >= 64)
return v128{};
#if defined(ARCH_X64)
return _mm_slli_epi64(a, count);
#elif defined(ARCH_ARM64)
return vshlq_s64(a, vdupq_n_s64(count));
#endif
}
template <typename A> requires (asmjit::any_operand_v<A>)
inline auto gv_shl64(A&& a, u32 count)
{
FOR_X64(unary_op, kIdPsllq, kIdVpsllq, std::forward<A>(a), count);
}
inline v128 gv_shr16(const v128& a, u32 count)
{
if (count >= 16)
return v128{};
#if defined(ARCH_X64)
return _mm_srli_epi16(a, count);
#elif defined(ARCH_ARM64)
return vshlq_u16(a, vdupq_n_s16(0 - count));
#endif
}
template <typename A> requires (asmjit::any_operand_v<A>)
inline auto gv_shr16(A&& a, u32 count)
{
FOR_X64(unary_op, kIdPsrlw, kIdVpsrlw, std::forward<A>(a), count);
}
inline v128 gv_shr32(const v128& a, u32 count)
{
if (count >= 32)
return v128{};
#if defined(ARCH_X64)
return _mm_srli_epi32(a, count);
#elif defined(ARCH_ARM64)
return vshlq_u32(a, vdupq_n_s32(0 - count));
#endif
}
template <typename A> requires (asmjit::any_operand_v<A>)
inline auto gv_shr32(A&& a, u32 count)
{
FOR_X64(unary_op, kIdPsrld, kIdVpsrld, std::forward<A>(a), count);
}
inline v128 gv_shr64(const v128& a, u32 count)
{
if (count >= 64)
return v128{};
#if defined(ARCH_X64)
return _mm_srli_epi64(a, count);
#elif defined(ARCH_ARM64)
return vshlq_u64(a, vdupq_n_s64(0 - count));
#endif
}
template <typename A> requires (asmjit::any_operand_v<A>)
inline auto gv_shr64(A&& a, u32 count)
{
FOR_X64(unary_op, kIdPsrlq, kIdVpsrlq, std::forward<A>(a), count);
}
inline v128 gv_sar16(const v128& a, u32 count)
{
if (count >= 16)
count = 15;
#if defined(ARCH_X64)
return _mm_srai_epi16(a, count);
#elif defined(ARCH_ARM64)
return vshlq_s16(a, vdupq_n_s16(0 - count));
#endif
}
template <typename A> requires (asmjit::any_operand_v<A>)
inline auto gv_sar16(A&& a, u32 count)
{
FOR_X64(unary_op, kIdPsraw, kIdVpsraw, std::forward<A>(a), count);
}
inline v128 gv_sar32(const v128& a, u32 count)
{
if (count >= 32)
count = 31;
#if defined(ARCH_X64)
return _mm_srai_epi32(a, count);
#elif defined(ARCH_ARM64)
return vshlq_s32(a, vdupq_n_s32(0 - count));
#endif
}
template <typename A> requires (asmjit::any_operand_v<A>)
inline auto gv_sar32(A&& a, u32 count)
{
FOR_X64(unary_op, kIdPsrad, kIdVpsrad, std::forward<A>(a), count);
}
inline v128 gv_sar64(const v128& a, u32 count)
{
if (count >= 64)
count = 63;
#if defined(__AVX512VL__)
return _mm_srai_epi64(a, count);
#elif defined(__SSE2__) && !defined(_M_X64)
return static_cast<__v2di>(a) >> count;
#elif defined(ARCH_ARM64)
return vshlq_s64(a, vdupq_n_s64(0 - count));
#else
v128 r;
r._s64[0] = a._s64[0] >> count;
r._s64[1] = a._s64[1] >> count;
return r;
#endif
}
template <typename A> requires (asmjit::any_operand_v<A>)
inline auto gv_sar64(A&& a, u32 count)
{
if (count >= 64)
count = 63;
#if defined(ARCH_X64)
using enum asmjit::x86::Inst::Id;
if (utils::has_avx512())
return asmjit::unary_op(kIdNone, kIdVpsraq, std::forward<A>(a), count);
g_vc->fail_flag = true;
return std::forward<A>(a);
#endif
}
inline v128 gv_add8(const v128& a, const v128& b)
{
#if defined(ARCH_X64)
return _mm_add_epi8(a, b);
#elif defined(ARCH_ARM64)
return vaddq_s8(a, b);
#endif
}
template <typename A, typename B> requires (asmjit::any_operand_v<A, B>)
inline auto gv_add8(A&& a, B&& b)
{
FOR_X64(binary_op, 1, kIdMovdqa, kIdPaddb, kIdVpaddb, kIdNone, std::forward<A>(a), std::forward<B>(b));
}
inline v128 gv_add16(const v128& a, const v128& b)
{
#if defined(ARCH_X64)
return _mm_add_epi16(a, b);
#elif defined(ARCH_ARM64)
return vaddq_s16(a, b);
#endif
}
template <typename A, typename B> requires (asmjit::any_operand_v<A, B>)
inline auto gv_add16(A&& a, B&& b)
{
FOR_X64(binary_op, 2, kIdMovdqa, kIdPaddw, kIdVpaddw, kIdNone, std::forward<A>(a), std::forward<B>(b));
}
inline v128 gv_add32(const v128& a, const v128& b)
{
#if defined(ARCH_X64)
return _mm_add_epi32(a, b);
#elif defined(ARCH_ARM64)
return vaddq_s32(a, b);
#endif
}
template <typename A, typename B> requires (asmjit::any_operand_v<A, B>)
inline auto gv_add32(A&& a, B&& b)
{
FOR_X64(binary_op, 4, kIdMovdqa, kIdPaddd, kIdVpaddd, kIdVpaddd, std::forward<A>(a), std::forward<B>(b));
}
inline v128 gv_add64(const v128& a, const v128& b)
{
#if defined(ARCH_X64)
return _mm_add_epi64(a, b);
#elif defined(ARCH_ARM64)
return vaddq_s64(a, b);
#endif
}
template <typename A, typename B> requires (asmjit::any_operand_v<A, B>)
inline auto gv_add64(A&& a, B&& b)
{
FOR_X64(binary_op, 8, kIdMovdqa, kIdPaddq, kIdVpaddq, kIdVpaddq, std::forward<A>(a), std::forward<B>(b));
}
inline v128 gv_adds_s8(const v128& a, const v128& b)
{
#if defined(ARCH_X64)
return _mm_adds_epi8(a, b);
#elif defined(ARCH_ARM64)
return vqaddq_s8(a, b);
#endif
}
template <typename A, typename B> requires (asmjit::any_operand_v<A, B>)
inline auto gv_adds_s8(A&& a, B&& b)
{
FOR_X64(binary_op, 1, kIdMovdqa, kIdPaddsb, kIdVpaddsb, kIdNone, std::forward<A>(a), std::forward<B>(b));
}
inline v128 gv_adds_s16(const v128& a, const v128& b)
{
#if defined(ARCH_X64)
return _mm_adds_epi16(a, b);
#elif defined(ARCH_ARM64)
return vqaddq_s16(a, b);
#endif
}
template <typename A, typename B> requires (asmjit::any_operand_v<A, B>)
inline auto gv_adds_s16(A&& a, B&& b)
{
FOR_X64(binary_op, 2, kIdMovdqa, kIdPaddsw, kIdVpaddsw, kIdNone, std::forward<A>(a), std::forward<B>(b));
}
inline v128 gv_adds_s32(const v128& a, const v128& b)
{
#if defined(ARCH_X64)
const v128 s = _mm_add_epi32(a, b);
const v128 m = (a ^ s) & (b ^ s); // overflow bit
const v128 x = _mm_srai_epi32(m, 31); // saturation mask
const v128 y = _mm_srai_epi32(_mm_and_si128(s, m), 31); // positive saturation mask
return _mm_xor_si128(_mm_xor_si128(_mm_srli_epi32(x, 1), y), _mm_or_si128(s, x));
#elif defined(ARCH_ARM64)
return vqaddq_s32(a, b);
#endif
}
template <typename A, typename B> requires (asmjit::any_operand_v<A, B>)
inline auto gv_adds_s32(A&& a, B&& b)
{
#if defined(ARCH_X64)
auto s = gv_add32(a, b);
auto m = gv_and32(gv_xor32(std::forward<A>(a), s), gv_xor32(std::forward<B>(b), s));
auto x = gv_sar32(m, 31);
auto y = gv_sar32(gv_and32(s, std::move(m)), 31);
auto z = gv_xor32(gv_shr32(x, 1), std::move(y));
return gv_xor32(std::move(z), gv_or32(std::move(s), std::move(x)));
#endif
}
inline v128 gv_addus_u8(const v128& a, const v128& b)
{
#if defined(ARCH_X64)
return _mm_adds_epu8(a, b);
#elif defined(ARCH_ARM64)
return vqaddq_u8(a, b);
#endif
}
template <typename A, typename B> requires (asmjit::any_operand_v<A, B>)
inline auto gv_addus_u8(A&& a, B&& b)
{
FOR_X64(binary_op, 1, kIdMovdqa, kIdPaddusb, kIdVpaddusb, kIdNone, std::forward<A>(a), std::forward<B>(b));
}
inline v128 gv_addus_u16(const v128& a, const v128& b)
{
#if defined(ARCH_X64)
return _mm_adds_epu16(a, b);
#elif defined(ARCH_ARM64)
return vqaddq_u16(a, b);
#endif
}
template <typename A, typename B> requires (asmjit::any_operand_v<A, B>)
inline auto gv_addus_u16(A&& a, B&& b)
{
FOR_X64(binary_op, 2, kIdMovdqa, kIdPaddusw, kIdVpaddusw, kIdNone, std::forward<A>(a), std::forward<B>(b));
}
inline v128 gv_addus_u32(const v128& a, const v128& b)
{
#if defined(__SSE4_1__)
return _mm_add_epi32(a, _mm_min_epu32(~a, b));
#elif defined(ARCH_X64)
const v128 s = _mm_add_epi32(a, b);
return _mm_or_si128(s, _mm_cmpgt_epi32(_mm_xor_si128(b, _mm_set1_epi32(smin)), _mm_xor_si128(a, _mm_set1_epi32(smax))));
#elif defined(ARCH_ARM64)
return vqaddq_u32(a, b);
#endif
}
template <typename A, typename B> requires (asmjit::any_operand_v<A, B>)
inline asmjit::vec_type gv_addus_u32(A&& a, B&& b)
{
#if defined(ARCH_X64)
if (utils::has_sse41())
return gv_add32(gv_minu32(std::forward<B>(b), gv_not32(a)), std::forward<A>(a));
auto s = gv_add32(a, b);
auto x = gv_xor32(std::forward<B>(b), gv_bcst32(0x80000000));
auto y = gv_xor32(std::forward<A>(a), gv_bcst32(0x7fffffff));
return gv_or32(std::move(s), gv_gts32(std::move(x), std::move(y)));
#endif
return {};
}
inline v128 gv_addfs(const v128& a, const v128& b)
{
#if defined(ARCH_X64)
return _mm_add_ps(a, b);
#elif defined(ARCH_ARM64)
return vaddq_f32(a, b);
#endif
}
inline v128 gv_addfd(const v128& a, const v128& b)
{
#if defined(ARCH_X64)
return _mm_add_pd(a, b);
#elif defined(ARCH_ARM64)
return vaddq_f64(a, b);
#endif
}
inline v128 gv_sub8(const v128& a, const v128& b)
{
#if defined(ARCH_X64)
return _mm_sub_epi8(a, b);
#elif defined(ARCH_ARM64)
return vsubq_s8(a, b);
#endif
}
template <typename A, typename B> requires (asmjit::any_operand_v<A, B>)
inline auto gv_sub8(A&& a, B&& b)
{
FOR_X64(binary_op, 1, kIdMovdqa, kIdPsubb, kIdVpsubb, kIdNone, std::forward<A>(a), std::forward<B>(b));
}
inline v128 gv_sub16(const v128& a, const v128& b)
{
#if defined(ARCH_X64)
return _mm_sub_epi16(a, b);
#elif defined(ARCH_ARM64)
return vsubq_s16(a, b);
#endif
}
inline v128 gv_sub32(const v128& a, const v128& b)
{
#if defined(ARCH_X64)
return _mm_sub_epi32(a, b);
#elif defined(ARCH_ARM64)
return vsubq_s32(a, b);
#endif
}
inline v128 gv_sub64(const v128& a, const v128& b)
{
#if defined(ARCH_X64)
return _mm_sub_epi64(a, b);
#elif defined(ARCH_ARM64)
return vsubq_s64(a, b);
#endif
}
inline v128 gv_subs_s8(const v128& a, const v128& b)
{
#if defined(ARCH_X64)
return _mm_subs_epi8(a, b);
#elif defined(ARCH_ARM64)
return vqsubq_s8(a, b);
#endif
}
inline v128 gv_subs_s16(const v128& a, const v128& b)
{
#if defined(ARCH_X64)
return _mm_subs_epi16(a, b);
#elif defined(ARCH_ARM64)
return vqsubq_s16(a, b);
#endif
}
inline v128 gv_subs_s32(const v128& a, const v128& b)
{
#if defined(ARCH_X64)
const v128 d = _mm_sub_epi32(a, b);
const v128 m = (a ^ b) & (a ^ d); // overflow bit
const v128 x = _mm_srai_epi32(m, 31);
return _mm_or_si128(_mm_andnot_si128(x, d), _mm_and_si128(x, _mm_xor_si128(_mm_srli_epi32(x, 1), _mm_srai_epi32(a, 31))));
#elif defined(ARCH_ARM64)
return vqsubq_s32(a, b);
#endif
}
inline v128 gv_subus_u8(const v128& a, const v128& b)
{
#if defined(ARCH_X64)
return _mm_subs_epu8(a, b);
#elif defined(ARCH_ARM64)
return vqsubq_u8(a, b);
#endif
}
inline v128 gv_subus_u16(const v128& a, const v128& b)
{
#if defined(ARCH_X64)
return _mm_subs_epu16(a, b);
#elif defined(ARCH_ARM64)
return vqsubq_u16(a, b);
#endif
}
inline v128 gv_subus_u32(const v128& a, const v128& b)
{
#if defined(__SSE4_1__)
return _mm_sub_epi32(a, _mm_min_epu32(a, b));
#elif defined(ARCH_X64)
const auto sign = _mm_set1_epi32(smin);
return _mm_andnot_si128(_mm_cmpgt_epi32(_mm_xor_si128(b, sign), _mm_xor_si128(a, sign)), _mm_sub_epi32(a, b));
#elif defined(ARCH_ARM64)
return vqsubq_u32(a, b);
#endif
}
inline v128 gv_subfs(const v128& a, const v128& b)
{
#if defined(ARCH_X64)
return _mm_sub_ps(a, b);
#elif defined(ARCH_ARM64)
return vsubq_f32(a, b);
#endif
}
inline v128 gv_subfd(const v128& a, const v128& b)
{
#if defined(ARCH_X64)
return _mm_sub_pd(a, b);
#elif defined(ARCH_ARM64)
return vsubq_f64(a, b);
#endif
}
inline v128 gv_maxu8(const v128& a, const v128& b)
{
#if defined(ARCH_X64)
return _mm_max_epu8(a, b);
#elif defined(ARCH_ARM64)
return vmaxq_u8(a, b);
#endif
}
inline v128 gv_maxu16(const v128& a, const v128& b)
{
#if defined(__SSE4_1__)
return _mm_max_epu16(a, b);
#elif defined(ARCH_X64)
return _mm_add_epi16(_mm_subs_epu16(a, b), b);
#elif defined(ARCH_ARM64)
return vmaxq_u16(a, b);
#endif
}
inline v128 gv_maxu32(const v128& a, const v128& b)
{
#if defined(__SSE4_1__)
return _mm_max_epu32(a, b);
#elif defined(ARCH_X64)
const __m128i s = _mm_set1_epi32(smin);
const __m128i m = _mm_cmpgt_epi32(_mm_xor_si128(a, s), _mm_xor_si128(b, s));
return _mm_or_si128(_mm_and_si128(m, a), _mm_andnot_si128(m, b));
#elif defined(ARCH_ARM64)
return vmaxq_u32(a, b);
#endif
}
inline v128 gv_maxs8(const v128& a, const v128& b)
{
#if defined(__SSE4_1__)
return _mm_max_epi8(a, b);
#elif defined(ARCH_X64)
const __m128i m = _mm_cmpgt_epi8(a, b);
return _mm_or_si128(_mm_and_si128(m, a), _mm_andnot_si128(m, b));
#elif defined(ARCH_ARM64)
return vmaxq_s8(a, b);
#endif
}
inline v128 gv_maxs16(const v128& a, const v128& b)
{
#if defined(ARCH_X64)
return _mm_max_epi16(a, b);
#elif defined(ARCH_ARM64)
return vmaxq_s16(a, b);
#endif
}
inline v128 gv_maxs32(const v128& a, const v128& b)
{
#if defined(__SSE4_1__)
return _mm_max_epi32(a, b);
#elif defined(ARCH_X64)
const __m128i m = _mm_cmpgt_epi32(a, b);
return _mm_or_si128(_mm_and_si128(m, a), _mm_andnot_si128(m, b));
#elif defined(ARCH_ARM64)
return vmaxq_s32(a, b);
#endif
}
inline v128 gv_maxfs(const v128& a, const v128& b)
{
#if defined(ARCH_X64)
return _mm_and_ps(_mm_max_ps(a, b), _mm_max_ps(b, a));
#elif defined(ARCH_ARM64)
return vmaxq_f32(a, b);
#endif
}
inline v128 gv_minu8(const v128& a, const v128& b)
{
#if defined(ARCH_X64)
return _mm_min_epu8(a, b);
#elif defined(ARCH_ARM64)
return vminq_u8(a, b);
#endif
}
inline v128 gv_minu16(const v128& a, const v128& b)
{
#if defined(__SSE4_1__)
return _mm_min_epu16(a, b);
#elif defined(ARCH_X64)
return _mm_sub_epi16(a, _mm_subs_epu16(a, b));
#elif defined(ARCH_ARM64)
return vminq_u16(a, b);
#endif
}
inline v128 gv_minu32(const v128& a, const v128& b)
{
#if defined(__SSE4_1__)
return _mm_min_epu32(a, b);
#elif defined(ARCH_X64)
const __m128i s = _mm_set1_epi32(smin);
const __m128i m = _mm_cmpgt_epi32(_mm_xor_si128(a, s), _mm_xor_si128(b, s));
return _mm_or_si128(_mm_andnot_si128(m, a), _mm_and_si128(m, b));
#elif defined(ARCH_ARM64)
return vminq_u32(a, b);
#endif
}
template <typename A, typename B> requires (asmjit::any_operand_v<A, B>)
inline asmjit::vec_type gv_minu32(A&& a, B&& b)
{
#if defined(ARCH_X64)
if (utils::has_sse41())
FOR_X64(binary_op, 4, kIdMovdqa, kIdPminud, kIdVpminud, kIdVpminud, std::forward<A>(a), std::forward<B>(b));
auto s = gv_bcst32(0x80000000);
auto x = gv_xor32(a, s);
auto m = gv_gts32(std::move(x), gv_xor32(std::move(s), b));
auto z = gv_and32(m, std::move(b));
return gv_or32(std::move(z), gv_andn32(std::move(m), std::move(a)));
#endif
return {};
}
inline v128 gv_mins8(const v128& a, const v128& b)
{
#if defined(__SSE4_1__)
return _mm_min_epi8(a, b);
#elif defined(ARCH_X64)
const __m128i m = _mm_cmpgt_epi8(a, b);
return _mm_or_si128(_mm_andnot_si128(m, a), _mm_and_si128(m, b));
#elif defined(ARCH_ARM64)
return vminq_s8(a, b);
#endif
}
inline v128 gv_mins16(const v128& a, const v128& b)
{
#if defined(ARCH_X64)
return _mm_min_epi16(a, b);
#elif defined(ARCH_ARM64)
return vminq_s16(a, b);
#endif
}
inline v128 gv_mins32(const v128& a, const v128& b)
{
#if defined(__SSE4_1__)
return _mm_min_epi32(a, b);
#elif defined(ARCH_X64)
const __m128i m = _mm_cmpgt_epi32(a, b);
return _mm_or_si128(_mm_andnot_si128(m, a), _mm_and_si128(m, b));
#elif defined(ARCH_ARM64)
return vminq_s32(a, b);
#endif
}
inline v128 gv_minfs(const v128& a, const v128& b)
{
#if defined(ARCH_X64)
return _mm_or_ps(_mm_min_ps(a, b), _mm_min_ps(b, a));
#elif defined(ARCH_ARM64)
return vminq_f32(a, b);
#endif
}
inline v128 gv_eq8(const v128& a, const v128& b)
{
#if defined(ARCH_X64)
return _mm_cmpeq_epi8(a, b);
#elif defined(ARCH_ARM64)
return vceqq_s8(a, b);
#endif
}
inline v128 gv_eq16(const v128& a, const v128& b)
{
#if defined(ARCH_X64)
return _mm_cmpeq_epi16(a, b);
#elif defined(ARCH_ARM64)
return vceqq_s16(a, b);
#endif
}
inline v128 gv_eq32(const v128& a, const v128& b)
{
#if defined(ARCH_X64)
return _mm_cmpeq_epi32(a, b);
#elif defined(ARCH_ARM64)
return vceqq_s32(a, b);
#endif
}
// Ordered and equal
inline v128 gv_eqfs(const v128& a, const v128& b)
{
#if defined(ARCH_X64)
return _mm_cmpeq_ps(a, b);
#elif defined(ARCH_ARM64)
return vceqq_f32(a, b);
#endif
}
// Unordered or not equal
inline v128 gv_neqfs(const v128& a, const v128& b)
{
#if defined(ARCH_X64)
return _mm_cmpneq_ps(a, b);
#elif defined(ARCH_ARM64)
return ~vceqq_f32(a, b);
#endif
}
inline v128 gv_gtu8(const v128& a, const v128& b)
{
#if defined(__AVX512VL__) && defined(__AVX512BW__)
return _mm_movm_epi8(_mm_cmpgt_epu8_mask(a, b));
#elif defined(ARCH_X64)
return _mm_cmpeq_epi8(_mm_cmpeq_epi8(a, _mm_min_epu8(a, b)), _mm_setzero_si128());
#elif defined(ARCH_ARM64)
return vcgtq_u8(a, b);
#endif
}
inline v128 gv_gtu16(const v128& a, const v128& b)
{
#if defined(__AVX512VL__) && defined(__AVX512BW__)
return _mm_movm_epi16(_mm_cmpgt_epu16_mask(a, b));
#elif defined(__SSE4_1__)
return _mm_cmpeq_epi16(_mm_cmpeq_epi16(a, _mm_min_epu16(a, b)), _mm_setzero_si128());
#elif defined(ARCH_X64)
return _mm_cmpeq_epi16(_mm_cmpeq_epi16(_mm_subs_epu16(a, b), _mm_setzero_si128()), _mm_setzero_si128());
#elif defined(ARCH_ARM64)
return vcgtq_u16(a, b);
#endif
}
inline v128 gv_gtu32(const v128& a, const v128& b)
{
#if defined(__AVX512VL__) && defined(__AVX512DQ__)
return _mm_movm_epi32(_mm_cmpgt_epu32_mask(a, b));
#elif defined(__SSE4_1__)
return _mm_cmpeq_epi32(_mm_cmpeq_epi32(a, _mm_min_epu32(a, b)), _mm_setzero_si128());
#elif defined(ARCH_X64)
const auto sign = _mm_set1_epi32(smin);
return _mm_cmpgt_epi32(_mm_xor_si128(a, sign), _mm_xor_si128(b, sign));
#elif defined(ARCH_ARM64)
return vcgtq_u32(a, b);
#endif
}
// Ordered and greater than
inline v128 gv_gtfs(const v128& a, const v128& b)
{
#if defined(ARCH_X64)
return _mm_cmpgt_ps(a, b);
#elif defined(ARCH_ARM64)
return vcgtq_f32(a, b);
#endif
}
// Ordered and less than
inline v128 gv_ltfs(const v128& a, const v128& b)
{
#if defined(ARCH_X64)
return _mm_cmplt_ps(a, b);
#elif defined(ARCH_ARM64)
return vcltq_f32(a, b);
#endif
}
// Unordered or less or equal
inline v128 gv_ngtfs(const v128& a, const v128& b)
{
#if defined(ARCH_X64)
return _mm_cmpngt_ps(a, b);
#elif defined(ARCH_ARM64)
return ~vcgtq_f32(a, b);
#endif
}
// Unordered or greater or equal
inline v128 gv_nlefs(const v128& a, const v128& b)
{
#if defined(ARCH_X64)
return _mm_cmpnle_ps(a, b);
#elif defined(ARCH_ARM64)
return ~vcleq_f32(a, b);
#endif
}
inline v128 gv_geu8(const v128& a, const v128& b)
{
#if defined(ARCH_X64)
return _mm_cmpeq_epi8(b, _mm_min_epu8(a, b));
#elif defined(ARCH_ARM64)
return vcgeq_u8(a, b);
#endif
}
inline v128 gv_geu16(const v128& a, const v128& b)
{
#if defined(__SSE4_1__)
return _mm_cmpeq_epi16(b, _mm_min_epu16(a, b));
#elif defined(ARCH_X64)
return _mm_cmpeq_epi16(_mm_subs_epu16(b, a), _mm_setzero_si128());
#elif defined(ARCH_ARM64)
return vcgeq_u16(a, b);
#endif
}
inline v128 gv_geu32(const v128& a, const v128& b)
{
#if defined(__SSE4_1__)
return _mm_cmpeq_epi32(b, _mm_min_epu32(a, b));
#elif defined(ARCH_X64)
const auto sign = _mm_set1_epi32(smin);
return _mm_cmpeq_epi32(_mm_cmpgt_epi32(_mm_xor_si128(b, sign), _mm_xor_si128(a, sign)), _mm_setzero_si128());
#elif defined(ARCH_ARM64)
return vcgeq_u32(a, b);
#endif
}
// Ordered and not less than
inline v128 gv_gefs(const v128& a, const v128& b)
{
#if defined(ARCH_X64)
return _mm_cmpge_ps(a, b);
#elif defined(ARCH_ARM64)
return vcgeq_f32(a, b);
#endif
}
// Unordered or less than
inline v128 gv_ngefs(const v128& a, const v128& b)
{
#if defined(ARCH_X64)
return _mm_cmpnge_ps(a, b);
#elif defined(ARCH_ARM64)
return ~vcgeq_f32(a, b);
#endif
}
inline v128 gv_gts8(const v128& a, const v128& b)
{
#if defined(ARCH_X64)
return _mm_cmpgt_epi8(a, b);
#elif defined(ARCH_ARM64)
return vcgtq_s8(a, b);
#endif
}
template <typename A, typename B> requires (asmjit::any_operand_v<A, B>)
inline asmjit::vec_type gv_gts8(A&& a, B&& b)
{
FOR_X64(binary_op, 1, kIdMovdqa, kIdPcmpgtb, kIdVpcmpgtb, kIdNone, std::forward<A>(a), std::forward<B>(b));
return {};
}
inline v128 gv_gts16(const v128& a, const v128& b)
{
#if defined(ARCH_X64)
return _mm_cmpgt_epi16(a, b);
#elif defined(ARCH_ARM64)
return vcgtq_s16(a, b);
#endif
}
inline v128 gv_gts32(const v128& a, const v128& b)
{
#if defined(ARCH_X64)
return _mm_cmpgt_epi32(a, b);
#elif defined(ARCH_ARM64)
return vcgtq_s32(a, b);
#endif
}
template <typename A, typename B> requires (asmjit::any_operand_v<A, B>)
inline asmjit::vec_type gv_gts32(A&& a, B&& b)
{
FOR_X64(binary_op, 4, kIdMovdqa, kIdPcmpgtd, kIdVpcmpgtd, kIdNone, std::forward<A>(a), std::forward<B>(b));
return {};
}
inline v128 gv_avgu8(const v128& a, const v128& b)
{
#if defined(ARCH_X64)
return _mm_avg_epu8(a, b);
#elif defined(ARCH_ARM64)
return vrhaddq_u8(a, b);
#endif
}
inline v128 gv_avgu16(const v128& a, const v128& b)
{
#if defined(ARCH_X64)
return _mm_avg_epu16(a, b);
#elif defined(ARCH_ARM64)
return vrhaddq_u16(a, b);
#endif
}
inline v128 gv_avgu32(const v128& a, const v128& b)
{
#if defined(ARCH_X64)
const auto ones = _mm_set1_epi32(-1);
const auto summ = gv_sub32(gv_add32(a, b), ones);
const auto carry = _mm_slli_epi32(gv_geu32(a, summ), 31);
return _mm_or_si128(carry, _mm_srli_epi32(summ, 1));
#elif defined(ARCH_ARM64)
return vrhaddq_u32(a, b);
#endif
}
inline v128 gv_avgs8(const v128& a, const v128& b)
{
#if defined(ARCH_X64)
const v128 sign = _mm_set1_epi8(smin);
return gv_avgu8(a ^ sign, b ^ sign) ^ sign;
#elif defined(ARCH_ARM64)
return vrhaddq_s8(a, b);
#endif
}
inline v128 gv_avgs16(const v128& a, const v128& b)
{
#if defined(ARCH_X64)
const v128 sign = _mm_set1_epi16(smin);
return gv_avgu16(a ^ sign, b ^ sign) ^ sign;
#elif defined(ARCH_ARM64)
return vrhaddq_s16(a, b);
#endif
}
inline v128 gv_avgs32(const v128& a, const v128& b)
{
#if defined(ARCH_X64)
const v128 sign = _mm_set1_epi32(smin);
return gv_avgu32(a ^ sign, b ^ sign) ^ sign;
#elif defined(ARCH_ARM64)
return vrhaddq_s32(a, b);
#endif
}
inline v128 gv_divfs(const v128& a, const v128& b)
{
#if defined(ARCH_X64)
return _mm_div_ps(a, b);
#elif defined(ARCH_ARM64)
return vdivq_f32(a, b);
#endif
}
inline v128 gv_sqrtfs(const v128& a)
{
#if defined(ARCH_X64)
return _mm_sqrt_ps(a);
#elif defined(ARCH_ARM64)
return vsqrtq_f32(a);
#endif
}
inline v128 gv_fmafs(const v128& a, const v128& b, const v128& c)
{
#if defined(ARCH_X64) && defined(__FMA__)
return _mm_fmadd_ps(a, b, c);
#elif defined(__FMA4__)
return _mm_macc_ps(a, b, c);
#elif defined(ARCH_X64)
// This is inaccurate implementation
#ifdef __AVX__
const __m128 r = _mm256_cvtpd_ps(_mm256_add_pd(_mm256_mul_pd(_mm256_cvtps_pd(a), _mm256_cvtps_pd(b)), _mm256_cvtps_pd(c)));
#else
const __m128d a0 = _mm_cvtps_pd(a);
const __m128d a1 = _mm_cvtps_pd(_mm_movehl_ps(a, a));
const __m128d b0 = _mm_cvtps_pd(b);
const __m128d b1 = _mm_cvtps_pd(_mm_movehl_ps(b, b));
const __m128d c0 = _mm_cvtps_pd(c);
const __m128d c1 = _mm_cvtps_pd(_mm_movehl_ps(c, c));
const __m128d m0 = _mm_mul_pd(a0, b0);
const __m128d m1 = _mm_mul_pd(a1, b1);
const __m128d r0 = _mm_add_pd(m0, c0);
const __m128d r1 = _mm_add_pd(m1, c1);
const __m128 r = _mm_movelh_ps(_mm_cvtpd_ps(r0), _mm_cvtpd_ps(r1));
#endif
return r;
#elif defined(ARCH_ARM64)
return vfmaq_f32(c, a, b);
#else
v128 r;
for (int i = 0; i < 4; i++)
{
r._f[i] = std::fmaf(a._f[i], b._f[i], c._f[i]);
}
return r;
#endif
}
inline v128 gv_muladdfs(const v128& a, const v128& b, const v128& c)
{
#if defined(ARCH_X64) && defined(__FMA__)
return _mm_fmadd_ps(a, b, c);
#elif defined(__FMA4__)
return _mm_macc_ps(a, b, c);
#elif defined(ARCH_ARM64)
return vfmaq_f32(c, a, b);
#elif defined(ARCH_X64)
return _mm_add_ps(_mm_mul_ps(a, b), c);
#endif
}
// -> ssat((a * b * 2 + (c << 16) + 0x8000) >> 16)
inline v128 gv_rmuladds_hds16(const v128& a, const v128& b, const v128& c)
{
#if defined(ARCH_ARM64)
return vqrdmlahq_s16(c, a, b);
#elif defined(ARCH_X64)
const auto x80 = _mm_set1_epi16(0x80); // 0x80 * 0x80 = 0x4000, add this to the product
const auto al = _mm_unpacklo_epi16(a, x80);
const auto ah = _mm_unpackhi_epi16(a, x80);
const auto bl = _mm_unpacklo_epi16(b, x80);
const auto bh = _mm_unpackhi_epi16(b, x80);
const auto ml = _mm_srai_epi32(_mm_madd_epi16(al, bl), 15);
const auto mh = _mm_srai_epi32(_mm_madd_epi16(ah, bh), 15);
const auto cl = _mm_srai_epi32(_mm_unpacklo_epi16(_mm_setzero_si128(), c), 16);
const auto ch = _mm_srai_epi32(_mm_unpackhi_epi16(_mm_setzero_si128(), c), 16);
const auto sl = _mm_add_epi32(ml, cl);
const auto sh = _mm_add_epi32(mh, ch);
return _mm_packs_epi32(sl, sh);
#endif
}
// -> ssat((a * b * 2 + 0x8000) >> 16)
inline v128 gv_rmuls_hds16(const v128& a, const v128& b)
{
#if defined(ARCH_ARM64)
return vqrdmulhq_s16(a, b);
#elif defined(ARCH_X64)
const auto x80 = _mm_set1_epi16(0x80); // 0x80 * 0x80 = 0x4000, add this to the product
const auto al = _mm_unpacklo_epi16(a, x80);
const auto ah = _mm_unpackhi_epi16(a, x80);
const auto bl = _mm_unpacklo_epi16(b, x80);
const auto bh = _mm_unpackhi_epi16(b, x80);
const auto ml = _mm_srai_epi32(_mm_madd_epi16(al, bl), 15);
const auto mh = _mm_srai_epi32(_mm_madd_epi16(ah, bh), 15);
return _mm_packs_epi32(ml, mh);
#endif
}
// -> ssat((a * b * 2) >> 16)
inline v128 gv_muls_hds16(const v128& a, const v128& b)
{
#if defined(ARCH_ARM64)
return vqdmulhq_s16(a, b);
#elif defined(ARCH_X64)
const auto m = _mm_or_si128(_mm_srli_epi16(_mm_mullo_epi16(a, b), 15), _mm_slli_epi16(_mm_mulhi_epi16(a, b), 1));
const auto s = _mm_cmpeq_epi16(m, _mm_set1_epi16(-0x8000)); // detect special case (positive 0x8000)
return _mm_xor_si128(m, s);
#endif
}
inline v128 gv_muladd16(const v128& a, const v128& b, const v128& c)
{
#if defined(ARCH_X64)
return _mm_add_epi16(_mm_mullo_epi16(a, b), c);
#elif defined(ARCH_ARM64)
return vmlaq_s16(c, a, b);
#endif
}
inline v128 gv_mul16(const v128& a, const v128& b)
{
#if defined(ARCH_X64)
return _mm_mullo_epi16(a, b);
#elif defined(ARCH_ARM64)
return vmulq_s16(a, b);
#endif
}
inline v128 gv_mul32(const v128& a, const v128& b)
{
#if defined(__SSE4_1__)
return _mm_mullo_epi32(a, b);
#elif defined(ARCH_X64)
const __m128i lows = _mm_shuffle_epi32(_mm_mul_epu32(a, b), 8);
const __m128i highs = _mm_shuffle_epi32(_mm_mul_epu32(_mm_srli_epi64(a, 32), _mm_srli_epi64(b, 32)), 8);
return _mm_unpacklo_epi32(lows, highs);
#elif defined(ARCH_ARM64)
return vmulq_s32(a, b);
#endif
}
inline v128 gv_mulfs(const v128& a, const v128& b)
{
#if defined(ARCH_X64)
return _mm_mul_ps(a, b);
#elif defined(ARCH_ARM64)
return vmulq_f32(a, b);
#endif
}
inline v128 gv_hadds8x2(const v128& a)
{
#if defined(__SSSE3__)
return _mm_maddubs_epi16(_mm_set1_epi8(1), a);
#elif defined(ARCH_X64)
return _mm_add_epi16(_mm_srai_epi16(a, 8), _mm_srai_epi16(_mm_slli_epi16(a, 8), 8));
#elif defined(ARCH_ARM64)
return vpaddlq_s8(a);
#endif
}
inline v128 gv_hadds8x4(const v128& a, const v128& c)
{
#if (defined(__AVX512VL__) && defined(__AVX512VNNI__)) || defined(__AVXVNNI__)
return _mm_dpbusd_epi32(c, _mm_set1_epi8(1), a);
#elif defined(__SSSE3__)
return _mm_add_epi32(_mm_madd_epi16(_mm_maddubs_epi16(_mm_set1_epi8(1), a), _mm_set1_epi16(1)), c);
#elif defined(ARCH_X64)
return _mm_add_epi32(_mm_madd_epi16(_mm_add_epi16(_mm_srai_epi16(a, 8), _mm_srai_epi16(_mm_slli_epi16(a, 8), 8)), _mm_set1_epi16(1)), c);
#elif defined(ARCH_ARM64)
return vaddq_s32(vpaddlq_s16(vpaddlq_s8(a)), c);
#endif
}
inline v128 gv_haddu8x2(const v128& a)
{
#if defined(__SSSE3__)
return _mm_maddubs_epi16(a, _mm_set1_epi8(1));
#elif defined(ARCH_X64)
return _mm_add_epi16(_mm_srli_epi16(a, 8), _mm_and_si128(a, _mm_set1_epi16(0x00ff)));
#elif defined(ARCH_ARM64)
return vpaddlq_u8(a);
#endif
}
inline v128 gv_haddu8x4(const v128& a)
{
#if (defined(__AVX512VL__) && defined(__AVX512VNNI__)) || defined(__AVXVNNI__)
return _mm_dpbusd_epi32(_mm_setzero_si128(), a, _mm_set1_epi8(1));
#elif defined(__SSSE3__)
return _mm_madd_epi16(_mm_maddubs_epi16(a, _mm_set1_epi8(1)), _mm_set1_epi16(1));
#elif defined(ARCH_X64)
return _mm_madd_epi16(_mm_add_epi16(_mm_srli_epi16(a, 8), _mm_and_si128(a, _mm_set1_epi16(0x00ff))), _mm_set1_epi16(1));
#elif defined(ARCH_ARM64)
return vpaddlq_u16(vpaddlq_u8(a));
#endif
}
inline v128 gv_hadds16x2(const v128& a, const v128& c)
{
#if (defined(__AVX512VL__) && defined(__AVX512VNNI__)) || defined(__AVXVNNI__)
return _mm_dpwssd_epi32(c, a, _mm_set1_epi8(1));
#elif defined(ARCH_X64)
return _mm_add_epi32(_mm_madd_epi16(a, _mm_set1_epi16(1)), c);
#elif defined(ARCH_ARM64)
return vaddq_s32(vpaddlq_s16(a), c);
#endif
}
// Unsigned bytes from a, signed bytes from b, 32-bit accumulator c
inline v128 gv_dotu8s8x4(const v128& a, const v128& b, const v128& c)
{
#if (defined(__AVX512VL__) && defined(__AVX512VNNI__)) || defined(__AVXVNNI__)
return _mm_dpbusd_epi32(c, a, b);
#elif defined(ARCH_X64)
const __m128i ah = _mm_srli_epi16(a, 8);
const __m128i al = _mm_and_si128(a, _mm_set1_epi16(0x00ff));
const __m128i bh = _mm_srai_epi16(b, 8);
const __m128i bl = _mm_srai_epi16(_mm_slli_epi16(b, 8), 8);
const __m128i mh = _mm_madd_epi16(ah, bh);
const __m128i ml = _mm_madd_epi16(al, bl);
const __m128i x = _mm_add_epi32(mh, ml);
return _mm_add_epi32(c, x);
#elif defined(__ARM_FEATURE_MATMUL_INT8)
return vusdotq_s32(c, a, b);
#elif defined(ARCH_ARM64)
const auto l = vpaddlq_s16(vmulq_s16(vreinterpretq_s16_u16(vmovl_u8(vget_low_u8(a))), vmovl_s8(vget_low_s8(b))));
const auto h = vpaddlq_s16(vmulq_s16(vreinterpretq_s16_u16(vmovl_u8(vget_high_u8(a))), vmovl_s8(vget_high_s8(b))));
return vaddq_s32(c, vaddq_s32(vuzp1q_s32(l, h), vuzp2q_s32(l, h)));
#endif
}
inline v128 gv_dotu8x4(const v128& a, const v128& b, const v128& c)
{
#if defined(ARCH_X64)
const __m128i ah = _mm_srli_epi16(a, 8);
const __m128i al = _mm_and_si128(a, _mm_set1_epi16(0x00ff));
const __m128i bh = _mm_srli_epi16(b, 8);
const __m128i bl = _mm_and_si128(b, _mm_set1_epi16(0x00ff));
const __m128i mh = _mm_madd_epi16(ah, bh);
const __m128i ml = _mm_madd_epi16(al, bl);
const __m128i x = _mm_add_epi32(mh, ml);
return _mm_add_epi32(c, x);
#elif defined(__ARM_FEATURE_DOTPROD)
return vdotq_u32(c, a, b);
#elif defined(ARCH_ARM64)
const auto l = vpaddlq_u16(vmulq_u16(vmovl_u8(vget_low_u8(a)), vmovl_u8(vget_low_u8(b))));
const auto h = vpaddlq_u16(vmulq_u16(vmovl_u8(vget_high_u8(a)), vmovl_u8(vget_high_u8(b))));
return vaddq_u32(c, vaddq_u32(vuzp1q_u32(l, h), vuzp2q_u32(l, h)));
#endif
}
inline v128 gv_dots16x2(const v128& a, const v128& b)
{
#if defined(ARCH_X64)
return _mm_madd_epi16(a, b);
#elif defined(ARCH_ARM64)
const auto ml = vmull_s16(vget_low_s16(a), vget_low_s16(b));
const auto mh = vmull_s16(vget_high_s16(a), vget_high_s16(b));
const auto sl = vpadd_s32(vget_low_s32(ml), vget_high_s32(ml));
const auto sh = vpadd_s32(vget_low_s32(mh), vget_high_s32(mh));
return vcombine_s32(sl, sh);
#endif
}
// Signed s16 from a and b, 32-bit accumulator c
inline v128 gv_dots16x2(const v128& a, const v128& b, const v128& c)
{
#if (defined(__AVX512VL__) && defined(__AVX512VNNI__)) || defined(__AVXVNNI__)
return _mm_dpwssd_epi32(c, a, b);
#else
return gv_add32(c, gv_dots16x2(a, b));
#endif
}
inline v128 gv_dotu16x2(const v128& a, const v128& b)
{
#if defined(ARCH_X64)
const auto ml = _mm_mullo_epi16(a, b); // low results
const auto mh = _mm_mulhi_epu16(a, b); // high results
const auto ls = _mm_add_epi32(_mm_srli_epi32(ml, 16), _mm_and_si128(ml, _mm_set1_epi32(0x0000ffff)));
const auto hs = _mm_add_epi32(_mm_slli_epi32(mh, 16), _mm_and_si128(mh, _mm_set1_epi32(0xffff0000)));
return _mm_add_epi32(ls, hs);
#elif defined(ARCH_ARM64)
const auto ml = vmull_u16(vget_low_u16(a), vget_low_u16(b));
const auto mh = vmull_u16(vget_high_u16(a), vget_high_u16(b));
const auto sl = vpadd_u32(vget_low_u32(ml), vget_high_u32(ml));
const auto sh = vpadd_u32(vget_low_u32(mh), vget_high_u32(mh));
return vcombine_u32(sl, sh);
#endif
}
// Unsigned bytes from a, signed bytes from b, 32-bit accumulator c
inline v128 gv_dots_u8s8x4(const v128& a, const v128& b, const v128& c)
{
#if (defined(__AVX512VL__) && defined(__AVX512VNNI__)) || defined(__AVXVNNI__)
return _mm_dpbusds_epi32(c, a, b);
#elif defined(ARCH_X64)
const __m128i ah = _mm_srli_epi16(a, 8);
const __m128i al = _mm_and_si128(a, _mm_set1_epi16(0x00ff));
const __m128i bh = _mm_srai_epi16(b, 8);
const __m128i bl = _mm_srai_epi16(_mm_slli_epi16(b, 8), 8);
const __m128i mh = _mm_madd_epi16(ah, bh);
const __m128i ml = _mm_madd_epi16(al, bl);
return gv_adds_s32(c, _mm_add_epi32(mh, ml));
#elif defined(ARCH_ARM64)
const auto l = vpaddlq_s16(vmulq_s16(vreinterpretq_s16_u16(vmovl_u8(vget_low_u8(a))), vmovl_s8(vget_low_s8(b))));
const auto h = vpaddlq_s16(vmulq_s16(vreinterpretq_s16_u16(vmovl_u8(vget_high_u8(a))), vmovl_s8(vget_high_s8(b))));
return vqaddq_s32(c, vaddq_s32(vuzp1q_s32(l, h), vuzp2q_s32(l, h)));
#endif
}
// Signed s16 from a and b, 32-bit accumulator c; signed saturation
inline v128 gv_dots_s16x2(const v128& a, const v128& b, const v128& c)
{
#if (defined(__AVX512VL__) && defined(__AVX512VNNI__)) || defined(__AVXVNNI__)
return _mm_dpwssds_epi32(c, a, b);
#else
const auto ab = gv_dots16x2(a, b);
const auto s0 = gv_adds_s32(ab, c);
const auto s1 = gv_eq32(ab, gv_bcst32(0x80000000)); // +0x80000000, negative c -> c^0x80000000; otherwise 0x7fffffff
const auto s2 = gv_select32(gv_gts32(gv_bcst32(0), c), gv_xor32(c, gv_bcst32(0x80000000)), gv_bcst32(0x7fffffff));
return gv_select32(s1, s2, s0);
#endif
}
// Multiply s16 elements 0, 2, 4, 6 to produce s32 results in corresponding lanes
inline v128 gv_mul_even_s16(const v128& a, const v128& b)
{
#if defined(ARCH_X64)
const auto c = _mm_set1_epi32(0x0000ffff);
return _mm_madd_epi16(_mm_and_si128(a, c), _mm_and_si128(b, c));
#else
// TODO
return gv_mul32(gv_sar32(gv_shl32(a, 16), 16), gv_sar32(gv_shl32(b, 16), 16));
#endif
}
// Multiply u16 elements 0, 2, 4, 6 to produce u32 results in corresponding lanes
inline v128 gv_mul_even_u16(const v128& a, const v128& b)
{
#if defined(__SSE4_1__) || defined(ARCH_ARM64)
const auto c = gv_bcst32(0x0000ffff);
return gv_mul32(a & c, b & c);
#elif defined(ARCH_X64)
const auto ml = _mm_mullo_epi16(a, b);
const auto mh = _mm_mulhi_epu16(a, b);
return _mm_or_si128(_mm_and_si128(ml, _mm_set1_epi32(0x0000ffff)), _mm_slli_epi32(mh, 16));
#endif
}
// Multiply s16 elements 1, 3, 5, 7 to produce s32 results in corresponding lanes
inline v128 gv_mul_odds_s16(const v128& a, const v128& b)
{
#if defined(ARCH_X64)
return _mm_madd_epi16(_mm_srli_epi32(a, 16), _mm_srli_epi32(b, 16));
#else
return gv_mul32(gv_sar32(a, 16), gv_sar32(b, 16));
#endif
}
// Multiply u16 elements 1, 3, 5, 7 to produce u32 results in corresponding lanes
inline v128 gv_mul_odds_u16(const v128& a, const v128& b)
{
#if defined(__SSE4_1__) || defined(ARCH_ARM64)
return gv_mul32(gv_shr32(a, 16), gv_shr32(b, 16));
#elif defined(ARCH_X64)
const auto ml = _mm_mullo_epi16(a, b);
const auto mh = _mm_mulhi_epu16(a, b);
return _mm_or_si128(_mm_and_si128(mh, _mm_set1_epi32(0xffff0000)), _mm_srli_epi32(ml, 16));
#endif
}
inline v128 gv_cvts32_tofs(const v128& src)
{
#if defined(ARCH_X64)
return _mm_cvtepi32_ps(src);
#elif defined(ARCH_ARM64)
return vcvtq_f32_s32(src);
#endif
}
inline v128 gv_cvtu32_tofs(const v128& src)
{
#if defined(__AVX512VL__)
return _mm_cvtepu32_ps(src);
#elif defined(ARCH_X64)
const auto fix = _mm_and_ps(_mm_castsi128_ps(_mm_srai_epi32(src, 31)), _mm_set1_ps(0x80000000));
return _mm_add_ps(_mm_cvtepi32_ps(_mm_and_si128(src, _mm_set1_epi32(0x7fffffff))), fix);
#elif defined(ARCH_ARM64)
return vcvtq_f32_u32(src);
#endif
}
inline v128 gv_cvtfs_tos32(const v128& src)
{
#if defined(ARCH_X64)
return _mm_cvttps_epi32(src);
#elif defined(ARCH_ARM64)
return vcvtq_s32_f32(src);
#endif
}
inline v128 gv_cvtfs_tou32(const v128& src)
{
#if defined(__AVX512VL__)
return _mm_cvttps_epu32(src);
#elif defined(ARCH_X64)
const auto c1 = _mm_cvttps_epi32(src);
const auto s1 = _mm_srai_epi32(c1, 31);
const auto c2 = _mm_cvttps_epi32(_mm_sub_ps(src, _mm_set1_ps(2147483648.)));
return _mm_or_si128(c1, _mm_and_si128(c2, s1));
#elif defined(ARCH_ARM64)
return vcvtq_u32_f32(src);
#endif
}
namespace utils
{
inline f32 roundevenf32(f32 arg)
{
u32 val = std::bit_cast<u32>(arg);
u32 exp = (val >> 23) & 0xff;
u32 abs = val & 0x7fffffff;
if (exp >= 127 + 23)
{
// Big enough, NaN or INF
return arg;
}
else if (exp >= 127)
{
u32 int_pos = (127 + 23) - exp;
u32 half_pos = int_pos - 1;
u32 half_bit = 1u << half_pos;
u32 int_bit = 1u << int_pos;
if (val & (int_bit | (half_bit - 1)))
val += half_bit;
val &= ~(int_bit - 1);
}
else if (exp == 126 && abs > 0x3f000000)
{
val &= 0x80000000;
val |= 0x3f800000;
}
else
{
val &= 0x80000000;
}
return std::bit_cast<f32>(val);
}
}
#if defined(ARCH_X64)
template <uint Mode>
const auto sse41_roundf = build_function_asm<__m128(*)(__m128)>("sse41_roundf", [](native_asm& c, native_args&)
{
static_assert(Mode < 4);
using namespace asmjit;
if (utils::has_avx())
c.vroundps(x86::xmm0, x86::xmm0, 8 + Mode);
else if (utils::has_sse41())
c.roundps(x86::xmm0, x86::xmm0, 8 + Mode);
else
c.jmp(+[](__m128 a) -> __m128
{
v128 r = a;
for (u32 i = 0; i < 4; i++)
if constexpr (Mode == 0)
r._f[i] = utils::roundevenf32(r._f[i]);
else if constexpr (Mode == 1)
r._f[i] = ::floorf(r._f[i]);
else if constexpr (Mode == 2)
r._f[i] = ::ceilf(r._f[i]);
else if constexpr (Mode == 3)
r._f[i] = ::truncf(r._f[i]);
return r;
});
c.ret();
});
#endif
inline v128 gv_roundfs_even(const v128& a)
{
#if defined(__SSE4_1__)
return _mm_round_ps(a, 8 + 0);
#elif defined(ARCH_ARM64)
return vrndnq_f32(a);
#elif defined(ARCH_X64)
return sse41_roundf<0>(a);
#else
v128 r;
for (u32 i = 0; i < 4; i++)
r._f[i] = utils::roundevenf32(a._f[i]);
return r;
#endif
}
inline v128 gv_roundfs_ceil(const v128& a)
{
#if defined(__SSE4_1__)
return _mm_round_ps(a, 8 + 2);
#elif defined(ARCH_ARM64)
return vrndpq_f32(a);
#elif defined(ARCH_X64)
return sse41_roundf<2>(a);
#else
v128 r;
for (u32 i = 0; i < 4; i++)
r._f[i] = ::ceilf(a._f[i]);
return r;
#endif
}
inline v128 gv_roundfs_floor(const v128& a)
{
#if defined(__SSE4_1__)
return _mm_round_ps(a, 8 + 1);
#elif defined(ARCH_ARM64)
return vrndmq_f32(a);
#elif defined(ARCH_X64)
return sse41_roundf<1>(a);
#else
v128 r;
for (u32 i = 0; i < 4; i++)
r._f[i] = ::floorf(a._f[i]);
return r;
#endif
}
inline v128 gv_roundfs_trunc(const v128& a)
{
#if defined(__SSE4_1__)
return _mm_round_ps(a, 8 + 3);
#elif defined(ARCH_ARM64)
return vrndq_f32(a);
#elif defined(ARCH_X64)
return sse41_roundf<3>(a);
#else
v128 r;
for (u32 i = 0; i < 4; i++)
r._f[i] = ::truncf(a._f[i]);
return r;
#endif
}
inline bool gv_testz(const v128& a)
{
#if defined(__SSE4_1__)
return !!_mm_testz_si128(a, a);
#elif defined(ARCH_X64)
return _mm_cvtsi128_si64(_mm_packs_epi32(a, a)) == 0;
#elif defined(ARCH_ARM64)
return std::bit_cast<s64>(vqmovn_s32(a)) == 0;
#else
return !(a._u64[0] | a._u64[1]);
#endif
}
// Same as gv_testz but tuned for pairing with gv_testall1
inline bool gv_testall0(const v128& a)
{
#if defined(__SSE4_1__)
return !!_mm_testz_si128(a, _mm_set1_epi32(-1));
#elif defined(ARCH_X64)
return _mm_cvtsi128_si64(_mm_packs_epi32(a, a)) == 0;
#elif defined(ARCH_ARM64)
return std::bit_cast<s64>(vqmovn_s32(a)) == 0;
#else
return !(a._u64[0] | a._u64[1]);
#endif
}
inline bool gv_testall1(const v128& a)
{
#if defined(__SSE4_1__)
return !!_mm_test_all_ones(a);
#elif defined(ARCH_X64)
return _mm_cvtsi128_si64(_mm_packs_epi32(a, a)) == -1;
#elif defined(ARCH_ARM64)
return std::bit_cast<s64>(vqmovn_s32(a)) == -1;
#else
return (a._u64[0] & a._u64[1]) == UINT64_MAX;
#endif
}
// result = (~a) & (b)
inline v128 gv_andn(const v128& a, const v128& b)
{
#if defined(ARCH_X64)
return _mm_andnot_si128(a, b);
#elif defined(ARCH_ARM64)
return vbicq_s32(b, a);
#endif
}
// Select elements; _cmp must be result of SIMD comparison; undefined otherwise
FORCE_INLINE v128 gv_select8(const v128& _cmp, const v128& _true, const v128& _false)
{
#if defined(__SSE4_1__)
return _mm_blendv_epi8(_false, _true, _cmp);
#elif defined(ARCH_ARM64)
return vbslq_u8(_cmp, _true, _false);
#else
return (_cmp & _true) | gv_andn(_cmp, _false);
#endif
}
// Select elements using sign bit only
FORCE_INLINE v128 gv_signselect8(const v128& bits, const v128& _true, const v128& _false)
{
#if defined(__SSE4_1__)
return _mm_blendv_epi8(_false, _true, bits);
#else
return gv_select8(gv_gts8(gv_bcst8(0), bits), _true, _false);
#endif
}
template <typename A, typename B, typename C> requires (asmjit::any_operand_v<A, B, C>)
inline asmjit::vec_type gv_signselect8(A&& bits, B&& _true, C&& _false)
{
using namespace asmjit;
#if defined(ARCH_X64)
if (utils::has_avx())
{
Operand arg0{};
Operand arg1 = arg_eval(std::forward<A>(bits), 16);
Operand arg2 = arg_eval(std::forward<B>(_true), 16);
Operand arg3 = arg_eval(std::forward<C>(_false), 16);
if constexpr (!std::is_reference_v<A>)
arg0.isReg() ? arg_free(bits) : arg0.copyFrom(arg1);
if constexpr (!std::is_reference_v<B>)
arg0.isReg() ? arg_free(_true) : arg0.copyFrom(arg2);
if constexpr (!std::is_reference_v<C>)
arg0.isReg() ? arg_free(_false) : arg0.copyFrom(arg3);
if (arg0.isNone())
arg0 = g_vc->vec_alloc();
g_vc->emit(x86::Inst::kIdVpblendvb, arg0, arg3, arg2, arg1);
vec_type r;
r.copyFrom(arg0);
return r;
}
#endif
g_vc->fail_flag = true;
return vec_type{0};
}
// Select elements; _cmp must be result of SIMD comparison; undefined otherwise
inline v128 gv_select16(const v128& _cmp, const v128& _true, const v128& _false)
{
#if defined(__SSE4_1__)
return _mm_blendv_epi8(_false, _true, _cmp);
#elif defined(ARCH_ARM64)
return vbslq_u16(_cmp, _true, _false);
#else
return (_cmp & _true) | gv_andn(_cmp, _false);
#endif
}
// Select elements; _cmp must be result of SIMD comparison; undefined otherwise
inline v128 gv_select32(const v128& _cmp, const v128& _true, const v128& _false)
{
#if defined(__SSE4_1__)
return _mm_blendv_epi8(_false, _true, _cmp);
#elif defined(ARCH_ARM64)
return vbslq_u32(_cmp, _true, _false);
#else
return (_cmp & _true) | gv_andn(_cmp, _false);
#endif
}
// Select elements; _cmp must be result of SIMD comparison; undefined otherwise
inline v128 gv_selectfs(const v128& _cmp, const v128& _true, const v128& _false)
{
#if defined(__SSE4_1__)
return _mm_blendv_ps(_false, _true, _cmp);
#elif defined(ARCH_ARM64)
return vbslq_f32(_cmp, _true, _false);
#else
return _mm_or_ps(_mm_and_ps(_cmp, _true), _mm_andnot_ps(_cmp, _false));
#endif
}
inline v128 gv_packss_s16(const v128& low, const v128& high)
{
#if defined(ARCH_X64)
return _mm_packs_epi16(low, high);
#elif defined(ARCH_ARM64)
return vcombine_s8(vqmovn_s16(low), vqmovn_s16(high));
#endif
}
inline v128 gv_packus_s16(const v128& low, const v128& high)
{
#if defined(ARCH_X64)
return _mm_packus_epi16(low, high);
#elif defined(ARCH_ARM64)
return vcombine_u8(vqmovun_s16(low), vqmovun_s16(high));
#endif
}
inline v128 gv_packus_u16(const v128& low, const v128& high)
{
#if defined(__SSE4_1__)
return _mm_packus_epi16(_mm_min_epu16(low, _mm_set1_epi16(0xff)), _mm_min_epu16(high, _mm_set1_epi16(0xff)));
#elif defined(ARCH_X64)
return _mm_packus_epi16(_mm_sub_epi16(low, _mm_subs_epu16(low, _mm_set1_epi16(0xff))), _mm_sub_epi16(high, _mm_subs_epu16(high, _mm_set1_epi16(0xff))));
#elif defined(ARCH_ARM64)
return vcombine_u8(vqmovn_u16(low), vqmovn_u16(high));
#endif
}
inline v128 gv_packtu16(const v128& low, const v128& high)
{
#if defined(ARCH_X64)
return _mm_packus_epi16(low & _mm_set1_epi16(0xff), high & _mm_set1_epi16(0xff));
#elif defined(ARCH_ARM64)
return vuzp1q_s8(low, high);
#endif
}
inline v128 gv_packss_s32(const v128& low, const v128& high)
{
#if defined(ARCH_X64)
return _mm_packs_epi32(low, high);
#elif defined(ARCH_ARM64)
return vcombine_s16(vqmovn_s32(low), vqmovn_s32(high));
#endif
}
inline v128 gv_packus_s32(const v128& low, const v128& high)
{
#if defined(__SSE4_1__)
return _mm_packus_epi32(low, high);
#elif defined(ARCH_X64)
const auto s = _mm_srai_epi16(_mm_packs_epi32(low, high), 15);
const auto r = gv_add16(_mm_packs_epi32(gv_sub32(low, gv_bcst32(0x8000)), gv_sub32(high, gv_bcst32(0x8000))), gv_bcst16(0x8000));
return gv_andn(s, r);
#elif defined(ARCH_ARM64)
return vcombine_u16(vqmovun_s32(low), vqmovun_s32(high));
#endif
}
inline v128 gv_packus_u32(const v128& low, const v128& high)
{
#if defined(__SSE4_1__)
return _mm_packus_epi32(_mm_min_epu32(low, _mm_set1_epi32(0xffff)), _mm_min_epu32(high, _mm_set1_epi32(0xffff)));
#elif defined(ARCH_X64)
const v128 s = _mm_cmpgt_epi16(_mm_packs_epi32(_mm_srli_epi32(low, 16), _mm_srli_epi32(high, 16)), _mm_setzero_si128());
const v128 r = _mm_packs_epi32(_mm_srai_epi32(_mm_slli_epi32(low, 16), 16), _mm_srai_epi32(_mm_slli_epi32(high, 16), 16));
return _mm_or_si128(r, s);
#elif defined(ARCH_ARM64)
return vcombine_u16(vqmovn_u32(low), vqmovn_u32(high));
#endif
}
inline v128 gv_packtu32(const v128& low, const v128& high)
{
#if defined(__SSE4_1__)
return _mm_packus_epi32(low & _mm_set1_epi32(0xffff), high & _mm_set1_epi32(0xffff));
#elif defined(ARCH_X64)
return _mm_packs_epi32(_mm_srai_epi32(_mm_slli_epi32(low, 16), 16), _mm_srai_epi32(_mm_slli_epi32(high, 16), 16));
#elif defined(ARCH_ARM64)
return vuzp1q_s16(low, high);
#endif
}
inline v128 gv_unpacklo8(const v128& lows, const v128& highs)
{
#if defined(ARCH_X64)
return _mm_unpacklo_epi8(lows, highs);
#elif defined(ARCH_ARM64)
return vzip1q_s8(lows, highs);
#endif
}
inline v128 gv_extend_lo_s8(const v128& vec)
{
#if defined(__SSE4_1__)
return _mm_cvtepi8_epi16(vec);
#elif defined(ARCH_X64)
return _mm_srai_epi16(_mm_unpacklo_epi8(vec, vec), 8);
#elif defined(ARCH_ARM64)
return int16x8_t(vmovl_s8(vget_low_s8(vec)));
#endif
}
template <typename A> requires (asmjit::any_operand_v<A>)
inline auto gv_extend_lo_s8(A&& a)
{
#if defined(ARCH_X64)
using enum asmjit::x86::Inst::Id;
if (utils::has_sse41())
return asmjit::unary_op(kIdNone, kIdPmovsxbw, std::forward<A>(a));
return asmjit::unary_op(kIdPsraw, kIdVpsraw, asmjit::unary_op(kIdNone, kIdPunpcklbw, std::forward<A>(a)), 8);
#endif
}
inline v128 gv_extend_hi_s8(const v128& vec)
{
#if defined(__SSE4_1__)
return _mm_cvtepi8_epi16(_mm_loadu_si64(vec._bytes + 8));
#elif defined(ARCH_X64)
return _mm_srai_epi16(_mm_unpackhi_epi8(vec, vec), 8);
#elif defined(ARCH_ARM64)
return int16x8_t(vmovl_s8(vget_high_s8(vec)));
#endif
}
template <typename A> requires (asmjit::any_operand_v<A>)
inline auto gv_extend_hi_s8(A&& a)
{
#if defined(ARCH_X64)
using enum asmjit::x86::Inst::Id;
return asmjit::unary_op(kIdPsraw, kIdVpsraw, asmjit::unary_op(kIdNone, kIdPunpckhbw, std::forward<A>(a)), 8);
#endif
}
inline v128 gv_unpacklo16(const v128& lows, const v128& highs)
{
#if defined(ARCH_X64)
return _mm_unpacklo_epi16(lows, highs);
#elif defined(ARCH_ARM64)
return vzip1q_s16(lows, highs);
#endif
}
inline v128 gv_extend_lo_s16(const v128& vec)
{
#if defined(__SSE4_1__)
return _mm_cvtepi16_epi32(vec);
#elif defined(ARCH_X64)
return _mm_srai_epi32(_mm_unpacklo_epi16(vec, vec), 16);
#elif defined(ARCH_ARM64)
return int32x4_t(vmovl_s16(vget_low_s16(vec)));
#endif
}
template <typename A> requires (asmjit::any_operand_v<A>)
inline auto gv_extend_lo_s16(A&& a)
{
#if defined(ARCH_X64)
using enum asmjit::x86::Inst::Id;
if (utils::has_sse41())
return asmjit::unary_op(kIdNone, kIdPmovsxwd, std::forward<A>(a));
return asmjit::unary_op(kIdPsrad, kIdVpsrad, asmjit::unary_op(kIdNone, kIdPunpcklwd, std::forward<A>(a)), 16);
#endif
}
inline v128 gv_extend_hi_s16(const v128& vec)
{
#if defined(__SSE4_1__)
return _mm_cvtepi16_epi32(_mm_loadu_si64(vec._bytes + 8));
#elif defined(ARCH_X64)
return _mm_srai_epi32(_mm_unpackhi_epi16(vec, vec), 16);
#elif defined(ARCH_ARM64)
return int32x4_t(vmovl_s16(vget_high_s16(vec)));
#endif
}
template <typename A> requires (asmjit::any_operand_v<A>)
inline auto gv_extend_hi_s16(A&& a)
{
#if defined(ARCH_X64)
using enum asmjit::x86::Inst::Id;
return asmjit::unary_op(kIdPsrad, kIdVpsrad, asmjit::unary_op(kIdNone, kIdPunpckhwd, std::forward<A>(a)), 16);
#endif
}
inline v128 gv_unpacklo32(const v128& lows, const v128& highs)
{
#if defined(ARCH_X64)
return _mm_unpacklo_epi32(lows, highs);
#elif defined(ARCH_ARM64)
return vzip1q_s32(lows, highs);
#endif
}
inline v128 gv_unpackhi8(const v128& lows, const v128& highs)
{
#if defined(ARCH_X64)
return _mm_unpackhi_epi8(lows, highs);
#elif defined(ARCH_ARM64)
return vzip2q_s8(lows, highs);
#endif
}
inline v128 gv_unpackhi16(const v128& lows, const v128& highs)
{
#if defined(ARCH_X64)
return _mm_unpackhi_epi16(lows, highs);
#elif defined(ARCH_ARM64)
return vzip2q_s16(lows, highs);
#endif
}
inline v128 gv_unpackhi32(const v128& lows, const v128& highs)
{
#if defined(ARCH_X64)
return _mm_unpackhi_epi32(lows, highs);
#elif defined(ARCH_ARM64)
return vzip2q_s32(lows, highs);
#endif
}
inline bool v128::operator==(const v128& b) const
{
#if defined(ARCH_X64)
return gv_testz(_mm_xor_si128(*this, b));
#else
return gv_testz(*this ^ b);
#endif
}
inline v128 v128::operator|(const v128& rhs) const
{
#if defined(ARCH_X64)
return _mm_or_si128(*this, rhs);
#elif defined(ARCH_ARM64)
return vorrq_s32(*this, rhs);
#endif
}
inline v128 v128::operator&(const v128& rhs) const
{
#if defined(ARCH_X64)
return _mm_and_si128(*this, rhs);
#elif defined(ARCH_ARM64)
return vandq_s32(*this, rhs);
#endif
}
inline v128 v128::operator^(const v128& rhs) const
{
#if defined(ARCH_X64)
return _mm_xor_si128(*this, rhs);
#elif defined(ARCH_ARM64)
return veorq_s32(*this, rhs);
#endif
}
inline v128 v128::operator~() const
{
#if defined(ARCH_X64)
return _mm_xor_si128(*this, _mm_set1_epi32(-1));
#elif defined(ARCH_ARM64)
return vmvnq_u32(*this);
#endif
}
inline v128 gv_exp2_approxfs(const v128& a)
{
// TODO
#if 0
const auto x0 = _mm_max_ps(_mm_min_ps(a, _mm_set1_ps(127.4999961f)), _mm_set1_ps(-127.4999961f));
const auto x1 = _mm_add_ps(x0, _mm_set1_ps(0.5f));
const auto x2 = _mm_sub_epi32(_mm_cvtps_epi32(x1), _mm_and_si128(_mm_castps_si128(_mm_cmpnlt_ps(_mm_setzero_ps(), x1)), _mm_set1_epi32(1)));
const auto x3 = _mm_sub_ps(x0, _mm_cvtepi32_ps(x2));
const auto x4 = _mm_mul_ps(x3, x3);
const auto x5 = _mm_mul_ps(x3, _mm_add_ps(_mm_mul_ps(_mm_add_ps(_mm_mul_ps(x4, _mm_set1_ps(0.023093347705f)), _mm_set1_ps(20.20206567f)), x4), _mm_set1_ps(1513.906801f)));
const auto x6 = _mm_mul_ps(x5, _mm_rcp_ps(_mm_sub_ps(_mm_add_ps(_mm_mul_ps(_mm_set1_ps(233.1842117f), x4), _mm_set1_ps(4368.211667f)), x5)));
return _mm_mul_ps(_mm_add_ps(_mm_add_ps(x6, x6), _mm_set1_ps(1.0f)), _mm_castsi128_ps(_mm_slli_epi32(_mm_add_epi32(x2, _mm_set1_epi32(127)), 23)));
#else
v128 r;
for (u32 i = 0; i < 4; i++)
r._f[i] = std::exp2f(a._f[i]);
return r;
#endif
}
inline v128 gv_log2_approxfs(const v128& a)
{
// TODO
#if 0
const auto _1 = _mm_set1_ps(1.0f);
const auto _c = _mm_set1_ps(1.442695040f);
const auto x0 = _mm_max_ps(a, _mm_castsi128_ps(_mm_set1_epi32(0x00800000)));
const auto x1 = _mm_or_ps(_mm_and_ps(x0, _mm_castsi128_ps(_mm_set1_epi32(0x807fffff))), _1);
const auto x2 = _mm_rcp_ps(_mm_add_ps(x1, _1));
const auto x3 = _mm_mul_ps(_mm_sub_ps(x1, _1), x2);
const auto x4 = _mm_add_ps(x3, x3);
const auto x5 = _mm_mul_ps(x4, x4);
const auto x6 = _mm_add_ps(_mm_mul_ps(_mm_add_ps(_mm_mul_ps(_mm_set1_ps(-0.7895802789f), x5), _mm_set1_ps(16.38666457f)), x5), _mm_set1_ps(-64.1409953f));
const auto x7 = _mm_rcp_ps(_mm_add_ps(_mm_mul_ps(_mm_add_ps(_mm_mul_ps(_mm_set1_ps(-35.67227983f), x5), _mm_set1_ps(312.0937664f)), x5), _mm_set1_ps(-769.6919436f)));
const auto x8 = _mm_cvtepi32_ps(_mm_sub_epi32(_mm_srli_epi32(_mm_castps_si128(x0), 23), _mm_set1_epi32(127)));
return _mm_add_ps(_mm_mul_ps(_mm_mul_ps(_mm_mul_ps(_mm_mul_ps(x5, x6), x7), x4), _c), _mm_add_ps(_mm_mul_ps(x4, _c), x8));
#else
v128 r;
for (u32 i = 0; i < 4; i++)
r._f[i] = std::log2f(a._f[i]);
return r;
#endif
}
// For each 8-bit element, r = a << (b & 7)
inline v128 gv_shl8(const v128& a, const v128& b)
{
#if defined(ARCH_ARM64)
return vshlq_u8(a, vandq_s8(b, gv_bcst8(7)));
#else
const v128 x1 = gv_add8(a, a); // shift left by 1
const v128 r1 = gv_signselect8(gv_shl64(b, 7), x1, a);
const v128 x2 = gv_and32(gv_shl64(r1, 2), gv_bcst8(0xfc)); // shift by 2
const v128 r2 = gv_signselect8(gv_shl64(b, 6), x2, r1);
const v128 x3 = gv_and32(gv_shl64(r2, 4), gv_bcst8(0xf0)); // shift by 4
return gv_signselect8(gv_shl64(b, 5), x3, r2);
#endif
}
// For each 16-bit element, r = a << (b & 15)
inline v128 gv_shl16(const v128& a, const v128& b)
{
#if defined(__AVX512VL__) && defined(__AVX512BW__)
return _mm_sllv_epi16(a, _mm_and_si128(b, _mm_set1_epi16(15)));
#elif defined(ARCH_ARM64)
return vshlq_u16(a, vandq_s16(b, gv_bcst8(15)));
#else
v128 r;
for (u32 i = 0; i < 8; i++)
r._u16[i] = a._u16[i] << (b._u16[i] & 15);
return r;
#endif
}
// For each 32-bit element, r = a << (b & 31)
inline v128 gv_shl32(const v128& a, const v128& b)
{
#if defined(__AVX2__)
return _mm_sllv_epi32(a, _mm_and_si128(b, _mm_set1_epi32(31)));
#elif defined(ARCH_ARM64)
return vshlq_u32(a, vandq_s32(b, gv_bcst8(31)));
#else
v128 r;
for (u32 i = 0; i < 4; i++)
r._u32[i] = a._u32[i] << (b._u32[i] & 31);
return r;
#endif
}
// For each unsigned 8-bit element, r = a >> (b & 7)
inline v128 gv_shr8(const v128& a, const v128& b)
{
#if defined(ARCH_ARM64)
return vshlq_u8(a, vnegq_s8(vandq_s8(b, gv_bcst8(7))));
#else
const v128 x1 = gv_and32(gv_shr64(a, 1), gv_bcst8(0x7f)); // shift right by 1
const v128 r1 = gv_signselect8(gv_shl64(b, 7), x1, a);
const v128 x2 = gv_and32(gv_shr64(r1, 2), gv_bcst8(0x3f)); // shift by 2
const v128 r2 = gv_signselect8(gv_shl64(b, 6), x2, r1);
const v128 x3 = gv_and32(gv_shr64(r2, 4), gv_bcst8(0x0f)); // shift by 4
return gv_signselect8(gv_shl64(b, 5), x3, r2);
#endif
}
// For each unsigned 16-bit element, r = a >> (b & 15)
inline v128 gv_shr16(const v128& a, const v128& b)
{
#if defined(__AVX512VL__) && defined(__AVX512BW__)
return _mm_srlv_epi16(a, _mm_and_si128(b, _mm_set1_epi16(15)));
#elif defined(ARCH_ARM64)
return vshlq_u16(a, vnegq_s16(vandq_s16(b, gv_bcst8(15))));
#else
v128 r;
for (u32 i = 0; i < 8; i++)
r._u16[i] = a._u16[i] >> (b._u16[i] & 15);
return r;
#endif
}
// For each unsigned 32-bit element, r = a >> (b & 31)
inline v128 gv_shr32(const v128& a, const v128& b)
{
#if defined(__AVX2__)
return _mm_srlv_epi32(a, _mm_and_si128(b, _mm_set1_epi32(31)));
#elif defined(ARCH_ARM64)
return vshlq_u32(a, vnegq_s32(vandq_s32(b, gv_bcst8(31))));
#else
v128 r;
for (u32 i = 0; i < 4; i++)
r._u32[i] = a._u32[i] >> (b._u32[i] & 31);
return r;
#endif
}
// For each signed 8-bit element, r = a >> (b & 7)
inline v128 gv_sar8(const v128& a, const v128& b)
{
#if defined(ARCH_ARM64)
return vshlq_s8(a, vnegq_s8(vandq_s8(b, gv_bcst8(7))));
#else
v128 r;
for (u32 i = 0; i < 16; i++)
r._s8[i] = a._s8[i] >> (b._s8[i] & 7);
return r;
#endif
}
// For each signed 16-bit element, r = a >> (b & 15)
inline v128 gv_sar16(const v128& a, const v128& b)
{
#if defined(__AVX512VL__) && defined(__AVX512BW__)
return _mm_srav_epi16(a, _mm_and_si128(b, _mm_set1_epi16(15)));
#elif defined(ARCH_ARM64)
return vshlq_s16(a, vnegq_s16(vandq_s16(b, gv_bcst8(15))));
#else
v128 r;
for (u32 i = 0; i < 8; i++)
r._s16[i] = a._s16[i] >> (b._s16[i] & 15);
return r;
#endif
}
// For each signed 32-bit element, r = a >> (b & 31)
inline v128 gv_sar32(const v128& a, const v128& b)
{
#if defined(__AVX2__)
return _mm_srav_epi32(a, _mm_and_si128(b, _mm_set1_epi32(31)));
#elif defined(ARCH_ARM64)
return vshlq_s32(a, vnegq_s32(vandq_s32(b, gv_bcst8(31))));
#else
v128 r;
for (u32 i = 0; i < 4; i++)
r._s32[i] = a._s32[i] >> (b._s32[i] & 31);
return r;
#endif
}
// For each 8-bit element, r = rotate a by b
inline v128 gv_rol8(const v128& a, const v128& b)
{
#if defined(ARCH_ARM64)
const auto amt1 = vandq_s8(b, gv_bcst8(7));
const auto amt2 = vsubq_s8(amt1, gv_bcst8(8));
return vorrq_u8(vshlq_u8(a, amt1), vshlq_u8(a, amt2));
#else
const v128 x1 = gv_sub8(gv_add8(a, a), gv_gts8(gv_bcst8(0), a)); // rotate left by 1
const v128 r1 = gv_signselect8(gv_shl64(b, 7), x1, a);
const v128 c2 = gv_bcst8(0x3);
const v128 x2 = gv_or32(gv_and32(gv_shr64(r1, 6), c2), gv_andn32(c2, gv_shl64(r1, 2))); // rotate by 2
const v128 r2 = gv_signselect8(gv_shl64(b, 6), x2, r1);
const v128 c3 = gv_bcst8(0xf);
const v128 x3 = gv_or32(gv_and32(gv_shr64(r2, 4), c3), gv_andn32(c3, gv_shl64(r2, 4))); // rotate by 4
return gv_signselect8(gv_shl64(b, 5), x3, r2);
#endif
}
// For each 16-bit element, r = rotate a by b
inline v128 gv_rol16(const v128& a, const v128& b)
{
#if defined(ARCH_ARM64)
const auto amt1 = vandq_s16(b, gv_bcst16(15));
const auto amt2 = vsubq_s16(amt1, gv_bcst16(16));
return vorrq_u16(vshlq_u16(a, amt1), vshlq_u16(a, amt2));
#else
v128 r;
for (u32 i = 0; i < 8; i++)
r._u16[i] = utils::rol16(a._u16[i], b._u16[i]);
return r;
#endif
}
// For each 32-bit element, r = rotate a by b
inline v128 gv_rol32(const v128& a, const v128& b)
{
#if defined(__AVX512VL__)
return _mm_rolv_epi32(a, b);
#elif defined(ARCH_ARM64)
const auto amt1 = vandq_s32(b, gv_bcst32(31));
const auto amt2 = vsubq_s32(amt1, gv_bcst32(32));
return vorrq_u32(vshlq_u32(a, amt1), vshlq_u32(a, amt2));
#else
v128 r;
for (u32 i = 0; i < 4; i++)
r._u32[i] = utils::rol32(a._u32[i], b._u32[i]);
return r;
#endif
}
// For each 32-bit element, r = rotate a by count
inline v128 gv_rol32(const v128& a, u32 count)
{
count %= 32;
#if defined(ARCH_X64)
return _mm_or_epi32(_mm_srli_epi32(a, 32 - count), _mm_slli_epi32(a, count));
#elif defined(ARCH_ARM64)
const auto amt1 = vdupq_n_s32(count);
const auto amt2 = vdupq_n_s32(count - 32);
return vorrq_u32(vshlq_u32(a, amt1), vshlq_u32(a, amt2));
#else
v128 r;
for (u32 i = 0; i < 4; i++)
r._u32[i] = utils::rol32(a._u32[i], count);
return r;
#endif
}
// For each 8-bit element, r = (a << (c & 7)) | (b >> (~c & 7) >> 1)
template <typename A, typename B, typename C>
inline auto gv_fshl8(A&& a, B&& b, C&& c)
{
#if defined(ARCH_ARM64)
const auto amt1 = vandq_s8(c, gv_bcst8(7));
const auto amt2 = vsubq_s8(amt1, gv_bcst8(8));
return v128(vorrq_u8(vshlq_u8(a, amt1), vshlq_u8(b, amt2)));
#else
auto x1 = gv_sub8(gv_add8(a, a), gv_gts8(gv_bcst8(0), b));
auto s1 = gv_shl64(c, 7);
auto r1 = gv_signselect8(s1, std::move(x1), std::forward<A>(a));
auto b1 = gv_signselect8(std::move(s1), gv_shl64(b, 1), std::forward<B>(b));
auto c2 = gv_bcst8(0x3);
auto x2 = gv_and32(gv_shr64(b1, 6), c2); x2 = gv_or32(std::move(x2), gv_andn32(std::move(c2), gv_shl64(r1, 2)));
auto s2 = gv_shl64(c, 6);
auto r2 = gv_signselect8(s2, std::move(x2), std::move(r1));
auto b2 = gv_signselect8(std::move(s2), gv_shl64(b1, 2), std::move(b1));
auto c3 = gv_bcst8(0xf);
auto x3 = gv_and32(gv_shr64(std::move(b2), 4), c3); x3 = gv_or32(std::move(x3), gv_andn32(std::move(c3), gv_shl64(r2, 4)));
return gv_signselect8(gv_shl64(std::move(c), 5), std::move(x3), std::move(r2));
#endif
}
// For each 8-bit element, r = (b >> (c & 7)) | (a << (~c & 7) << 1)
template <typename A, typename B, typename C>
inline auto gv_fshr8(A&& a, B&& b, C&& c)
{
#if defined(ARCH_ARM64)
const auto amt1 = vandq_s8(c, gv_bcst8(7));
const auto amt2 = vsubq_s8(gv_bcst8(8), amt1);
return vorrq_u8(vshlq_u8(b, vnegq_s8(amt1)), vshlq_u8(a, amt2));
#else
auto c1 = gv_bcst8(0x7f);
auto x1 = gv_and32(gv_shr64(b, 1), c1); x1 = gv_or32(std::move(x1), gv_andn32(std::move(c1), gv_shl64(a, 7)));
auto s1 = gv_shl64(c, 7);
auto r1 = gv_signselect8(s1, std::move(x1), std::move(b));
auto a1 = gv_signselect8(std::move(s1), gv_shr64(a, 1), std::move(a));
auto c2 = gv_bcst8(0x3f);
auto x2 = gv_and32(gv_shr64(r1, 2), c2); x2 = gv_or32(std::move(x2), gv_andn32(std::move(c2), gv_shl64(a1, 6)));
auto s2 = gv_shl64(c, 6);
auto r2 = gv_signselect8(s2, std::move(x2), std::move(r1));
auto a2 = gv_signselect8(std::move(s2), gv_shr64(a1, 2), std::move(a1));
auto c3 = gv_bcst8(0x0f);
auto x3 = gv_and32(gv_shr64(r2, 4), c3); x3 = gv_or32(std::move(x3), gv_andn32(std::move(c3), gv_shl64(std::move(a2), 4)));
return gv_signselect8(gv_shl64(std::move(c), 5), std::move(x3), std::move(r2));
#endif
}
// Shift left by byte amount
template <u32 Count>
inline v128 gv_shuffle_left(const v128& a)
{
if (Count > 15)
return {};
#if defined(ARCH_X64)
return _mm_slli_si128(a, Count);
#elif defined(ARCH_ARM64)
v128 idx;
for (u32 i = 0; i < 16; i++)
idx._u8[i] = u8(i - Count);
return vqtbl1q_u8(a, idx);
#endif
}
template <u32 Count, typename A> requires (asmjit::any_operand_v<A>)
inline auto gv_shuffle_left(A&& a)
{
FOR_X64(unary_op, kIdPslldq, kIdVpslldq, std::forward<A>(a), Count);
}
// Shift right by byte amount
template <u32 Count>
inline v128 gv_shuffle_right(const v128& a)
{
if (Count > 15)
return {};
#if defined(ARCH_X64)
return _mm_srli_si128(a, Count);
#elif defined(ARCH_ARM64)
v128 idx;
for (u32 i = 0; i < 16; i++)
idx._u8[i] = u8(i + Count);
return vqtbl1q_u8(a, idx);
#endif
}
template <u32 Count, typename A> requires (asmjit::any_operand_v<A>)
inline auto gv_shuffle_right(A&& a)
{
FOR_X64(unary_op, kIdPsrldq, kIdVpsrldq, std::forward<A>(a), Count);
}
#if defined(__clang__)
#pragma clang diagnostic pop
#elif defined(__GNUC__)
#pragma GCC diagnostic pop
#endif
| 82,255
|
C++
|
.h
| 2,807
| 27.393659
| 172
| 0.671169
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
5,668
|
coro.hpp
|
RPCS3_rpcs3/rpcs3/util/coro.hpp
|
#pragma once
#if __has_include(<coroutine>)
#if defined(__clang__) && !defined(__cpp_impl_coroutine)
#define __cpp_impl_coroutine 123
#endif
#include <coroutine>
#if defined(__clang__) && (__cpp_impl_coroutine == 123)
namespace std::experimental
{
using ::std::coroutine_traits;
using ::std::coroutine_handle;
}
#endif
#elif __has_include(<experimental/coroutine>)
#include <experimental/coroutine>
namespace std
{
using experimental::coroutine_traits;
using experimental::coroutine_handle;
using experimental::noop_coroutine_handle;
using experimental::suspend_always;
using experimental::suspend_never;
}
#endif
#include <iterator>
namespace stx
{
template <typename T>
struct lazy;
template <typename T>
struct generator;
namespace detail
{
struct lazy_promise_base
{
struct final_suspend_t
{
constexpr bool await_ready() const noexcept { return false; }
template <typename P>
std::coroutine_handle<> await_suspend(std::coroutine_handle<P> h) noexcept
{
return h.promise().m_handle;
}
void await_resume() noexcept {}
};
constexpr lazy_promise_base() noexcept = default;
lazy_promise_base(const lazy_promise_base&) = delete;
lazy_promise_base& operator=(const lazy_promise_base&) = delete;
std::suspend_always initial_suspend() { return {}; }
final_suspend_t final_suspend() noexcept { return {}; }
void unhandled_exception() {}
protected:
std::coroutine_handle<> m_handle{};
};
template <typename T>
struct lazy_promise final : lazy_promise_base
{
constexpr lazy_promise() noexcept = default;
lazy<T> get_return_object() noexcept;
template <typename U>
void return_value(U&& value)
{
m_value = std::forward<U>(value);
}
T& result() &
{
return m_value;
}
T&& result() &&
{
return m_value;
}
private:
T m_value{};
};
template <typename T>
struct lazy_promise<T&> final : lazy_promise_base
{
constexpr lazy_promise() noexcept = default;
lazy<T&> get_return_object() noexcept;
void return_value(T& value) noexcept
{
m_value = std::addressof(value);
}
T& result()
{
return *m_value;
}
private:
T* m_value{};
};
template <>
struct lazy_promise<void> final : lazy_promise_base
{
constexpr lazy_promise() noexcept = default;
lazy<void> get_return_object() noexcept;
void return_void() noexcept {}
void result() {}
};
}
template <typename T = void>
struct [[nodiscard]] lazy
{
using promise_type = detail::lazy_promise<T>;
using value_type = T;
struct awaitable_base
{
std::coroutine_handle<promise_type> coro;
bool await_ready() const noexcept
{
return !coro || coro.done();
}
std::coroutine_handle<> await_suspend(std::coroutine_handle<> h) noexcept
{
coro.promise().m_handle = h;
return coro;
}
};
lazy(const lazy&) = delete;
lazy(lazy&& rhs) noexcept
: m_handle(rhs.m_handle)
{
rhs.m_handle = nullptr;
}
lazy& operator=(const lazy&) = delete;
~lazy()
{
if (m_handle)
{
m_handle.destroy();
}
}
bool is_ready() const noexcept
{
return !m_handle || m_handle.done();
}
auto operator co_await() const & noexcept
{
struct awaitable : awaitable_base
{
using awaitable_base::awaitable_base;
decltype(auto) await_resume()
{
return this->m_handle.promise().result();
}
};
return awaitable{m_handle};
}
auto operator co_await() const && noexcept
{
struct awaitable : awaitable_base
{
using awaitable_base::awaitable_base;
decltype(auto) await_resume()
{
return std::move(this->m_handle.promise()).result();
}
};
return awaitable{m_handle};
}
private:
friend promise_type;
explicit constexpr lazy(std::coroutine_handle<promise_type> h) noexcept
: m_handle(h)
{
}
std::coroutine_handle<promise_type> m_handle;
};
template <typename T>
inline lazy<T> detail::lazy_promise<T>::get_return_object() noexcept
{
return lazy<T>{std::coroutine_handle<lazy_promise>::from_promise(*this)};
}
template <typename T>
inline lazy<T&> detail::lazy_promise<T&>::get_return_object() noexcept
{
return lazy<T&>{std::coroutine_handle<lazy_promise>::from_promise(*this)};
}
inline lazy<void> detail::lazy_promise<void>::get_return_object() noexcept
{
return lazy<void>{std::coroutine_handle<lazy_promise>::from_promise(*this)};
}
namespace detail
{
template <typename T>
struct generator_promise
{
using value_type = std::remove_reference_t<T>;
using reference_type = std::conditional_t<std::is_reference_v<T>, T, T&>;
generator_promise() = default;
generator<T> get_return_object() noexcept;
constexpr std::suspend_always initial_suspend() const noexcept { return {}; }
constexpr std::suspend_always final_suspend() const noexcept { return {}; }
void unhandled_exception() {}
std::suspend_always yield_value(std::remove_reference_t<T>& value) noexcept
{
m_ptr = std::addressof(value);
return {};
}
std::suspend_always yield_value(std::remove_reference_t<T>&& value) noexcept
{
m_ptr = std::addressof(value);
return {};
}
void return_void() {}
reference_type value() const noexcept
{
return static_cast<reference_type>(*m_ptr);
}
template <typename U>
std::suspend_never await_transform(U&& value) = delete;
private:
value_type* m_ptr;
};
struct generator_end
{
};
template<typename T>
struct generator_iterator
{
using iterator_category = std::input_iterator_tag;
using value_type = typename generator_promise<T>::value_type;
using reference = typename generator_promise<T>::reference_type;
constexpr generator_iterator() noexcept = default;
explicit constexpr generator_iterator(std::coroutine_handle<generator_promise<T>> coro) noexcept
: m_coro(coro)
{
}
bool operator==(generator_end) const noexcept
{
return !m_coro || m_coro.done();
}
generator_iterator& operator++()
{
m_coro.resume();
return *this;
}
void operator++(int)
{
m_coro.resume();
}
reference operator*() const noexcept
{
return m_coro.promise().value();
}
value_type* operator->() const noexcept
{
return std::addressof(operator*());
}
private:
std::coroutine_handle<generator_promise<T>> m_coro;
};
}
template<typename T>
struct [[nodiscard]] generator
{
using promise_type = detail::generator_promise<T>;
using iterator = detail::generator_iterator<T>;
generator(const generator&) = delete;
generator(generator&& rhs) noexcept
: m_handle(rhs.m_handle)
{
rhs.m_handle = nullptr;
}
generator& operator=(const generator&) = delete;
~generator()
{
if (m_handle)
{
m_handle.destroy();
}
}
iterator begin()
{
if (m_handle)
{
m_handle.resume();
}
return iterator{m_handle};
}
detail::generator_end end() noexcept
{
return detail::generator_end{};
}
private:
friend promise_type;
explicit constexpr generator(std::coroutine_handle<promise_type> h) noexcept
: m_handle(h)
{
}
std::coroutine_handle<promise_type> m_handle;
};
template <typename T>
generator<T> detail::generator_promise<T>::get_return_object() noexcept
{
return generator<T>{std::coroutine_handle<generator_promise<T>>::from_promise(*this)};
}
}
| 7,424
|
C++
|
.h
| 298
| 21.281879
| 99
| 0.682934
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
5,669
|
yaml.hpp
|
RPCS3_rpcs3/rpcs3/util/yaml.hpp
|
#pragma once
#include <utility>
#include <string>
#ifdef _MSC_VER
#pragma warning(push, 0)
#include "yaml-cpp/yaml.h"
#pragma warning(pop)
#else
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wall"
#pragma GCC diagnostic ignored "-Wextra"
#pragma GCC diagnostic ignored "-Wold-style-cast"
#pragma GCC diagnostic ignored "-Wattributes"
#pragma GCC diagnostic ignored "-Wstrict-aliasing"
#pragma GCC diagnostic ignored "-Weffc++"
#include "yaml-cpp/yaml.h"
#pragma GCC diagnostic pop
#endif
// Load from string and consume exception
std::pair<YAML::Node, std::string> yaml_load(const std::string& from);
// Use try/catch in YAML::Node::as<T>() instead of YAML::Node::as<T>(fallback) in order to get an error message
template <typename T>
T get_yaml_node_value(const YAML::Node& node, std::string& error_message);
// Get the location of the node in the document
std::string get_yaml_node_location(const YAML::Node& node);
std::string get_yaml_node_location(const YAML::detail::iterator_value& it);
| 1,014
|
C++
|
.h
| 26
| 37.807692
| 111
| 0.769074
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
5,670
|
shared_ptr.hpp
|
RPCS3_rpcs3/rpcs3/util/shared_ptr.hpp
|
#pragma once // No BOM and only basic ASCII in this header, or a neko will die
#include <cstdint>
#include <memory>
#include "atomic.hpp"
#include "bless.hpp"
namespace stx
{
template <typename To, typename From>
constexpr bool same_ptr_implicit_v = std::is_convertible_v<const volatile From*, const volatile To*> ? is_same_ptr<From, To>() : false;
template <typename T>
class single_ptr;
template <typename T>
class shared_ptr;
template <typename T>
class atomic_ptr;
// Basic assumption of userspace pointer size
constexpr uint c_ptr_size = 48;
// Use lower 16 bits as atomic_ptr internal counter of borrowed refs (pointer itself is shifted)
constexpr uint c_ref_mask = 0xffff, c_ref_size = 16;
// Remaining pointer bits
constexpr uptr c_ptr_mask = static_cast<uptr>(-1) << c_ref_size;
struct shared_counter
{
// Stored destructor
atomic_t<void (*)(shared_counter* _this) noexcept> destroy{};
// Reference counter
atomic_t<usz> refs{1};
};
template <usz Size, usz Align>
struct align_filler
{
};
template <usz Size, usz Align> requires (Align > Size)
struct align_filler<Size, Align>
{
char dummy[Align - Size];
};
// Control block with data and reference counter
template <typename T>
class shared_data final : align_filler<sizeof(shared_counter), alignof(T)>
{
public:
shared_counter m_ctr{};
T m_data;
template <typename... Args>
explicit constexpr shared_data(Args&&... args) noexcept
: m_data(std::forward<Args>(args)...)
{
}
};
template <typename T>
class shared_data<T[]> final : align_filler<sizeof(shared_counter) + sizeof(usz), alignof(T)>
{
public:
usz m_count{};
shared_counter m_ctr{};
constexpr shared_data() noexcept = default;
};
// Simplified unique pointer. In some cases, std::unique_ptr is preferred.
// This one is shared_ptr counterpart, it has a control block with refs and deleter.
// It's trivially convertible to shared_ptr, and back if refs == 1.
template <typename T>
class single_ptr
{
std::remove_extent_t<T>* m_ptr{};
shared_counter* d() const noexcept
{
// Shared counter, deleter, should be at negative offset
return std::launder(reinterpret_cast<shared_counter*>(reinterpret_cast<u64>(m_ptr) - sizeof(shared_counter)));
}
template <typename U>
friend class single_ptr;
template <typename U>
friend class shared_ptr;
template <typename U>
friend class atomic_ptr;
public:
using element_type = std::remove_extent_t<T>;
constexpr single_ptr() noexcept = default;
single_ptr(const single_ptr&) = delete;
// Default constructor or null_ptr should be used instead
[[deprecated("Use null_ptr")]] single_ptr(std::nullptr_t) = delete;
explicit single_ptr(shared_data<T>&, element_type* ptr) noexcept
: m_ptr(ptr)
{
}
single_ptr(single_ptr&& r) noexcept
: m_ptr(r.m_ptr)
{
r.m_ptr = nullptr;
}
template <typename U> requires same_ptr_implicit_v<T, U>
single_ptr(single_ptr<U>&& r) noexcept
{
m_ptr = r.m_ptr;
r.m_ptr = nullptr;
}
~single_ptr()
{
reset();
}
single_ptr& operator=(const single_ptr&) = delete;
[[deprecated("Use null_ptr")]] single_ptr& operator=(std::nullptr_t) = delete;
single_ptr& operator=(single_ptr&& r) noexcept
{
single_ptr(std::move(r)).swap(*this);
return *this;
}
template <typename U> requires same_ptr_implicit_v<T, U>
single_ptr& operator=(single_ptr<U>&& r) noexcept
{
single_ptr(std::move(r)).swap(*this);
return *this;
}
void reset() noexcept
{
if (m_ptr) [[likely]]
{
const auto o = d();
o->destroy.load()(o);
m_ptr = nullptr;
}
}
void swap(single_ptr& r) noexcept
{
std::swap(m_ptr, r.m_ptr);
}
element_type* get() const noexcept
{
return m_ptr;
}
decltype(auto) operator*() const noexcept requires (!std::is_void_v<element_type>)
{
return *m_ptr;
}
element_type* operator->() const noexcept
{
return m_ptr;
}
decltype(auto) operator[](std::ptrdiff_t idx) const noexcept requires (!std::is_void_v<element_type>)
{
if constexpr (std::is_array_v<T>)
{
return m_ptr[idx];
}
else
{
return *m_ptr;
}
}
template <typename... Args> requires (std::is_invocable_v<T, Args&&...>)
decltype(auto) operator()(Args&&... args) const noexcept
{
return std::invoke(*m_ptr, std::forward<Args>(args)...);
}
operator element_type*() const noexcept
{
return m_ptr;
}
explicit constexpr operator bool() const noexcept
{
return m_ptr != nullptr;
}
// "Moving" "static cast"
template <typename U> requires PtrSame<T, U>
explicit operator single_ptr<U>() && noexcept
{
single_ptr<U> r;
r.m_ptr = static_cast<decltype(r.m_ptr)>(std::exchange(m_ptr, nullptr));
return r;
}
};
#ifndef _MSC_VER
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Winvalid-offsetof"
#endif
template <typename T, bool Init = true, typename... Args>
static std::enable_if_t<!(std::is_unbounded_array_v<T>) && (Init || !sizeof...(Args)), single_ptr<T>> make_single(Args&&... args) noexcept
{
static_assert(offsetof(shared_data<T>, m_data) - offsetof(shared_data<T>, m_ctr) == sizeof(shared_counter));
using etype = std::remove_extent_t<T>;
shared_data<T>* ptr = nullptr;
if constexpr (Init && !std::is_array_v<T>)
{
ptr = new shared_data<T>(std::forward<Args>(args)...);
}
else
{
ptr = new shared_data<T>;
if constexpr (Init && std::is_array_v<T>)
{
// Weird case, destroy and reinitialize every fixed array arg (fill)
for (auto& e : ptr->m_data)
{
e.~etype();
new (&e) etype(std::forward<Args>(args)...);
}
}
}
ptr->m_ctr.destroy.raw() = [](shared_counter* _this) noexcept
{
delete reinterpret_cast<shared_data<T>*>(reinterpret_cast<u64>(_this) - offsetof(shared_data<T>, m_ctr));
};
return single_ptr<T>(*ptr, &ptr->m_data);
}
template <typename T, bool Init = true, usz Align = alignof(std::remove_extent_t<T>)>
static std::enable_if_t<std::is_unbounded_array_v<T>, single_ptr<T>> make_single(usz count) noexcept
{
static_assert(sizeof(shared_data<T>) - offsetof(shared_data<T>, m_ctr) == sizeof(shared_counter));
using etype = std::remove_extent_t<T>;
const usz size = sizeof(shared_data<T>) + count * sizeof(etype);
std::byte* bytes = nullptr;
if constexpr (Align > (__STDCPP_DEFAULT_NEW_ALIGNMENT__))
{
bytes = static_cast<std::byte*>(::operator new(size, std::align_val_t{Align}));
}
else
{
bytes = new std::byte[size];
}
// Initialize control block
shared_data<T>* ptr = new (reinterpret_cast<shared_data<T>*>(bytes)) shared_data<T>();
// Initialize array next to the control block
etype* arr = reinterpret_cast<etype*>(bytes + sizeof(shared_data<T>));
if constexpr (Init)
{
std::uninitialized_value_construct_n(arr, count);
}
else
{
std::uninitialized_default_construct_n(arr, count);
}
ptr->m_count = count;
ptr->m_ctr.destroy.raw() = [](shared_counter* _this) noexcept
{
shared_data<T>* ptr = reinterpret_cast<shared_data<T>*>(reinterpret_cast<u64>(_this) - offsetof(shared_data<T>, m_ctr));
std::byte* bytes = reinterpret_cast<std::byte*>(ptr);
std::destroy_n(std::launder(reinterpret_cast<etype*>(bytes + sizeof(shared_data<T>))), ptr->m_count);
ptr->~shared_data<T>();
if constexpr (Align > (__STDCPP_DEFAULT_NEW_ALIGNMENT__))
{
::operator delete[](bytes, std::align_val_t{Align});
}
else
{
delete[] bytes;
}
};
return single_ptr<T>(*ptr, std::launder(arr));
}
template <typename T>
static single_ptr<std::remove_reference_t<T>> make_single_value(T&& value)
{
return make_single<std::remove_reference_t<T>>(std::forward<T>(value));
}
#ifndef _MSC_VER
#pragma GCC diagnostic pop
#endif
// Simplified shared pointer
template <typename T>
class shared_ptr
{
std::remove_extent_t<T>* m_ptr{};
shared_counter* d() const noexcept
{
// Shared counter, deleter, should be at negative offset
return std::launder(reinterpret_cast<shared_counter*>(reinterpret_cast<u64>(m_ptr) - sizeof(shared_counter)));
}
template <typename U>
friend class shared_ptr;
template <typename U>
friend class atomic_ptr;
public:
using element_type = std::remove_extent_t<T>;
constexpr shared_ptr() noexcept = default;
shared_ptr(const shared_ptr& r) noexcept
: m_ptr(r.m_ptr)
{
if (m_ptr)
d()->refs++;
}
// Default constructor or null_ptr constant should be used instead
[[deprecated("Use null_ptr")]] shared_ptr(std::nullptr_t) = delete;
// Not-so-aliasing constructor: emulates std::enable_shared_from_this without its overhead
explicit shared_ptr(T* _this) noexcept
: m_ptr(_this)
{
// Random checks which may fail on invalid pointer
ensure((reinterpret_cast<u64>(d()->destroy) - 0x10000) >> 47 == 0);
ensure((d()->refs++ - 1) >> 58 == 0);
}
template <typename U> requires same_ptr_implicit_v<T, U>
shared_ptr(const shared_ptr<U>& r) noexcept
{
m_ptr = r.m_ptr;
if (m_ptr)
d()->refs++;
}
shared_ptr(shared_ptr&& r) noexcept
: m_ptr(r.m_ptr)
{
r.m_ptr = nullptr;
}
template <typename U> requires same_ptr_implicit_v<T, U>
shared_ptr(shared_ptr<U>&& r) noexcept
{
m_ptr = r.m_ptr;
r.m_ptr = nullptr;
}
template <typename U> requires same_ptr_implicit_v<T, U>
shared_ptr(single_ptr<U>&& r) noexcept
{
m_ptr = r.m_ptr;
r.m_ptr = nullptr;
}
~shared_ptr()
{
reset();
}
shared_ptr& operator=(const shared_ptr& r) noexcept
{
shared_ptr(r).swap(*this);
return *this;
}
[[deprecated("Use null_ptr")]] shared_ptr& operator=(std::nullptr_t) = delete;
template <typename U> requires same_ptr_implicit_v<T, U>
shared_ptr& operator=(const shared_ptr<U>& r) noexcept
{
shared_ptr(r).swap(*this);
return *this;
}
shared_ptr& operator=(shared_ptr&& r) noexcept
{
shared_ptr(std::move(r)).swap(*this);
return *this;
}
template <typename U> requires same_ptr_implicit_v<T, U>
shared_ptr& operator=(shared_ptr<U>&& r) noexcept
{
shared_ptr(std::move(r)).swap(*this);
return *this;
}
template <typename U> requires same_ptr_implicit_v<T, U>
shared_ptr& operator=(single_ptr<U>&& r) noexcept
{
shared_ptr(std::move(r)).swap(*this);
return *this;
}
// Set to null
void reset() noexcept
{
const auto o = d();
if (m_ptr && !--o->refs) [[unlikely]]
{
o->destroy(o);
m_ptr = nullptr;
}
}
// Converts to unique (single) ptr if reference is 1, otherwise returns null. Nullifies self.
template <typename U> requires PtrSame<T, U>
explicit operator single_ptr<U>() && noexcept
{
const auto o = d();
if (m_ptr && !--o->refs)
{
// Convert last reference to single_ptr instance.
o->refs.release(1);
single_ptr<T> r;
r.m_ptr = static_cast<decltype(r.m_ptr)>(std::exchange(m_ptr, nullptr));
return r;
}
// Otherwise, both pointers are gone. Didn't seem right to do it in the constructor.
m_ptr = nullptr;
return {};
}
void swap(shared_ptr& r) noexcept
{
std::swap(this->m_ptr, r.m_ptr);
}
element_type* get() const noexcept
{
return m_ptr;
}
decltype(auto) operator*() const noexcept requires (!std::is_void_v<element_type>)
{
return *m_ptr;
}
element_type* operator->() const noexcept
{
return m_ptr;
}
decltype(auto) operator[](std::ptrdiff_t idx) const noexcept requires (!std::is_void_v<element_type>)
{
if constexpr (std::is_array_v<T>)
{
return m_ptr[idx];
}
else
{
return *m_ptr;
}
}
template <typename... Args> requires (std::is_invocable_v<T, Args&&...>)
decltype(auto) operator()(Args&&... args) const noexcept
{
return std::invoke(*m_ptr, std::forward<Args>(args)...);
}
usz use_count() const noexcept
{
if (m_ptr)
{
return d()->refs;
}
else
{
return 0;
}
}
operator element_type*() const noexcept
{
return m_ptr;
}
explicit constexpr operator bool() const noexcept
{
return m_ptr != nullptr;
}
// Basic "static cast" support
template <typename U> requires PtrSame<T, U>
explicit operator shared_ptr<U>() const& noexcept
{
if (m_ptr)
{
d()->refs++;
}
shared_ptr<U> r;
r.m_ptr = static_cast<decltype(r.m_ptr)>(m_ptr);
return r;
}
// "Moving" "static cast"
template <typename U> requires PtrSame<T, U>
explicit operator shared_ptr<U>() && noexcept
{
shared_ptr<U> r;
r.m_ptr = static_cast<decltype(r.m_ptr)>(std::exchange(m_ptr, nullptr));
return r;
}
};
template <typename T, bool Init = true, typename... Args>
static std::enable_if_t<!std::is_unbounded_array_v<T> && (!Init || !sizeof...(Args)), shared_ptr<T>> make_shared(Args&&... args) noexcept
{
return make_single<T, Init>(std::forward<Args>(args)...);
}
template <typename T, bool Init = true>
static std::enable_if_t<std::is_unbounded_array_v<T>, shared_ptr<T>> make_shared(usz count) noexcept
{
return make_single<T, Init>(count);
}
template <typename T>
static shared_ptr<std::remove_reference_t<T>> make_shared_value(T&& value)
{
return make_single_value(std::forward<T>(value));
}
// Atomic simplified shared pointer
template <typename T>
class atomic_ptr
{
mutable atomic_t<uptr> m_val{0};
static shared_counter* d(uptr val)
{
return std::launder(reinterpret_cast<shared_counter*>((val >> c_ref_size) - sizeof(shared_counter)));
}
shared_counter* d() const noexcept
{
return d(m_val);
}
template <typename U>
friend class atomic_ptr;
public:
using element_type = std::remove_extent_t<T>;
using shared_type = shared_ptr<T>;
constexpr atomic_ptr() noexcept = default;
// Optimized value construct
template <typename... Args> requires (!(sizeof...(Args) == 1 && (std::is_same_v<std::remove_cvref_t<Args>, shared_type> || ...)) && std::is_constructible_v<T, Args...>)
explicit atomic_ptr(Args&&... args) noexcept
{
shared_type r = make_single<T>(std::forward<Args>(args)...);
m_val = reinterpret_cast<uptr>(std::exchange(r.m_ptr, nullptr)) << c_ref_size;
d()->refs.raw() += c_ref_mask;
}
template <typename U> requires same_ptr_implicit_v<T, U>
atomic_ptr(const shared_ptr<U>& r) noexcept
{
// Obtain a ref + as many refs as an atomic_ptr can additionally reference
m_val = reinterpret_cast<uptr>(r.m_ptr) << c_ref_size;
if (m_val)
d()->refs += c_ref_mask + 1;
}
template <typename U> requires same_ptr_implicit_v<T, U>
atomic_ptr(shared_ptr<U>&& r) noexcept
{
m_val = reinterpret_cast<uptr>(r.m_ptr) << c_ref_size;
r.m_ptr = nullptr;
if (m_val)
d()->refs += c_ref_mask;
}
template <typename U> requires same_ptr_implicit_v<T, U>
atomic_ptr(single_ptr<U>&& r) noexcept
{
m_val = reinterpret_cast<uptr>(r.m_ptr) << c_ref_size;
r.m_ptr = nullptr;
if (m_val)
d()->refs += c_ref_mask;
}
~atomic_ptr()
{
const uptr v = m_val.raw();
const auto o = d(v);
if (v >> c_ref_size && !o->refs.sub_fetch(c_ref_mask + 1 - (v & c_ref_mask)))
{
o->destroy.load()(o);
}
}
// Optimized value assignment
atomic_ptr& operator=(std::remove_cv_t<T> value) noexcept
{
shared_type r = make_single<T>(std::move(value));
r.d()->refs.raw() += c_ref_mask;
atomic_ptr old;
old.m_val.raw() = m_val.exchange(reinterpret_cast<uptr>(std::exchange(r.m_ptr, nullptr)) << c_ref_size);
return *this;
}
template <typename U> requires same_ptr_implicit_v<T, U>
atomic_ptr& operator=(const shared_ptr<U>& r) noexcept
{
store(r);
return *this;
}
template <typename U> requires same_ptr_implicit_v<T, U>
atomic_ptr& operator=(shared_ptr<U>&& r) noexcept
{
store(std::move(r));
return *this;
}
template <typename U> requires same_ptr_implicit_v<T, U>
atomic_ptr& operator=(single_ptr<U>&& r) noexcept
{
store(std::move(r));
return *this;
}
void reset() noexcept
{
store(shared_type{});
}
shared_type load() const noexcept
{
shared_type r;
// Add reference
const auto [prev, did_ref] = m_val.fetch_op([](uptr& val)
{
if (val >> c_ref_size)
{
val++;
return true;
}
return false;
});
if (!did_ref)
{
// Null pointer
return r;
}
// Set referenced pointer
r.m_ptr = std::launder(reinterpret_cast<element_type*>(prev >> c_ref_size));
r.d()->refs++;
// Dereference if still the same pointer
const auto [_, did_deref] = m_val.fetch_op([prev = prev](uptr& val)
{
if (val >> c_ref_size == prev >> c_ref_size)
{
val--;
return true;
}
return false;
});
if (!did_deref)
{
// Otherwise fix ref count (atomic_ptr has been overwritten)
r.d()->refs--;
}
return r;
}
// Atomically inspect pointer with the possibility to reference it if necessary
template <typename F, typename RT = std::invoke_result_t<F, const shared_type&>>
RT peek_op(F op) const noexcept
{
shared_type r;
// Add reference
const auto [prev, did_ref] = m_val.fetch_op([](uptr& val)
{
if (val >> c_ref_size)
{
val++;
return true;
}
return false;
});
// Set fake unreferenced pointer
if (did_ref)
{
r.m_ptr = std::launder(reinterpret_cast<element_type*>(prev >> c_ref_size));
}
// Result temp storage
[[maybe_unused]] std::conditional_t<std::is_void_v<RT>, int, RT> result;
// Invoke
if constexpr (std::is_void_v<RT>)
{
std::invoke(op, std::as_const(r));
if (!did_ref)
{
return;
}
}
else
{
result = std::invoke(op, std::as_const(r));
if (!did_ref)
{
return result;
}
}
// Dereference if still the same pointer
const auto [_, did_deref] = m_val.fetch_op([prev = prev](uptr& val)
{
if (val >> c_ref_size == prev >> c_ref_size)
{
val--;
return true;
}
return false;
});
if (did_deref)
{
// Deactivate fake pointer
r.m_ptr = nullptr;
}
if constexpr (std::is_void_v<RT>)
{
return;
}
else
{
return result;
}
}
// Create an object from variadic args
// If a type needs shared_type to be constructed, std::reference_wrapper can be used
template <typename... Args> requires (!(sizeof...(Args) == 1 && (std::is_same_v<std::remove_cvref_t<Args>, shared_type> || ...)) && std::is_constructible_v<T, Args...>)
void store(Args&&... args) noexcept
{
shared_type r = make_single<T>(std::forward<Args>(args)...);
r.d()->refs.raw() += c_ref_mask;
atomic_ptr old;
old.m_val.raw() = m_val.exchange(reinterpret_cast<uptr>(std::exchange(r.m_ptr, nullptr)) << c_ref_size);
}
void store(shared_type value) noexcept
{
if (value.m_ptr)
{
// Consume value and add refs
value.d()->refs += c_ref_mask;
}
atomic_ptr old;
old.m_val.raw() = m_val.exchange(reinterpret_cast<uptr>(std::exchange(value.m_ptr, nullptr)) << c_ref_size);
}
template <typename... Args> requires (!(sizeof...(Args) == 1 && (std::is_same_v<std::remove_cvref_t<Args>, shared_type> || ...)) && std::is_constructible_v<T, Args...>)
[[nodiscard]] shared_type exchange(Args&&... args) noexcept
{
shared_type r = make_single<T>(std::forward<Args>(args)...);
r.d()->refs.raw() += c_ref_mask;
atomic_ptr old;
old.m_val.raw() += m_val.exchange(reinterpret_cast<uptr>(r.m_ptr) << c_ref_size);
old.m_val.raw() += 1;
r.m_ptr = std::launder(reinterpret_cast<element_type*>(old.m_val >> c_ref_size));
return r;
}
[[nodiscard]] shared_type exchange(shared_type value) noexcept
{
if (value.m_ptr)
{
// Consume value and add refs
value.d()->refs += c_ref_mask;
}
atomic_ptr old;
old.m_val.raw() += m_val.exchange(reinterpret_cast<uptr>(value.m_ptr) << c_ref_size);
old.m_val.raw() += 1;
value.m_ptr = std::launder(reinterpret_cast<element_type*>(old.m_val >> c_ref_size));
return value;
}
// Ineffective
[[nodiscard]] bool compare_exchange(shared_type& cmp_and_old, shared_type exch)
{
const uptr _old = reinterpret_cast<uptr>(cmp_and_old.m_ptr);
const uptr _new = reinterpret_cast<uptr>(exch.m_ptr);
if (exch.m_ptr)
{
exch.d()->refs += c_ref_mask;
}
atomic_ptr old;
const uptr _val = m_val.fetch_op([&](uptr& val)
{
if (val >> c_ref_size == _old)
{
// Set new value
val = _new << c_ref_size;
}
else if (val)
{
// Reference previous value
val++;
}
});
if (_val >> c_ref_size == _old)
{
// Success (exch is consumed, cmp_and_old is unchanged)
if (exch.m_ptr)
{
exch.m_ptr = nullptr;
}
// Cleanup
old.m_val.raw() = _val;
return true;
}
atomic_ptr old_exch;
old_exch.m_val.raw() = reinterpret_cast<uptr>(std::exchange(exch.m_ptr, nullptr)) << c_ref_size;
// Set to reset old cmp_and_old value
old.m_val.raw() = (reinterpret_cast<uptr>(cmp_and_old.m_ptr) << c_ref_size) | c_ref_mask;
if (!_val)
{
return false;
}
// Set referenced pointer
cmp_and_old.m_ptr = std::launder(reinterpret_cast<element_type*>(_val >> c_ref_size));
cmp_and_old.d()->refs++;
// Dereference if still the same pointer
const auto [_, did_deref] = m_val.fetch_op([_val](uptr& val)
{
if (val >> c_ref_size == _val >> c_ref_size)
{
val--;
return true;
}
return false;
});
if (!did_deref)
{
// Otherwise fix ref count (atomic_ptr has been overwritten)
cmp_and_old.d()->refs--;
}
return false;
}
// Unoptimized
template <typename U> requires same_ptr_implicit_v<T, U>
shared_type compare_and_swap(const shared_ptr<U>& cmp, shared_type exch)
{
shared_type old = cmp;
static_cast<void>(compare_exchange(old, std::move(exch)));
return old;
}
// More lightweight than compare_exchange
template <typename U> requires same_ptr_implicit_v<T, U>
bool compare_and_swap_test(const shared_ptr<U>& cmp, shared_type exch)
{
const uptr _old = reinterpret_cast<uptr>(cmp.m_ptr);
const uptr _new = reinterpret_cast<uptr>(exch.m_ptr);
if (exch.m_ptr)
{
exch.d()->refs += c_ref_mask;
}
atomic_ptr old;
const auto [_val, ok] = m_val.fetch_op([&](uptr& val)
{
if (val >> c_ref_size == _old)
{
// Set new value
val = _new << c_ref_size;
return true;
}
return false;
});
if (ok)
{
// Success (exch is consumed, cmp_and_old is unchanged)
exch.m_ptr = nullptr;
old.m_val.raw() = _val;
return true;
}
// Failure (return references)
old.m_val.raw() = reinterpret_cast<uptr>(std::exchange(exch.m_ptr, nullptr)) << c_ref_size;
return false;
}
// Unoptimized
template <typename U> requires same_ptr_implicit_v<T, U>
shared_type compare_and_swap(const single_ptr<U>& cmp, shared_type exch)
{
shared_type old = cmp;
static_cast<void>(compare_exchange(old, std::move(exch)));
return old;
}
// Supplementary
template <typename U> requires same_ptr_implicit_v<T, U>
bool compare_and_swap_test(const single_ptr<U>& cmp, shared_type exch)
{
return compare_and_swap_test(reinterpret_cast<const shared_ptr<U>&>(cmp), std::move(exch));
}
// Helper utility
void push_head(shared_type& next, shared_type exch) noexcept
{
if (exch.m_ptr) [[likely]]
{
// Add missing references first
exch.d()->refs += c_ref_mask;
}
if (next.m_ptr) [[unlikely]]
{
// Just in case
next.reset();
}
atomic_ptr old;
old.m_val.raw() = m_val.load();
do
{
// Update old head with current value
next.m_ptr = reinterpret_cast<T*>(old.m_val.raw() >> c_ref_size);
} while (!m_val.compare_exchange(old.m_val.raw(), reinterpret_cast<uptr>(exch.m_ptr) << c_ref_size));
// This argument is consumed (moved from)
exch.m_ptr = nullptr;
if (next.m_ptr)
{
// Compensation for `next` assignment
old.m_val.raw() += 1;
}
}
// Simple atomic load is much more effective than load(), but it's a non-owning reference
const volatile void* observe() const noexcept
{
return reinterpret_cast<const volatile void*>(m_val >> c_ref_size);
}
explicit constexpr operator bool() const noexcept
{
return m_val != 0;
}
template <typename U> requires same_ptr_implicit_v<T, U>
bool is_equal(const shared_ptr<U>& r) const noexcept
{
return observe() == r.get();
}
template <typename U> requires same_ptr_implicit_v<T, U>
bool is_equal(const single_ptr<U>& r) const noexcept
{
return observe() == r.get();
}
void wait(std::nullptr_t, atomic_wait_timeout timeout = atomic_wait_timeout::inf)
{
utils::bless<atomic_t<u32>>(&m_val)[1].wait(0, timeout);
}
void notify_one()
{
utils::bless<atomic_t<u32>>(&m_val)[1].notify_one();
}
void notify_all()
{
utils::bless<atomic_t<u32>>(&m_val)[1].notify_all();
}
};
// Some nullptr replacement for few cases
constexpr struct null_ptr_t
{
template <typename T>
constexpr operator single_ptr<T>() const noexcept
{
return {};
}
template <typename T>
constexpr operator shared_ptr<T>() const noexcept
{
return {};
}
template <typename T>
constexpr operator atomic_ptr<T>() const noexcept
{
return {};
}
explicit constexpr operator bool() const noexcept
{
return false;
}
constexpr operator std::nullptr_t() const noexcept
{
return nullptr;
}
constexpr std::nullptr_t get() const noexcept
{
return nullptr;
}
} null_ptr;
}
using stx::null_ptr;
using stx::single_ptr;
using stx::shared_ptr;
using stx::atomic_ptr;
using stx::make_single;
using stx::make_single_value;
using stx::make_shared_value;
| 25,748
|
C++
|
.h
| 913
| 24.480832
| 170
| 0.647501
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
5,671
|
fifo_mutex.hpp
|
RPCS3_rpcs3/rpcs3/util/fifo_mutex.hpp
|
#pragma once
#include "util/types.hpp"
#include "util/atomic.hpp"
// Mutex that tries to maintain the order of acquisition
class fifo_mutex
{
// Low 16 bits are incremented on acquisition, high 16 bits are incremented on release
atomic_t<u32> m_value{0};
public:
constexpr fifo_mutex() noexcept = default;
void lock() noexcept
{
// clang-format off
const u32 val = m_value.fetch_op([](u32& val)
{
val = (val & 0xffff0000) | ((val + 1) & 0xffff);
});
// clang-format on
if (val >> 16 != (val & 0xffff)) [[unlikely]]
{
// TODO: implement busy waiting along with moving to cpp file
m_value.wait((val & 0xffff0000) | ((val + 1) & 0xffff));
}
}
bool try_lock() noexcept
{
const u32 val = m_value.load();
if (val >> 16 == (val & 0xffff))
{
if (m_value.compare_and_swap(val, ((val + 1) & 0xffff) | (val & 0xffff0000)))
{
return true;
}
}
return false;
}
void unlock() noexcept
{
const u32 val = m_value.add_fetch(0x10000);
if (val >> 16 != (val & 0xffff))
{
m_value.notify_one();
}
}
bool is_free() const noexcept
{
const u32 val = m_value.load();
return (val >> 16) == (val & 0xffff);
}
void lock_unlock() noexcept
{
if (!is_free())
{
lock();
unlock();
}
}
};
| 1,260
|
C++
|
.h
| 58
| 18.896552
| 87
| 0.628259
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,672
|
atomic.hpp
|
RPCS3_rpcs3/rpcs3/util/atomic.hpp
|
#pragma once // No BOM and only basic ASCII in this header, or a neko will die
#include "util/types.hpp"
#include <functional>
#include <mutex>
#ifndef _MSC_VER
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wold-style-cast"
#endif
#ifdef _MSC_VER
#pragma warning(push)
#pragma warning(disable: 4996)
extern "C"
{
void _ReadWriteBarrier();
void* _AddressOfReturnAddress();
uchar _bittest(const long*, long);
uchar _interlockedbittestandset(volatile long*, long);
uchar _interlockedbittestandreset(volatile long*, long);
char _InterlockedCompareExchange8(volatile char*, char, char);
char _InterlockedExchange8(volatile char*, char);
char _InterlockedExchangeAdd8(volatile char*, char);
char _InterlockedAnd8(volatile char*, char);
char _InterlockedOr8(volatile char*, char);
char _InterlockedXor8(volatile char*, char);
short _InterlockedCompareExchange16(volatile short*, short, short);
short _InterlockedExchange16(volatile short*, short);
short _InterlockedExchangeAdd16(volatile short*, short);
short _InterlockedAnd16(volatile short*, short);
short _InterlockedOr16(volatile short*, short);
short _InterlockedXor16(volatile short*, short);
short _InterlockedIncrement16(volatile short*);
short _InterlockedDecrement16(volatile short*);
long _InterlockedCompareExchange(volatile long*, long, long);
long _InterlockedCompareExchange_HLEAcquire(volatile long*, long, long);
long _InterlockedExchange(volatile long*, long);
long _InterlockedExchangeAdd(volatile long*, long);
long _InterlockedExchangeAdd_HLERelease(volatile long*, long);
long _InterlockedAnd(volatile long*, long);
long _InterlockedOr(volatile long*, long);
long _InterlockedXor(volatile long*, long);
long _InterlockedIncrement(volatile long*);
long _InterlockedDecrement(volatile long*);
s64 _InterlockedCompareExchange64(volatile s64*, s64, s64);
s64 _InterlockedCompareExchange64_HLEAcquire(volatile s64*, s64, s64);
s64 _InterlockedExchange64(volatile s64*, s64);
s64 _InterlockedExchangeAdd64(volatile s64*, s64);
s64 _InterlockedExchangeAdd64_HLERelease(volatile s64*, s64);
s64 _InterlockedAnd64(volatile s64*, s64);
s64 _InterlockedOr64(volatile s64*, s64);
s64 _InterlockedXor64(volatile s64*, s64);
s64 _InterlockedIncrement64(volatile s64*);
s64 _InterlockedDecrement64(volatile s64*);
uchar _InterlockedCompareExchange128(volatile s64*, s64, s64, s64*);
}
namespace utils
{
u128 __vectorcall atomic_load16(const void*);
void __vectorcall atomic_store16(void*, u128);
}
#endif
FORCE_INLINE void atomic_fence_consume()
{
#if defined(_M_X64) && defined(_MSC_VER)
_ReadWriteBarrier();
#else
__atomic_thread_fence(__ATOMIC_CONSUME);
#endif
}
FORCE_INLINE void atomic_fence_acquire()
{
#if defined(_M_X64) && defined(_MSC_VER)
_ReadWriteBarrier();
#else
__atomic_thread_fence(__ATOMIC_ACQUIRE);
#endif
}
FORCE_INLINE void atomic_fence_release()
{
#if defined(_M_X64) && defined(_MSC_VER)
_ReadWriteBarrier();
#else
__atomic_thread_fence(__ATOMIC_RELEASE);
#endif
}
FORCE_INLINE void atomic_fence_acq_rel()
{
#if defined(_M_X64) && defined(_MSC_VER)
_ReadWriteBarrier();
#else
__atomic_thread_fence(__ATOMIC_ACQ_REL);
#endif
}
FORCE_INLINE void atomic_fence_seq_cst()
{
#if defined(_M_X64) && defined(_MSC_VER)
_ReadWriteBarrier();
_InterlockedOr(static_cast<long*>(_AddressOfReturnAddress()), 0);
_ReadWriteBarrier();
#elif defined(ARCH_X64)
__asm__ volatile ("lock orl $0, 0(%%rsp);" ::: "cc", "memory");
#else
__atomic_thread_fence(__ATOMIC_SEQ_CST);
#endif
}
#if defined(_M_X64) && defined(_MSC_VER)
#pragma warning(pop)
#endif
// Wait timeout extension (in nanoseconds)
enum class atomic_wait_timeout : u64
{
inf = 0xffffffffffffffff,
};
template <typename T>
class lf_queue;
namespace stx
{
template <typename T>
class atomic_ptr;
}
// Various extensions for atomic_t::wait
namespace atomic_wait
{
// Max number of simultaneous atomic variables to wait on (can be extended if really necessary)
constexpr uint max_list = 8;
constexpr struct any_value_t
{
template <typename T>
operator T() const noexcept
{
return T();
}
} any_value;
struct info
{
const void* data;
u32 old;
};
template <uint Max, typename... T>
class list
{
static_assert(Max <= max_list, "Too many elements in the atomic wait list.");
// Null-terminated list of wait info
info m_info[Max + 1]{};
public:
constexpr list() noexcept = default;
constexpr list(const list&) noexcept = default;
constexpr list& operator=(const list&) noexcept = default;
template <typename... U, typename = std::void_t<decltype(std::declval<U>().wait(any_value))...>>
constexpr list(U&... vars)
: m_info{{&vars, 0}...}
{
static_assert(sizeof...(U) == Max, "Inconsistent amount of atomics.");
}
template <typename... U>
constexpr list& values(U... values)
{
static_assert(sizeof...(U) == Max, "Inconsistent amount of values.");
auto* ptr = m_info;
(((ptr->old = std::bit_cast<u32>(values)), ptr++), ...);
return *this;
}
template <uint Index, typename T2, typename U, typename = std::void_t<decltype(std::declval<T2>().wait(any_value))>>
constexpr void set(T2& var, U value)
{
static_assert(Index < Max);
m_info[Index].data = &var;
m_info[Index].old = std::bit_cast<u32>(value);
}
template <uint Index, typename T2>
constexpr void set(lf_queue<T2>& var, std::nullptr_t = nullptr)
{
static_assert(Index < Max);
static_assert(sizeof(var) == sizeof(uptr));
m_info[Index].data = reinterpret_cast<char*>(&var) + sizeof(u32);
m_info[Index].old = 0;
}
template <uint Index, typename T2>
constexpr void set(stx::atomic_ptr<T2>& var, std::nullptr_t = nullptr)
{
static_assert(Index < Max);
static_assert(sizeof(var) == sizeof(uptr));
m_info[Index].data = reinterpret_cast<char*>(&var) + sizeof(u32);
m_info[Index].old = 0;
}
// Timeout is discouraged
void wait(atomic_wait_timeout timeout = atomic_wait_timeout::inf);
// Same as wait
void start()
{
wait();
}
};
template <typename... T, typename = std::void_t<decltype(std::declval<T>().wait(any_value))...>>
list(T&... vars) -> list<sizeof...(T), T...>;
}
namespace utils
{
// RDTSC with adjustment for being unique
u64 get_unique_tsc();
}
// Helper for waitable atomics (as in C++20 std::atomic)
struct atomic_wait_engine
{
private:
template <typename T, usz Align>
friend class atomic_t;
template <uint Max, typename... T>
friend class atomic_wait::list;
static void wait(const void* data, u32 old_value, u64 timeout, atomic_wait::info* ext = nullptr);
public:
static void notify_one(const void* data);
static void notify_all(const void* data);
static void set_wait_callback(bool(*cb)(const void* data, u64 attempts, u64 stamp0));
static void set_one_time_use_wait_callback(bool (*cb)(u64 progress));
};
template <uint Max, typename... T>
void atomic_wait::list<Max, T...>::wait(atomic_wait_timeout timeout)
{
static_assert(!!Max, "Cannot initiate atomic wait with empty list.");
atomic_wait_engine::wait(m_info[0].data, m_info[0].old, static_cast<u64>(timeout), m_info + 1);
}
// Helper class, provides access to compiler-specific atomic intrinsics
template <typename T, usz Size = sizeof(T)>
struct atomic_storage
{
/* First part: Non-MSVC intrinsics */
using type = get_uint_t<sizeof(T)>;
#if !defined(_MSC_VER) || !defined(_M_X64)
#if defined(__ATOMIC_HLE_ACQUIRE) && defined(__ATOMIC_HLE_RELEASE)
static constexpr int s_hle_ack = __ATOMIC_SEQ_CST | __ATOMIC_HLE_ACQUIRE;
static constexpr int s_hle_rel = __ATOMIC_SEQ_CST | __ATOMIC_HLE_RELEASE;
#else
static constexpr int s_hle_ack = __ATOMIC_SEQ_CST;
static constexpr int s_hle_rel = __ATOMIC_SEQ_CST;
#endif
// clang often thinks atomics are misaligned, GCC doesn't like reinterpret_cast for breaking strict aliasing
#ifdef __clang__
#define MAYBE_CAST(...) (reinterpret_cast<type*>(__VA_ARGS__))
#else
#define MAYBE_CAST(...) (__VA_ARGS__)
#endif
static inline bool compare_exchange(T& dest, T& comp, T exch)
{
return __atomic_compare_exchange(MAYBE_CAST(&dest), MAYBE_CAST(&comp), MAYBE_CAST(&exch), false, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST);
}
static inline bool compare_exchange_hle_acq(T& dest, T& comp, T exch)
{
static_assert(sizeof(T) == 4 || sizeof(T) == 8);
return __atomic_compare_exchange(MAYBE_CAST(&dest), MAYBE_CAST(&comp), MAYBE_CAST(&exch), false, s_hle_ack, s_hle_ack);
}
static inline T load(const T& dest)
{
#ifdef __clang__
type result;
__atomic_load(reinterpret_cast<const type*>(&dest), MAYBE_CAST(&result), __ATOMIC_SEQ_CST);
return std::bit_cast<T>(result);
#else
alignas(sizeof(T)) T result;
__atomic_load(&dest, &result, __ATOMIC_SEQ_CST);
return result;
#endif
}
static inline T observe(const T& dest)
{
#ifdef __clang__
type result;
__atomic_load(reinterpret_cast<const type*>(&dest), MAYBE_CAST(&result), __ATOMIC_RELAXED);
return std::bit_cast<T>(result);
#else
alignas(sizeof(T)) T result;
__atomic_load(&dest, &result, __ATOMIC_RELAXED);
return result;
#endif
}
static inline void store(T& dest, T value)
{
static_cast<void>(exchange(dest, value));
}
static inline void release(T& dest, T value)
{
__atomic_store(MAYBE_CAST(&dest), MAYBE_CAST(&value), __ATOMIC_RELEASE);
}
static inline T exchange(T& dest, T value)
{
alignas(sizeof(T)) T result;
__atomic_exchange(MAYBE_CAST(&dest), MAYBE_CAST(&value), MAYBE_CAST(&result), __ATOMIC_SEQ_CST);
return result;
}
static inline T fetch_add(T& dest, T value)
{
return __atomic_fetch_add(&dest, value, __ATOMIC_SEQ_CST);
}
static inline T fetch_add_hle_rel(T& dest, T value)
{
static_assert(sizeof(T) == 4 || sizeof(T) == 8);
return __atomic_fetch_add(&dest, value, s_hle_rel);
}
static inline T add_fetch(T& dest, T value)
{
return __atomic_add_fetch(&dest, value, __ATOMIC_SEQ_CST);
}
static inline T fetch_sub(T& dest, T value)
{
return __atomic_fetch_sub(&dest, value, __ATOMIC_SEQ_CST);
}
static inline T sub_fetch(T& dest, T value)
{
return __atomic_sub_fetch(&dest, value, __ATOMIC_SEQ_CST);
}
static inline T fetch_and(T& dest, T value)
{
return __atomic_fetch_and(&dest, value, __ATOMIC_SEQ_CST);
}
static inline T and_fetch(T& dest, T value)
{
return __atomic_and_fetch(&dest, value, __ATOMIC_SEQ_CST);
}
static inline T fetch_xor(T& dest, T value)
{
return __atomic_fetch_xor(&dest, value, __ATOMIC_SEQ_CST);
}
static inline T xor_fetch(T& dest, T value)
{
return __atomic_xor_fetch(&dest, value, __ATOMIC_SEQ_CST);
}
static inline T fetch_or(T& dest, T value)
{
return __atomic_fetch_or(&dest, value, __ATOMIC_SEQ_CST);
}
static inline T or_fetch(T& dest, T value)
{
return __atomic_or_fetch(&dest, value, __ATOMIC_SEQ_CST);
}
#endif
/* Second part: MSVC-specific */
#if defined(_M_X64) && defined(_MSC_VER)
static inline T add_fetch(T& dest, T value)
{
return atomic_storage<T>::fetch_add(dest, value) + value;
}
static inline T fetch_sub(T& dest, T value)
{
return atomic_storage<T>::fetch_add(dest, 0 - value);
}
static inline T sub_fetch(T& dest, T value)
{
return atomic_storage<T>::fetch_add(dest, 0 - value) - value;
}
static inline T and_fetch(T& dest, T value)
{
return atomic_storage<T>::fetch_and(dest, value) & value;
}
static inline T or_fetch(T& dest, T value)
{
return atomic_storage<T>::fetch_or(dest, value) | value;
}
static inline T xor_fetch(T& dest, T value)
{
return atomic_storage<T>::fetch_xor(dest, value) ^ value;
}
#undef MAYBE_CAST
#endif
/* Third part: fallbacks, may be hidden by subsequent atomic_storage<> specializations */
static inline T fetch_inc(T& dest)
{
return atomic_storage<T>::fetch_add(dest, 1);
}
static inline T inc_fetch(T& dest)
{
return atomic_storage<T>::add_fetch(dest, 1);
}
static inline T fetch_dec(T& dest)
{
return atomic_storage<T>::fetch_sub(dest, 1);
}
static inline T dec_fetch(T& dest)
{
return atomic_storage<T>::sub_fetch(dest, 1);
}
static inline bool bts(T& dest, uint bit)
{
#if defined(ARCH_X64)
uchar* dst = reinterpret_cast<uchar*>(&dest);
if constexpr (sizeof(T) < 4)
{
const uptr ptr = reinterpret_cast<uptr>(dst);
// Align the bit up and pointer down
bit = bit + (ptr & 3) * 8;
dst = reinterpret_cast<T*>(ptr & -4);
}
#endif
#if defined(_M_X64) && defined(_MSC_VER)
return _interlockedbittestandset((long*)dst, bit) != 0;
#elif defined(ARCH_X64)
bool result;
__asm__ volatile ("lock btsl %2, 0(%1)\n" : "=@ccc" (result) : "r" (dst), "Ir" (bit) : "cc", "memory");
return result;
#else
const T value = static_cast<T>(1) << bit;
return (__atomic_fetch_or(&dest, value, __ATOMIC_SEQ_CST) & value) != 0;
#endif
}
static inline bool btr(T& dest, uint bit)
{
#if defined(ARCH_X64)
uchar* dst = reinterpret_cast<uchar*>(&dest);
if constexpr (sizeof(T) < 4)
{
const uptr ptr = reinterpret_cast<uptr>(dst);
// Align the bit up and pointer down
bit = bit + (ptr & 3) * 8;
dst = reinterpret_cast<T*>(ptr & -4);
}
#endif
#if defined(_M_X64) && defined(_MSC_VER)
return _interlockedbittestandreset((long*)dst, bit) != 0;
#elif defined(ARCH_X64)
bool result;
__asm__ volatile ("lock btrl %2, 0(%1)\n" : "=@ccc" (result) : "r" (dst), "Ir" (bit) : "cc", "memory");
return result;
#else
const T value = static_cast<T>(1) << bit;
return (__atomic_fetch_and(&dest, ~value, __ATOMIC_SEQ_CST) & value) != 0;
#endif
}
static inline bool btc(T& dest, uint bit)
{
#if defined(ARCH_X64)
uchar* dst = reinterpret_cast<uchar*>(&dest);
if constexpr (sizeof(T) < 4)
{
const uptr ptr = reinterpret_cast<uptr>(dst);
// Align the bit up and pointer down
bit = bit + (ptr & 3) * 8;
dst = reinterpret_cast<T*>(ptr & -4);
}
#endif
#if defined(_M_X64) && defined(_MSC_VER)
while (true)
{
// Keep trying until we actually invert desired bit
if (!_bittest((long*)dst, bit) && !_interlockedbittestandset((long*)dst, bit))
return false;
if (_interlockedbittestandreset((long*)dst, bit))
return true;
}
#elif defined(ARCH_X64)
bool result;
__asm__ volatile ("lock btcl %2, 0(%1)\n" : "=@ccc" (result) : "r" (dst), "Ir" (bit) : "cc", "memory");
return result;
#else
const T value = static_cast<T>(1) << bit;
return (__atomic_fetch_xor(&dest, value, __ATOMIC_SEQ_CST) & value) != 0;
#endif
}
};
/* The rest: ugly MSVC intrinsics + inline asm implementations */
template <typename T>
struct atomic_storage<T, 1> : atomic_storage<T, 0>
{
#if defined(_M_X64) && defined(_MSC_VER)
static inline bool compare_exchange(T& dest, T& comp, T exch)
{
const char v = std::bit_cast<char>(comp);
const char r = _InterlockedCompareExchange8(reinterpret_cast<volatile char*>(&dest), std::bit_cast<char>(exch), v);
comp = std::bit_cast<T>(r);
return r == v;
}
static inline T load(const T& dest)
{
atomic_fence_acquire();
const char value = *reinterpret_cast<const volatile char*>(&dest);
atomic_fence_acquire();
return std::bit_cast<T>(value);
}
static inline T observe(const T& dest)
{
const char value = *reinterpret_cast<const volatile char*>(&dest);
return std::bit_cast<T>(value);
}
static inline void release(T& dest, T value)
{
atomic_fence_release();
*reinterpret_cast<volatile char*>(&dest) = std::bit_cast<char>(value);
atomic_fence_release();
}
static inline T exchange(T& dest, T value)
{
const char r = _InterlockedExchange8(reinterpret_cast<volatile char*>(&dest), std::bit_cast<char>(value));
return std::bit_cast<T>(r);
}
static inline void store(T& dest, T value)
{
exchange(dest, value);
}
static inline T fetch_add(T& dest, T value)
{
const char r = _InterlockedExchangeAdd8(reinterpret_cast<volatile char*>(&dest), std::bit_cast<char>(value));
return std::bit_cast<T>(r);
}
static inline T fetch_and(T& dest, T value)
{
const char r = _InterlockedAnd8(reinterpret_cast<volatile char*>(&dest), std::bit_cast<char>(value));
return std::bit_cast<T>(r);
}
static inline T fetch_or(T& dest, T value)
{
const char r = _InterlockedOr8(reinterpret_cast<volatile char*>(&dest), std::bit_cast<char>(value));
return std::bit_cast<T>(r);
}
static inline T fetch_xor(T& dest, T value)
{
const char r = _InterlockedXor8(reinterpret_cast<volatile char*>(&dest), std::bit_cast<char>(value));
return std::bit_cast<T>(r);
}
#endif
};
template <typename T>
struct atomic_storage<T, 2> : atomic_storage<T, 0>
{
#if defined(_M_X64) && defined(_MSC_VER)
static inline bool compare_exchange(T& dest, T& comp, T exch)
{
const short v = std::bit_cast<short>(comp);
const short r = _InterlockedCompareExchange16(reinterpret_cast<volatile short*>(&dest), std::bit_cast<short>(exch), v);
comp = std::bit_cast<T>(r);
return r == v;
}
static inline T load(const T& dest)
{
atomic_fence_acquire();
const short value = *reinterpret_cast<const volatile short*>(&dest);
atomic_fence_acquire();
return std::bit_cast<T>(value);
}
static inline T observe(const T& dest)
{
const short value = *reinterpret_cast<const volatile short*>(&dest);
return std::bit_cast<T>(value);
}
static inline void release(T& dest, T value)
{
atomic_fence_release();
*reinterpret_cast<volatile short*>(&dest) = std::bit_cast<short>(value);
atomic_fence_release();
}
static inline T exchange(T& dest, T value)
{
const short r = _InterlockedExchange16(reinterpret_cast<volatile short*>(&dest), std::bit_cast<short>(value));
return std::bit_cast<T>(r);
}
static inline void store(T& dest, T value)
{
exchange(dest, value);
}
static inline T fetch_add(T& dest, T value)
{
const short r = _InterlockedExchangeAdd16(reinterpret_cast<volatile short*>(&dest), std::bit_cast<short>(value));
return std::bit_cast<T>(r);
}
static inline T fetch_and(T& dest, T value)
{
const short r = _InterlockedAnd16(reinterpret_cast<volatile short*>(&dest), std::bit_cast<short>(value));
return std::bit_cast<T>(r);
}
static inline T fetch_or(T& dest, T value)
{
const short r = _InterlockedOr16(reinterpret_cast<volatile short*>(&dest), std::bit_cast<short>(value));
return std::bit_cast<T>(r);
}
static inline T fetch_xor(T& dest, T value)
{
const short r = _InterlockedXor16(reinterpret_cast<volatile short*>(&dest), std::bit_cast<short>(value));
return std::bit_cast<T>(r);
}
static inline T inc_fetch(T& dest)
{
const short r = _InterlockedIncrement16(reinterpret_cast<volatile short*>(&dest));
return std::bit_cast<T>(r);
}
static inline T dec_fetch(T& dest)
{
const short r = _InterlockedDecrement16(reinterpret_cast<volatile short*>(&dest));
return std::bit_cast<T>(r);
}
#endif
};
template <typename T>
struct atomic_storage<T, 4> : atomic_storage<T, 0>
{
#if defined(_M_X64) && defined(_MSC_VER)
static inline bool compare_exchange(T& dest, T& comp, T exch)
{
const long v = std::bit_cast<long>(comp);
const long r = _InterlockedCompareExchange(reinterpret_cast<volatile long*>(&dest), std::bit_cast<long>(exch), v);
comp = std::bit_cast<T>(r);
return r == v;
}
static inline bool compare_exchange_hle_acq(T& dest, T& comp, T exch)
{
const long v = std::bit_cast<long>(comp);
const long r = _InterlockedCompareExchange_HLEAcquire(reinterpret_cast<volatile long*>(&dest), std::bit_cast<long>(exch), v);
comp = std::bit_cast<T>(r);
return r == v;
}
static inline T load(const T& dest)
{
atomic_fence_acquire();
const long value = *reinterpret_cast<const volatile long*>(&dest);
atomic_fence_acquire();
return std::bit_cast<T>(value);
}
static inline T observe(const T& dest)
{
const long value = *reinterpret_cast<const volatile long*>(&dest);
return std::bit_cast<T>(value);
}
static inline void release(T& dest, T value)
{
atomic_fence_release();
*reinterpret_cast<volatile long*>(&dest) = std::bit_cast<long>(value);
atomic_fence_release();
}
static inline T exchange(T& dest, T value)
{
const long r = _InterlockedExchange(reinterpret_cast<volatile long*>(&dest), std::bit_cast<long>(value));
return std::bit_cast<T>(r);
}
static inline void store(T& dest, T value)
{
exchange(dest, value);
}
static inline T fetch_add(T& dest, T value)
{
const long r = _InterlockedExchangeAdd(reinterpret_cast<volatile long*>(&dest), std::bit_cast<long>(value));
return std::bit_cast<T>(r);
}
static inline T fetch_add_hle_rel(T& dest, T value)
{
const long r = _InterlockedExchangeAdd_HLERelease(reinterpret_cast<volatile long*>(&dest), std::bit_cast<long>(value));
return std::bit_cast<T>(r);
}
static inline T fetch_and(T& dest, T value)
{
long r = _InterlockedAnd(reinterpret_cast<volatile long*>(&dest), std::bit_cast<long>(value));
return std::bit_cast<T>(r);
}
static inline T fetch_or(T& dest, T value)
{
const long r = _InterlockedOr(reinterpret_cast<volatile long*>(&dest), std::bit_cast<long>(value));
return std::bit_cast<T>(r);
}
static inline T fetch_xor(T& dest, T value)
{
const long r = _InterlockedXor(reinterpret_cast<volatile long*>(&dest), std::bit_cast<long>(value));
return std::bit_cast<T>(r);
}
static inline T inc_fetch(T& dest)
{
const long r = _InterlockedIncrement(reinterpret_cast<volatile long*>(&dest));
return std::bit_cast<T>(r);
}
static inline T dec_fetch(T& dest)
{
const long r = _InterlockedDecrement(reinterpret_cast<volatile long*>(&dest));
return std::bit_cast<T>(r);
}
#endif
};
template <typename T>
struct atomic_storage<T, 8> : atomic_storage<T, 0>
{
#if defined(_M_X64) && defined(_MSC_VER)
static inline bool compare_exchange(T& dest, T& comp, T exch)
{
const llong v = std::bit_cast<llong>(comp);
const llong r = _InterlockedCompareExchange64(reinterpret_cast<volatile llong*>(&dest), std::bit_cast<llong>(exch), v);
comp = std::bit_cast<T>(r);
return r == v;
}
static inline bool compare_exchange_hle_acq(T& dest, T& comp, T exch)
{
const llong v = std::bit_cast<llong>(comp);
const llong r = _InterlockedCompareExchange64_HLEAcquire(reinterpret_cast<volatile llong*>(&dest), std::bit_cast<llong>(exch), v);
comp = std::bit_cast<T>(r);
return r == v;
}
static inline T load(const T& dest)
{
atomic_fence_acquire();
const llong value = *reinterpret_cast<const volatile llong*>(&dest);
atomic_fence_acquire();
return std::bit_cast<T>(value);
}
static inline T observe(const T& dest)
{
const llong value = *reinterpret_cast<const volatile llong*>(&dest);
return std::bit_cast<T>(value);
}
static inline void release(T& dest, T value)
{
atomic_fence_release();
*reinterpret_cast<volatile llong*>(&dest) = std::bit_cast<llong>(value);
atomic_fence_release();
}
static inline T exchange(T& dest, T value)
{
const llong r = _InterlockedExchange64(reinterpret_cast<volatile llong*>(&dest), std::bit_cast<llong>(value));
return std::bit_cast<T>(r);
}
static inline void store(T& dest, T value)
{
exchange(dest, value);
}
static inline T fetch_add(T& dest, T value)
{
const llong r = _InterlockedExchangeAdd64(reinterpret_cast<volatile llong*>(&dest), std::bit_cast<llong>(value));
return std::bit_cast<T>(r);
}
static inline T fetch_add_hle_rel(T& dest, T value)
{
const llong r = _InterlockedExchangeAdd64_HLERelease(reinterpret_cast<volatile llong*>(&dest), std::bit_cast<llong>(value));
return std::bit_cast<T>(r);
}
static inline T fetch_and(T& dest, T value)
{
const llong r = _InterlockedAnd64(reinterpret_cast<volatile llong*>(&dest), std::bit_cast<llong>(value));
return std::bit_cast<T>(r);
}
static inline T fetch_or(T& dest, T value)
{
const llong r = _InterlockedOr64(reinterpret_cast<volatile llong*>(&dest), std::bit_cast<llong>(value));
return std::bit_cast<T>(r);
}
static inline T fetch_xor(T& dest, T value)
{
const llong r = _InterlockedXor64(reinterpret_cast<volatile llong*>(&dest), std::bit_cast<llong>(value));
return std::bit_cast<T>(r);
}
static inline T inc_fetch(T& dest)
{
const llong r = _InterlockedIncrement64(reinterpret_cast<volatile llong*>(&dest));
return std::bit_cast<T>(r);
}
static inline T dec_fetch(T& dest)
{
const llong r = _InterlockedDecrement64(reinterpret_cast<volatile llong*>(&dest));
return std::bit_cast<T>(r);
}
#endif
};
template <typename T>
struct atomic_storage<T, 16> : atomic_storage<T, 0>
{
#if defined(_M_X64) && defined(_MSC_VER)
static inline T load(const T& dest)
{
atomic_fence_acquire();
u128 val = utils::atomic_load16(&dest);
atomic_fence_acquire();
return std::bit_cast<T>(val);
}
static inline T observe(const T& dest)
{
return load(dest);
}
static inline bool compare_exchange(T& dest, T& comp, T exch)
{
struct alignas(16) llong2 { llong ll[2]; };
const llong2 _exch = std::bit_cast<llong2>(exch);
return _InterlockedCompareExchange128(reinterpret_cast<volatile llong*>(&dest), _exch.ll[1], _exch.ll[0], reinterpret_cast<llong*>(&comp)) != 0;
}
static inline T exchange(T& dest, T value)
{
struct alignas(16) llong2 { llong ll[2]; };
const llong2 _value = std::bit_cast<llong2>(value);
const auto llptr = reinterpret_cast<volatile llong*>(&dest);
llong2 cmp{ llptr[0], llptr[1] };
while (!_InterlockedCompareExchange128(llptr, _value.ll[1], _value.ll[0], cmp.ll));
return std::bit_cast<T>(cmp);
}
static inline void store(T& dest, T value)
{
atomic_fence_acq_rel();
release(dest, value);
atomic_fence_seq_cst();
}
static inline void release(T& dest, T value)
{
atomic_fence_release();
utils::atomic_store16(&dest, std::bit_cast<u128>(value));
atomic_fence_release();
}
#elif defined(ARCH_X64)
static inline T load(const T& dest)
{
alignas(16) T r;
#ifdef __AVX__
__asm__ volatile("vmovdqa %1, %0;" : "=x" (r) : "m" (dest) : "memory");
#else
__asm__ volatile("movdqa %1, %0;" : "=x" (r) : "m" (dest) : "memory");
#endif
return r;
}
static inline T observe(const T& dest)
{
return load(dest);
}
static inline bool compare_exchange(T& dest, T& comp, T exch)
{
bool result;
ullong cmp_lo = 0;
ullong cmp_hi = 0;
ullong exc_lo = 0;
ullong exc_hi = 0;
if constexpr (std::is_same_v<T, u128> || std::is_same_v<T, s128>)
{
cmp_lo = comp;
cmp_hi = comp >> 64;
exc_lo = exch;
exc_hi = exch >> 64;
}
else
{
std::memcpy(&cmp_lo, reinterpret_cast<char*>(&comp) + 0, 8);
std::memcpy(&cmp_hi, reinterpret_cast<char*>(&comp) + 8, 8);
std::memcpy(&exc_lo, reinterpret_cast<char*>(&exch) + 0, 8);
std::memcpy(&exc_hi, reinterpret_cast<char*>(&exch) + 8, 8);
}
__asm__ volatile("lock cmpxchg16b %1;"
: "=@ccz" (result)
, "+m" (dest)
, "+d" (cmp_hi)
, "+a" (cmp_lo)
: "c" (exc_hi)
, "b" (exc_lo)
: "cc");
if constexpr (std::is_same_v<T, u128> || std::is_same_v<T, s128>)
{
comp = T{cmp_hi} << 64 | cmp_lo;
}
else
{
std::memcpy(reinterpret_cast<char*>(&comp) + 0, &cmp_lo, 8);
std::memcpy(reinterpret_cast<char*>(&comp) + 8, &cmp_hi, 8);
}
return result;
}
static inline T exchange(T& dest, T value)
{
__atomic_thread_fence(__ATOMIC_ACQ_REL);
return std::bit_cast<T>(__sync_lock_test_and_set(reinterpret_cast<u128*>(&dest), std::bit_cast<u128>(value)));
}
static inline void store(T& dest, T value)
{
release(dest, value);
atomic_fence_seq_cst();
}
static inline void release(T& dest, T value)
{
u128 val = std::bit_cast<u128>(value);
#ifdef __AVX__
__asm__ volatile("vmovdqa %0, %1;" :: "x" (val), "m" (dest) : "memory");
#else
__asm__ volatile("movdqa %0, %1;" :: "x" (val), "m" (dest) : "memory");
#endif
}
#elif defined(ARCH_ARM64)
static inline T load(const T& dest)
{
#if defined(ARM_FEATURE_LSE2)
u64 data[2];
__asm__ volatile("1:\n"
"ldp %x[data0], %x[data1], %[dest]\n"
"dmb ish\n"
: [data0] "=r"(data[0]), [data1] "=r"(data[1])
: [dest] "Q"(dest)
: "memory");
T result;
std::memcpy(&result, data, 16);
return result;
#else
u32 tmp;
u64 data[2];
__asm__ volatile("1:\n"
"ldaxp %x[data0], %x[data1], %[dest]\n"
"stlxp %w[tmp], %x[data0], %x[data1], %[dest]\n"
"cbnz %w[tmp], 1b\n"
: [tmp] "=&r" (tmp), [data0] "=&r" (data[0]), [data1] "=&r" (data[1])
: [dest] "Q" (dest)
: "memory"
);
T result;
std::memcpy(&result, data, 16);
return result;
#endif
}
static inline T observe(const T& dest)
{
// TODO
return load(dest);
}
static inline bool compare_exchange(T& dest, T& comp, T exch)
{
bool result;
u64 cmp[2];
std::memcpy(cmp, &comp, 16);
u64 data[2];
std::memcpy(data, &exch, 16);
u64 prev[2];
__asm__ volatile("1:\n"
"ldaxp %x[prev0], %x[prev1], %[storage]\n"
"cmp %x[prev0], %x[cmp0]\n"
"ccmp %x[prev1], %x[cmp1], #0, eq\n"
"b.ne 2f\n"
"stlxp %w[result], %x[data0], %x[data1], %[storage]\n"
"cbnz %w[result], 1b\n"
"2:\n"
"cset %w[result], eq\n"
: [result] "=&r" (result), [storage] "+Q" (dest), [prev0] "=&r" (prev[0]), [prev1] "=&r" (prev[1])
: [data0] "r" (data[0]), [data1] "r" (data[1]), [cmp0] "r" (cmp[0]), [cmp1] "r" (cmp[1])
: "cc", "memory"
);
if (result)
{
return true;
}
std::memcpy(&comp, prev, 16);
return false;
}
static inline T exchange(T& dest, T value)
{
u32 tmp;
u64 src[2];
u64 data[2];
std::memcpy(src, &value, 16);
__asm__ volatile("1:\n"
"ldaxp %x[data0], %x[data1], %[dest]\n"
"stlxp %w[tmp], %x[src0], %x[src1], %[dest]\n"
"cbnz %w[tmp], 1b\n"
: [tmp] "=&r" (tmp), [dest] "+Q" (dest), [data0] "=&r" (data[0]), [data1] "=&r" (data[1])
: [src0] "r" (src[0]), [src1] "r" (src[1])
: "memory"
);
T result;
std::memcpy(&result, data, 16);
return result;
}
static inline void store(T& dest, T value)
{
// TODO
#if defined(ARM_FEATURE_LSE2)
u64 src[2];
std::memcpy(src, &value, 16);
__asm__ volatile("1:\n"
"dmb ish\n"
"stp %x[data0], %x[data1], %[dest]\n"
"dmb ish\n"
: [dest] "=Q" (dest)
: [data0] "r" (src[0]), [data1] "r" (src[1])
: "memory"
);
#else
exchange(dest, value);
#endif
}
static inline void release(T& dest, T value)
{
#if defined(ARM_FEATURE_LSE2)
u64 src[2];
std::memcpy(src, &value, 16);
__asm__ volatile("1:\n"
"dmb ish\n"
"stp %x[data0], %x[data1], %[dest]\n"
: [dest] "=Q" (dest)
: [data0] "r" (src[0]), [data1] "r" (src[1])
: "memory"
);
#else
// TODO
exchange(dest, value);
#endif
}
#endif
// TODO
};
#ifndef _MSC_VER
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Weffc++"
#endif
// Atomic type with lock-free and standard layout guarantees (and appropriate limitations)
template <typename T, usz Align = sizeof(T)>
class atomic_t
{
protected:
using type = std::remove_cv_t<T>;
using ptr_rt = std::conditional_t<std::is_pointer_v<type>, ullong, type>;
static_assert((Align & (Align - 1)) == 0, "atomic_t<> error: unexpected Align parameter (not power of 2).");
static_assert(Align % sizeof(type) == 0, "atomic_t<> error: invalid type, must be power of 2.");
static_assert(sizeof(type) <= 16, "atomic_t<> error: invalid type, too big (max supported size is 16).");
static_assert(Align >= sizeof(type), "atomic_t<> error: bad args, specify bigger alignment if necessary.");
static_assert(std::is_trivially_copyable_v<type>);
static_assert(std::is_copy_constructible_v<type>);
static_assert(std::is_move_constructible_v<type>);
static_assert(std::is_copy_assignable_v<type>);
static_assert(std::is_move_assignable_v<type>);
alignas(Align) type m_data;
public:
static constexpr usz align = Align;
ENABLE_BITWISE_SERIALIZATION;
atomic_t() noexcept = default;
atomic_t(const atomic_t&) = delete;
atomic_t& operator =(const atomic_t&) = delete;
constexpr atomic_t(const type& value) noexcept
: m_data(value)
{
}
// Unsafe direct access
type& raw()
{
return m_data;
}
// Unsafe direct access
const type& raw() const
{
return m_data;
}
// Atomically compare data with cmp, replace with exch if equal, return previous data value anyway
type compare_and_swap(const type& cmp, const type& exch)
{
type old = cmp;
atomic_storage<type>::compare_exchange(m_data, old, exch);
return old;
}
// Atomically compare data with cmp, replace with exch if equal, return true if data was replaced
bool compare_and_swap_test(const type& cmp, const type& exch)
{
type old = cmp;
return atomic_storage<type>::compare_exchange(m_data, old, exch);
}
// As in std::atomic
bool compare_exchange(type& cmp_and_old, const type& exch)
{
return atomic_storage<type>::compare_exchange(m_data, cmp_and_old, exch);
}
// Atomic operation; returns old value, or pair of old value and return value (cancel op if evaluates to false)
template <typename F, typename RT = std::invoke_result_t<F, T&>>
requires (!std::is_invocable_v<F, const T> && !std::is_invocable_v<F, volatile T>)
std::conditional_t<std::is_void_v<RT>, type, std::pair<type, RT>> fetch_op(F func)
{
type _new, old = atomic_storage<type>::load(m_data);
while (true)
{
_new = old;
if constexpr (std::is_void_v<RT>)
{
std::invoke(func, _new);
if (atomic_storage<type>::compare_exchange(m_data, old, _new)) [[likely]]
{
return old;
}
}
else
{
RT ret = std::invoke(func, _new);
if (!ret || atomic_storage<type>::compare_exchange(m_data, old, _new)) [[likely]]
{
return {old, std::move(ret)};
}
}
}
}
// Atomic operation; returns function result value, function is the lambda
template <typename F, typename RT = std::invoke_result_t<F, T&>>
requires (!std::is_invocable_v<F, const T> && !std::is_invocable_v<F, volatile T>)
RT atomic_op(F func)
{
type _new, old = atomic_storage<type>::load(m_data);
while (true)
{
_new = old;
if constexpr (std::is_void_v<RT>)
{
std::invoke(func, _new);
if (atomic_storage<type>::compare_exchange(m_data, old, _new)) [[likely]]
{
return;
}
}
else
{
RT result = std::invoke(func, _new);
if (atomic_storage<type>::compare_exchange(m_data, old, _new)) [[likely]]
{
return result;
}
}
}
}
// Atomically read data
type load() const
{
return atomic_storage<type>::load(m_data);
}
// Atomically read data
operator std::common_type_t<T>() const
{
return atomic_storage<type>::load(m_data);
}
// Relaxed load
type observe() const
{
return atomic_storage<type>::observe(m_data);
}
// Atomically write data
void store(const type& rhs)
{
atomic_storage<type>::store(m_data, rhs);
}
type operator =(const type& rhs)
{
atomic_storage<type>::store(m_data, rhs);
return rhs;
}
// Atomically write data with release memory order (faster on x86)
void release(const type& rhs)
{
atomic_storage<type>::release(m_data, rhs);
}
// Atomically replace data with value, return previous data value
type exchange(const type& rhs)
{
return atomic_storage<type>::exchange(m_data, rhs);
}
auto fetch_add(const ptr_rt& rhs)
{
if constexpr(std::is_integral_v<type>)
{
return atomic_storage<type>::fetch_add(m_data, rhs);
}
return fetch_op([&](T& v)
{
v += rhs;
});
}
auto add_fetch(const ptr_rt& rhs)
{
if constexpr(std::is_integral_v<type>)
{
return atomic_storage<type>::add_fetch(m_data, rhs);
}
return atomic_op([&](T& v)
{
v += rhs;
return v;
});
}
auto operator +=(const ptr_rt& rhs)
{
if constexpr(std::is_integral_v<type>)
{
return atomic_storage<type>::add_fetch(m_data, rhs);
}
return atomic_op([&](T& v)
{
return v += rhs;
});
}
auto fetch_sub(const ptr_rt& rhs)
{
if constexpr(std::is_integral_v<type>)
{
return atomic_storage<type>::fetch_sub(m_data, rhs);
}
return fetch_op([&](T& v)
{
v -= rhs;
});
}
auto sub_fetch(const ptr_rt& rhs)
{
if constexpr(std::is_integral_v<type>)
{
return atomic_storage<type>::sub_fetch(m_data, rhs);
}
return atomic_op([&](T& v)
{
v -= rhs;
return v;
});
}
auto operator -=(const ptr_rt& rhs)
{
if constexpr(std::is_integral_v<type>)
{
return atomic_storage<type>::sub_fetch(m_data, rhs);
}
return atomic_op([&](T& v)
{
return v -= rhs;
});
}
auto fetch_and(const type& rhs)
{
if constexpr(std::is_integral_v<type>)
{
return atomic_storage<type>::fetch_and(m_data, rhs);
}
return fetch_op([&](T& v)
{
v &= rhs;
});
}
auto and_fetch(const type& rhs)
{
if constexpr(std::is_integral_v<type>)
{
return atomic_storage<type>::and_fetch(m_data, rhs);
}
return atomic_op([&](T& v)
{
v &= rhs;
return v;
});
}
auto operator &=(const type& rhs)
{
if constexpr(std::is_integral_v<type>)
{
return atomic_storage<type>::and_fetch(m_data, rhs);
}
return atomic_op([&](T& v)
{
return v &= rhs;
});
}
auto fetch_or(const type& rhs)
{
if constexpr(std::is_integral_v<type>)
{
return atomic_storage<type>::fetch_or(m_data, rhs);
}
return fetch_op([&](T& v)
{
v |= rhs;
});
}
auto or_fetch(const type& rhs)
{
if constexpr(std::is_integral_v<type>)
{
return atomic_storage<type>::or_fetch(m_data, rhs);
}
return atomic_op([&](T& v)
{
v |= rhs;
return v;
});
}
auto operator |=(const type& rhs)
{
if constexpr(std::is_integral_v<type>)
{
return atomic_storage<type>::or_fetch(m_data, rhs);
}
return atomic_op([&](T& v)
{
return v |= rhs;
});
}
auto fetch_xor(const type& rhs)
{
if constexpr(std::is_integral_v<type>)
{
return atomic_storage<type>::fetch_xor(m_data, rhs);
}
return fetch_op([&](T& v)
{
v ^= rhs;
});
}
auto xor_fetch(const type& rhs)
{
if constexpr(std::is_integral_v<type>)
{
return atomic_storage<type>::xor_fetch(m_data, rhs);
}
return atomic_op([&](T& v)
{
v ^= rhs;
return v;
});
}
auto operator ^=(const type& rhs)
{
if constexpr(std::is_integral_v<type>)
{
return atomic_storage<type>::xor_fetch(m_data, rhs);
}
return atomic_op([&](T& v)
{
return v ^= rhs;
});
}
auto operator ++()
{
if constexpr(std::is_integral_v<type>)
{
return atomic_storage<type>::inc_fetch(m_data);
}
return atomic_op([](T& v)
{
return ++v;
});
}
auto operator --()
{
if constexpr(std::is_integral_v<type>)
{
return atomic_storage<type>::dec_fetch(m_data);
}
return atomic_op([](T& v)
{
return --v;
});
}
auto operator ++(int)
{
if constexpr(std::is_integral_v<type>)
{
return atomic_storage<type>::fetch_inc(m_data);
}
return atomic_op([](T& v)
{
return v++;
});
}
auto operator --(int)
{
if constexpr(std::is_integral_v<type>)
{
return atomic_storage<type>::fetch_dec(m_data);
}
return atomic_op([](T& v)
{
return v--;
});
}
// Conditionally decrement
bool try_dec(std::common_type_t<T> greater_than)
{
type _new, old = atomic_storage<type>::load(m_data);
while (true)
{
_new = old;
if (!(_new > greater_than))
{
return false;
}
_new -= 1;
if (atomic_storage<type>::compare_exchange(m_data, old, _new)) [[likely]]
{
return true;
}
}
}
// Conditionally increment
bool try_inc(std::common_type_t<T> less_than)
{
type _new, old = atomic_storage<type>::load(m_data);
while (true)
{
_new = old;
if (!(_new < less_than))
{
return false;
}
_new += 1;
if (atomic_storage<type>::compare_exchange(m_data, old, _new)) [[likely]]
{
return true;
}
}
}
bool bit_test_set(uint bit)
{
if constexpr (std::is_integral_v<type>)
{
return atomic_storage<type>::bts(m_data, bit & (sizeof(T) * 8 - 1));
}
return atomic_op([](type& v)
{
const auto old = v;
const auto bit = type(1) << (sizeof(T) * 8 - 1);
v |= bit;
return !!(old & bit);
});
}
bool bit_test_reset(uint bit)
{
if constexpr (std::is_integral_v<type>)
{
return atomic_storage<type>::btr(m_data, bit & (sizeof(T) * 8 - 1));
}
return atomic_op([](type& v)
{
const auto old = v;
const auto bit = type(1) << (sizeof(T) * 8 - 1);
v &= ~bit;
return !!(old & bit);
});
}
bool bit_test_invert(uint bit)
{
if constexpr (std::is_integral_v<type>)
{
return atomic_storage<type>::btc(m_data, bit & (sizeof(T) * 8 - 1));
}
return atomic_op([](type& v)
{
const auto old = v;
const auto bit = type(1) << (sizeof(T) * 8 - 1);
v ^= bit;
return !!(old & bit);
});
}
void wait(type old_value, atomic_wait_timeout timeout = atomic_wait_timeout::inf) const
requires(sizeof(type) == 4)
{
atomic_wait_engine::wait(&m_data, std::bit_cast<u32>(old_value), static_cast<u64>(timeout));
}
[[deprecated]] void wait(type old_value, atomic_wait_timeout timeout = atomic_wait_timeout::inf) const
requires(sizeof(type) == 8)
{
atomic_wait::info ext[2]{};
ext[0].data = reinterpret_cast<const char*>(&m_data) + 4;
ext[0].old = std::bit_cast<u64>(old_value) >> 32;
atomic_wait_engine::wait(&m_data, static_cast<u32>(std::bit_cast<u64>(old_value)), static_cast<u64>(timeout), ext);
}
void notify_one()
requires(sizeof(type) == 4 || sizeof(type) == 8)
{
atomic_wait_engine::notify_one(&m_data);
}
void notify_all()
requires(sizeof(type) == 4 || sizeof(type) == 8)
{
atomic_wait_engine::notify_all(&m_data);
}
};
template <usz Align>
class atomic_t<bool, Align> : private atomic_t<uchar, Align>
{
using base = atomic_t<uchar, Align>;
public:
static constexpr usz align = Align;
atomic_t() noexcept = default;
atomic_t(const atomic_t&) = delete;
atomic_t& operator =(const atomic_t&) = delete;
constexpr atomic_t(bool value) noexcept
: base(value)
{
}
bool load() const noexcept
{
return base::load() != 0;
}
// Override implicit conversion from the parent type
explicit operator uchar() const = delete;
operator bool() const noexcept
{
return base::load() != 0;
}
bool observe() const noexcept
{
return base::observe() != 0;
}
void store(bool value)
{
base::store(value);
}
bool operator =(bool value)
{
base::store(value);
return value;
}
void release(bool value)
{
base::release(value);
}
bool exchange(bool value)
{
return base::exchange(value) != 0;
}
bool test_and_set()
{
return base::exchange(1) != 0;
}
bool test_and_reset()
{
return base::exchange(0) != 0;
}
bool test_and_invert()
{
return base::fetch_xor(1) != 0;
}
};
// Specializations
template <typename T, usz Align, typename T2, usz Align2>
struct std::common_type<atomic_t<T, Align>, atomic_t<T2, Align2>> : std::common_type<T, T2> {};
template <typename T, usz Align, typename T2>
struct std::common_type<atomic_t<T, Align>, T2> : std::common_type<T, std::common_type_t<T2>> {};
template <typename T, typename T2, usz Align2>
struct std::common_type<T, atomic_t<T2, Align2>> : std::common_type<std::common_type_t<T>, T2> {};
#ifndef _MSC_VER
#pragma GCC diagnostic pop
#pragma GCC diagnostic pop
#endif
namespace utils
{
template <typename F>
struct aofn_helper
{
F f;
aofn_helper(F&& f) noexcept
: f(std::forward<F>(f))
{
}
template <typename Arg> requires (std::is_same_v<std::remove_reference_t<Arg>, std::remove_cvref_t<Arg>> && !std::is_rvalue_reference_v<Arg>)
auto operator()(Arg& arg) const noexcept
{
return f(std::forward<Arg&>(arg));
}
};
template <typename F>
aofn_helper(F&& f) -> aofn_helper<F>;
}
// Shorter lambda for non-cv qualified L-values
// For use with atomic operations
#define AOFN(...) \
::utils::aofn_helper([&](auto& x) { return (__VA_ARGS__); })
| 43,435
|
C++
|
.h
| 1,541
| 25.493835
| 146
| 0.670761
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
5,673
|
v128.hpp
|
RPCS3_rpcs3/rpcs3/util/v128.hpp
|
#pragma once // No BOM and only basic ASCII in this header, or a neko will die
#include "util/types.hpp"
template <typename T>
concept Vector128 = (sizeof(T) == 16) && (std::is_trivial_v<T>);
// 128-bit vector type
union alignas(16) v128
{
uchar _bytes[16];
char _chars[16];
template <typename T, usz N, usz M>
struct masked_array_t // array type accessed as (index ^ M)
{
T m_data[N];
public:
T& operator[](usz index)
{
return m_data[index ^ M];
}
const T& operator[](usz index) const
{
return m_data[index ^ M];
}
};
template <typename T, usz N = 16 / sizeof(T)>
using normal_array_t = masked_array_t<T, N, std::endian::little == std::endian::native ? 0 : N - 1>;
template <typename T, usz N = 16 / sizeof(T)>
using reversed_array_t = masked_array_t<T, N, std::endian::little == std::endian::native ? N - 1 : 0>;
normal_array_t<u64> _u64;
normal_array_t<s64> _s64;
reversed_array_t<u64> u64r;
reversed_array_t<s64> s64r;
normal_array_t<u32> _u32;
normal_array_t<s32> _s32;
reversed_array_t<u32> u32r;
reversed_array_t<s32> s32r;
normal_array_t<u16> _u16;
normal_array_t<s16> _s16;
reversed_array_t<u16> u16r;
reversed_array_t<s16> s16r;
normal_array_t<u8> _u8;
normal_array_t<s8> _s8;
reversed_array_t<u8> u8r;
reversed_array_t<s8> s8r;
normal_array_t<f32> _f;
normal_array_t<f64> _d;
reversed_array_t<f32> fr;
reversed_array_t<f64> dr;
u128 _u;
s128 _s;
v128() = default;
constexpr v128(const v128&) noexcept = default;
template <Vector128 T>
constexpr v128(const T& rhs) noexcept
: v128(std::bit_cast<v128>(rhs))
{
}
constexpr v128& operator=(const v128&) noexcept = default;
template <Vector128 T>
constexpr operator T() const noexcept
{
return std::bit_cast<T>(*this);
}
ENABLE_BITWISE_SERIALIZATION;
static v128 from64(u64 _0, u64 _1 = 0)
{
v128 ret;
ret._u64[0] = _0;
ret._u64[1] = _1;
return ret;
}
static v128 from64r(u64 _1, u64 _0 = 0)
{
return from64(_0, _1);
}
static v128 from64p(u64 value)
{
v128 ret;
ret._u64[0] = value;
ret._u64[1] = value;
return ret;
}
static v128 from32(u32 _0, u32 _1 = 0, u32 _2 = 0, u32 _3 = 0)
{
v128 ret;
ret._u32[0] = _0;
ret._u32[1] = _1;
ret._u32[2] = _2;
ret._u32[3] = _3;
return ret;
}
static v128 from32r(u32 _3, u32 _2 = 0, u32 _1 = 0, u32 _0 = 0)
{
return from32(_0, _1, _2, _3);
}
static v128 from32p(u32 value)
{
v128 ret;
ret._u32[0] = value;
ret._u32[1] = value;
ret._u32[2] = value;
ret._u32[3] = value;
return ret;
}
static v128 fromf32p(f32 value)
{
v128 ret;
ret._f[0] = value;
ret._f[1] = value;
ret._f[2] = value;
ret._f[3] = value;
return ret;
}
static v128 from16p(u16 value)
{
v128 ret;
ret._u16[0] = value;
ret._u16[1] = value;
ret._u16[2] = value;
ret._u16[3] = value;
ret._u16[4] = value;
ret._u16[5] = value;
ret._u16[6] = value;
ret._u16[7] = value;
return ret;
}
static v128 from8p(u8 value)
{
v128 ret;
std::memset(&ret, value, sizeof(ret));
return ret;
}
static v128 undef()
{
#if defined(__GNUC__) || defined(__clang__)
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wuninitialized"
#elif _MSC_VER
#pragma warning(push)
#pragma warning(disable : 6001)
#endif
v128 ret;
return ret;
#if defined(__GNUC__) || defined(__clang__)
#pragma GCC diagnostic pop
#elif _MSC_VER
#pragma warning(pop)
#endif
}
// Unaligned load with optional index offset
static v128 loadu(const void* ptr, usz index = 0)
{
v128 ret;
std::memcpy(&ret, static_cast<const u8*>(ptr) + index * sizeof(v128), sizeof(v128));
return ret;
}
// Unaligned store with optional index offset
static void storeu(v128 value, void* ptr, usz index = 0)
{
std::memcpy(static_cast<u8*>(ptr) + index * sizeof(v128), &value, sizeof(v128));
}
v128 operator|(const v128&) const;
v128 operator&(const v128&) const;
v128 operator^(const v128&) const;
v128 operator~() const;
bool operator==(const v128& right) const;
void clear()
{
*this = {};
}
};
template <typename T, usz N, usz M>
struct offset32_array<v128::masked_array_t<T, N, M>>
{
template <typename Arg>
static inline u32 index32(const Arg& arg)
{
return u32{sizeof(T)} * (static_cast<u32>(arg) ^ static_cast<u32>(M));
}
};
template <>
struct std::hash<v128>
{
usz operator()(const v128& key) const
{
return key._u64[0] + key._u64[1];
}
};
| 4,391
|
C++
|
.h
| 187
| 21.101604
| 103
| 0.660749
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
5,674
|
cpu_stats.hpp
|
RPCS3_rpcs3/rpcs3/util/cpu_stats.hpp
|
#pragma once
#include "util/types.hpp"
#include <vector>
#ifdef _WIN32
#include <pdh.h>
#include <pdhmsg.h>
#endif
namespace utils
{
class cpu_stats
{
u64 m_last_cpu = 0;
u64 m_sys_cpu = 0;
u64 m_usr_cpu = 0;
#ifdef _WIN32
PDH_HQUERY m_cpu_query = nullptr;
PDH_HCOUNTER m_cpu_cores = nullptr;
#elif __linux__
size_t m_previous_idle_time_total = 0;
size_t m_previous_total_time_total = 0;
std::vector<size_t> m_previous_idle_times_per_cpu;
std::vector<size_t> m_previous_total_times_per_cpu;
#endif
public:
cpu_stats();
~cpu_stats();
double get_usage();
void init_cpu_query();
void get_per_core_usage(std::vector<double>& per_core_usage, double& total_usage);
static u32 get_current_thread_count();
};
}
| 745
|
C++
|
.h
| 32
| 20.96875
| 84
| 0.704965
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,675
|
qt_music_handler.h
|
RPCS3_rpcs3/rpcs3/rpcs3qt/qt_music_handler.h
|
#pragma once
#include "Emu/Io/music_handler_base.h"
#include <QMediaPlayer>
#include <QObject>
#include <mutex>
class qt_music_handler final : public QObject, public music_handler_base
{
Q_OBJECT
public:
qt_music_handler();
virtual ~qt_music_handler();
void stop() override;
void pause() override;
void play(const std::string& path) override;
void fast_forward(const std::string& path) override;
void fast_reverse(const std::string& path) override;
void set_volume(f32 volume) override;
f32 get_volume() const override;
private Q_SLOTS:
void handle_media_status(QMediaPlayer::MediaStatus status);
void handle_music_state(QMediaPlayer::PlaybackState state);
void handle_music_error(QMediaPlayer::Error error, const QString& errorString);
private:
mutable std::mutex m_mutex;
std::shared_ptr<QMediaPlayer> m_media_player;
std::string m_path;
};
| 866
|
C++
|
.h
| 27
| 30.222222
| 80
| 0.782452
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,676
|
emu_settings_type.h
|
RPCS3_rpcs3/rpcs3/rpcs3qt/emu_settings_type.h
|
#pragma once
#include <map>
#include <vector>
// Node location
using cfg_location = std::vector<const char*>;
enum class emu_settings_type
{
// Core
PPUDecoder,
SPUDecoder,
HookStaticFuncs,
ThreadSchedulerMode,
SPULoopDetection,
PreferredSPUThreads,
PPUDebug,
SPUDebug,
MFCDebug,
MaxLLVMThreads,
LLVMPrecompilation,
EnableTSX,
AccurateSpuDMA,
AccurateClineStores,
AccurateRSXAccess,
FIFOAccuracy,
XFloatAccuracy,
AccuratePPU128Loop,
MFCCommandsShuffling,
NumPPUThreads,
SetDAZandFTZ,
SPUBlockSize,
SPUCache,
DebugConsoleMode,
SilenceAllLogs,
SuspendEmulationSavestateMode,
CompatibleEmulationSavestateMode,
StartSavestatePaused,
MaxSPURSThreads,
SleepTimersAccuracy,
ClocksScale,
PerformanceReport,
FullWidthAVX512,
PPUNJFixup,
AccurateDFMA,
AccuratePPUSAT,
AccuratePPUNJ,
FixupPPUVNAN,
AccuratePPUVNAN,
AccuratePPUFPCC,
MaxPreemptCount,
SPUProfiler,
// Graphics
Renderer,
Resolution,
AspectRatio,
FrameLimit,
MSAA,
LogShaderPrograms,
WriteDepthBuffer,
WriteColorBuffers,
ReadColorBuffers,
ReadDepthBuffer,
HandleRSXTiledMemory,
VSync,
DebugOutput,
DebugOverlay,
RenderdocCompatibility,
GPUTextureScaling,
StretchToDisplayArea,
VulkanAdapter,
ForceHighpZ,
StrictRenderingMode,
DisableVertexCache,
DisableOcclusionQueries,
DisableVideoOutput,
DisableFIFOReordering,
StrictTextureFlushing,
ShaderPrecisionQuality,
StereoRenderMode,
AnisotropicFilterOverride,
TextureLodBias,
ResolutionScale,
MinimumScalableDimension,
FsrSharpeningStrength,
ExclusiveFullscreenMode,
ForceCPUBlitEmulation,
DisableOnDiskShaderCache,
DisableVulkanMemAllocator,
ShaderMode,
ShaderCompilerNumThreads,
MultithreadedRSX,
VBlankRate,
VBlankNTSCFixup,
RelaxedZCULL,
PreciseZCULL,
DriverWakeUpDelay,
VulkanAsyncTextureUploads,
VulkanAsyncSchedulerDriver,
AllowHostGPULabels,
DisableMSLFastMath,
OutputScalingMode,
ForceHwMSAAResolve,
// Performance Overlay
PerfOverlayEnabled,
PerfOverlayFramerateGraphEnabled,
PerfOverlayFrametimeGraphEnabled,
PerfOverlayFramerateDatapoints,
PerfOverlayFrametimeDatapoints,
PerfOverlayDetailLevel,
PerfOverlayFramerateDetailLevel,
PerfOverlayFrametimeDetailLevel,
PerfOverlayPosition,
PerfOverlayUpdateInterval,
PerfOverlayFontSize,
PerfOverlayOpacity,
PerfOverlayMarginX,
PerfOverlayMarginY,
PerfOverlayCenterX,
PerfOverlayCenterY,
// Shader Loading Dialog
ShaderLoadBgEnabled,
ShaderLoadBgDarkening,
ShaderLoadBgBlur,
// Audio
AudioRenderer,
DumpToFile,
ConvertTo16Bit,
AudioFormat,
AudioFormats,
AudioProvider,
AudioAvport,
AudioDevice,
AudioChannelLayout,
MasterVolume,
EnableBuffering,
AudioBufferDuration,
EnableTimeStretching,
TimeStretchingThreshold,
MicrophoneType,
MicrophoneDevices,
MusicHandler,
// Input / Output
BackgroundInput,
ShowMoveCursor,
LockOvlIptToP1,
PadHandlerMode,
PadConnection,
KeyboardHandler,
MouseHandler,
Camera,
CameraType,
CameraFlip,
CameraID,
Move,
Buzz,
Turntable,
GHLtar,
MidiDevices,
SDLMappings,
IoDebugOverlay,
// Misc
ExitRPCS3OnFinish,
StartOnBoot,
PauseOnFocusLoss,
StartGameFullscreen,
PreventDisplaySleep,
ShowTrophyPopups,
ShowRpcnPopups,
UseNativeInterface,
ShowShaderCompilationHint,
ShowPPUCompilationHint,
ShowPressureIntensityToggleHint,
ShowAnalogLimiterToggleHint,
ShowMouseAndKeyboardToggleHint,
ShowAutosaveAutoloadHint,
WindowTitleFormat,
PauseDuringHomeMenu,
// Network
InternetStatus,
DNSAddress,
IpSwapList,
PSNStatus,
BindAddress,
EnableUpnp,
PSNCountry,
// System
LicenseArea,
Language,
KeyboardType,
EnterButtonAssignment,
EnableHostRoot,
LimitCacheSize,
MaximumCacheSize,
ConsoleTimeOffset,
};
/** A helper map that keeps track of where a given setting type is located*/
inline static const std::map<emu_settings_type, cfg_location> settings_location =
{
// Core Tab
{ emu_settings_type::PPUDecoder, { "Core", "PPU Decoder"}},
{ emu_settings_type::SPUDecoder, { "Core", "SPU Decoder"}},
{ emu_settings_type::HookStaticFuncs, { "Core", "Hook static functions"}},
{ emu_settings_type::ThreadSchedulerMode, { "Core", "Thread Scheduler Mode"}},
{ emu_settings_type::SPULoopDetection, { "Core", "SPU loop detection"}},
{ emu_settings_type::PreferredSPUThreads, { "Core", "Preferred SPU Threads"}},
{ emu_settings_type::PPUDebug, { "Core", "PPU Debug"}},
{ emu_settings_type::SPUDebug, { "Core", "SPU Debug"}},
{ emu_settings_type::MFCDebug, { "Core", "MFC Debug"}},
{ emu_settings_type::MaxLLVMThreads, { "Core", "Max LLVM Compile Threads"}},
{ emu_settings_type::LLVMPrecompilation, { "Core", "LLVM Precompilation"}},
{ emu_settings_type::EnableTSX, { "Core", "Enable TSX"}},
{ emu_settings_type::AccurateSpuDMA, { "Core", "Accurate SPU DMA"}},
{ emu_settings_type::AccurateClineStores, { "Core", "Accurate Cache Line Stores"}},
{ emu_settings_type::AccurateRSXAccess, { "Core", "Accurate RSX reservation access"}},
{ emu_settings_type::FIFOAccuracy, { "Core", "RSX FIFO Accuracy"}},
{ emu_settings_type::XFloatAccuracy, { "Core", "XFloat Accuracy"}},
{ emu_settings_type::MFCCommandsShuffling, { "Core", "MFC Commands Shuffling Limit"}},
{ emu_settings_type::SetDAZandFTZ, { "Core", "Set DAZ and FTZ"}},
{ emu_settings_type::SPUBlockSize, { "Core", "SPU Block Size"}},
{ emu_settings_type::SPUCache, { "Core", "SPU Cache"}},
{ emu_settings_type::DebugConsoleMode, { "Core", "Debug Console Mode"}},
{ emu_settings_type::MaxSPURSThreads, { "Core", "Max SPURS Threads"}},
{ emu_settings_type::SleepTimersAccuracy, { "Core", "Sleep Timers Accuracy"}},
{ emu_settings_type::ClocksScale, { "Core", "Clocks scale"}},
{ emu_settings_type::AccuratePPU128Loop, { "Core", "Accurate PPU 128-byte Reservation Op Max Length"}},
{ emu_settings_type::PerformanceReport, { "Core", "Enable Performance Report"}},
{ emu_settings_type::FullWidthAVX512, { "Core", "Full Width AVX-512"}},
{ emu_settings_type::NumPPUThreads, { "Core", "PPU Threads"}},
{ emu_settings_type::PPUNJFixup, { "Core", "PPU LLVM Java Mode Handling"}},
{ emu_settings_type::AccurateDFMA, { "Core", "Use Accurate DFMA"}},
{ emu_settings_type::AccuratePPUSAT, { "Core", "PPU Set Saturation Bit"}},
{ emu_settings_type::AccuratePPUNJ, { "Core", "PPU Accurate Non-Java Mode"}},
{ emu_settings_type::FixupPPUVNAN, { "Core", "PPU Fixup Vector NaN Values"}},
{ emu_settings_type::AccuratePPUVNAN, { "Core", "PPU Accurate Vector NaN Values"}},
{ emu_settings_type::AccuratePPUFPCC, { "Core", "PPU Set FPCC Bits"}},
{ emu_settings_type::MaxPreemptCount, { "Core", "Max CPU Preempt Count"}},
{ emu_settings_type::SPUProfiler, { "Core", "SPU Profiler"}},
// Graphics Tab
{ emu_settings_type::Renderer, { "Video", "Renderer"}},
{ emu_settings_type::Resolution, { "Video", "Resolution"}},
{ emu_settings_type::AspectRatio, { "Video", "Aspect ratio"}},
{ emu_settings_type::FrameLimit, { "Video", "Frame limit"}},
{ emu_settings_type::MSAA, { "Video", "MSAA"}},
{ emu_settings_type::LogShaderPrograms, { "Video", "Log shader programs"}},
{ emu_settings_type::WriteDepthBuffer, { "Video", "Write Depth Buffer"}},
{ emu_settings_type::WriteColorBuffers, { "Video", "Write Color Buffers"}},
{ emu_settings_type::ReadColorBuffers, { "Video", "Read Color Buffers"}},
{ emu_settings_type::ReadDepthBuffer, { "Video", "Read Depth Buffer"}},
{ emu_settings_type::HandleRSXTiledMemory, { "Video", "Handle RSX Memory Tiling"}},
{ emu_settings_type::VSync, { "Video", "VSync"}},
{ emu_settings_type::DebugOutput, { "Video", "Debug output"}},
{ emu_settings_type::DebugOverlay, { "Video", "Debug overlay"}},
{ emu_settings_type::RenderdocCompatibility, { "Video", "Renderdoc Compatibility Mode"}},
{ emu_settings_type::GPUTextureScaling, { "Video", "Use GPU texture scaling"}},
{ emu_settings_type::StretchToDisplayArea, { "Video", "Stretch To Display Area"}},
{ emu_settings_type::ForceHighpZ, { "Video", "Force High Precision Z buffer"}},
{ emu_settings_type::StrictRenderingMode, { "Video", "Strict Rendering Mode"}},
{ emu_settings_type::DisableVertexCache, { "Video", "Disable Vertex Cache"}},
{ emu_settings_type::DisableOcclusionQueries, { "Video", "Disable ZCull Occlusion Queries"}},
{ emu_settings_type::DisableVideoOutput, { "Video", "Disable Video Output"}},
{ emu_settings_type::DisableFIFOReordering, { "Video", "Disable FIFO Reordering"}},
{ emu_settings_type::StereoRenderMode, { "Video", "3D Display Mode"}},
{ emu_settings_type::StrictTextureFlushing, { "Video", "Strict Texture Flushing"}},
{ emu_settings_type::ForceCPUBlitEmulation, { "Video", "Force CPU Blit"}},
{ emu_settings_type::DisableOnDiskShaderCache, { "Video", "Disable On-Disk Shader Cache"}},
{ emu_settings_type::DisableVulkanMemAllocator, { "Video", "Disable Vulkan Memory Allocator"}},
{ emu_settings_type::ShaderMode, { "Video", "Shader Mode"}},
{ emu_settings_type::ShaderCompilerNumThreads, { "Video", "Shader Compiler Threads"}},
{ emu_settings_type::ShaderPrecisionQuality, { "Video", "Shader Precision"}},
{ emu_settings_type::MultithreadedRSX, { "Video", "Multithreaded RSX"}},
{ emu_settings_type::RelaxedZCULL, { "Video", "Relaxed ZCULL Sync"}},
{ emu_settings_type::PreciseZCULL, { "Video", "Accurate ZCULL stats"}},
{ emu_settings_type::AnisotropicFilterOverride, { "Video", "Anisotropic Filter Override"}},
{ emu_settings_type::TextureLodBias, { "Video", "Texture LOD Bias Addend"}},
{ emu_settings_type::ResolutionScale, { "Video", "Resolution Scale"}},
{ emu_settings_type::MinimumScalableDimension, { "Video", "Minimum Scalable Dimension"}},
{ emu_settings_type::VulkanAdapter, { "Video", "Vulkan", "Adapter"}},
{ emu_settings_type::VBlankRate, { "Video", "Vblank Rate"}},
{ emu_settings_type::VBlankNTSCFixup, { "Video", "Vblank NTSC Fixup"}},
{ emu_settings_type::DriverWakeUpDelay, { "Video", "Driver Wake-Up Delay"}},
{ emu_settings_type::AllowHostGPULabels, { "Video", "Allow Host GPU Labels"}},
{ emu_settings_type::DisableMSLFastMath, { "Video", "Disable MSL Fast Math"}},
{ emu_settings_type::OutputScalingMode, { "Video", "Output Scaling Mode"}},
{ emu_settings_type::ForceHwMSAAResolve, { "Video", "Force Hardware MSAA Resolve"}},
// Vulkan
{ emu_settings_type::VulkanAsyncTextureUploads, { "Video", "Vulkan", "Asynchronous Texture Streaming 2"}},
{ emu_settings_type::VulkanAsyncSchedulerDriver, { "Video", "Vulkan", "Asynchronous Queue Scheduler"}},
{ emu_settings_type::FsrSharpeningStrength, { "Video", "Vulkan", "FidelityFX CAS Sharpening Intensity"}},
{ emu_settings_type::ExclusiveFullscreenMode, { "Video", "Vulkan", "Exclusive Fullscreen Mode"}},
// Performance Overlay
{ emu_settings_type::PerfOverlayEnabled, { "Video", "Performance Overlay", "Enabled" } },
{ emu_settings_type::PerfOverlayFramerateGraphEnabled, { "Video", "Performance Overlay", "Enable Framerate Graph" } },
{ emu_settings_type::PerfOverlayFrametimeGraphEnabled, { "Video", "Performance Overlay", "Enable Frametime Graph" } },
{ emu_settings_type::PerfOverlayFramerateDatapoints, { "Video", "Performance Overlay", "Framerate datapoints" } },
{ emu_settings_type::PerfOverlayFrametimeDatapoints, { "Video", "Performance Overlay", "Frametime datapoints" } },
{ emu_settings_type::PerfOverlayDetailLevel, { "Video", "Performance Overlay", "Detail level" } },
{ emu_settings_type::PerfOverlayFramerateDetailLevel, { "Video", "Performance Overlay", "Framerate graph detail level" } },
{ emu_settings_type::PerfOverlayFrametimeDetailLevel, { "Video", "Performance Overlay", "Frametime graph detail level" } },
{ emu_settings_type::PerfOverlayPosition, { "Video", "Performance Overlay", "Position" } },
{ emu_settings_type::PerfOverlayUpdateInterval, { "Video", "Performance Overlay", "Metrics update interval (ms)" } },
{ emu_settings_type::PerfOverlayFontSize, { "Video", "Performance Overlay", "Font size (px)" } },
{ emu_settings_type::PerfOverlayOpacity, { "Video", "Performance Overlay", "Opacity (%)" } },
{ emu_settings_type::PerfOverlayMarginX, { "Video", "Performance Overlay", "Horizontal Margin (px)" } },
{ emu_settings_type::PerfOverlayMarginY, { "Video", "Performance Overlay", "Vertical Margin (px)" } },
{ emu_settings_type::PerfOverlayCenterX, { "Video", "Performance Overlay", "Center Horizontally" } },
{ emu_settings_type::PerfOverlayCenterY, { "Video", "Performance Overlay", "Center Vertically" } },
// Shader Loading Dialog
{ emu_settings_type::ShaderLoadBgEnabled, { "Video", "Shader Loading Dialog", "Allow custom background" } },
{ emu_settings_type::ShaderLoadBgDarkening, { "Video", "Shader Loading Dialog", "Darkening effect strength" } },
{ emu_settings_type::ShaderLoadBgBlur, { "Video", "Shader Loading Dialog", "Blur effect strength" } },
// Audio
{ emu_settings_type::AudioRenderer, { "Audio", "Renderer"}},
{ emu_settings_type::DumpToFile, { "Audio", "Dump to file"}},
{ emu_settings_type::ConvertTo16Bit, { "Audio", "Convert to 16 bit"}},
{ emu_settings_type::AudioFormat, { "Audio", "Audio Format"}},
{ emu_settings_type::AudioFormats, { "Audio", "Audio Formats"}},
{ emu_settings_type::AudioProvider, { "Audio", "Audio Provider"}},
{ emu_settings_type::AudioAvport, { "Audio", "RSXAudio Avport"}},
{ emu_settings_type::AudioDevice, { "Audio", "Audio Device"}},
{ emu_settings_type::AudioChannelLayout, { "Audio", "Audio Channel Layout"}},
{ emu_settings_type::MasterVolume, { "Audio", "Master Volume"}},
{ emu_settings_type::EnableBuffering, { "Audio", "Enable Buffering"}},
{ emu_settings_type::AudioBufferDuration, { "Audio", "Desired Audio Buffer Duration"}},
{ emu_settings_type::EnableTimeStretching, { "Audio", "Enable Time Stretching"}},
{ emu_settings_type::TimeStretchingThreshold, { "Audio", "Time Stretching Threshold"}},
{ emu_settings_type::MicrophoneType, { "Audio", "Microphone Type" }},
{ emu_settings_type::MicrophoneDevices, { "Audio", "Microphone Devices" }},
{ emu_settings_type::MusicHandler, { "Audio", "Music Handler"}},
// Input / Output
{ emu_settings_type::BackgroundInput, { "Input/Output", "Background input enabled"}},
{ emu_settings_type::ShowMoveCursor, { "Input/Output", "Show move cursor"}},
{ emu_settings_type::LockOvlIptToP1, { "Input/Output", "Lock overlay input to player one"}},
{ emu_settings_type::PadHandlerMode, { "Input/Output", "Pad handler mode"}},
{ emu_settings_type::PadConnection, { "Input/Output", "Keep pads connected" }},
{ emu_settings_type::KeyboardHandler, { "Input/Output", "Keyboard"}},
{ emu_settings_type::MouseHandler, { "Input/Output", "Mouse"}},
{ emu_settings_type::Camera, { "Input/Output", "Camera"}},
{ emu_settings_type::CameraType, { "Input/Output", "Camera type"}},
{ emu_settings_type::CameraFlip, { "Input/Output", "Camera flip"}},
{ emu_settings_type::CameraID, { "Input/Output", "Camera ID"}},
{ emu_settings_type::Move, { "Input/Output", "Move" }},
{ emu_settings_type::Buzz, { "Input/Output", "Buzz emulated controller" }},
{ emu_settings_type::Turntable, { "Input/Output", "Turntable emulated controller" }},
{ emu_settings_type::GHLtar, { "Input/Output", "GHLtar emulated controller" }},
{ emu_settings_type::MidiDevices, { "Input/Output", "Emulated Midi devices" }},
{ emu_settings_type::SDLMappings, { "Input/Output", "Load SDL GameController Mappings" }},
{ emu_settings_type::IoDebugOverlay, { "Input/Output", "IO Debug overlay" }},
// Misc
{ emu_settings_type::ExitRPCS3OnFinish, { "Miscellaneous", "Exit RPCS3 when process finishes" }},
{ emu_settings_type::StartOnBoot, { "Miscellaneous", "Automatically start games after boot" }},
{ emu_settings_type::PauseOnFocusLoss, { "Miscellaneous", "Pause emulation on RPCS3 focus loss" }},
{ emu_settings_type::StartGameFullscreen, { "Miscellaneous", "Start games in fullscreen mode"}},
{ emu_settings_type::PreventDisplaySleep, { "Miscellaneous", "Prevent display sleep while running games"}},
{ emu_settings_type::ShowTrophyPopups, { "Miscellaneous", "Show trophy popups"}},
{ emu_settings_type::ShowRpcnPopups, { "Miscellaneous", "Show RPCN popups"}},
{ emu_settings_type::UseNativeInterface, { "Miscellaneous", "Use native user interface"}},
{ emu_settings_type::ShowShaderCompilationHint, { "Miscellaneous", "Show shader compilation hint"}},
{ emu_settings_type::ShowPPUCompilationHint, { "Miscellaneous", "Show PPU compilation hint"}},
{ emu_settings_type::ShowPressureIntensityToggleHint, { "Miscellaneous", "Show pressure intensity toggle hint"}},
{ emu_settings_type::ShowAnalogLimiterToggleHint, { "Miscellaneous", "Show analog limiter toggle hint"}},
{ emu_settings_type::ShowMouseAndKeyboardToggleHint, { "Miscellaneous", "Show mouse and keyboard toggle hint"}},
{ emu_settings_type::SilenceAllLogs, { "Miscellaneous", "Silence All Logs" }},
{ emu_settings_type::WindowTitleFormat, { "Miscellaneous", "Window Title Format" }},
{ emu_settings_type::PauseDuringHomeMenu, { "Miscellaneous", "Pause Emulation During Home Menu" }},
{ emu_settings_type::ShowAutosaveAutoloadHint, { "Miscellaneous", "Show autosave/autoload hint" }},
// Networking
{ emu_settings_type::InternetStatus, { "Net", "Internet enabled"}},
{ emu_settings_type::DNSAddress, { "Net", "DNS address"}},
{ emu_settings_type::IpSwapList, { "Net", "IP swap list"}},
{ emu_settings_type::PSNStatus, { "Net", "PSN status"}},
{ emu_settings_type::BindAddress, { "Net", "Bind address"}},
{ emu_settings_type::EnableUpnp, { "Net", "UPNP Enabled"}},
{ emu_settings_type::PSNCountry, { "Net", "PSN Country"}},
// System
{ emu_settings_type::LicenseArea, { "System", "License Area"}},
{ emu_settings_type::Language, { "System", "Language"}},
{ emu_settings_type::KeyboardType, { "System", "Keyboard Type"} },
{ emu_settings_type::EnterButtonAssignment, { "System", "Enter button assignment"}},
{ emu_settings_type::EnableHostRoot, { "VFS", "Enable /host_root/"}},
{ emu_settings_type::LimitCacheSize, { "VFS", "Limit disk cache size"}},
{ emu_settings_type::MaximumCacheSize, { "VFS", "Disk cache maximum size (MB)"}},
{ emu_settings_type::ConsoleTimeOffset, { "System", "Console time offset (s)"}},
// Savestates
{ emu_settings_type::SuspendEmulationSavestateMode, { "Savestate", "Suspend Emulation Savestate Mode" }},
{ emu_settings_type::CompatibleEmulationSavestateMode, { "Savestate", "Compatible Savestate Mode" }},
{ emu_settings_type::StartSavestatePaused, { "Savestate", "Start Paused" }},
};
| 19,858
|
C++
|
.h
| 386
| 49.419689
| 125
| 0.682519
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,677
|
flow_widget.h
|
RPCS3_rpcs3/rpcs3/rpcs3qt/flow_widget.h
|
#pragma once
#include "util/types.hpp"
#include "flow_widget_item.h"
#include "flow_layout.h"
#include <QWidget>
#include <QScrollArea>
#include <QPaintEvent>
class flow_widget : public QWidget
{
Q_OBJECT
public:
flow_widget(QWidget* parent);
virtual ~flow_widget();
void add_widget(flow_widget_item* widget);
void clear();
std::vector<flow_widget_item*>& items() { return m_widgets; }
flow_widget_item* selected_item() const;
QScrollArea* scroll_area() const { return m_scroll_area; }
void paintEvent(QPaintEvent* event) override;
Q_SIGNALS:
void ItemSelectionChanged(int index);
private Q_SLOTS:
void on_item_focus();
void on_navigate(flow_navigation value);
protected:
void select_item(flow_widget_item* item);
void mouseDoubleClickEvent(QMouseEvent* event) override;
private:
s64 find_item(const flow_layout::position& pos);
flow_layout::position find_item(flow_widget_item* item);
flow_layout::position find_next_item(flow_layout::position current_pos, flow_navigation value);
flow_layout* m_flow_layout{};
QScrollArea* m_scroll_area{};
std::vector<flow_widget_item*> m_widgets;
s64 m_selected_index = -1;
};
| 1,147
|
C++
|
.h
| 36
| 29.944444
| 96
| 0.767971
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,678
|
numbered_widget_item.h
|
RPCS3_rpcs3/rpcs3/rpcs3qt/numbered_widget_item.h
|
#pragma once
#include <QListWidgetItem>
class numbered_widget_item final : public QListWidgetItem
{
public:
explicit numbered_widget_item(const QString& text, QListWidget* listview = nullptr, int type = QListWidgetItem::Type)
: QListWidgetItem(text, listview, type)
{
}
QVariant data(int role) const override
{
switch (role)
{
case Qt::DisplayRole:
// Return number and original display text (e.g. "14. My Cool Game (BLUS12345)")
return QStringLiteral("%1. %2").arg(listWidget()->row(this) + 1).arg(QListWidgetItem::data(Qt::DisplayRole).toString());
default:
// Return original data
return QListWidgetItem::data(role);
}
}
bool operator<(const QListWidgetItem& other) const override
{
// Compare original display text
return QListWidgetItem::data(Qt::DisplayRole).toString() < other.QListWidgetItem::data(Qt::DisplayRole).toString();
}
};
| 881
|
C++
|
.h
| 27
| 30.111111
| 123
| 0.747059
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,679
|
update_manager.h
|
RPCS3_rpcs3/rpcs3/rpcs3qt/update_manager.h
|
#pragma once
#include "util/types.hpp"
#include <QObject>
#include <QByteArray>
#include <string>
class downloader;
class gui_settings;
class update_manager final : public QObject
{
Q_OBJECT
private:
downloader* m_downloader = nullptr;
QWidget* m_parent = nullptr;
std::shared_ptr<gui_settings> m_gui_settings;
// This message is empty if there is no download available
QString m_update_message;
struct changelog_data
{
QString version;
QString title;
};
std::vector<changelog_data> m_changelog;
std::string m_request_url;
std::string m_expected_hash;
std::string m_old_version;
std::string m_new_version;
u64 m_expected_size = 0;
bool handle_json(bool automatic, bool check_only, bool auto_accept, const QByteArray& data);
bool handle_rpcs3(const QByteArray& data, bool auto_accept);
public:
update_manager(QObject* parent, std::shared_ptr<gui_settings> gui_settings);
void check_for_updates(bool automatic, bool check_only, bool auto_accept, QWidget* parent = nullptr);
void update(bool auto_accept);
Q_SIGNALS:
void signal_update_available(bool update_available);
};
| 1,115
|
C++
|
.h
| 36
| 28.944444
| 102
| 0.771321
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,680
|
pad_device_info.h
|
RPCS3_rpcs3/rpcs3/rpcs3qt/pad_device_info.h
|
#pragma once
#include <string>
#include <QObject>
struct pad_device_info
{
std::string name;
QString localized_name;
bool is_connected{false};
};
Q_DECLARE_METATYPE(pad_device_info)
| 188
|
C++
|
.h
| 10
| 17.2
| 35
| 0.788571
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,682
|
skylander_dialog.h
|
RPCS3_rpcs3/rpcs3/rpcs3qt/skylander_dialog.h
|
#pragma once
#include <optional>
#include "util/types.hpp"
#include <QDialog>
#include <QLineEdit>
constexpr auto UI_SKY_NUM = 8;
class skylander_creator_dialog : public QDialog
{
Q_OBJECT
public:
explicit skylander_creator_dialog(QWidget* parent);
QString get_file_path() const;
protected:
QString file_path;
};
class skylander_dialog : public QDialog
{
Q_OBJECT
public:
explicit skylander_dialog(QWidget* parent);
~skylander_dialog();
static skylander_dialog* get_dlg(QWidget* parent);
skylander_dialog(skylander_dialog const&) = delete;
void operator=(skylander_dialog const&) = delete;
protected:
void clear_skylander(u8 slot);
void create_skylander(u8 slot);
void load_skylander(u8 slot);
void load_skylander_path(u8 slot, const QString& path);
void update_edits();
protected:
QLineEdit* edit_skylanders[UI_SKY_NUM]{};
static std::optional<std::tuple<u8, u16, u16>> sky_slots[UI_SKY_NUM];
private:
static skylander_dialog* inst;
};
| 968
|
C++
|
.h
| 36
| 25.027778
| 70
| 0.77802
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,683
|
_discord_utils.h
|
RPCS3_rpcs3/rpcs3/rpcs3qt/_discord_utils.h
|
#pragma once
#include <string>
namespace discord
{
// Convenience function for initialization
void initialize(const std::string& application_id = "424004941485572097");
// Convenience function for shutdown
void shutdown();
// Convenience function for status updates. The default is set to idle.
void update_presence(const std::string& state = "", const std::string& details = "Idle", bool reset_timer = true);
}
| 422
|
C++
|
.h
| 11
| 36.454545
| 115
| 0.766585
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,684
|
game_list.h
|
RPCS3_rpcs3/rpcs3/rpcs3qt/game_list.h
|
#pragma once
#include <QAction>
#include <QList>
#include <QTableWidget>
#include <QMouseEvent>
#include <QKeyEvent>
#include "game_list_base.h"
#include "util/atomic.hpp"
#include <functional>
class movie_item;
/*
class used in order to get deselection and hover change
if you know a simpler way, tell @Megamouse
*/
class game_list : public QTableWidget, public game_list_base
{
Q_OBJECT
public:
game_list();
void sync_header_actions(QList<QAction*>& actions, std::function<bool(int)> get_visibility);
void create_header_actions(QList<QAction*>& actions, std::function<bool(int)> get_visibility, std::function<void(int, bool)> set_visibility);
void clear_list() override; // Use this instead of clearContents
/** Fix columns with width smaller than the minimal section size */
void fix_narrow_columns();
public Q_SLOTS:
void FocusAndSelectFirstEntryIfNoneIs();
Q_SIGNALS:
void FocusToSearchBar();
void IconReady(const game_info& game);
protected:
movie_item* m_last_hover_item = nullptr;
void mousePressEvent(QMouseEvent* event) override;
void mouseMoveEvent(QMouseEvent* event) override;
void mouseDoubleClickEvent(QMouseEvent* event) override;
void keyPressEvent(QKeyEvent* event) override;
void leaveEvent(QEvent* event) override;
};
| 1,269
|
C++
|
.h
| 37
| 32.459459
| 142
| 0.787531
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,685
|
custom_table_widget_item.h
|
RPCS3_rpcs3/rpcs3/rpcs3qt/custom_table_widget_item.h
|
#pragma once
#include "movie_item.h"
class custom_table_widget_item : public movie_item
{
private:
int m_sort_role = Qt::DisplayRole;
public:
using QTableWidgetItem::setData;
custom_table_widget_item() = default;
custom_table_widget_item(const std::string& text, int sort_role = Qt::DisplayRole, const QVariant& sort_value = 0);
custom_table_widget_item(const QString& text, int sort_role = Qt::DisplayRole, const QVariant& sort_value = 0);
bool operator<(const QTableWidgetItem& other) const override;
void setData(int role, const QVariant& value, bool assign_sort_role);
};
| 589
|
C++
|
.h
| 14
| 40.142857
| 116
| 0.768014
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,686
|
localized_emu.h
|
RPCS3_rpcs3/rpcs3/rpcs3qt/localized_emu.h
|
#pragma once
#include <string>
#include <QObject>
#include "Emu/localized_string_id.h"
#include "Emu/Io/pad_types.h"
/**
* Localized emucore string collection class
* Due to special characters this file should stay in UTF-8 format
*/
class localized_emu : public QObject
{
Q_OBJECT
public:
localized_emu() = default;
static QString translated_pad_button(pad_button btn);
static QString translated_mouse_button(int btn);
template <typename... Args>
static std::string get_string(localized_string_id id, Args&&... args)
{
return translated(id, std::forward<Args>(args)...).toStdString();
}
template <typename... Args>
static std::u32string get_u32string(localized_string_id id, Args&&... args)
{
return translated(id, std::forward<Args>(args)...).toStdU32String();
}
private:
template <typename... Args>
static QString translated(localized_string_id id, Args&&... args)
{
switch (id)
{
case localized_string_id::RSX_OVERLAYS_TROPHY_BRONZE: return tr("You have earned a bronze trophy.\n%0", "Trophy text").arg(std::forward<Args>(args)...);
case localized_string_id::RSX_OVERLAYS_TROPHY_SILVER: return tr("You have earned a silver trophy.\n%0", "Trophy text").arg(std::forward<Args>(args)...);
case localized_string_id::RSX_OVERLAYS_TROPHY_GOLD: return tr("You have earned a gold trophy.\n%0", "Trophy text").arg(std::forward<Args>(args)...);
case localized_string_id::RSX_OVERLAYS_TROPHY_PLATINUM: return tr("You have earned a platinum trophy.\n%0", "Trophy text").arg(std::forward<Args>(args)...);
case localized_string_id::RSX_OVERLAYS_COMPILING_SHADERS: return tr("Compiling shaders");
case localized_string_id::RSX_OVERLAYS_COMPILING_PPU_MODULES: return tr("Compiling PPU Modules");
case localized_string_id::RSX_OVERLAYS_MSG_DIALOG_YES: return tr("Yes", "Message Dialog");
case localized_string_id::RSX_OVERLAYS_MSG_DIALOG_NO: return tr("No", "Message Dialog");
case localized_string_id::RSX_OVERLAYS_MSG_DIALOG_CANCEL: return tr("Back", "Message Dialog");
case localized_string_id::RSX_OVERLAYS_MSG_DIALOG_OK: return tr("OK", "Message Dialog");
case localized_string_id::RSX_OVERLAYS_SAVE_DIALOG_TITLE: return tr("Save Dialog", "Save Dialog");
case localized_string_id::RSX_OVERLAYS_SAVE_DIALOG_DELETE: return tr("Delete Save", "Save Dialog");
case localized_string_id::RSX_OVERLAYS_SAVE_DIALOG_LOAD: return tr("Load Save", "Save Dialog");
case localized_string_id::RSX_OVERLAYS_SAVE_DIALOG_SAVE: return tr("Save", "Save Dialog");
case localized_string_id::RSX_OVERLAYS_OSK_DIALOG_ACCEPT: return tr("Enter", "OSK Dialog");
case localized_string_id::RSX_OVERLAYS_OSK_DIALOG_CANCEL: return tr("Back", "OSK Dialog");
case localized_string_id::RSX_OVERLAYS_OSK_DIALOG_SPACE: return tr("Space", "OSK Dialog");
case localized_string_id::RSX_OVERLAYS_OSK_DIALOG_BACKSPACE: return tr("Backspace", "OSK Dialog");
case localized_string_id::RSX_OVERLAYS_OSK_DIALOG_SHIFT: return tr("Shift", "OSK Dialog");
case localized_string_id::RSX_OVERLAYS_OSK_DIALOG_ENTER_TEXT: return tr("[Enter Text]", "OSK Dialog");
case localized_string_id::RSX_OVERLAYS_OSK_DIALOG_ENTER_PASSWORD: return tr("[Enter Password]", "OSK Dialog");
case localized_string_id::RSX_OVERLAYS_MEDIA_DIALOG_TITLE: return tr("Select media", "Media dialog");
case localized_string_id::RSX_OVERLAYS_MEDIA_DIALOG_TITLE_PHOTO_IMPORT: return tr("Select photo to import", "Media dialog");
case localized_string_id::RSX_OVERLAYS_MEDIA_DIALOG_EMPTY: return tr("No media found.", "Media dialog");
case localized_string_id::RSX_OVERLAYS_LIST_SELECT: return tr("Enter", "Enter Dialog List");
case localized_string_id::RSX_OVERLAYS_LIST_CANCEL: return tr("Back", "Cancel Dialog List");
case localized_string_id::RSX_OVERLAYS_LIST_DENY: return tr("Deny", "Deny Dialog List");
case localized_string_id::RSX_OVERLAYS_PRESSURE_INTENSITY_TOGGLED_OFF: return tr("Pressure intensity mode of player %0 disabled", "Pressure intensity toggled off").arg(std::forward<Args>(args)...);
case localized_string_id::RSX_OVERLAYS_PRESSURE_INTENSITY_TOGGLED_ON: return tr("Pressure intensity mode of player %0 enabled", "Pressure intensity toggled on").arg(std::forward<Args>(args)...);
case localized_string_id::RSX_OVERLAYS_ANALOG_LIMITER_TOGGLED_OFF: return tr("Analog limiter of player %0 disabled", "Analog limiter toggled off").arg(std::forward<Args>(args)...);
case localized_string_id::RSX_OVERLAYS_ANALOG_LIMITER_TOGGLED_ON: return tr("Analog limiter of player %0 enabled", "Analog limiter toggled on").arg(std::forward<Args>(args)...);
case localized_string_id::RSX_OVERLAYS_MOUSE_AND_KEYBOARD_EMULATED: return tr("Mouse and keyboard are now used as emulated devices.", "Mouse and keyboard emulated");
case localized_string_id::RSX_OVERLAYS_MOUSE_AND_KEYBOARD_PAD: return tr("Mouse and keyboard are now used as pad.", "Mouse and keyboard pad");
case localized_string_id::CELL_GAME_ERROR_BROKEN_GAMEDATA: return tr("ERROR: Game data is corrupted. The application will continue.", "Game Error");
case localized_string_id::CELL_GAME_ERROR_BROKEN_HDDGAME: return tr("ERROR: HDD boot game is corrupted. The application will continue.", "Game Error");
case localized_string_id::CELL_GAME_ERROR_BROKEN_EXIT_GAMEDATA: return tr("ERROR: Game data is corrupted. The application will be terminated.", "Game Error");
case localized_string_id::CELL_GAME_ERROR_BROKEN_EXIT_HDDGAME: return tr("ERROR: HDD boot game is corrupted. The application will be terminated.", "Game Error");
case localized_string_id::CELL_GAME_ERROR_NOSPACE: return tr("ERROR: Not enough available space. The application will continue.\nSpace needed: %0 KB", "Game Error").arg(std::forward<Args>(args)...);
case localized_string_id::CELL_GAME_ERROR_NOSPACE_EXIT: return tr("ERROR: Not enough available space. The application will be terminated.\nSpace needed: %0 KB", "Game Error").arg(std::forward<Args>(args)...);
case localized_string_id::CELL_GAME_ERROR_DIR_NAME: return tr("Directory name: %0", "Game Error").arg(std::forward<Args>(args)...);
case localized_string_id::CELL_GAME_DATA_EXIT_BROKEN: return tr("There has been an error!\n\nPlease remove the game data for this title.", "Game Error");
case localized_string_id::CELL_HDD_GAME_EXIT_BROKEN: return tr("There has been an error!\n\nPlease reinstall the HDD boot game.", "Game Error");
case localized_string_id::CELL_HDD_GAME_CHECK_NOSPACE: return tr("Not enough space to create HDD boot game.\nSpace Needed: %0 KB", "HDD Game Check Error").arg(std::forward<Args>(args)...);
case localized_string_id::CELL_HDD_GAME_CHECK_BROKEN: return tr("HDD boot game %0 is corrupt!", "HDD Game Check Error").arg(std::forward<Args>(args)...);
case localized_string_id::CELL_HDD_GAME_CHECK_NODATA: return tr("HDD boot game %0 could not be found!", "HDD Game Check Error").arg(std::forward<Args>(args)...);
case localized_string_id::CELL_HDD_GAME_CHECK_INVALID: return tr("Error: %0", "HDD Game Check Error").arg(std::forward<Args>(args)...);
case localized_string_id::CELL_GAMEDATA_CHECK_NOSPACE: return tr("Not enough space to create game data.\nSpace Needed: %0 KB", "Gamedata Check Error").arg(std::forward<Args>(args)...);
case localized_string_id::CELL_GAMEDATA_CHECK_BROKEN: return tr("The game data in %0 is corrupt!", "Gamedata Check Error").arg(std::forward<Args>(args)...);
case localized_string_id::CELL_GAMEDATA_CHECK_NODATA: return tr("The game data in %0 could not be found!", "Gamedata Check Error").arg(std::forward<Args>(args)...);
case localized_string_id::CELL_GAMEDATA_CHECK_INVALID: return tr("Error: %0", "Gamedata Check Error").arg(std::forward<Args>(args)...);
case localized_string_id::CELL_MSG_DIALOG_ERROR_80010001: return tr("The resource is temporarily unavailable.\n(%0)", "Error code").arg(std::forward<Args>(args)...);
case localized_string_id::CELL_MSG_DIALOG_ERROR_80010002: return tr("Invalid argument or flag.\n(%0)", "Error code").arg(std::forward<Args>(args)...);
case localized_string_id::CELL_MSG_DIALOG_ERROR_80010003: return tr("The feature is not yet implemented.\n(%0)", "Error code").arg(std::forward<Args>(args)...);
case localized_string_id::CELL_MSG_DIALOG_ERROR_80010004: return tr("Memory allocation failed.\n(%0)", "Error code").arg(std::forward<Args>(args)...);
case localized_string_id::CELL_MSG_DIALOG_ERROR_80010005: return tr("The resource with the specified identifier does not exist.\n(%0)", "Error code").arg(std::forward<Args>(args)...);
case localized_string_id::CELL_MSG_DIALOG_ERROR_80010006: return tr("The file does not exist.\n(%0)", "Error code").arg(std::forward<Args>(args)...);
case localized_string_id::CELL_MSG_DIALOG_ERROR_80010007: return tr("The file is in an unrecognized format / The file is not a valid ELF file.\n(%0)", "Error code").arg(std::forward<Args>(args)...);
case localized_string_id::CELL_MSG_DIALOG_ERROR_80010008: return tr("Resource deadlock is avoided.\n(%0)", "Error code").arg(std::forward<Args>(args)...);
case localized_string_id::CELL_MSG_DIALOG_ERROR_80010009: return tr("Operation not permitted.\n(%0)", "Error code").arg(std::forward<Args>(args)...);
case localized_string_id::CELL_MSG_DIALOG_ERROR_8001000A: return tr("The device or resource is busy.\n(%0)", "Error code").arg(std::forward<Args>(args)...);
case localized_string_id::CELL_MSG_DIALOG_ERROR_8001000B: return tr("The operation is timed out.\n(%0)", "Error code").arg(std::forward<Args>(args)...);
case localized_string_id::CELL_MSG_DIALOG_ERROR_8001000C: return tr("The operation is aborted.\n(%0)", "Error code").arg(std::forward<Args>(args)...);
case localized_string_id::CELL_MSG_DIALOG_ERROR_8001000D: return tr("Invalid memory access.\n(%0)", "Error code").arg(std::forward<Args>(args)...);
case localized_string_id::CELL_MSG_DIALOG_ERROR_8001000F: return tr("State of the target thread is invalid.\n(%0)", "Error code").arg(std::forward<Args>(args)...);
case localized_string_id::CELL_MSG_DIALOG_ERROR_80010010: return tr("Alignment is invalid.\n(%0)", "Error code").arg(std::forward<Args>(args)...);
case localized_string_id::CELL_MSG_DIALOG_ERROR_80010011: return tr("Shortage of the kernel resources.\n(%0)", "Error code").arg(std::forward<Args>(args)...);
case localized_string_id::CELL_MSG_DIALOG_ERROR_80010012: return tr("The file is a directory.\n(%0)", "Error code").arg(std::forward<Args>(args)...);
case localized_string_id::CELL_MSG_DIALOG_ERROR_80010013: return tr("Operation cancelled.\n(%0)", "Error code").arg(std::forward<Args>(args)...);
case localized_string_id::CELL_MSG_DIALOG_ERROR_80010014: return tr("Entry already exists.\n(%0)", "Error code").arg(std::forward<Args>(args)...);
case localized_string_id::CELL_MSG_DIALOG_ERROR_80010015: return tr("Port is already connected.\n(%0)", "Error code").arg(std::forward<Args>(args)...);
case localized_string_id::CELL_MSG_DIALOG_ERROR_80010016: return tr("Port is not connected.\n(%0)", "Error code").arg(std::forward<Args>(args)...);
case localized_string_id::CELL_MSG_DIALOG_ERROR_80010017: return tr("Failure in authorizing SELF. Program authentication fail.\n(%0)", "Error code").arg(std::forward<Args>(args)...);
case localized_string_id::CELL_MSG_DIALOG_ERROR_80010018: return tr("The file is not MSELF.\n(%0)", "Error code").arg(std::forward<Args>(args)...);
case localized_string_id::CELL_MSG_DIALOG_ERROR_80010019: return tr("System version error.\n(%0)", "Error code").arg(std::forward<Args>(args)...);
case localized_string_id::CELL_MSG_DIALOG_ERROR_8001001A: return tr("Fatal system error occurred while authorizing SELF. SELF auth failure.\n(%0)", "Error code").arg(std::forward<Args>(args)...);
case localized_string_id::CELL_MSG_DIALOG_ERROR_8001001B: return tr("Math domain violation.\n(%0)", "Error code").arg(std::forward<Args>(args)...);
case localized_string_id::CELL_MSG_DIALOG_ERROR_8001001C: return tr("Math range violation.\n(%0)", "Error code").arg(std::forward<Args>(args)...);
case localized_string_id::CELL_MSG_DIALOG_ERROR_8001001D: return tr("Illegal multi-byte sequence in input.\n(%0)", "Error code").arg(std::forward<Args>(args)...);
case localized_string_id::CELL_MSG_DIALOG_ERROR_8001001E: return tr("File position error.\n(%0)", "Error code").arg(std::forward<Args>(args)...);
case localized_string_id::CELL_MSG_DIALOG_ERROR_8001001F: return tr("Syscall was interrupted.\n(%0)", "Error code").arg(std::forward<Args>(args)...);
case localized_string_id::CELL_MSG_DIALOG_ERROR_80010020: return tr("File too large.\n(%0)", "Error code").arg(std::forward<Args>(args)...);
case localized_string_id::CELL_MSG_DIALOG_ERROR_80010021: return tr("Too many links.\n(%0)", "Error code").arg(std::forward<Args>(args)...);
case localized_string_id::CELL_MSG_DIALOG_ERROR_80010022: return tr("File table overflow.\n(%0)", "Error code").arg(std::forward<Args>(args)...);
case localized_string_id::CELL_MSG_DIALOG_ERROR_80010023: return tr("No space left on device.\n(%0)", "Error code").arg(std::forward<Args>(args)...);
case localized_string_id::CELL_MSG_DIALOG_ERROR_80010024: return tr("Not a TTY.\n(%0)", "Error code").arg(std::forward<Args>(args)...);
case localized_string_id::CELL_MSG_DIALOG_ERROR_80010025: return tr("Broken pipe.\n(%0)", "Error code").arg(std::forward<Args>(args)...);
case localized_string_id::CELL_MSG_DIALOG_ERROR_80010026: return tr("Read-only filesystem.\n(%0)", "Error code").arg(std::forward<Args>(args)...);
case localized_string_id::CELL_MSG_DIALOG_ERROR_80010027: return tr("Illegal seek.\n(%0)", "Error code").arg(std::forward<Args>(args)...);
case localized_string_id::CELL_MSG_DIALOG_ERROR_80010028: return tr("Arg list too long.\n(%0)", "Error code").arg(std::forward<Args>(args)...);
case localized_string_id::CELL_MSG_DIALOG_ERROR_80010029: return tr("Access violation.\n(%0)", "Error code").arg(std::forward<Args>(args)...);
case localized_string_id::CELL_MSG_DIALOG_ERROR_8001002A: return tr("Invalid file descriptor.\n(%0)", "Error code").arg(std::forward<Args>(args)...);
case localized_string_id::CELL_MSG_DIALOG_ERROR_8001002B: return tr("Filesystem mounting failed.\n(%0)", "Error code").arg(std::forward<Args>(args)...);
case localized_string_id::CELL_MSG_DIALOG_ERROR_8001002C: return tr("Too many files open.\n(%0)", "Error code").arg(std::forward<Args>(args)...);
case localized_string_id::CELL_MSG_DIALOG_ERROR_8001002D: return tr("No device.\n(%0)", "Error code").arg(std::forward<Args>(args)...);
case localized_string_id::CELL_MSG_DIALOG_ERROR_8001002E: return tr("Not a directory.\n(%0)", "Error code").arg(std::forward<Args>(args)...);
case localized_string_id::CELL_MSG_DIALOG_ERROR_8001002F: return tr("No such device or IO.\n(%0)", "Error code").arg(std::forward<Args>(args)...);
case localized_string_id::CELL_MSG_DIALOG_ERROR_80010030: return tr("Cross-device link error.\n(%0)", "Error code").arg(std::forward<Args>(args)...);
case localized_string_id::CELL_MSG_DIALOG_ERROR_80010031: return tr("Bad Message.\n(%0)", "Error code").arg(std::forward<Args>(args)...);
case localized_string_id::CELL_MSG_DIALOG_ERROR_80010032: return tr("In progress.\n(%0)", "Error code").arg(std::forward<Args>(args)...);
case localized_string_id::CELL_MSG_DIALOG_ERROR_80010033: return tr("Message size error.\n(%0)", "Error code").arg(std::forward<Args>(args)...);
case localized_string_id::CELL_MSG_DIALOG_ERROR_80010034: return tr("Name too long.\n(%0)", "Error code").arg(std::forward<Args>(args)...);
case localized_string_id::CELL_MSG_DIALOG_ERROR_80010035: return tr("No lock.\n(%0)", "Error code").arg(std::forward<Args>(args)...);
case localized_string_id::CELL_MSG_DIALOG_ERROR_80010036: return tr("Not empty.\n(%0)", "Error code").arg(std::forward<Args>(args)...);
case localized_string_id::CELL_MSG_DIALOG_ERROR_80010037: return tr("Not supported.\n(%0)", "Error code").arg(std::forward<Args>(args)...);
case localized_string_id::CELL_MSG_DIALOG_ERROR_80010038: return tr("File-system specific error.\n(%0)", "Error code").arg(std::forward<Args>(args)...);
case localized_string_id::CELL_MSG_DIALOG_ERROR_80010039: return tr("Overflow occurred.\n(%0)", "Error code").arg(std::forward<Args>(args)...);
case localized_string_id::CELL_MSG_DIALOG_ERROR_8001003A: return tr("Filesystem not mounted.\n(%0)", "Error code").arg(std::forward<Args>(args)...);
case localized_string_id::CELL_MSG_DIALOG_ERROR_8001003B: return tr("Not SData.\n(%0)", "Error code").arg(std::forward<Args>(args)...);
case localized_string_id::CELL_MSG_DIALOG_ERROR_8001003C: return tr("Incorrect version in sys_load_param.\n(%0)", "Error code").arg(std::forward<Args>(args)...);
case localized_string_id::CELL_MSG_DIALOG_ERROR_8001003D: return tr("Pointer is null.\n(%0)", "Error code").arg(std::forward<Args>(args)...);
case localized_string_id::CELL_MSG_DIALOG_ERROR_8001003E: return tr("Pointer is null.\n(%0)", "Error code").arg(std::forward<Args>(args)...);
case localized_string_id::CELL_MSG_DIALOG_ERROR_DEFAULT: return tr("An error has occurred.\n(%0)", "Error code").arg(std::forward<Args>(args)...);
case localized_string_id::CELL_OSK_DIALOG_TITLE: return tr("On Screen Keyboard", "OSK Dialog");
case localized_string_id::CELL_OSK_DIALOG_BUSY: return tr("The Home Menu can't be opened while the On Screen Keyboard is busy!", "OSK Dialog");
case localized_string_id::CELL_SAVEDATA_CB_BROKEN: return tr("Error - Save data corrupted", "Savedata Error");
case localized_string_id::CELL_SAVEDATA_CB_FAILURE: return tr("Error - Failed to save or load", "Savedata Error");
case localized_string_id::CELL_SAVEDATA_CB_NO_DATA: return tr("Error - Save data cannot be found", "Savedata Error");
case localized_string_id::CELL_SAVEDATA_CB_NO_SPACE: return tr("Error - Insufficient free space\n\nSpace needed: %0 KB", "Savedata Error").arg(std::forward<Args>(args)...);
case localized_string_id::CELL_SAVEDATA_NO_DATA: return tr("There is no saved data.", "Savedata entry info");
case localized_string_id::CELL_SAVEDATA_NEW_SAVED_DATA_TITLE: return tr("New Saved Data", "Savedata Dialog");
case localized_string_id::CELL_SAVEDATA_NEW_SAVED_DATA_SUB_TITLE: return tr("Select to create a new entry", "Savedata Dialog");
case localized_string_id::CELL_SAVEDATA_SAVE_CONFIRMATION: return tr("Do you want to save this data?", "Savedata Dialog");
case localized_string_id::CELL_SAVEDATA_DELETE_CONFIRMATION: return tr("Do you really want to delete this data?\n\n%0", "Savedata entry info").arg(std::forward<Args>(args)...);
case localized_string_id::CELL_SAVEDATA_DELETE_SUCCESS: return tr("Successfully removed data!\n\n%0", "Savedata entry info").arg(std::forward<Args>(args)...);
case localized_string_id::CELL_SAVEDATA_DELETE: return tr("Delete this data?\n\n%0", "Savedata entry info").arg(std::forward<Args>(args)...);
case localized_string_id::CELL_SAVEDATA_LOAD: return tr("Load this data?\n\n%0", "Savedata entry info").arg(std::forward<Args>(args)...);
case localized_string_id::CELL_SAVEDATA_OVERWRITE: return tr("Do you want to overwrite the saved data?\n\n%0", "Savedata entry info").arg(std::forward<Args>(args)...);
case localized_string_id::CELL_SAVEDATA_AUTOSAVE: return tr("Saving");
case localized_string_id::CELL_SAVEDATA_AUTOLOAD: return tr("Loading");
case localized_string_id::CELL_CROSS_CONTROLLER_MSG: return tr("Start [%0] on the PS Vita system.\nIf you have not installed [%0], go to [Remote Play] on the PS Vita system and start [Cross-Controller] from the LiveAreaâ„¢ screen.", "Cross-Controller message").arg(std::forward<Args>(args)...);
case localized_string_id::CELL_CROSS_CONTROLLER_FW_MSG: return tr("If your system software version on the PS Vita system is earlier than 1.80, you must update the system software to the latest version.", "Cross-Controller firmware message");
case localized_string_id::CELL_NP_RECVMESSAGE_DIALOG_TITLE: return tr("Select Message", "RECVMESSAGE_DIALOG");
case localized_string_id::CELL_NP_RECVMESSAGE_DIALOG_TITLE_INVITE: return tr("Select Invite", "RECVMESSAGE_DIALOG");
case localized_string_id::CELL_NP_RECVMESSAGE_DIALOG_TITLE_ADD_FRIEND: return tr("Add Friend", "RECVMESSAGE_DIALOG");
case localized_string_id::CELL_NP_RECVMESSAGE_DIALOG_FROM: return tr("From:", "RECVMESSAGE_DIALOG");
case localized_string_id::CELL_NP_RECVMESSAGE_DIALOG_SUBJECT: return tr("Subject:", "RECVMESSAGE_DIALOG");
case localized_string_id::CELL_NP_SENDMESSAGE_DIALOG_TITLE: return tr("Select Message To Send", "SENDMESSAGE_DIALOG");
case localized_string_id::CELL_NP_SENDMESSAGE_DIALOG_TITLE_INVITE: return tr("Send Invite", "SENDMESSAGE_DIALOG");
case localized_string_id::CELL_NP_SENDMESSAGE_DIALOG_TITLE_ADD_FRIEND: return tr("Add Friend", "SENDMESSAGE_DIALOG");
case localized_string_id::CELL_NP_SENDMESSAGE_DIALOG_CONFIRMATION: return tr("Send message to %0 ?\n\nSubject:", "SENDMESSAGE_DIALOG").arg(std::forward<Args>(args)...);
case localized_string_id::CELL_NP_SENDMESSAGE_DIALOG_CONFIRMATION_INVITE: return tr("Send invite to %0 ?\n\nSubject:", "SENDMESSAGE_DIALOG").arg(std::forward<Args>(args)...);
case localized_string_id::CELL_NP_SENDMESSAGE_DIALOG_CONFIRMATION_ADD_FRIEND: return tr("Send friend request to %0 ?\n\nSubject:", "SENDMESSAGE_DIALOG").arg(std::forward<Args>(args)...);
case localized_string_id::RECORDING_ABORTED: return tr("Recording aborted!");
case localized_string_id::RPCN_NO_ERROR: return tr("RPCN: No Error");
case localized_string_id::RPCN_ERROR_INVALID_INPUT: return tr("RPCN: Invalid Input (Wrong Host/Port)");
case localized_string_id::RPCN_ERROR_WOLFSSL: return tr("RPCN Connection Error: WolfSSL Error");
case localized_string_id::RPCN_ERROR_RESOLVE: return tr("RPCN Connection Error: Resolve Error");
case localized_string_id::RPCN_ERROR_CONNECT: return tr("RPCN Connection Error");
case localized_string_id::RPCN_ERROR_LOGIN_ERROR: return tr("RPCN Login Error: Identification Error");
case localized_string_id::RPCN_ERROR_ALREADY_LOGGED: return tr("RPCN Login Error: User Already Logged In");
case localized_string_id::RPCN_ERROR_INVALID_LOGIN: return tr("RPCN Login Error: Invalid Username");
case localized_string_id::RPCN_ERROR_INVALID_PASSWORD: return tr("RPCN Login Error: Invalid Password");
case localized_string_id::RPCN_ERROR_INVALID_TOKEN: return tr("RPCN Login Error: Invalid Token");
case localized_string_id::RPCN_ERROR_INVALID_PROTOCOL_VERSION: return tr("RPCN Misc Error: Protocol Version Error (outdated RPCS3?)");
case localized_string_id::RPCN_ERROR_UNKNOWN: return tr("RPCN: Unknown Error");
case localized_string_id::RPCN_SUCCESS_LOGGED_ON: return tr("Successfully logged on RPCN!");
case localized_string_id::RPCN_FRIEND_REQUEST_RECEIVED: return tr("RPCN: Received friend request: %0", "RCPN Friends").arg(std::forward<Args>(args)...);
case localized_string_id::RPCN_FRIEND_ADDED: return tr("RPCN: Friend added: %0", "RCPN Friends").arg(std::forward<Args>(args)...);
case localized_string_id::RPCN_FRIEND_LOST: return tr("RPCN: Friend removed: %0", "RCPN Friends").arg(std::forward<Args>(args)...);
case localized_string_id::RPCN_FRIEND_LOGGED_IN: return tr("RPCN: %0 logged in", "RCPN Friends").arg(std::forward<Args>(args)...);
case localized_string_id::RPCN_FRIEND_LOGGED_OUT: return tr("RPCN: %0 logged out", "RCPN Friends").arg(std::forward<Args>(args)...);
case localized_string_id::HOME_MENU_TITLE: return tr("Home Menu");
case localized_string_id::HOME_MENU_EXIT_GAME: return tr("Exit Game");
case localized_string_id::HOME_MENU_RESUME: return tr("Resume Game");
case localized_string_id::HOME_MENU_FRIENDS: return tr("Friends");
case localized_string_id::HOME_MENU_FRIENDS_REQUESTS: return tr("Pending Friend Requests");
case localized_string_id::HOME_MENU_FRIENDS_BLOCKED: return tr("Blocked Users");
case localized_string_id::HOME_MENU_FRIENDS_STATUS_ONLINE: return tr("Online");
case localized_string_id::HOME_MENU_FRIENDS_STATUS_OFFLINE: return tr("Offline");
case localized_string_id::HOME_MENU_FRIENDS_STATUS_BLOCKED: return tr("Blocked");
case localized_string_id::HOME_MENU_FRIENDS_REQUEST_SENT: return tr("You sent a friend request");
case localized_string_id::HOME_MENU_FRIENDS_REQUEST_RECEIVED: return tr("Sent you a friend request");
case localized_string_id::HOME_MENU_FRIENDS_BLOCK_USER_MSG: return tr("Block this user?\n\n%0").arg(std::forward<Args>(args)...);
case localized_string_id::HOME_MENU_FRIENDS_UNBLOCK_USER_MSG: return tr("Unblock this user?\n\n%0").arg(std::forward<Args>(args)...);
case localized_string_id::HOME_MENU_FRIENDS_REMOVE_USER_MSG: return tr("Remove this user?\n\n%0").arg(std::forward<Args>(args)...);
case localized_string_id::HOME_MENU_FRIENDS_ACCEPT_REQUEST_MSG: return tr("Accept Request?\n\n%0").arg(std::forward<Args>(args)...);
case localized_string_id::HOME_MENU_FRIENDS_CANCEL_REQUEST_MSG: return tr("Cancel Request?\n\n%0").arg(std::forward<Args>(args)...);
case localized_string_id::HOME_MENU_FRIENDS_REJECT_REQUEST_MSG: return tr("Reject Request?\n\n%0").arg(std::forward<Args>(args)...);
case localized_string_id::HOME_MENU_FRIENDS_REJECT_REQUEST: return tr("Reject Request");
case localized_string_id::HOME_MENU_FRIENDS_NEXT_LIST: return tr("Next list");
case localized_string_id::HOME_MENU_RESTART: return tr("Restart Game");
case localized_string_id::HOME_MENU_SETTINGS: return tr("Settings");
case localized_string_id::HOME_MENU_SETTINGS_SAVE: return tr("Save custom configuration?");
case localized_string_id::HOME_MENU_SETTINGS_SAVE_BUTTON: return tr("Save");
case localized_string_id::HOME_MENU_SETTINGS_DISCARD: return tr("Discard the current settings' changes?");
case localized_string_id::HOME_MENU_SETTINGS_DISCARD_BUTTON: return tr("Discard");
case localized_string_id::HOME_MENU_SETTINGS_AUDIO: return tr("Audio");
case localized_string_id::HOME_MENU_SETTINGS_AUDIO_MASTER_VOLUME: return tr("Master Volume", "Audio");
case localized_string_id::HOME_MENU_SETTINGS_AUDIO_BACKEND: return tr("Audio Backend", "Audio");
case localized_string_id::HOME_MENU_SETTINGS_AUDIO_BUFFERING: return tr("Enable Buffering", "Audio");
case localized_string_id::HOME_MENU_SETTINGS_AUDIO_BUFFER_DURATION: return tr("Desired Audio Buffer Duration", "Audio");
case localized_string_id::HOME_MENU_SETTINGS_AUDIO_TIME_STRETCHING: return tr("Enable Time Stretching", "Audio");
case localized_string_id::HOME_MENU_SETTINGS_AUDIO_TIME_STRETCHING_THRESHOLD: return tr("Time Stretching Threshold", "Audio");
case localized_string_id::HOME_MENU_SETTINGS_VIDEO: return tr("Video");
case localized_string_id::HOME_MENU_SETTINGS_VIDEO_FRAME_LIMIT: return tr("Frame Limit", "Video");
case localized_string_id::HOME_MENU_SETTINGS_VIDEO_ANISOTROPIC_OVERRIDE: return tr("Anisotropic Filter Override", "Video");
case localized_string_id::HOME_MENU_SETTINGS_VIDEO_OUTPUT_SCALING: return tr("Output Scaling", "Video");
case localized_string_id::HOME_MENU_SETTINGS_VIDEO_RCAS_SHARPENING: return tr("FidelityFX CAS Sharpening Intensity", "Video");
case localized_string_id::HOME_MENU_SETTINGS_VIDEO_STRETCH_TO_DISPLAY: return tr("Stretch To Display Area", "Video");
case localized_string_id::HOME_MENU_SETTINGS_INPUT: return tr("Input");
case localized_string_id::HOME_MENU_SETTINGS_INPUT_BACKGROUND_INPUT: return tr("Background Input Enabled", "Input");
case localized_string_id::HOME_MENU_SETTINGS_INPUT_KEEP_PADS_CONNECTED: return tr("Keep Pads Connected", "Input");
case localized_string_id::HOME_MENU_SETTINGS_INPUT_SHOW_PS_MOVE_CURSOR: return tr("Show PS Move Cursor", "Input");
case localized_string_id::HOME_MENU_SETTINGS_INPUT_CAMERA_FLIP: return tr("Camera Flip", "Input");
case localized_string_id::HOME_MENU_SETTINGS_INPUT_PAD_MODE: return tr("Pad Handler Mode", "Input");
case localized_string_id::HOME_MENU_SETTINGS_INPUT_PAD_SLEEP: return tr("Pad Handler Sleep", "Input");
case localized_string_id::HOME_MENU_SETTINGS_ADVANCED: return tr("Advanced");
case localized_string_id::HOME_MENU_SETTINGS_ADVANCED_PREFERRED_SPU_THREADS: return tr("Preferred SPU Threads", "Advanced");
case localized_string_id::HOME_MENU_SETTINGS_ADVANCED_MAX_CPU_PREEMPTIONS: return tr("Max Power Saving CPU-Preemptions", "Advanced");
case localized_string_id::HOME_MENU_SETTINGS_ADVANCED_ACCURATE_RSX_RESERVATION_ACCESS: return tr("Accurate RSX reservation access", "Advanced");
case localized_string_id::HOME_MENU_SETTINGS_ADVANCED_SLEEP_TIMERS_ACCURACY: return tr("Sleep Timers Accuracy", "Advanced");
case localized_string_id::HOME_MENU_SETTINGS_ADVANCED_MAX_SPURS_THREADS: return tr("Max SPURS Threads", "Advanced");
case localized_string_id::HOME_MENU_SETTINGS_ADVANCED_DRIVER_WAKE_UP_DELAY: return tr("Driver Wake-Up Delay", "Advanced");
case localized_string_id::HOME_MENU_SETTINGS_ADVANCED_VBLANK_FREQUENCY: return tr("VBlank Frequency", "Advanced");
case localized_string_id::HOME_MENU_SETTINGS_ADVANCED_VBLANK_NTSC: return tr("VBlank NTSC Fixup", "Advanced");
case localized_string_id::HOME_MENU_SETTINGS_OVERLAYS: return tr("Overlays");
case localized_string_id::HOME_MENU_SETTINGS_OVERLAYS_SHOW_TROPHY_POPUPS: return tr("Show Trophy Popups", "Overlays");
case localized_string_id::HOME_MENU_SETTINGS_OVERLAYS_SHOW_RPCN_POPUPS: return tr("Show RPCN Popups", "Overlays");
case localized_string_id::HOME_MENU_SETTINGS_OVERLAYS_SHOW_SHADER_COMPILATION_HINT: return tr("Show Shader Compilation Hint", "Overlays");
case localized_string_id::HOME_MENU_SETTINGS_OVERLAYS_SHOW_PPU_COMPILATION_HINT: return tr("Show PPU Compilation Hint", "Overlays");
case localized_string_id::HOME_MENU_SETTINGS_OVERLAYS_SHOW_AUTO_SAVE_LOAD_HINT: return tr("Show Autosave/Autoload Hint", "Overlays");
case localized_string_id::HOME_MENU_SETTINGS_OVERLAYS_SHOW_PRESSURE_INTENSITY_TOGGLE_HINT: return tr("Show Pressure Intensity Toggle Hint", "Overlays");
case localized_string_id::HOME_MENU_SETTINGS_OVERLAYS_SHOW_ANALOG_LIMITER_TOGGLE_HINT: return tr( "Show Analog Limiter Toggle Hint", "Overlays");
case localized_string_id::HOME_MENU_SETTINGS_OVERLAYS_SHOW_MOUSE_AND_KB_TOGGLE_HINT: return tr("Show Mouse And Keyboard Toggle Hint", "Overlays");
case localized_string_id::HOME_MENU_SETTINGS_PERFORMANCE_OVERLAY: return tr("Performance Overlay");
case localized_string_id::HOME_MENU_SETTINGS_PERFORMANCE_OVERLAY_ENABLE: return tr("Enable Performance Overlay", "Performance Overlay");
case localized_string_id::HOME_MENU_SETTINGS_PERFORMANCE_OVERLAY_ENABLE_FRAMERATE_GRAPH: return tr("Enable Framerate Graph", "Performance Overlay");
case localized_string_id::HOME_MENU_SETTINGS_PERFORMANCE_OVERLAY_ENABLE_FRAMETIME_GRAPH: return tr("Enable Frametime Graph", "Performance Overlay");
case localized_string_id::HOME_MENU_SETTINGS_PERFORMANCE_OVERLAY_DETAIL_LEVEL: return tr("Detail level", "Performance Overlay");
case localized_string_id::HOME_MENU_SETTINGS_PERFORMANCE_OVERLAY_FRAMERATE_DETAIL_LEVEL: return tr("Framerate Graph Detail Level", "Performance Overlay");
case localized_string_id::HOME_MENU_SETTINGS_PERFORMANCE_OVERLAY_FRAMETIME_DETAIL_LEVEL: return tr("Frametime Graph Detail Level", "Performance Overlay");
case localized_string_id::HOME_MENU_SETTINGS_PERFORMANCE_OVERLAY_FRAMERATE_DATAPOINT_COUNT: return tr("Framerate Datapoints", "Performance Overlay");
case localized_string_id::HOME_MENU_SETTINGS_PERFORMANCE_OVERLAY_FRAMETIME_DATAPOINT_COUNT: return tr("Frametime Datapoints", "Performance Overlay");
case localized_string_id::HOME_MENU_SETTINGS_PERFORMANCE_OVERLAY_UPDATE_INTERVAL: return tr("Metrics Update Interval", "Performance Overlay");
case localized_string_id::HOME_MENU_SETTINGS_PERFORMANCE_OVERLAY_POSITION: return tr("Position", "Performance Overlay");
case localized_string_id::HOME_MENU_SETTINGS_PERFORMANCE_OVERLAY_CENTER_X: return tr("Center Horizontally", "Performance Overlay");
case localized_string_id::HOME_MENU_SETTINGS_PERFORMANCE_OVERLAY_CENTER_Y: return tr("Center Vertically", "Performance Overlay");
case localized_string_id::HOME_MENU_SETTINGS_PERFORMANCE_OVERLAY_MARGIN_X: return tr("Horizontal Margin", "Performance Overlay");
case localized_string_id::HOME_MENU_SETTINGS_PERFORMANCE_OVERLAY_MARGIN_Y: return tr("Vertical Margin", "Performance Overlay");
case localized_string_id::HOME_MENU_SETTINGS_PERFORMANCE_OVERLAY_FONT_SIZE: return tr("Font Size", "Performance Overlay");
case localized_string_id::HOME_MENU_SETTINGS_PERFORMANCE_OVERLAY_OPACITY: return tr("Opacity", "Performance Overlay");
case localized_string_id::HOME_MENU_SETTINGS_DEBUG: return tr("Debug");
case localized_string_id::HOME_MENU_SETTINGS_DEBUG_OVERLAY: return tr("Debug Overlay", "Debug");
case localized_string_id::HOME_MENU_SETTINGS_DEBUG_INPUT_OVERLAY: return tr("Input Debug Overlay", "Debug");
case localized_string_id::HOME_MENU_SETTINGS_DEBUG_DISABLE_VIDEO_OUTPUT: return tr("Disable Video Output", "Debug");
case localized_string_id::HOME_MENU_SETTINGS_DEBUG_TEXTURE_LOD_BIAS: return tr("Texture LOD Bias Addend", "Debug");
case localized_string_id::HOME_MENU_SCREENSHOT: return tr("Take Screenshot");
case localized_string_id::HOME_MENU_SAVESTATE: return tr("Save Emulation State");
case localized_string_id::HOME_MENU_SAVESTATE_AND_EXIT: return tr("Save Emulation State And Exit");
case localized_string_id::HOME_MENU_RELOAD_SAVESTATE: return tr("Reload Last Emulation State");
case localized_string_id::HOME_MENU_RECORDING: return tr("Start/Stop Recording");
case localized_string_id::PROGRESS_DIALOG_PROGRESS: return tr("Progress:");
case localized_string_id::PROGRESS_DIALOG_PROGRESS_ANALYZING: return tr("Progress: analyzing...");
case localized_string_id::PROGRESS_DIALOG_REMAINING: return tr("remaining");
case localized_string_id::PROGRESS_DIALOG_DONE: return tr("done");
case localized_string_id::PROGRESS_DIALOG_FILE: return tr("file");
case localized_string_id::PROGRESS_DIALOG_MODULE: return tr("module");
case localized_string_id::PROGRESS_DIALOG_OF: return tr("of");
case localized_string_id::PROGRESS_DIALOG_PLEASE_WAIT: return tr("Please wait");
case localized_string_id::PROGRESS_DIALOG_STOPPING_PLEASE_WAIT: return tr("Stopping. Please wait...");
case localized_string_id::PROGRESS_DIALOG_SCANNING_PPU_EXECUTABLE: return tr("Scanning PPU Executable...");
case localized_string_id::PROGRESS_DIALOG_ANALYZING_PPU_EXECUTABLE: return tr("Analyzing PPU Executable...");
case localized_string_id::PROGRESS_DIALOG_SCANNING_PPU_MODULES: return tr("Scanning PPU Modules...");
case localized_string_id::PROGRESS_DIALOG_LOADING_PPU_MODULES: return tr("Loading PPU Modules...");
case localized_string_id::PROGRESS_DIALOG_COMPILING_PPU_MODULES: return tr("Compiling PPU Modules...");
case localized_string_id::PROGRESS_DIALOG_LINKING_PPU_MODULES: return tr("Linking PPU Modules...");
case localized_string_id::PROGRESS_DIALOG_APPLYING_PPU_CODE: return tr("Applying PPU Code...");
case localized_string_id::PROGRESS_DIALOG_BUILDING_SPU_CACHE: return tr("Building SPU Cache...");
case localized_string_id::EMULATION_PAUSED_RESUME_WITH_START: return tr("Press and hold the START button to resume");
case localized_string_id::EMULATION_RESUMING: return tr("Resuming...!");
case localized_string_id::EMULATION_FROZEN: return tr("The PS3 application has likely crashed, you can close it.");
case localized_string_id::SAVESTATE_FAILED_DUE_TO_SAVEDATA: return tr("SaveState failed: Game saving is in progress, wait until finished.");
case localized_string_id::SAVESTATE_FAILED_DUE_TO_VDEC: return tr("SaveState failed: VDEC-base video/cutscenes are in order, wait for them to end or enable libvdec.sprx.");
case localized_string_id::SAVESTATE_FAILED_DUE_TO_MISSING_SPU_SETTING: return tr("SaveState failed: Failed to lock SPU state, enabling SPU-Compatible mode may fix it.");
case localized_string_id::SAVESTATE_FAILED_DUE_TO_SPU: return tr("SaveState failed: Failed to lock SPU state, using SPU ASMJIT will fix it.");
case localized_string_id::INVALID: return tr("Invalid");
default: return tr("Unknown");
}
}
};
| 36,082
|
C++
|
.h
| 312
| 112.753205
| 296
| 0.745009
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,687
|
render_creator.h
|
RPCS3_rpcs3/rpcs3/rpcs3qt/render_creator.h
|
#pragma once
#include "emu_settings_type.h"
#include <QObject>
#include <QString>
#include <QStringList>
class render_creator : public QObject
{
Q_OBJECT
public:
render_creator(QObject* parent);
void update_names(const QStringList& names);
struct render_info
{
QString name;
QString old_adapter;
QStringList adapters;
emu_settings_type type = emu_settings_type::VulkanAdapter;
bool supported = true;
bool has_adapters = true;
bool has_msaa = false;
render_info()
: has_adapters(false) {}
render_info(QStringList adapters, bool supported, emu_settings_type type, bool has_msaa)
: adapters(std::move(adapters))
, type(type)
, supported(supported)
, has_msaa(has_msaa) {}
};
bool abort_requested = false;
bool supports_vulkan = false;
QStringList vulkan_adapters;
render_info Vulkan;
render_info OpenGL;
render_info NullRender;
std::vector<render_info*> renderers;
};
| 920
|
C++
|
.h
| 36
| 23.027778
| 90
| 0.753143
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,688
|
save_data_dialog.h
|
RPCS3_rpcs3/rpcs3/rpcs3qt/save_data_dialog.h
|
#pragma once
#include "util/types.hpp"
#include "Emu/Memory/vm.h"
#include "Emu/Cell/Modules/cellSaveData.h"
class save_data_dialog : public SaveDialogBase
{
public:
s32 ShowSaveDataList(std::vector<SaveDataEntry>& save_entries, s32 focused, u32 op, vm::ptr<CellSaveDataListSet> listSet, bool enable_overlay) override;
};
| 325
|
C++
|
.h
| 9
| 34.777778
| 153
| 0.796178
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,689
|
gl_gs_frame.h
|
RPCS3_rpcs3/rpcs3/rpcs3qt/gl_gs_frame.h
|
#pragma once
#include "gs_frame.h"
#include <memory>
struct GLContext
{
QSurface *surface = nullptr;
QOpenGLContext *handle = nullptr;
bool owner = false;
};
class gl_gs_frame : public gs_frame
{
private:
QSurfaceFormat m_format;
GLContext *m_primary_context = nullptr;
public:
explicit gl_gs_frame(QScreen* screen, const QRect& geometry, const QIcon& appIcon, std::shared_ptr<gui_settings> gui_settings, bool force_fullscreen);
draw_context_t make_context() override;
void set_current(draw_context_t ctx) override;
void delete_context(draw_context_t ctx) override;
void flip(draw_context_t context, bool skip_frame = false) override;
};
| 654
|
C++
|
.h
| 21
| 29.380952
| 151
| 0.776715
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,690
|
sendmessage_dialog_frame.h
|
RPCS3_rpcs3/rpcs3/rpcs3qt/sendmessage_dialog_frame.h
|
#pragma once
#include <QObject>
#include <QListWidget>
#include "util/types.hpp"
#include "custom_dialog.h"
#include "Emu/NP/rpcn_client.h"
class sendmessage_dialog_frame : public QObject, public SendMessageDialogBase
{
Q_OBJECT
public:
sendmessage_dialog_frame() = default;
~sendmessage_dialog_frame();
error_code Exec(message_data& msg_data, std::set<std::string>& npids) override;
void callback_handler(u16 ntype, const std::string& username, bool status) override;
private:
void add_friend(QListWidget* list, const QString& name);
void remove_friend(QListWidget* list, const QString& name);
private:
custom_dialog* m_dialog = nullptr;
QListWidget* m_lst_friends = nullptr;
Q_SIGNALS:
void signal_add_friend(QString name);
void signal_remove_friend(QString name);
private Q_SLOTS:
void slot_add_friend(QString name);
void slot_remove_friend(QString name);
};
| 883
|
C++
|
.h
| 27
| 30.925926
| 85
| 0.783019
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,691
|
game_compatibility.h
|
RPCS3_rpcs3/rpcs3/rpcs3qt/game_compatibility.h
|
#pragma once
#include <memory>
#include <QJsonObject>
class downloader;
class gui_settings;
namespace compat
{
/** Represents the "title" json object */
struct pkg_title
{
std::string type; // TITLE or TITLE_08 etc. (system languages)
std::string title; // The Last of Arse
};
/** Represents the "changelog" json object */
struct pkg_changelog
{
std::string type; // paramhip or paramhip_08 etc. (system languages)
std::string content; // "This system software update improves system performance."
};
/** Represents the "package" json object */
struct pkg_package
{
std::string version; // 01.04
int size = 0;
std::string sha1sum; // a5c83b88394ea3ae99974caedd38690981a80f3e
std::string ps3_system_ver; // 04.4000
std::string drm_type; // local or mbind etc.
std::vector<pkg_changelog> changelogs;
std::vector<pkg_title> titles;
std::string get_changelog(const std::string& type) const
{
if (const auto it = std::find_if(changelogs.cbegin(), changelogs.cend(), [type](const pkg_changelog& cl) { return cl.type == type; });
it != changelogs.cend())
{
return it->content;
}
if (const auto it = std::find_if(changelogs.cbegin(), changelogs.cend(), [](const pkg_changelog& cl) { return cl.type == "paramhip"; });
it != changelogs.cend())
{
return it->content;
}
return "";
}
std::string get_title(const std::string& type) const
{
if (const auto it = std::find_if(titles.cbegin(), titles.cend(), [type](const pkg_title& t) { return t.type == type; });
it != titles.cend())
{
return it->title;
}
if (const auto it = std::find_if(titles.cbegin(), titles.cend(), [](const pkg_title& t) { return t.type == "TITLE"; });
it != titles.end())
{
return it->title;
}
return "";
}
};
/** Represents the "patchset" json object */
struct pkg_patchset
{
std::string tag_id; // BLES01269_T7
bool popup = false;
bool signoff = false;
int popup_delay = 0;
std::string min_system_ver; // 03.60
std::vector<pkg_package> packages;
};
/** Represents the json object that contains an app's information and some additional info that is used in the GUI */
struct status
{
int index = 0;
QString date;
QString color;
QString text;
QString tooltip;
QString latest_version;
std::vector<pkg_patchset> patch_sets;
};
// The type of the package. In the future this should signify the proper PKG_CONTENT_TYPE.
enum class package_type
{
update,
dlc,
other
};
/** Concicely represents a specific pkg's localized information for use in the GUI */
struct package_info
{
bool is_valid = true;
QString path; // File path
QString title_id; // TEST12345
QString title; // Localized
QString changelog; // Localized, may be empty
QString version; // May be empty
QString category; // HG, DG, GD etc.
QString local_cat; // Localized category
package_type type = package_type::other; // The type of package (Update, DLC or other)
};
}
class game_compatibility : public QObject
{
Q_OBJECT
private:
const std::map<QString, compat::status> Status_Data =
{
{ "Playable", { 0, "", "#1ebc61", tr("Playable"), tr("Games that can be properly played from start to finish") } },
{ "Ingame", { 1, "", "#f9b32f", tr("Ingame"), tr("Games that either can't be finished, have serious glitches or have insufficient performance") } },
{ "Intro", { 2, "", "#e08a1e", tr("Intro"), tr("Games that display image but don't make it past the menus") } },
{ "Loadable", { 3, "", "#e74c3c", tr("Loadable"), tr("Games that display a black screen with a framerate on the window's title") } },
{ "Nothing", { 4, "", "#455556", tr("Nothing"), tr("Games that don't initialize properly, not loading at all and/or crashing the emulator") } },
{ "NoResult", { 5, "", "", tr("No results found"), tr("There is no entry for this game or application in the compatibility database yet.") } },
{ "NoData", { 6, "", "", tr("Database missing"), tr("Right click here and download the current database.\nMake sure you are connected to the internet.") } },
{ "Download", { 7, "", "", tr("Retrieving..."), tr("Downloading the compatibility database. Please wait...") } }
};
std::shared_ptr<gui_settings> m_gui_settings;
QString m_filepath;
downloader* m_downloader = nullptr;
std::map<std::string, compat::status> m_compat_database;
/** Creates new map from the database */
bool ReadJSON(const QJsonObject& json_data, bool after_download);
public:
/** Handles reads, writes and downloads for the compatibility database */
game_compatibility(std::shared_ptr<gui_settings> settings, QWidget* parent);
/** Reads database. If online set to true: Downloads and writes the database to file */
void RequestCompatibility(bool online = false);
/** Returns the compatibility status for the requested title */
compat::status GetCompatibility(const std::string& title_id);
/** Returns the data for the requested status */
compat::status GetStatusData(const QString& status) const;
/** Returns package information like title, version, changelog etc. */
static compat::package_info GetPkgInfo(const QString& pkg_path, game_compatibility* compat);
Q_SIGNALS:
void DownloadStarted();
void DownloadFinished();
void DownloadCanceled();
void DownloadError(const QString& error);
private Q_SLOTS:
void handle_download_error(const QString& error);
void handle_download_finished(const QByteArray& content);
void handle_download_canceled();
};
| 5,598
|
C++
|
.h
| 142
| 36.640845
| 168
| 0.683726
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,692
|
msg_dialog_frame.h
|
RPCS3_rpcs3/rpcs3/rpcs3qt/msg_dialog_frame.h
|
#pragma once
#include "util/types.hpp"
#include "Emu/Cell/Modules/cellMsgDialog.h"
#include "progress_indicator.h"
#include <QProgressBar>
#include <QLabel>
#include <string>
class custom_dialog;
class msg_dialog_frame : public QObject, public MsgDialogBase
{
Q_OBJECT
private:
custom_dialog* m_dialog = nullptr;
QLabel* m_text = nullptr;
QLabel* m_text1 = nullptr;
QLabel* m_text2 = nullptr;
QProgressBar* m_gauge1 = nullptr;
QProgressBar* m_gauge2 = nullptr;
int m_gauge_max = 0;
std::unique_ptr<progress_indicator> m_progress_indicator;
public:
msg_dialog_frame() = default;
~msg_dialog_frame();
void Create(const std::string& msg, const std::string& title = "") override;
void Close(bool success) override;
void SetMsg(const std::string& msg) override;
void ProgressBarSetMsg(u32 progressBarIndex, const std::string& msg) override;
void ProgressBarReset(u32 progressBarIndex) override;
void ProgressBarInc(u32 progressBarIndex, u32 delta) override;
void ProgressBarSetValue(u32 progressBarIndex, u32 value) override;
void ProgressBarSetLimit(u32 index, u32 limit) override;
};
| 1,108
|
C++
|
.h
| 32
| 32.78125
| 79
| 0.784644
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,693
|
vfs_dialog_usb_input.h
|
RPCS3_rpcs3/rpcs3/rpcs3qt/vfs_dialog_usb_input.h
|
#pragma once
#include "vfs_dialog_path_widget.h"
#include <QDialog>
#include <QLineEdit>
namespace cfg
{
struct device_info;
}
class gui_settings;
class vfs_dialog_usb_input : public QDialog
{
Q_OBJECT
public:
explicit vfs_dialog_usb_input(const QString& name, const cfg::device_info& default_info, cfg::device_info* info, std::shared_ptr<gui_settings> _gui_settings, QWidget* parent = nullptr);
private:
std::shared_ptr<gui_settings> m_gui_settings;
gui_save m_gui_save;
vfs_dialog_path_widget* m_path_widget;
QLineEdit* m_vid_edit = nullptr;
QLineEdit* m_pid_edit = nullptr;
QLineEdit* m_serial_edit = nullptr;
};
| 632
|
C++
|
.h
| 22
| 27
| 186
| 0.766169
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,694
|
kernel_explorer.h
|
RPCS3_rpcs3/rpcs3/rpcs3qt/kernel_explorer.h
|
#pragma once
#include <QDialog>
#include <QString>
#include "util/types.hpp"
class QTreeWidget;
class QTreeWidgetItem;
class kernel_explorer : public QDialog
{
Q_OBJECT
static const usz sys_size = 256;
enum additional_nodes
{
memory_containers = sys_size,
virtual_memory,
sockets,
ppu_threads,
spu_threads,
spu_thread_groups,
rsx_contexts,
file_descriptors,
process_info,
};
public:
explicit kernel_explorer(QWidget* parent);
private:
QTreeWidget* m_tree;
QString m_log_buf;
void log(u32 level = 0, QTreeWidgetItem* node = nullptr);
private Q_SLOTS:
void update();
};
| 606
|
C++
|
.h
| 31
| 17.322581
| 58
| 0.766372
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,695
|
gui_settings.h
|
RPCS3_rpcs3/rpcs3/rpcs3qt/gui_settings.h
|
#pragma once
#include "settings.h"
#include "util/logs.hpp"
#include <QVariant>
#include <QSize>
#include <QColor>
#include <QMessageBox>
#include <QWindow>
namespace gui
{
extern QString stylesheet;
extern bool custom_stylesheet_active;
enum custom_roles
{
game_role = Qt::UserRole + 1337,
};
enum class game_list_columns
{
icon,
name,
serial,
firmware,
version,
category,
path,
move,
resolution,
sound,
parental,
last_play,
playtime,
compat,
dir_size,
count
};
enum class trophy_list_columns
{
icon = 0,
name = 1,
description = 2,
type = 3,
is_unlocked = 4,
id = 5,
platinum_link = 6,
time_unlocked = 7,
count
};
enum class trophy_game_list_columns
{
icon = 0,
name = 1,
progress = 2,
trophies = 3,
count
};
QString get_trophy_game_list_column_name(trophy_game_list_columns col);
QString get_trophy_list_column_name(trophy_list_columns col);
QString get_game_list_column_name(game_list_columns col);
const QSize gl_icon_size_min = QSize(40, 22);
const QSize gl_icon_size_small = QSize(80, 44);
const QSize gl_icon_size_medium = QSize(160, 88);
const QSize gl_icon_size_max = QSize(320, 176);
const int gl_max_slider_pos = 100;
inline int get_Index(const QSize& current)
{
const int size_delta = gl_icon_size_max.width() - gl_icon_size_min.width();
const int current_delta = current.width() - gl_icon_size_min.width();
return gl_max_slider_pos * current_delta / size_delta;
}
inline q_string_pair Recent_Game(const QString& path, const QString& title)
{
return q_string_pair(path, title.simplified()); // simplified() forces single line text
}
const QString Settings = "CurrentSettings";
const QString DefaultStylesheet = "default";
const QString NoStylesheet = "none";
const QString NativeStylesheet = "native";
const QString main_window = "main_window";
const QString game_list = "GameList";
const QString logger = "Logger";
const QString debugger = "Debugger";
const QString rsx = "RSX_Debugger";
const QString meta = "Meta";
const QString fs = "FileSystem";
const QString gs_frame = "GSFrame";
const QString trophy = "Trophy";
const QString patches = "Patches";
const QString localization = "Localization";
const QString pad_settings = "PadSettings";
const QString config = "Config";
const QString log_viewer = "LogViewer";
const QString sc = "Shortcuts";
const QString navigation = "PadNavigation";
const QString update_on = "true";
const QString update_off = "false";
const QString update_auto = "auto";
const QString update_bkg = "background";
const QColor gl_icon_color = QColor(240, 240, 240, 255);
const gui_save rg_freeze = gui_save(main_window, "recentGamesFrozen", false);
const gui_save rg_entries = gui_save(main_window, "recentGamesNames", QVariant::fromValue(q_pair_list()));
const gui_save ib_pkg_success = gui_save(main_window, "infoBoxEnabledInstallPKG", true);
const gui_save ib_pup_success = gui_save(main_window, "infoBoxEnabledInstallPUP", true);
const gui_save ib_show_welcome = gui_save(main_window, "infoBoxEnabledWelcome", true);
const gui_save ib_confirm_exit = gui_save(main_window, "confirmationBoxExitGame", true);
const gui_save ib_confirm_boot = gui_save(main_window, "confirmationBoxBootGame", true);
const gui_save ib_obsolete_cfg = gui_save(main_window, "confirmationObsoleteCfg", true);
const gui_save ib_same_buttons = gui_save(main_window, "confirmationSameButtons", true);
const gui_save ib_restart_hint = gui_save(main_window, "confirmationRestart", true);
const gui_save fd_install_pkg = gui_save(main_window, "lastExplorePathPKG", "");
const gui_save fd_install_pup = gui_save(main_window, "lastExplorePathPUP", "");
const gui_save fd_boot_elf = gui_save(main_window, "lastExplorePathELF", "");
const gui_save fd_boot_game = gui_save(main_window, "lastExplorePathGAME", "");
const gui_save fd_decrypt_sprx = gui_save(main_window, "lastExplorePathSPRX", "");
const gui_save fd_cg_disasm = gui_save(main_window, "lastExplorePathCGD", "");
const gui_save fd_log_viewer = gui_save(main_window, "lastExplorePathLOG", "");
const gui_save fd_ext_mself = gui_save(main_window, "lastExplorePathExMSELF", "");
const gui_save fd_ext_tar = gui_save(main_window, "lastExplorePathExTAR", "");
const gui_save fd_insert_disc = gui_save(main_window, "lastExplorePathDISC", "");
const gui_save fd_cfg_check = gui_save(main_window, "lastExplorePathCfgChk", "");
const gui_save fd_save_elf = gui_save(main_window, "lastExplorePathSaveElf", "");
const gui_save fd_save_log = gui_save(main_window, "lastExplorePathSaveLog", "");
const gui_save mw_debugger = gui_save(main_window, "debuggerVisible", false);
const gui_save mw_logger = gui_save(main_window, "loggerVisible", true);
const gui_save mw_gamelist = gui_save(main_window, "gamelistVisible", true);
const gui_save mw_toolBarVisible = gui_save(main_window, "toolBarVisible", true);
const gui_save mw_titleBarsVisible = gui_save(main_window, "titleBarsVisible", true);
const gui_save mw_geometry = gui_save(main_window, "geometry", QByteArray());
const gui_save mw_windowState = gui_save(main_window, "windowState", QByteArray());
const gui_save mw_mwState = gui_save(main_window, "mwState", QByteArray());
const gui_save cat_hdd_game = gui_save(game_list, "categoryVisibleHDDGame", true);
const gui_save cat_disc_game = gui_save(game_list, "categoryVisibleDiscGame", true);
const gui_save cat_ps1_game = gui_save(game_list, "categoryVisiblePS1Game", true);
const gui_save cat_ps2_game = gui_save(game_list, "categoryVisiblePS2Game", true);
const gui_save cat_psp_game = gui_save(game_list, "categoryVisiblePSPGame", true);
const gui_save cat_home = gui_save(game_list, "categoryVisibleHome", true);
const gui_save cat_audio_video = gui_save(game_list, "categoryVisibleAudioVideo", true);
const gui_save cat_game_data = gui_save(game_list, "categoryVisibleGameData", false);
const gui_save cat_unknown = gui_save(game_list, "categoryVisibleUnknown", true);
const gui_save cat_other = gui_save(game_list, "categoryVisibleOther", true);
const gui_save grid_cat_hdd_game = gui_save(game_list, "gridCategoryVisibleHDDGame", true);
const gui_save grid_cat_disc_game = gui_save(game_list, "gridCategoryVisibleDiscGame", true);
const gui_save grid_cat_ps1_game = gui_save(game_list, "gridCategoryVisiblePS1Game", true);
const gui_save grid_cat_ps2_game = gui_save(game_list, "gridCategoryVisiblePS2Game", true);
const gui_save grid_cat_psp_game = gui_save(game_list, "gridCategoryVisiblePSPGame", true);
const gui_save grid_cat_home = gui_save(game_list, "gridCategoryVisibleHome", true);
const gui_save grid_cat_audio_video = gui_save(game_list, "gridCategoryVisibleAudioVideo", true);
const gui_save grid_cat_game_data = gui_save(game_list, "gridCategoryVisibleGameData", false);
const gui_save grid_cat_unknown = gui_save(game_list, "gridCategoryVisibleUnknown", true);
const gui_save grid_cat_other = gui_save(game_list, "gridCategoryVisibleOther", true);
const gui_save gl_sortAsc = gui_save(game_list, "sortAsc", true);
const gui_save gl_sortCol = gui_save(game_list, "sortCol", 1);
const gui_save gl_state = gui_save(game_list, "state", QByteArray());
const gui_save gl_iconSize = gui_save(game_list, "iconSize", get_Index(gl_icon_size_small));
const gui_save gl_iconSizeGrid = gui_save(game_list, "iconSizeGrid", get_Index(gl_icon_size_small));
const gui_save gl_iconColor = gui_save(game_list, "iconColor", gl_icon_color);
const gui_save gl_listMode = gui_save(game_list, "listMode", true);
const gui_save gl_textFactor = gui_save(game_list, "textFactor", qreal{2.0});
const gui_save gl_marginFactor = gui_save(game_list, "marginFactor", qreal{0.09});
const gui_save gl_show_hidden = gui_save(game_list, "show_hidden", false);
const gui_save gl_hidden_list = gui_save(game_list, "hidden_list", QStringList());
const gui_save gl_draw_compat = gui_save(game_list, "draw_compat", false);
const gui_save gl_custom_icon = gui_save(game_list, "custom_icon", true);
const gui_save gl_hover_gifs = gui_save(game_list, "hover_gifs", true);
const gui_save fs_emulator_dir_list = gui_save(fs, "emulator_dir_list", QStringList());
const gui_save fs_dev_hdd0_list = gui_save(fs, "dev_hdd0_list", QStringList());
const gui_save fs_dev_hdd1_list = gui_save(fs, "dev_hdd1_list", QStringList());
const gui_save fs_dev_flash_list = gui_save(fs, "dev_flash_list", QStringList());
const gui_save fs_dev_flash2_list = gui_save(fs, "dev_flash2_list", QStringList());
const gui_save fs_dev_flash3_list = gui_save(fs, "dev_flash3_list", QStringList());
const gui_save fs_dev_bdvd_list = gui_save(fs, "dev_bdvd_list", QStringList());
const gui_save fs_games_list = gui_save(fs, "games_list", QStringList());
const gui_save fs_dev_usb_list = gui_save(fs, "dev_usb00X_list", QStringList()); // Used as a template for all usb paths
const gui_save l_tty = gui_save(logger, "TTY", true);
const gui_save l_level = gui_save(logger, "level", static_cast<uchar>(logs::level::success));
const gui_save l_prefix = gui_save(logger, "prefix_on", false);
const gui_save l_stack_err = gui_save(logger, "ERR_stack", true);
const gui_save l_stack = gui_save(logger, "stack", true);
const gui_save l_stack_tty = gui_save(logger, "TTY_stack", false);
const gui_save l_ansi_code = gui_save(logger, "ANSI_code", true);
const gui_save l_limit = gui_save(logger, "limit", 1000);
const gui_save l_limit_tty = gui_save(logger, "TTY_limit", 1000);
const gui_save d_splitterState = gui_save(debugger, "splitterState", QByteArray());
const gui_save rsx_geometry = gui_save(rsx, "geometry", QByteArray());
const gui_save rsx_states = gui_save(rsx, "states", QVariantMap());
#ifdef __APPLE__
const gui_save m_currentStylesheet = gui_save(meta, "currentStylesheet", "native (macOS)");
#else
const gui_save m_currentStylesheet = gui_save(meta, "currentStylesheet", DefaultStylesheet);
#endif
const gui_save m_showDebugTab = gui_save(meta, "showDebugTab", false);
const gui_save m_attachCommandLine = gui_save(meta, "attachCommandLine", false);
const gui_save m_enableUIColors = gui_save(meta, "enableUIColors", false);
const gui_save m_richPresence = gui_save(meta, "useRichPresence", true);
const gui_save m_discordState = gui_save(meta, "discordState", "");
const gui_save m_check_upd_start = gui_save(meta, "checkUpdateStart", update_on);
const gui_save gs_disableMouse = gui_save(gs_frame, "disableMouse", false);
const gui_save gs_disableKbHotkeys = gui_save(gs_frame, "disableKbHotkeys", false);
const gui_save gs_showMouseFs = gui_save(gs_frame, "showMouseInFullscreen", false);
const gui_save gs_lockMouseFs = gui_save(gs_frame, "lockMouseInFullscreen", true);
const gui_save gs_resize = gui_save(gs_frame, "resize", false);
const gui_save gs_resize_manual = gui_save(gs_frame, "resizeManual", true);
const gui_save gs_screen = gui_save(gs_frame, "screen", 0);
const gui_save gs_width = gui_save(gs_frame, "width", 1280);
const gui_save gs_height = gui_save(gs_frame, "height", 720);
const gui_save gs_hideMouseIdle = gui_save(gs_frame, "hideMouseOnIdle", false);
const gui_save gs_hideMouseIdleTime = gui_save(gs_frame, "hideMouseOnIdleTime", 2000);
const gui_save gs_geometry = gui_save(gs_frame, "geometry", QRect());
const gui_save gs_visibility = gui_save(gs_frame, "visibility", QWindow::Visibility::AutomaticVisibility);
const gui_save tr_icon_color = gui_save(trophy, "icon_color", gl_icon_color);
const gui_save tr_icon_height = gui_save(trophy, "icon_height", 75);
const gui_save tr_game_iconSize = gui_save(trophy, "game_iconSize", 25);
const gui_save tr_show_locked = gui_save(trophy, "show_locked", true);
const gui_save tr_show_unlocked = gui_save(trophy, "show_unlocked", true);
const gui_save tr_show_hidden = gui_save(trophy, "show_hidden", false);
const gui_save tr_show_bronze = gui_save(trophy, "show_bronze", true);
const gui_save tr_show_silver = gui_save(trophy, "show_silver", true);
const gui_save tr_show_gold = gui_save(trophy, "show_gold", true);
const gui_save tr_show_platinum = gui_save(trophy, "show_platinum", true);
const gui_save tr_geometry = gui_save(trophy, "geometry", QByteArray());
const gui_save tr_splitterState = gui_save(trophy, "splitterState", QByteArray());
const gui_save tr_games_state = gui_save(trophy, "games_state", QByteArray());
const gui_save tr_trophy_state = gui_save(trophy, "trophy_state", QByteArray());
const gui_save pm_show_owned = gui_save(patches, "show_owned", false);
const gui_save pm_geometry = gui_save(patches, "geometry", QByteArray());
const gui_save pm_splitter_state = gui_save(patches, "splitter_state", QByteArray());
const gui_save sd_geometry = gui_save(savedata, "geometry", QByteArray());
const gui_save sd_icon_size = gui_save(savedata, "icon_size", 60);
const gui_save sd_icon_color = gui_save(savedata, "icon_color", gl_icon_color);
const gui_save um_geometry = gui_save(users, "geometry", QByteArray());
const gui_save cfg_geometry = gui_save(config, "geometry", QByteArray());
const gui_save loc_language = gui_save(localization, "language", "en");
const gui_save pads_show_emulated = gui_save(pad_settings, "show_emulated_values", false);
const gui_save pads_geometry = gui_save(pad_settings, "geometry", QByteArray());
const gui_save lv_show_timestamps = gui_save(log_viewer, "show_timestamps", true);
const gui_save lv_show_threads = gui_save(log_viewer, "show_threads", true);
const gui_save lv_log_levels = gui_save(log_viewer, "log_levels", 0b11111111u);
const gui_save sc_shortcuts = gui_save(sc, "shortcuts", QVariantMap());
const gui_save nav_enabled = gui_save(navigation, "pad_input_enabled", false);
const gui_save nav_global = gui_save(navigation, "allow_global_pad_input", false);
}
/** Class for GUI settings..
*/
class gui_settings : public settings
{
Q_OBJECT
public:
explicit gui_settings(QObject* parent = nullptr);
bool GetCategoryVisibility(int cat, bool is_list_mode) const;
void ShowConfirmationBox(const QString& title, const QString& text, const gui_save& entry, int* result, QWidget* parent);
void ShowInfoBox(const QString& title, const QString& text, const gui_save& entry, QWidget* parent);
bool GetBootConfirmation(QWidget* parent, const gui_save& gui_save_entry = gui_save());
logs::level GetLogLevel() const;
bool GetTrophyGamelistColVisibility(gui::trophy_game_list_columns col) const;
bool GetTrophylistColVisibility(gui::trophy_list_columns col) const;
bool GetGamelistColVisibility(gui::game_list_columns col) const;
QColor GetCustomColor(int col) const;
QStringList GetStylesheetEntries() const;
QStringList GetGameListCategoryFilters(bool is_list_mode) const;
static QSize SizeFromSlider(int pos);
/** Sets the visibility of the chosen category. */
void SetCategoryVisibility(int cat, bool val, bool is_list_mode) const;
void SetTrophyGamelistColVisibility(gui::trophy_game_list_columns col, bool val) const;
void SetTrophylistColVisibility(gui::trophy_list_columns col, bool val) const;
void SetGamelistColVisibility(gui::game_list_columns col, bool val) const;
void SetCustomColor(int col, const QColor& val) const;
private:
static gui_save GetGuiSaveForTrophyGameColumn(gui::trophy_game_list_columns col);
static gui_save GetGuiSaveForTrophyColumn(gui::trophy_list_columns col);
static gui_save GetGuiSaveForGameColumn(gui::game_list_columns col);
static gui_save GetGuiSaveForCategory(int cat, bool is_list_mode);
void ShowBox(QMessageBox::Icon icon, const QString& title, const QString& text, const gui_save& entry, int* result, QWidget* parent, bool always_on_top);
};
| 16,555
|
C++
|
.h
| 272
| 58.617647
| 154
| 0.703943
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,696
|
gui_application.h
|
RPCS3_rpcs3/rpcs3/rpcs3qt/gui_application.h
|
#pragma once
#include "util/types.hpp"
#include "util/atomic.hpp"
#include <QApplication>
#include <QAbstractNativeEventFilter>
#include <QElapsedTimer>
#include <QTimer>
#include <QTranslator>
#include <QSoundEffect>
#include "main_application.h"
#include "Emu/System.h"
#include "Input/raw_mouse_handler.h"
#include <memory>
#include <functional>
#include <deque>
class gs_frame;
class main_window;
class gui_settings;
class emu_settings;
class persistent_settings;
extern std::unique_ptr<raw_mouse_handler> g_raw_mouse_handler; // Only used for GUI
/** RPCS3 GUI Application Class
* The main point of this class is to do application initialization, to hold the main and game windows and to initialize callbacks.
*/
class gui_application : public QApplication, public main_application
{
Q_OBJECT
public:
gui_application(int& argc, char** argv);
~gui_application();
void SetShowGui(bool show_gui = true)
{
m_show_gui = show_gui;
}
void SetUseCliStyle(bool use_cli_style = false)
{
m_use_cli_style = use_cli_style;
}
void SetWithCliBoot(bool with_cli_boot = false)
{
m_with_cli_boot = with_cli_boot;
}
void SetStartGamesFullscreen(bool start_games_fullscreen = false)
{
m_start_games_fullscreen = start_games_fullscreen;
}
void SetGameScreenIndex(int screen_index = -1)
{
m_game_screen_index = screen_index;
}
/** Call this method before calling app.exec */
bool Init() override;
std::unique_ptr<gs_frame> get_gs_frame();
main_window* m_main_window = nullptr;
private:
QThread* get_thread() override
{
return thread();
}
void SwitchTranslator(QTranslator& translator, const QString& filename, const QString& language_code);
void LoadLanguage(const QString& language_code);
static QStringList GetAvailableLanguageCodes();
void InitializeCallbacks();
void InitializeConnects();
void StartPlaytime(bool start_playtime);
void UpdatePlaytime();
void StopPlaytime();
class native_event_filter : public QAbstractNativeEventFilter
{
public:
bool nativeEventFilter(const QByteArray& eventType, void* message, qintptr* result) override;
} m_native_event_filter;
QTranslator m_translator;
QString m_language_code;
QTimer m_timer;
QElapsedTimer m_timer_playtime;
std::deque<std::unique_ptr<QSoundEffect>> m_sound_effects{};
std::shared_ptr<emu_settings> m_emu_settings;
std::shared_ptr<gui_settings> m_gui_settings;
std::shared_ptr<persistent_settings> m_persistent_settings;
QString m_default_style;
bool m_show_gui = true;
bool m_use_cli_style = false;
bool m_with_cli_boot = false;
bool m_start_games_fullscreen = false;
int m_game_screen_index = -1;
u64 m_pause_amend_time_on_focus_loss = umax;
u64 m_pause_delayed_tag = 0;
typename Emulator::stop_counter_t m_emu_focus_out_emulation_id{};
bool m_is_pause_on_focus_loss_active = false;
private Q_SLOTS:
void OnChangeStyleSheetRequest();
void OnShortcutChange();
void OnAppStateChanged(Qt::ApplicationState state);
Q_SIGNALS:
void OnEmulatorRun(bool start_playtime);
void OnEmulatorPause();
void OnEmulatorResume(bool start_playtime);
void OnEmulatorStop();
void OnEmulatorReady();
void OnEnableDiscEject(bool enabled);
void OnEnableDiscInsert(bool enabled);
void RequestCallFromMainThread(std::function<void()> func, atomic_t<u32>* wake_up);
private Q_SLOTS:
static void CallFromMainThread(const std::function<void()>& func, atomic_t<u32>* wake_up);
};
| 3,411
|
C++
|
.h
| 106
| 30.084906
| 131
| 0.7772
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,697
|
shortcut_settings.h
|
RPCS3_rpcs3/rpcs3/rpcs3qt/shortcut_settings.h
|
#pragma once
#include "gui_settings.h"
#include <QKeySequence>
namespace gui
{
namespace shortcuts
{
enum class shortcut_handler_id : int
{
main_window,
game_window,
};
enum class shortcut : int
{
mw_start,
mw_stop,
mw_pause,
mw_restart,
mw_toggle_fullscreen,
mw_exit_fullscreen,
mw_refresh,
gw_toggle_fullscreen,
gw_exit_fullscreen,
gw_log_mark,
gw_mouse_lock,
gw_screenshot,
gw_toggle_recording,
gw_pause_play,
gw_savestate,
gw_restart,
gw_rsx_capture,
gw_frame_limit,
gw_toggle_mouse_and_keyboard,
gw_home_menu,
count
};
}
}
struct shortcut_info
{
QString name;
QString localized_name;
QString key_sequence;
gui::shortcuts::shortcut_handler_id handler_id{};
};
class shortcut_settings : public QObject
{
Q_OBJECT
public:
shortcut_settings();
~shortcut_settings();
const std::map<const gui::shortcuts::shortcut, const shortcut_info> shortcut_map;
gui_save get_shortcut_gui_save(const QString& shortcut_name);
QKeySequence get_key_sequence(const shortcut_info& entry, const std::shared_ptr<gui_settings>& gui_settings);
};
| 1,130
|
C++
|
.h
| 55
| 17.618182
| 110
| 0.733772
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,698
|
qt_camera_handler.h
|
RPCS3_rpcs3/rpcs3/rpcs3qt/qt_camera_handler.h
|
#pragma once
#include "Emu/Io/camera_handler_base.h"
#include "qt_camera_video_sink.h"
#include "util/types.hpp"
#include <QCamera>
#include <QMediaCaptureSession>
#include <QObject>
#include <QVideoSink>
class qt_camera_handler final : public QObject, public camera_handler_base
{
Q_OBJECT
public:
qt_camera_handler();
virtual ~qt_camera_handler();
void set_camera(const QCameraDevice& camera_info);
void open_camera() override;
void close_camera() override;
void start_camera() override;
void stop_camera() override;
void set_format(s32 format, u32 bytesize) override;
void set_frame_rate(u32 frame_rate) override;
void set_resolution(u32 width, u32 height) override;
void set_mirrored(bool mirrored) override;
u64 frame_number() const override;
camera_handler_state get_image(u8* buf, u64 size, u32& width, u32& height, u64& frame_number, u64& bytes_read) override;
private:
void reset();
void update_camera_settings();
std::string m_camera_id;
std::shared_ptr<QCamera> m_camera;
std::unique_ptr<QMediaCaptureSession> m_media_capture_session;
std::unique_ptr<qt_camera_video_sink> m_video_sink;
private Q_SLOTS:
void handle_camera_active(bool is_active);
void handle_camera_error(QCamera::Error error, const QString& errorString);
};
| 1,268
|
C++
|
.h
| 36
| 33.361111
| 121
| 0.777596
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,699
|
gs_frame.h
|
RPCS3_rpcs3/rpcs3/rpcs3qt/gs_frame.h
|
#pragma once
#include "shortcut_handler.h"
#include "progress_indicator.h"
#include "util/types.hpp"
#include "util/atomic.hpp"
#include "util/media_utils.h"
#include "Emu/RSX/GSFrameBase.h"
#include <QWindow>
#include <QPaintEvent>
#include <QTimer>
#include <memory>
#include <vector>
class gui_settings;
class gs_frame : public QWindow, public GSFrameBase
{
Q_OBJECT
private:
// taskbar progress
std::unique_ptr<progress_indicator> m_progress_indicator;
shortcut_handler* m_shortcut_handler = nullptr;
QRect m_initial_geometry;
std::shared_ptr<gui_settings> m_gui_settings;
QTimer m_mousehide_timer;
u64 m_frames = 0;
std::string m_window_title;
QWindow::Visibility m_last_visibility = Visibility::Windowed;
atomic_t<bool> m_is_closing = false;
atomic_t<bool> m_show_mouse = true;
bool m_disable_mouse = false;
bool m_disable_kb_hotkeys = false;
bool m_mouse_hide_and_lock = false;
bool m_show_mouse_in_fullscreen = false;
bool m_lock_mouse_in_fullscreen = true;
bool m_hide_mouse_after_idletime = false;
u32 m_hide_mouse_idletime = 2000; // ms
bool m_flip_showed_frame = false;
bool m_start_games_fullscreen = false;
std::shared_ptr<utils::video_encoder> m_video_encoder{};
public:
explicit gs_frame(QScreen* screen, const QRect& geometry, const QIcon& appIcon, std::shared_ptr<gui_settings> gui_settings, bool force_fullscreen);
~gs_frame();
draw_context_t make_context() override;
void set_current(draw_context_t context) override;
void delete_context(draw_context_t context) override;
void toggle_fullscreen() override;
void update_shortcuts();
// taskbar progress
void progress_reset(bool reset_limit = false);
void progress_set_value(int value);
void progress_increment(int delta);
void progress_set_limit(int limit);
/*
Returns true if the mouse is locked inside the game window.
Also conveniently updates the cursor visibility, because using it from a mouse handler indicates mouse emulation.
*/
bool get_mouse_lock_state();
bool can_consume_frame() const override;
void present_frame(std::vector<u8>& data, u32 pitch, u32 width, u32 height, bool is_bgra) const override;
void take_screenshot(std::vector<u8> data, u32 sshot_width, u32 sshot_height, bool is_bgra) override;
protected:
void paintEvent(QPaintEvent *event) override;
void showEvent(QShowEvent *event) override;
void close() override;
bool shown() override;
void hide() override;
void show() override;
void mouseDoubleClickEvent(QMouseEvent* ev) override;
display_handle_t handle() const override;
void flip(draw_context_t context, bool skip_frame = false) override;
int client_width() override;
int client_height() override;
f64 client_display_rate() override;
bool has_alpha() override;
bool event(QEvent* ev) override;
private:
void load_gui_settings();
void hide_on_close();
void toggle_recording();
void toggle_mouselock();
void update_cursor();
void handle_cursor(QWindow::Visibility visibility, bool visibility_changed, bool active_changed, bool start_idle_timer);
private Q_SLOTS:
void mouse_hide_timeout();
void handle_shortcut(gui::shortcuts::shortcut shortcut_key, const QKeySequence& key_sequence);
};
| 3,179
|
C++
|
.h
| 85
| 35.329412
| 148
| 0.773216
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,700
|
dimensions_dialog.h
|
RPCS3_rpcs3/rpcs3/rpcs3qt/dimensions_dialog.h
|
#pragma once
#include "util/types.hpp"
#include <QDialog>
#include <QLineEdit>
#include <QGridLayout>
class minifig_creator_dialog : public QDialog
{
Q_OBJECT
public:
explicit minifig_creator_dialog(QWidget* parent);
QString get_file_path() const;
protected:
QString m_file_path;
};
class minifig_move_dialog : public QDialog
{
Q_OBJECT
public:
explicit minifig_move_dialog(QWidget* parent, u8 old_index);
u8 get_new_pad() const;
u8 get_new_index() const;
protected:
u8 m_pad = 0;
u8 m_index = 0;
private:
void add_minifig_position(QGridLayout* grid_panel, u8 index, u8 row, u8 column, u8 old_index);
};
class dimensions_dialog : public QDialog
{
Q_OBJECT
public:
explicit dimensions_dialog(QWidget* parent);
~dimensions_dialog();
static dimensions_dialog* get_dlg(QWidget* parent);
dimensions_dialog(dimensions_dialog const&) = delete;
void operator=(dimensions_dialog const&) = delete;
protected:
void clear_figure(u8 pad, u8 index);
void create_figure(u8 pad, u8 index);
void load_figure(u8 pad, u8 index);
void move_figure(u8 pad, u8 index);
void load_figure_path(u8 pad, u8 index, const QString& path);
protected:
std::array<QLineEdit*, 7> m_edit_figures{};
private:
void add_minifig_slot(QHBoxLayout* layout, u8 pad, u8 index);
static dimensions_dialog* inst;
};
| 1,309
|
C++
|
.h
| 48
| 25.4375
| 95
| 0.766453
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,701
|
vfs_dialog_path_widget.h
|
RPCS3_rpcs3/rpcs3/rpcs3qt/vfs_dialog_path_widget.h
|
#pragma once
#include "util/types.hpp"
#include "gui_settings.h"
#include <QListWidget>
#include <QLabel>
#include <memory>
namespace cfg
{
class string;
}
class vfs_dialog_path_widget : public QWidget
{
Q_OBJECT
public:
explicit vfs_dialog_path_widget(const QString& name, const QString& current_path, QString default_path, gui_save list_location, std::shared_ptr<gui_settings> _gui_settings, QWidget* parent = nullptr);
QStringList get_dir_list() const;
std::string get_selected_path() const;
// Reset this widget without saving the settings yet
void reset() const;
protected:
void add_new_directory() const;
void remove_directory() const;
const QString EmptyPath = tr("Empty Path");
QString m_default_path;
gui_save m_list_location;
std::shared_ptr<gui_settings> m_gui_settings;
// UI variables needed in higher scope
QListWidget* m_dir_list;
QLabel* m_selected_config_label;
};
| 909
|
C++
|
.h
| 30
| 28.4
| 201
| 0.773041
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,702
|
register_editor_dialog.h
|
RPCS3_rpcs3/rpcs3/rpcs3qt/register_editor_dialog.h
|
#pragma once
#include "util/types.hpp"
#include <QDialog>
#include <QComboBox>
#include <QLineEdit>
class CPUDisAsm;
class cpu_thread;
class register_editor_dialog : public QDialog
{
Q_OBJECT
CPUDisAsm* m_disasm;
QComboBox* m_register_combo;
QLineEdit* m_value_line;
const std::function<cpu_thread*()> m_get_cpu;
public:
register_editor_dialog(QWidget *parent, CPUDisAsm* _disasm, std::function<cpu_thread*()> func);
private:
void OnOkay();
private Q_SLOTS:
void updateRegister(int reg) const;
};
| 514
|
C++
|
.h
| 21
| 22.666667
| 96
| 0.774793
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,703
|
find_dialog.h
|
RPCS3_rpcs3/rpcs3/rpcs3qt/find_dialog.h
|
#pragma once
#include <QDialog>
#include <QPlainTextEdit>
#include <QLineEdit>
#include <QPushButton>
#include <QLabel>
class find_dialog : public QDialog
{
Q_OBJECT
public:
find_dialog(QPlainTextEdit* edit, QWidget *parent = Q_NULLPTR, Qt::WindowFlags f = Qt::WindowFlags());
private:
int m_count_lines = 0;
int m_count_total = 0;
QLabel* m_label_count_lines;
QLabel* m_label_count_total;
QPlainTextEdit* m_text_edit;
QLineEdit* m_find_bar;
QPushButton* m_find_first;
QPushButton* m_find_last;
QPushButton* m_find_next;
QPushButton* m_find_previous;
private Q_SLOTS:
int count_all();
void find_first();
void find_last();
void find_next();
void find_previous();
void show_count() const;
};
| 713
|
C++
|
.h
| 30
| 22
| 103
| 0.752212
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,704
|
emulated_pad_settings_dialog.h
|
RPCS3_rpcs3/rpcs3/rpcs3qt/emulated_pad_settings_dialog.h
|
#pragma once
#include "Emu/Io/pad_types.h"
#include <QComboBox>
#include <QDialog>
#include <QTabWidget>
#include <vector>
class emulated_pad_settings_dialog : public QDialog
{
Q_OBJECT
public:
enum class pad_type
{
buzz,
turntable,
ghltar,
usio,
ds3gem,
guncon3,
topshotelite,
topshotfearmaster,
};
emulated_pad_settings_dialog(pad_type type, QWidget* parent = nullptr);
private:
template <typename T>
void add_tabs(QTabWidget* tabs);
void load_config();
void save_config();
void reset_config();
pad_type m_type;
std::vector<std::vector<QComboBox*>> m_combos;
};
| 602
|
C++
|
.h
| 31
| 17.193548
| 72
| 0.752228
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,705
|
shortcut_handler.h
|
RPCS3_rpcs3/rpcs3/rpcs3qt/shortcut_handler.h
|
#pragma once
#include "gui_settings.h"
#include "shortcut_settings.h"
#include <QShortcut>
#include <QWidget>
#include <map>
class shortcut_handler : public QObject
{
Q_OBJECT
public:
shortcut_handler(gui::shortcuts::shortcut_handler_id handler_id, QObject* parent, const std::shared_ptr<gui_settings>& gui_settings);
Q_SIGNALS:
void shortcut_activated(gui::shortcuts::shortcut shortcut_key, const QKeySequence& key_sequence);
public Q_SLOTS:
void update();
private:
void handle_shortcut(gui::shortcuts::shortcut shortcut_key, const QKeySequence& key_sequence);
gui::shortcuts::shortcut_handler_id m_handler_id;
std::shared_ptr<gui_settings> m_gui_settings;
struct shortcut_key_info
{
QShortcut* shortcut = nullptr;
QKeySequence key_sequence{};
shortcut_info info{};
};
std::map<gui::shortcuts::shortcut, shortcut_key_info> m_shortcuts;
};
| 867
|
C++
|
.h
| 27
| 30.111111
| 134
| 0.779518
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,706
|
game_list_table.h
|
RPCS3_rpcs3/rpcs3/rpcs3qt/game_list_table.h
|
#pragma once
#include "game_list.h"
class persistent_settings;
class game_list_frame;
class game_list_table : public game_list
{
Q_OBJECT
public:
game_list_table(game_list_frame* frame, std::shared_ptr<persistent_settings> persistent_settings);
/** Restores the initial layout of the table */
void restore_layout(const QByteArray& state);
/** Resizes the columns to their contents and adds a small spacing */
void resize_columns_to_contents(int spacing = 20);
void adjust_icon_column();
void sort(usz game_count, int sort_column, Qt::SortOrder col_sort_order);
void set_custom_config_icon(const game_info& game);
void populate(
const std::vector<game_info>& game_data,
const std::map<QString, QString>& notes_map,
const std::map<QString, QString>& title_map,
const std::string& selected_item_id,
bool play_hover_movies) override;
void repaint_icons(std::vector<game_info>& game_data, const QColor& icon_color, const QSize& icon_size, qreal device_pixel_ratio) override;
Q_SIGNALS:
void size_on_disk_ready(const game_info& game);
private:
game_list_frame* m_game_list_frame{};
std::shared_ptr<persistent_settings> m_persistent_settings;
};
| 1,176
|
C++
|
.h
| 29
| 38.275862
| 140
| 0.76455
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,707
|
game_list_frame.h
|
RPCS3_rpcs3/rpcs3/rpcs3qt/game_list_frame.h
|
#pragma once
#include "game_list.h"
#include "custom_dock_widget.h"
#include "gui_save.h"
#include "shortcut_utils.h"
#include "Utilities/lockless.h"
#include "Utilities/mutex.h"
#include "util/auto_typemap.hpp"
#include "Emu/config_mode.h"
#include <QMainWindow>
#include <QToolBar>
#include <QStackedWidget>
#include <QSet>
#include <QTableWidgetItem>
#include <QFutureWatcher>
#include <QTimer>
#include <memory>
#include <optional>
#include <set>
class game_list_table;
class game_list_grid;
class gui_settings;
class emu_settings;
class persistent_settings;
class progress_dialog;
class game_list_frame : public custom_dock_widget
{
Q_OBJECT
public:
explicit game_list_frame(std::shared_ptr<gui_settings> gui_settings, std::shared_ptr<emu_settings> emu_settings, std::shared_ptr<persistent_settings> persistent_settings, QWidget* parent = nullptr);
~game_list_frame();
/** Refresh the gamelist with/without loading game data from files. Public so that main frame can refresh after vfs or install */
void Refresh(const bool from_drive = false, const std::vector<std::string>& serials_to_remove_from_yml = {}, const bool scroll_after = true);
/** Adds/removes categories that should be shown on gamelist. Public so that main frame menu actions can apply them */
void ToggleCategoryFilter(const QStringList& categories, bool show);
/** Loads from settings. Public so that main frame can easily reset these settings if needed. */
void LoadSettings();
/** Saves settings. Public so that main frame can save this when a caching of column widths is needed for settings backup */
void SaveSettings();
/** Resize Gamelist Icons to size given by slider position */
void ResizeIcons(const int& slider_pos);
/** Repaint Gamelist Icons with new background color */
void RepaintIcons(const bool& from_settings = false);
void SetShowHidden(bool show);
game_compatibility* GetGameCompatibility() const { return m_game_compat; }
const std::vector<game_info>& GetGameInfo() const;
void CreateShortcuts(const game_info& gameinfo, const std::set<gui::utils::shortcut_location>& locations);
bool IsEntryVisible(const game_info& game, bool search_fallback = false) const;
public Q_SLOTS:
void BatchCreateCPUCaches(const std::vector<game_info>& game_data = {});
void BatchRemovePPUCaches();
void BatchRemoveSPUCaches();
void BatchRemoveCustomConfigurations();
void BatchRemoveCustomPadConfigurations();
void BatchRemoveShaderCaches();
void SetListMode(const bool& is_list);
void SetSearchText(const QString& text);
void SetShowCompatibilityInGrid(bool show);
void SetShowCustomIcons(bool show);
void SetPlayHoverGifs(bool play);
void FocusAndSelectFirstEntryIfNoneIs();
private Q_SLOTS:
void OnParsingFinished();
void OnRefreshFinished();
void OnCompatFinished();
void OnColClicked(int col);
void ShowContextMenu(const QPoint &pos);
void doubleClickedSlot(QTableWidgetItem* item);
void doubleClickedSlot(const game_info& game);
void ItemSelectionChangedSlot();
Q_SIGNALS:
void GameListFrameClosed();
void NotifyGameSelection(const game_info& game);
void RequestBoot(const game_info& game, cfg_mode config_mode = cfg_mode::custom, const std::string& config_path = "", const std::string& savestate = "");
void RequestIconSizeChange(const int& val);
void NotifyEmuSettingsChange();
void FocusToSearchBar();
void Refreshed();
public:
template <typename KeyType>
struct GameIdsTable
{
// List of game paths an operation has been done on for the use of the slot function
std::set<std::string> m_done_paths;
};
// Enqueue slot for refreshed signal
// Allowing for an individual container for each distinct use case (currently disabled and contains only one such entry)
template <typename KeySlot = void, typename Func>
void AddRefreshedSlot(Func&& func)
{
// NOTE: Remove assert when the need for individual containers arises
static_assert(std::is_void_v<KeySlot>);
connect(this, &game_list_frame::Refreshed, this, [this, func = std::move(func)]() mutable
{
func(m_refresh_funcs_manage_type->get<GameIdsTable<KeySlot>>().m_done_paths);
}, Qt::SingleShotConnection);
}
protected:
/** Override inherited method from Qt to allow signalling when close happened.*/
void closeEvent(QCloseEvent* event) override;
bool eventFilter(QObject *object, QEvent *event) override;
private:
void push_path(const std::string& path, std::vector<std::string>& legit_paths);
void ShowCustomConfigIcon(const game_info& game);
bool SearchMatchesApp(const QString& name, const QString& serial, bool fallback = false) const;
bool RemoveCustomConfiguration(const std::string& title_id, const game_info& game = nullptr, bool is_interactive = false);
bool RemoveCustomPadConfiguration(const std::string& title_id, const game_info& game = nullptr, bool is_interactive = false);
bool RemoveShadersCache(const std::string& base_dir, bool is_interactive = false);
bool RemovePPUCache(const std::string& base_dir, bool is_interactive = false);
bool RemoveSPUCache(const std::string& base_dir, bool is_interactive = false);
void RemoveHDD1Cache(const std::string& base_dir, const std::string& title_id, bool is_interactive = false);
static bool CreateCPUCaches(const std::string& path, const std::string& serial = {});
static bool CreateCPUCaches(const game_info& game);
static bool RemoveContentPath(const std::string& path, const std::string& desc);
static u32 RemoveContentPathList(const std::vector<std::string>& path_list, const std::string& desc);
static bool RemoveContentBySerial(const std::string& base_dir, const std::string& serial, const std::string& desc);
static std::vector<std::string> GetDirListBySerial(const std::string& base_dir, const std::string& serial);
static std::string GetCacheDirBySerial(const std::string& serial);
static std::string GetDataDirBySerial(const std::string& serial);
std::string CurrentSelectionPath();
game_info GetGameInfoByMode(const QTableWidgetItem* item) const;
static game_info GetGameInfoFromItem(const QTableWidgetItem* item);
void WaitAndAbortRepaintThreads();
void WaitAndAbortSizeCalcThreads();
// Which widget we are displaying depends on if we are in grid or list mode.
QMainWindow* m_game_dock = nullptr;
QStackedWidget* m_central_widget = nullptr;
// Game Grid
game_list_grid* m_game_grid = nullptr;
// Game List
game_list_table* m_game_list = nullptr;
game_compatibility* m_game_compat = nullptr;
progress_dialog* m_progress_dialog = nullptr;
QList<QAction*> m_columnActs;
Qt::SortOrder m_col_sort_order{};
int m_sort_column{};
bool m_initial_refresh_done = false;
std::map<QString, QString> m_notes;
std::map<QString, QString> m_titles;
// Categories
QStringList m_category_filters;
QStringList m_grid_category_filters;
// List Mode
bool m_is_list_layout = true;
bool m_old_layout_is_list = true;
// Data
std::shared_ptr<gui_settings> m_gui_settings;
std::shared_ptr<emu_settings> m_emu_settings;
std::shared_ptr<persistent_settings> m_persistent_settings;
std::vector<game_info> m_game_data;
struct path_entry
{
std::string path;
bool is_disc{};
bool is_from_yml{};
};
std::vector<path_entry> m_path_entries;
shared_mutex m_path_mutex;
std::set<std::string> m_path_list;
QSet<QString> m_serials;
QMutex m_games_mutex;
lf_queue<game_info> m_games;
const std::array<int, 1> m_parsing_threads{0};
QFutureWatcher<void> m_parsing_watcher;
QFutureWatcher<void> m_refresh_watcher;
QSet<QString> m_hidden_list;
bool m_show_hidden{false};
// Search
QString m_search_text;
// Icon Size
int m_icon_size_index = 0;
// Icons
QColor m_icon_color;
QSize m_icon_size;
qreal m_margin_factor;
qreal m_text_factor;
bool m_draw_compat_status_to_grid = false;
bool m_show_custom_icons = true;
bool m_play_hover_movies = true;
std::optional<auto_typemap<game_list_frame>> m_refresh_funcs_manage_type{std::in_place};
};
| 7,896
|
C++
|
.h
| 181
| 41.546961
| 199
| 0.773639
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,708
|
flow_widget_item.h
|
RPCS3_rpcs3/rpcs3/rpcs3qt/flow_widget_item.h
|
#pragma once
#include <QWidget>
#include <QKeyEvent>
#include <functional>
enum class flow_navigation
{
up,
down,
left,
right,
home,
end,
page_up,
page_down
};
class flow_widget_item : public QWidget
{
Q_OBJECT
Q_PROPERTY(bool hover MEMBER m_hover) // Stylesheet workaround for descendants with parent pseudo state
Q_PROPERTY(bool selected MEMBER selected) // Stylesheet workaround for descendants with parent pseudo state
public:
flow_widget_item(QWidget* parent);
virtual ~flow_widget_item();
virtual void polish_style();
void paintEvent(QPaintEvent* event) override;
void focusInEvent(QFocusEvent* event) override;
void focusOutEvent(QFocusEvent* event) override;
void keyPressEvent(QKeyEvent* event) override;
bool event(QEvent* event) override;
bool got_visible{};
bool selected{};
std::function<void()> cb_on_first_visibility{};
protected:
bool m_hover{};
Q_SIGNALS:
void navigate(flow_navigation value);
void focused();
};
| 966
|
C++
|
.h
| 38
| 23.473684
| 108
| 0.78626
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,709
|
tooltips.h
|
RPCS3_rpcs3/rpcs3/rpcs3qt/tooltips.h
|
#pragma once
#include "qt_utils.h"
#include <QString>
#include <QObject>
/**
* Localized tooltips collection class
* Due to special characters this file should stay in UTF-8 format
*/
class Tooltips : public QObject
{
Q_OBJECT
public:
Tooltips();
const struct settings
{
// advanced
const QString lle_list = tr("These libraries are LLE'd by default (lower list), selection will switch to HLE.\nLLE - \"Low Level Emulated\", function code inside the selected SPRX file will be used for exported firmware functions.\nHLE - \"High Level Emulated\", alternative emulator code will be used instead for exported firmware functions.\nIf chosen wrongly, games will not work! If unsure, leave both lists empty. HLEing all SPRX allows to boot without firmware installed. (experimental)");
const QString hle_list = tr("These libraries are HLE'd by default (upper list), selection will switch to LLE.\nLLE - \"Low Level Emulated\", function code inside the selected SPRX file will be used for exported firmware functions.\nHLE - \"High Level Emulated\", alternative emulator code will be used instead for exported firmware functions.\nIf chosen wrongly, games will not work! If unsure, leave both lists empty. HLEing all SPRX allows to boot without firmware installed. (experimental)");
const QString lib_default_hle = tr("Select to LLE. (HLE by default)");
const QString lib_default_lle = tr("Select to HLE. (LLE by default)");
const QString debug_console_mode = tr("Increases the amount of usable system memory to match a DECR console and more.\nCauses some software to behave differently than on retail hardware.");
const QString accurate_rsx_access = tr("Forces RSX pauses on SPU MFC_GETLLAR and SPU MFC_PUTLLUC operations.");
const QString accurate_spu_dma = tr("Accurately processes SPU DMA operations.");
const QString fixup_ppunj = tr("Legacy option. Fixup result vector values in Non-Java Mode in PPU LLVM.\nIf unsure, do not modify this setting.");
const QString accurate_dfma = tr("Use accurate double-precision FMA instructions in PPU and SPU backends.\nWhile disabling it might give a decent performance boost if your CPU doesn't support FMA, it may also introduce subtle bugs that otherwise do not occur.\nYou shouldn't disable it if your CPU supports FMA.");
const QString fixup_ppuvnan = tr("Fixup NaN results in vector instructions in PPU backends.\nIf unsure, do not modify this setting.");
const QString silence_all_logs = tr("Stop writing any logs after game startup. Don't use unless you believe it's necessary.");
const QString read_color = tr("Initializes render target memory using vm memory.");
const QString read_depth = tr("Initializes render target memory using vm memory.");
const QString dump_depth = tr("Writes depth buffer values to vm memory.");
const QString handle_tiled_memory = tr("Obey RSX memory tiling configuration when writing GPU data to vm memory.\nThis can fix graphics corruption observed when Read Color or Read Depth options are enabled.");
const QString disable_on_disk_shader_cache = tr("Disables the loading and saving of shaders from and to the shader cache in the data directory.");
const QString allow_host_labels = tr("Allows the host GPU to synchronize with CELL directly. This incurs a performance penalty, but exposes the true state of GPU objects to the guest CPU. Can help eliminate visual noise and glitching at the cost of performance. Use with caution.");
const QString force_hw_MSAA = tr("Forces MSAA to use the host GPU's resolve capabilities for all sampling operations.\nThis option incurs a performance penalty as well as the risk of visual artifacts but can yield crisper visuals when MSAA is enabled.");
const QString disable_vertex_cache = tr("Disables the vertex cache.\nMight resolve missing or flickering graphics output.\nMay degrade performance.");
const QString zcull_operation_mode = tr("Changes ZCULL report synchronization behaviour. Experiment to find the best option for your game. Approximate mode is recommended for most games.\n· Precise is the most accurate to PS3 behaviour. Required for accurate visuals in some titles such as Demon's Souls and The Darkness.\n· Approximate is a much faster way to generate occlusion data which may not always match what the PS3 would generate. Works well with most PS3 games.\n· Relaxed changes the synchronization method completely and can greatly improve performance in some games or completely break others.");
const QString max_spurs_threads = tr("Limits the maximum number of SPURS threads in each thread group.\nMay improve performance in some cases, especially on systems with limited number of hardware threads.\nLimiting the number of threads is likely to cause crashes; it's recommended to keep this at the default value.");
const QString sleep_timers_accuracy = tr("Changes the sleep period accuracy.\n'As Host' uses default accuracy of the underlying operating system, while 'All Timers' attempts to improve it.\n'Usleep Only' limits the adjustments to usleep syscall only.\nCan affect performance in unexpected ways.");
const QString rsx_fifo_accuracy = tr("\"Fast\" is the least accurate setting, RSX does not emulate atomic FIFO buffer.\n\"Atomic\" benefits stability greatly in many games with little performance penalty.\n\"Atomic & Ordered\" is the most accurate but it is the slowest and without much stability benefit in games.");
const QString vblank_rate = tr("Adjusts the frequency of vertical blanking signals that the emulator sends.\nAffects timing of events which rely on these signals.");
const QString vblank_ntsc_fixup = tr("Multiplies the rate of VBLANK by 1000/1001 for values like 59.94Hz.\nKnown to fix the rhythm game Space Channel 5 Part 2");
const QString clocks_scale = tr("Changes the scale of emulated system time.\nAffects software which uses system time to calculate things such as dynamic timesteps.");
const QString wake_up_delay = tr("Controls how much time it takes for RSX to start processing after waking up by the Cell processor.\nIncreasing wakeup delay improves stability, but very high values can lower RSX/GPU performance.\nIt is recommend to adjust this at 20µs to 40µs increments until the best value for optimal stability is reached.");
const QString disabled_from_global = tr("Do not change this setting globally.\nRight-click a game in the game list and choose \"Configure\" instead.");
const QString vulkan_async_scheduler = tr("Determines how to schedule GPU async compute jobs when using asynchronous streaming.\nUse 'Safe' mode for more spec compliant behavior at the cost of some CPU overhead. This setting works with all devices.\nUse 'Fast' to use a faster but hacky version. This option is internally disabled for NVIDIA GPUs due to causing GPU hangs.");
const QString disable_msl_fast_math = tr("Disables Fast Math for MSL shaders, which may violate the IEEE 754 standard.\nDisabling it may fix some artifacts, especially on Apple GPUs, at the cost of performance.");
const QString anti_cheat_savestates = tr("When this mode is on, emulation exits when saving and the savestate file is concealed after its load, preventing reuse by RPCS3.\nThis mode is like hibernation of emulation: if you don't want to be able to cheat using savestates when playing the game, consider using this mode.\nDo note that the savestate file is not gone completely, just ignored by RPCS3. You can manually relaunch it if needed.");
const QString compatible_savestates = tr("When this mode is on, SPU emulation prioritizes savestate compatibility, however, it may reduce performance slightly.\nWhen this mode is off, some games may not allow making a savestate and show an SPU pause error in the log.");
const QString paused_savestates = tr("When this mode is on, savestates are loaded and paused on the first frame.\nThis allows players to prepare for gameplay without being thrown into the action immediately.");
const QString spu_profiler = tr("When enabled, SPU performance is measured at runtime.\nEnable only at a developr's request because when enabled it reduces performance a bit by itself.");
// audio
const QString audio_out = tr("Cubeb uses a cross-platform approach and supports audio buffering, so it is the recommended option.\nXAudio2 uses native Windows sounds system and is the next best alternative.");
const QString audio_out_linux = tr("Cubeb uses a cross-platform approach and supports audio buffering, so it is the recommended option.\nIf it's not available, FAudio could be used instead.");
const QString audio_provider = tr("Controls which PS3 audio API is used.\nGames use CellAudio, while VSH requires RSXAudio.");
const QString audio_avport = tr("Controls which avport is used to sample audio data from.");
const QString audio_device = tr("Controls which device is used by audio backend.");
const QString audio_dump = tr("Saves all audio as a raw wave file. If unsure, leave this unchecked.");
const QString convert = tr("Uses 16-bit audio samples instead of default 32-bit floating point.\nUse with buggy audio drivers if you have no sound or completely broken sound.");
const QString audio_format = tr("Determines the sound format of the emulation.\nConfigure this setting if you want to switch between stereo and surround sound.\nChanging these values requires a restart of the game.\nThe manual setting will use your selected formats while the automatic setting will let the game choose from all available formats.");
const QString audio_channel_layout = tr("Determines the sound format of RPCS3.\nUse 'Auto' to let RPCS3 decide the best format based on the audio device and the emulated audio format.");
const QString master_volume = tr("Controls the overall volume of the emulation.\nValues above 100% might reduce the audio quality.");
const QString enable_buffering = tr("Enables audio buffering, which reduces crackle/stutter but increases audio latency.");
const QString audio_buffer_duration = tr("Target buffer duration in milliseconds.\nHigher values make the buffering algorithm's job easier, but may introduce noticeable audio latency.");
const QString enable_time_stretching = tr("Enables time stretching - requires buffering to be enabled.\nReduces crackle/stutter further, but may cause a very noticeable reduction in audio quality on slower CPUs.");
const QString time_stretching_threshold = tr("Buffer fill level (in percentage) below which time stretching will start.");
const QString microphone = tr("Standard should be used for most games.\nSingStar emulates a SingStar device and should be used with SingStar games.\nReal SingStar should only be used with a REAL SingStar device with SingStar games.\nRocksmith should be used with a Rocksmith dongle.");
// cpu
const QString ppu__static = tr("Interpreter (slow). Try this if PPU Recompiler (LLVM) doesn't work.");
const QString ppu_dynamic = tr("Alternative interpreter (slow). May be faster than static interpreter. Try this if PPU Recompiler (LLVM) doesn't work.");
const QString ppu_llvm = tr("Recompiles and caches the game's PPU code using the LLVM Recompiler once before running it for the first time.\nThis is by far the fastest option and should always be used.\nShould you face compatibility issues, fall back to one of the Interpreters and retry.\nIf unsure, use this option.");
const QString llvm_precompilation = tr("Searches the game's directory and precompiles extra PPU and SPU modules during boot.\nIf disabled, these modules will only be compiled when needed. Depending on the game, this might interrupt the gameplay unexpectedly and possibly frequently.\nOnly disable this if you want to get ingame more quickly.");
const QString spu__static = tr("Interpreter (slow). Try this if SPU Recompiler (LLVM) doesn't work.");
const QString spu_dynamic = tr("Alternative interpreter (slow). May be faster than static interpreter. Try this if SPU Recompiler (LLVM) doesn't work.");
const QString spu_asmjit = tr("Recompiles the game's SPU code using the ASMJIT Recompiler.\nThis is the fast option with very good compatibility.\nIf unsure, use this option.");
const QString spu_llvm = tr("Recompiles and caches the game's SPU code using the LLVM Recompiler before running which adds extra start-up time.\nThis is the fastest option with very good compatibility.\nIf you experience issues, use the ASMJIT Recompiler.");
const QString xfloat = tr("Control accuracy to SPU float vectors processing.\nFixes bugs in various games at the cost of performance.\nThis setting is only applied when SPU Decoder is set to Dynamic or LLVM.");
const QString enable_thread_scheduler = tr("Control how RPCS3 utilizes the threads of your system.\nEach option heavily depends on the game and on your CPU. It's recommended to try each option to find out which performs the best.\nChanging the thread scheduler is not supported on CPUs with less than 12 threads.");
const QString spu_loop_detection = tr("Try to detect loop conditions in SPU kernels and use them as scheduling hints.\nImproves performance and reduces CPU usage.\nMay cause severe audio stuttering in rare cases.");
const QString enable_tsx = tr("Enable usage of TSX instructions.\nNeeds to be forced on some Haswell or Broadwell CPUs or CPUs with the TSX-FA instruction set.\nForcing TSX in these cases may lead to system and performance instability, use it with caution.");
const QString spu_block_size = tr("This option controls the SPU analyser, particularly the size of compiled units. The Mega and Giga modes may improve performance by tying smaller units together, decreasing the number of compiled units but increasing their size.\nUse the Safe mode for maximum compatibility.");
const QString preferred_spu_threads = tr("Some SPU stages are sensitive to race conditions and allowing a limited number at a time helps alleviate performance stalls.\nSetting this to a smaller value might improve performance and reduce stuttering in some games.\nLeave this on auto if performance is negatively affected when setting a small value.");
const QString max_cpu_preempt = tr("Reduces CPU usage and power consumption, improving battery life on mobile devices. (0 means disabled)\nHigher values cause a more pronounced effect, but may cause audio or performance issues. A value of 50 or less is recommended.\nThis option forces an FPS limit because it's active when framerate is stable.\nThe lighter the game is on the hardware, the more power is saved by it. (until the preemption count barrier is reached)");
// debug
const QString start_on_boot = tr("Leave this enabled unless you are a developer.");
const QString ppu_debug = tr("Creates PPU logs.\nOnly useful to developers.\nNever use this.");
const QString spu_debug = tr("Creates SPU logs.\nOnly useful to developers.\nNever use this.");
const QString mfc_debug = tr("Creates MFC logs.\nOnly useful to developers.\nNever use this.");
const QString set_daz_and_ftz = tr("Sets special MXCSR flags to debug errors in SSE operations.\nOnly used in PPU thread when it's not precise.\nOnly useful to developers.\nNever use this.");
const QString accurate_ppusat = tr("Accurately set Saturation Bit values in PPU backends.\nIf unsure, do not modify this setting.");
const QString accurate_ppunj = tr("Respect Non-Java Mode Bit values for vector ops in PPU backends.\nIf unsure, do not modify this setting.");
const QString accurate_ppuvnan = tr("Accurately set NaN results in vector instructions in PPU backends.\nIf unsure, do not modify this setting.");
const QString accurate_ppufpcc = tr("Accurately set FPCC Bits in PPU backends.\nIf unsure, do not modify this setting.");
const QString accurate_cache_line_stores = tr("Accurately processes PPU DCBZ instruction.\nIn addition, when combined with Accurate SPU DMA, SPU PUT cache line accesses will be processed atomically.");
const QString mfc_delay_command = tr("Forces delaying any odd MFC command, waits for at least 2 pending commands to execute them in a random order.\nMust be used with either SPU interpreters currently.\nSeverely degrades performance! If unsure, don't use this option.");
const QString hook_static_functions = tr("Allows to hook some functions like 'memcpy' replacing them with high-level implementations. May do nothing or break things. Experimental.");
const QString renderdoc_compatibility = tr("Enables use of classic OpenGL buffers which allows capturing tools to work with RPCS3 e.g RenderDoc.\nAlso allows Vulkan to use debug markers for nicer Renderdoc captures.\nIf unsure, don't use this option.");
const QString force_high_pz = tr("Only useful when debugging differences in GPU hardware.\nNot necessary for average users.\nIf unsure, don't use this option.");
const QString debug_output = tr("Enables the selected API's inbuilt debugging functionality.\nWill cause severe performance degradation especially with Vulkan.\nOnly useful to developers.\nIf unsure, don't use this option.");
const QString debug_overlay = tr("Provides a graphical overlay of various debugging information.\nIf unsure, don't use this option.");
const QString debug_overlay_io = tr("Provides a graphical overlay with pad input values for player 1.\nThis is only shown if the other debug overlay is disabled.\nIf unsure, don't use this option.");
const QString log_shader_programs = tr("Dump game shaders to file. Only useful to developers.\nIf unsure, don't use this option.");
const QString disable_occlusion_queries = tr("Disables running occlusion queries. Minor to moderate performance boost.\nMight introduce issues with broken occlusion e.g missing geometry and extreme pop-in.");
const QString disable_video_output = tr("Disables all video output and PS3 graphical rendering.\nIts only use case is to evaluate performance on CELL for development.");
const QString force_cpu_blit_emulation = tr("Forces emulation of all blit and image manipulation operations on the CPU.\nRequires 'Write Color Buffers' option to also be enabled in most cases to avoid missing graphics.\nSignificantly degrades performance but is more accurate in some cases.\nThis setting overrides the 'GPU texture scaling' option.");
const QString disable_vulkan_mem_allocator = tr("Disables the custom Vulkan memory allocator and reverts to direct calls to VkAllocateMemory/VkFreeMemory.");
const QString disable_fifo_reordering = tr("Disables RSX FIFO optimizations completely. Draws are processed as they are received by the DMA puller.");
const QString gpu_texture_scaling = tr("Force all texture transfer, scaling and conversion operations on the GPU.\nMay cause texture corruption in some cases.");
const QString strict_texture_flushing = tr("Forces texture flushing even in situations where it is not necessary/correct. Known to cause visual artifacts, but useful for debugging certain texture cache issues.");
const QString stereo_render_mode = tr("Sets the 3D stereo rendering mode (only available in custom configurations with a default resolution of 720p).\nAnaglyph uses different colors for each eye, which can then be filtered with certain glasses.\nSide-by-Side is more commonly supported by VR viewer apps.\nOver-Under is closer to the native stereo output, but less commonly supported.");
const QString accurate_ppu_128_loop = tr("When enabled, PPU atomic operations will operate on entire cache line data, as opposed to a single 64bit block of memory when disabled.\nNumerical values control whether or not to enable the accurate version based on the atomic operation's length.");
const QString enable_performance_report = tr("Measure certain events and print a chart after the emulator is stopped. Don't enable if not asked to.");
const QString num_ppu_threads = tr("Affects maximum amount of PPU threads running concurrently, the value of 1 has very low compatibility with games.\n2 is the default, if unsure do not modify this setting.");
// emulator
const QString exit_on_stop = tr("Automatically close RPCS3 when closing a game, or when a game closes itself.");
const QString pause_on_focus_loss = tr("Automatically pause emulation when RPCS3 loses its focus or the application is inactive in order to save power and reduce CPU usage.\nDo note that emulation pausing in general is not perfect and may not be compatible with all games.\nAlthough it currently also pauses gameplay, it is not recommended to rely on it as this behavior may be changed in the future and it is not the purpose of this setting.");
const QString start_game_fullscreen = tr("Automatically puts the game window in fullscreen.\nDouble click on the game window or press Alt+Enter to toggle fullscreen and windowed mode.");
const QString prevent_display_sleep = tr("Prevent the display from sleeping while a game is running.\nThis requires the org.freedesktop.ScreenSaver D-Bus service on Linux.\nThis option will be disabled if the current platform does not support display sleep control.");
const QString game_window_title_format = tr("Configure the game window title.\nChanging this and/or adding the framerate may cause buggy or outdated recording software to not notice RPCS3.");
const QString resize_on_boot = tr("Automatically resizes the game window on boot.\nThis does not change the internal game resolution.");
const QString show_trophy_popups = tr("Show trophy pop-ups when a trophy is unlocked.");
const QString show_rpcn_popups = tr("Show RPCN friend list pop-ups.");
const QString disable_mouse = tr("Disables the activation of fullscreen mode per double-click while the game screen is active.\nCheck this if you want to play with mouse and keyboard (for example with UCR).");
const QString disable_kb_hotkeys = tr("Disables keyboard hotkeys such as Ctrl+S, Ctrl+E, Ctrl+R, Ctrl+P while the game screen is active.\nThis does not include Ctrl+L (hide and lock mouse) and Alt+Enter (toggle fullscreen).\nCheck this if you want to play with mouse and keyboard.");
const QString max_llvm_threads = tr("Limits the maximum number of threads used for the initial PPU and SPU module compilation.\nLower this in order to increase performance of other open applications.\nThe default uses all available threads.");
const QString show_mouse_in_fullscreen = tr("Shows the mouse cursor when the fullscreen mode is active.\nCurrently this may not work every time.");
const QString lock_mouse_in_fullscreen = tr("Locks the mouse cursor to the center when the fullscreen mode is active.");
const QString hide_mouse_on_idle = tr("Hides the mouse cursor if no mouse movement is detected for the configured time.");
const QString show_shader_compilation_hint = tr("Shows 'Compiling shaders' hint using the native overlay.");
const QString show_ppu_compilation_hint = tr("Shows 'Compiling PPU modules' hint using the native overlay.");
const QString show_pressure_intensity_toggle_hint = tr("Shows pressure intensity toggle hint using the native overlay.");
const QString show_analog_limiter_toggle_hint = tr("Shows analog limiter toggle hint using the native overlay.");
const QString show_mouse_and_keyboard_toggle_hint = tr("Shows mouse and keyboard toggle hint using the native overlay.");
const QString show_autosave_autoload_hint = tr("Shows autosave/autoload hint using the native overlay.");
const QString use_native_interface = tr("Enables use of native HUD within the game window that can interact with game controllers.\nWhen disabled, regular Qt dialogs are used instead.\nCurrently, the on-screen keyboard only supports the English key layout.");
const QString pause_during_home_menu = tr("When enabled, opening the home menu will also pause emulation.\nWhile most games pause themselves while the home menu is shown, some do not.\nIn that case it can be helpful to pause the emulation whenever the home menu is open.");
const QString perf_overlay_enabled = tr("Enables or disables the performance overlay.");
const QString perf_overlay_framerate_graph_enabled = tr("Enables or disables the framerate graph.");
const QString perf_overlay_frametime_graph_enabled = tr("Enables or disables the frametime graph.");
const QString perf_overlay_framerate_datapoints = tr("Sets the amount of datapoints used in the framerate graph.");
const QString perf_overlay_frametime_datapoints = tr("Sets the amount of datapoints used in the frametime graph.");
const QString perf_overlay_position = tr("Sets the on-screen position (quadrant) of the performance overlay.");
const QString perf_overlay_detail_level = tr("Controls the amount of information displayed on the performance overlay.");
const QString perf_overlay_update_interval = tr("Sets the time interval in which the performance overlay is being updated (measured in milliseconds).\nSetting this to 16 milliseconds will refresh the performance overlay at roughly 60Hz.\nThe performance overlay refresh rate does not affect the frame graph statistics and can only be as fast as the current game allows.");
const QString perf_overlay_font_size = tr("Sets the font size of the performance overlay (measured in pixels).");
const QString perf_overlay_opacity = tr("Sets the opacity of the performance overlay (measured in %).");
const QString perf_overlay_margin_x = tr("Sets the horizontal distance to the screen border relative to the screen quadrant (measured in pixels).");
const QString perf_overlay_margin_y = tr("Sets the vertical distance to the screen border relative to the screen quadrant (measured in pixels).");
const QString perf_overlay_center_x = tr("Centers the performance overlay horizontally and overrides the horizontal margin.");
const QString perf_overlay_center_y = tr("Centers the performance overlay vertically and overrides the vertical margin.");
const QString shader_load_bg_enabled = tr("Shows a background image during the native shader loading dialog/loading screen.\nBy default the used image will be <gamedir>/PS3_GAME/PIC1.PNG or <gamedir>/PS3_GAME/PIC0.PNG.");
const QString shader_load_bg_darkening = tr("Changes the background image darkening effect strength of the native shader loading dialog.\nThis may be used to improve readability and/or aesthetics.");
const QString shader_load_bg_blur = tr("Changes the background image blur effect strength of the native shader loading dialog.\nThis may be used to improve readability and/or aesthetics.");
// gpu
const QString renderer = tr("Vulkan is the fastest renderer. OpenGL is the most accurate renderer.\nIf unsure, use Vulkan. Should you have any compatibility issues, fall back to OpenGL.");
const QString resolution = tr("This setting will be ignored if the Resolution Scale is set to anything other than 100%!\nLeave this on 1280x720. Every PS3 game is compatible with this resolution.\nOnly use 1920x1080 if the game supports it.\nRarely due to emulation bugs some games will only render at low resolutions like 480p.");
const QString graphics_adapter = tr("On multi GPU systems select which GPU to use in RPCS3 when using Vulkan.\nThis is not needed when using OpenGL.");
const QString aspect_ratio = tr("Leave this on 16:9 unless you have a 4:3 monitor.");
const QString frame_limit = tr("Off is the fastest option.\nUsing the frame limiter will add extra overhead and slow down the game. However, some games will crash if the framerate is too high.\nPS3 native should only be used if Auto is not working correctly as it can introduce frame-pacing issues.\nInfinite adds a positive feedback loop which adds another vblank signal per frame allowing more games to be fps limitless.\nExperienced users with need of other frame limits should use the setting \"Second Frame Limit\" in the configuration file.");
const QString anti_aliasing = tr("Emulate PS3 multisampling layout.\nCan fix some otherwise difficult to solve graphics glitches.\nLow to moderate performance hit depending on your GPU hardware.");
const QString anisotropic_filter = tr("Higher values increase sharpness of textures on sloped surfaces at the cost of GPU resources.\nModern GPUs can handle this setting just fine, even at 16x.\nKeep this on Automatic if you want to use the original setting used by a real PS3.");
const QString resolution_scale = tr("Scales the game's resolution by the given percentage.\nThe base resolution is always 1280x720.\nSet this value to 100% if you want to use the normal Resolution options.\nValues below 100% will usually not improve performance.");
const QString minimum_scalable_dimension = tr("Only framebuffers greater than this size will be upscaled.\nIncreasing this value might fix problems with missing graphics when upscaling, especially when Write Color Buffers is enabled.\nIf unsure, don't change this option.");
const QString dump_color = tr("Enable this option if you get missing graphics or broken lighting ingame.\nMight degrade performance and introduce stuttering in some cases.\nRequired for Demon's Souls.");
const QString vsync = tr("By having this off you might obtain a higher framerate at the cost of tearing artifacts in the game.");
const QString strict_rendering_mode = tr("Enforces strict compliance to the API specification.\nMight result in degraded performance in some games.\nCan resolve rare cases of missing graphics and flickering.\nIf unsure, don't use this option.");
const QString stretch_to_display_area = tr("Overrides the aspect ratio and stretches the image to the full display area.");
const QString multithreaded_rsx = tr("Offloads some RSX operations to a secondary thread.\nImproves performance for high-core processors.\nMay cause slowdown in weaker CPUs due to the extra worker thread load.");
const QString legacy_shader_recompiler = tr("Disables asynchronous shader compilation.\nFixes missing graphics while shaders are compiling but introduces severe stuttering or lag.\nUse this if you do not want to deal with graphics pop-in, or for testing before filing any bug reports.");
const QString async_shader_recompiler = tr("This is the recommended option.\nIf a shader is not found in the cache, nothing will be rendered for this shader until it has compiled.\nYou may experience graphics pop-in.");
const QString async_with_shader_interpreter = tr("Hybrid rendering mode.\nIf a shader is not found in the cache, the interpreter will be used to render approximated graphics for this shader until it has compiled.");
const QString shader_interpreter_only = tr("All rendering is handled by the interpreter with no attempt to compile native shaders.\nThis mode is very slow and experimental.");
const QString shader_compiler_threads = tr("Number of threads to use for the shader compiler backend.\nOnly has an impact when shader mode is set to one of the asynchronous modes.");
const QString shader_precision = tr("Controls the precision level of generated shaders. Low precision generates much faster code depending on the hardware, but can sometimes generate minor visual glitches or flicker.");
const QString async_texture_streaming = tr("Stream textures to GPU in parallel with 3D rendering using asynchronous compute.\nCan improve performance on more powerful GPUs that have spare headroom.\nOnly works with Vulkan renderer and greatly benefits from having MTRSX enabled if you have a capable CPU.");
const QString exclusive_fullscreen_mode = tr("Controls which fullscreen mode RPCS3 requests from drivers when using Vulkan renderer.\nAutomatic will let the driver choose an appropriate mode, while the other options will hint the drivers on whether they should use exclusive or borderless fullscreen.\nUsing Prefer borderless fullscreen option can help if you have issues with streaming RPCS3 gameplay or if your system incorrectly enables HDR mode when using fullscreen.");
const QString output_scaling_mode = tr("Final image filtering. Nearest applies no filtering, Bilinear smooths the image, and FidelityFX Super Resolution enhances upscaled images.\nIf the game is rendering at an internal resolution lower than your window resolution, FidelityFX will handle the upscale.\nFidelityFX can cause visual artifacts.\nFidelityFX does not work with stereo 3D output for now.");
const QString fsr_rcas_strength = tr("Control the sharpening strength applied by FidelityFX Super Resolution. Higher values will give sharper output but may introduce artifacts.");
const QString texture_lod_bias = tr("Changes Texture sampling accuracy. (Small changes have a big effect.)\nAvoid using values outside the range of -12 to +12 if you're unsure.\n-3 to +3 is plenty for most usecases");
// gui
const QString log_limit = tr("Sets the maximum amount of blocks that the log can display.\nThis usually equals the number of lines.\nSet 0 in order to remove the limit.");
const QString tty_limit = tr("Sets the maximum amount of blocks that the TTY can display.\nThis usually equals the number of lines.\nSet 0 in order to remove the limit.");
const QString stylesheets = tr("Changes the overall look of RPCS3.\nChoose a stylesheet and click Apply to change between styles.");
const QString show_welcome = tr("Shows the initial welcome screen upon starting RPCS3.");
const QString show_exit_game = tr("Shows a confirmation dialog when the game window is being closed.");
const QString show_boot_game = tr("Shows a confirmation dialog when a game was booted while another game is running.");
const QString show_pkg_install = tr("Shows a dialog when packages were installed successfully.");
const QString show_pup_install = tr("Shows a dialog when firmware was installed successfully.");
const QString show_obsolete_cfg = tr("Shows a dialog when obsolete settings were found.");
const QString show_same_buttons = tr("Shows a dialog in the game pad configuration when the same button was assigned twice.");
const QString show_restart_hint = tr("Shows a dialog when RPCS3 is ready to restart after an update.");
const QString check_update_start = tr("Checks if an update is available on startup and asks if you want to update.\nIf \"Automatic\" is selected, the update will run automatically without user confirmation.\nIf \"Background\" is selected, the check is done silently in the background and a new download option is shown in the top right corner of the menu if a new version was found.");
const QString use_rich_presence = tr("Enables use of Discord Rich Presence to show what game you are playing on Discord.\nRequires a restart of RPCS3 to completely close the connection.");
const QString discord_state = tr("Tell your friends what you are doing.");
const QString custom_colors = tr("Prioritize custom user interface colors over properties set in stylesheet.");
const QString uuid = tr("This is the ID used for hardware statistics.\nIt should only be reset if you change your hardware configuration or if you copied RPCS3 to another PC.");
const QString pad_navigation = tr("Use the game pad that is configured for player 1 to navigate in the GUI.");
const QString global_navigation = tr("Keep control over pad navigation if RPCS3 is not the active window.");
// input
const QString pad_mode = tr("Single-threaded: All pad handlers run on the same thread sequentially.\nMulti-threaded: Each pad handler has its own thread.\nOnly use multi-threaded if you can spare the extra threads.");
const QString pad_connection = tr("Shows all configured pads as always connected ingame even if they are physically disconnected.");
const QString keyboard_handler = tr("Some games support native keyboard input.\nBasic will work in these cases.");
const QString mouse_handler = tr("Some games support native mouse input.\nBasic or Raw will work in these cases.");
const QString music_handler = tr("Currently only used for cellMusic emulation.\nSelect Qt to use the default output device of your operating system.\nThis may not be able to play all audio formats.");
const QString camera = tr("Select Qt Camera to use the default camera device of your operating system.");
const QString camera_type = tr("Depending on the game, you may need to select a specific camera type.");
const QString camera_flip = tr("Flips the camera image either horizontally, vertically, or on both axes.");
const QString camera_id = tr("Select the camera that you want to use during gameplay.");
const QString move = tr("PlayStation Move support.\nFake: Experimental! This maps Move controls to DS3 controller mappings.\nMouse: Emulate PSMove with Mouse handler.\nRaw Mouse: Emulate PSMove with Raw Mouse handler.");
const QString buzz = tr("Buzz! support.\nSelect 1 or 2 controllers if the game requires Buzz! controllers and you don't have real controllers.\nSelect Null if the game has support for DualShock or if you have real Buzz! controllers.");
const QString turntable = tr("DJ Hero Turntable controller support.\nSelect 1 or 2 controllers if the game requires DJ Hero Turntable controllers and you don't have real turntable controllers.\nSelect Null if the game has support for DualShock or if you have real turntable controllers.\nA real turntable controller can be used at the same time as an emulated turntable controller.");
const QString ghltar = tr("Guitar Hero Live (GHL) Guitar controller support.\nSelect 1 or 2 controllers if the game requires GHL Guitar controllers and you don't have real guitar controllers.\nSelect Null if the game has support for DualShock or if you have real guitar controllers.\nA real guitar controller can be used at the same time as an emulated guitar controller.");
const QString background_input = tr("Allows pad and keyboard input while the game window is unfocused.");
const QString show_move_cursor = tr("Shows the raw position of the PS Move input.\nThis can be very helpful during calibration screens.");
const QString midi_devices = tr("Select up to 3 emulated MIDI devices and their types.");
const QString sdl_mappings = tr("Loads the SDL GameController database for improved gamepad compatibility. Only used in the SDL pad handler.");
const QString lock_overlay_input_to_player_one = tr("Locks the native overlay input to the first player.");
// network
const QString net_status = tr("If set to Connected, RPCS3 will allow programs to use your internet connection.");
const QString psn_status = tr("If set to RPCN, RPCS3 will use the RPCN server as PSN connection if the game is supported.\nIf set to Simulated, RPCS3 will try to fake the PSN connection, but any actual attempt at using the PSN functionality may result in errors or crashes.\nSimulated is only available in custom configurations.");
const QString dns = tr("DNS used to resolve hostnames by applications.");
const QString dns_swap = tr("DNS Swap List.\nOnly available in custom configurations.");
const QString bind = tr("Interface IP Address to bind to.\nOnly available in custom configurations.");
const QString enable_upnp = tr("Enable UPNP.\nThis will automatically forward ports bound on 0.0.0.0 if your router has UPNP enabled.");
const QString psn_country = tr("Changes the RPCN country.");
// system
const QString license_area = tr("The console region defines the license area of the PS3.\nDepending on the license area, some games may not work.");
const QString system_language = tr("Some games may fail to boot if the system language is not available in the game itself.\nOther games will switch language automatically to what is selected here.\nIt is recommended leaving this on a language supported by the game.");
const QString keyboard_type = tr("Sets the used keyboard layout.\nCurrently only US, Japanese and German layouts are fully supported at this moment.");
const QString enter_button_assignment = tr("The button used for enter/accept/confirm in system dialogs.\nChange this to use the Circle button instead, which is the default configuration on Japanese systems and in many Japanese games.\nIn these cases having the cross button assigned can often lead to confusion.");
const QString enable_host_root = tr("Required for some Homebrew.\nIf unsure, don't use this option.");
const QString limit_cache_size = tr("Automatically removes older files from disk cache on boot if it grows larger than the specified value.\nGames can use the cache folder to temporarily store data outside of system memory. It is not used for long-term storage.\n\nThis setting is only available in the global configuration.");
const QString console_time_offset = tr("Sets the time to be used within the console. This will be applied as an offset that tracks wall clock time.\nCan be reset to current wall clock time by clicking \"Set to Now\".");
} settings;
const struct gamepad_settings
{
const QString null = tr("This controller is disabled and will appear as disconnected to software. Choose another handler to enable it.");
const QString ldd_pad = tr("This port is currently assigned to a custom controller by the application and can't be changed.");
const QString keyboard = tr("While it is possible to use a keyboard as a pad in RPCS3, the use of an actual controller is strongly recommended.<br>To bind mouse movement to a button or joystick, click on the desired button to activate it, then click and hold while dragging the mouse to a direction.");
const QString ds3_windows = tr("In order to use the DualShock 3 handler, you need to install the official DualShock 3 driver first.<br>See the <a %0 href=\"https://wiki.rpcs3.net/index.php?title=Help:Controller_Configuration\">RPCS3 Wiki</a> for instructions.").arg(gui::utils::get_link_style());
const QString ds3_linux = tr("In order to use the DualShock 3 handler, you might need to add udev rules to let RPCS3 access the controller.<br>See the <a %0 href=\"https://wiki.rpcs3.net/index.php?title=Help:Controller_Configuration\">RPCS3 Wiki</a> for instructions.").arg(gui::utils::get_link_style());
const QString ds3_other = tr("The DualShock 3 handler is recommended for official DualShock 3 controllers.");
const QString ds4_windows = tr("If you have any issues with the DualShock 4 handler, it might be caused by third-party tools such as DS4Windows. It's recommended that you disable them while using this handler.");
const QString ds4_linux = tr("In order to use the DualShock 4 handler, you might need to add udev rules to let RPCS3 access the controller.<br>See the <a %0 href=\"https://wiki.rpcs3.net/index.php?title=Help:Controller_Configuration\">RPCS3 Wiki</a> for instructions.").arg(gui::utils::get_link_style());
const QString ds4_other = tr("The DualShock 4 handler is recommended for official DualShock 4 controllers.");
const QString dualsense_windows = tr("The DualSense handler is recommended for official DualSense controllers.");
const QString dualsense_linux = tr("The DualSense handler is recommended for official DualSense controllers.");
const QString dualsense_other = tr("The DualSense handler is recommended for official DualSense controllers.");
const QString skateboard = tr("The Skateboard handler is recommended for official RIDE skateboard controllers.");
const QString xinput = tr("The XInput handler will work with Xbox controllers and many third-party PC-compatible controllers. Pressure sensitive buttons from SCP are supported when SCP's XInput1_3.dll is placed in the main RPCS3 directory. For more details, see the <a %0 href=\"https://wiki.rpcs3.net/index.php?title=Help:Controller_Configuration\">RPCS3 Wiki</a>.").arg(gui::utils::get_link_style());
const QString evdev = tr("The evdev handler should work with any controller that has Linux support.<br>If your joystick is not being centered properly, read the <a %0 href=\"https://wiki.rpcs3.net/index.php?title=Help:Controller_Configuration\">RPCS3 Wiki</a> for instructions.").arg(gui::utils::get_link_style());
const QString mmjoy = tr("The MMJoystick handler should work with almost any controller recognized by Windows. However, it is recommended that you use the more specific handlers if you have a controller that supports them.");
const QString sdl = tr("The SDL handler supports a variety of controllers across different platforms.");
const QString analog_limiter = tr("Applies the stick multipliers while this special button is pressed.<br>Enable \"Toggle\" if you want to toggle the analog limiter on button press instead.");
const QString pressure_intensity = tr("Controls the intensity of pressure sensitive buttons while this special button is pressed.<br>Enable \"Toggle\" if you want to toggle the intensity on button press instead.<br>Use the percentage to change how hard you want to press a button.");
const QString pressure_deadzone = tr("Controls the deadzone of pressure sensitive buttons. It determines how far the button has to be pressed until it is recognized by the game. The resulting range will be projected onto the full button sensitivity range.");
const QString squircle_factor = tr("The actual DualShock 3's stick range is not circular but formed like a rounded square (or squircle) which represents the maximum range of the emulated sticks. You can use the squircle values to modify the stick input if your sticks can't reach the corners of that range. A value of 0 does not apply any so called squircling. A value of 8000 is usually recommended.");
const QString stick_multiplier = tr("The stick multipliers can be used to change the sensitivity of your stick movements.<br>The default setting is 1 and represents normal input.");
const QString stick_deadzones = tr("A stick's deadzone determines how far the stick has to be moved until it is fully recognized by the game. The resulting range will be projected onto the full input range in order to give you a smooth experience. Movement inside the deadzone is simulated using the anti-deadzone slider (default is 13%), so don't worry if there is still movement shown in the emulated stick preview.");
const QString vibration = tr("The PS3 activates two motors (large and small) to handle controller vibrations.<br>You can enable, disable or even switch these signals for the currently selected pad here.");
const QString motion_controls = tr("Use this to configure the gamepad motion controls.");
const QString emulated_preview = tr("The emulated stick values (red dots) in the stick preview represent the actual stick positions as they will be visible to the game. The actual DualShock 3's stick range is not circular but formed like a rounded square (or squircle) which represents the maximum range of the emulated sticks. The blue regular dots represent the raw stick values (including stick multipliers) before they are converted for ingame usage.");
const QString trigger_deadzones = tr("A trigger's deadzone determines how far the trigger has to be moved until it is recognized by the game. The resulting range will be projected onto the full input range in order to give you a smooth experience.");
const QString stick_lerp = tr("With keyboards, you are inevitably restricted to 8 stick directions (4 straight + 4 diagonal). Furthermore, the stick will jump to the maximum value of the chosen direction immediately when a key is pressed. The stick interpolation can be used to work-around both of these issues by smoothening out these directional changes. The lower the value, the longer you have to press or release a key until the maximum amplitude is reached.");
const QString mouse_deadzones = tr("The mouse deadzones represent the games' own deadzones on the x and y axes. Games usually enforce their own deadzones to filter out small unwanted stick movements. In consequence, mouse input feels unintuitive since it relies on immediate responsiveness. You can change these values temporarily during gameplay in order to find out the optimal values for your game (Alt+T and Alt+Y for x, Alt+U and Alt+I for y).");
const QString mouse_acceleration = tr("The mouse acceleration can be used to amplify your mouse movements on the x and y axes. Increase these values if your mouse movements feel too slow while playing a game. You can change these values temporarily during gameplay in order to find out the optimal values (Alt+G and Alt+H for x, Alt+J and Alt+K for y). Keep in mind that modern mice usually provide different modes and settings that can be used to change mouse movement speeds as well.");
const QString mouse_movement = tr("The mouse movement mode determines how the mouse movement is translated to pad input.<br>Use the relative mode for traditional mouse movement.<br>Use the absolute mode to use the mouse's distance to the center of the screen as input value.");
const QString button_assignment = tr("Left-click: remap this button.<br>Shift + Left-click: add an additional button mapping.<br>Alt + Left-click: differentiate between trigger press and release (only XInput for now).<br>Right-click: clear this button mapping.");
} gamepad_settings;
};
| 50,861
|
C++
|
.h
| 269
| 186.033457
| 620
| 0.756152
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,710
|
raw_mouse_settings_dialog.h
|
RPCS3_rpcs3/rpcs3/rpcs3qt/raw_mouse_settings_dialog.h
|
#pragma once
#include "util/types.hpp"
#include <QButtonGroup>
#include <QComboBox>
#include <QDialogButtonBox>
#include <QDialog>
#include <QDoubleSpinBox>
#include <QMouseEvent>
#include <QPalette>
#include <QPushButton>
#include <QTabWidget>
#include <QTimer>
#include <vector>
#include <unordered_map>
class raw_mouse_settings_dialog : public QDialog
{
Q_OBJECT
public:
raw_mouse_settings_dialog(QWidget* parent = nullptr);
virtual ~raw_mouse_settings_dialog();
private:
void update_combo_box(usz player);
void add_tabs(QTabWidget* tabs);
void on_enumeration();
void reset_config();
void on_button_click(int id);
void mouse_press(const std::string& device_name, s32 cell_code, bool pressed);
void handle_device_change(const std::string& device_name);
bool is_device_active(const std::string& device_name);
std::string get_current_device_name(int player);
void reactivate_buttons();
QTabWidget* m_tab_widget = nullptr;
std::vector<QComboBox*> m_device_combos;
std::vector<QDoubleSpinBox*> m_accel_spin_boxes;
// Buttons
QDialogButtonBox* m_button_box = nullptr;
QButtonGroup* m_buttons = nullptr;
std::vector<std::unordered_map<int, QPushButton*>> m_push_buttons;
int m_button_id = -1;
// Backup for standard button palette
QPalette m_palette;
// Remap Timer
static constexpr int MAX_SECONDS = 5;
int m_seconds = MAX_SECONDS;
QTimer m_remap_timer;
QTimer m_mouse_release_timer;
bool m_disable_mouse_release_event = false;
// Update Timer
QTimer m_update_timer;
protected:
bool eventFilter(QObject* object, QEvent* event) override;
};
| 1,581
|
C++
|
.h
| 52
| 28.557692
| 79
| 0.771918
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,711
|
curl_handle.h
|
RPCS3_rpcs3/rpcs3/rpcs3qt/curl_handle.h
|
#pragma once
#include <array>
#ifndef CURL_STATICLIB
#define CURL_STATICLIB
#endif
#include <curl/curl.h>
namespace rpcs3::curl
{
inline bool g_curl_verbose = false;
class curl_handle
{
public:
explicit curl_handle();
~curl_handle();
CURL* get_curl() const;
operator CURL*() const
{
return get_curl();
}
void reset_error_buffer();
std::string get_verbose_error(CURLcode code) const;
private:
CURL* m_curl = nullptr;
bool m_uses_error_buffer = false;
std::array<char, CURL_ERROR_SIZE> m_error_buffer;
};
}
| 527
|
C++
|
.h
| 27
| 17.703704
| 52
| 0.747454
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,712
|
localized.h
|
RPCS3_rpcs3/rpcs3/rpcs3qt/localized.h
|
#pragma once
#include "category.h"
#include <QString>
#include <QObject>
#include "util/types.hpp"
typedef std::map<const QString, const QString> localized_cat;
class Localized : public QObject
{
Q_OBJECT
public:
Localized() {}
QString GetVerboseTimeByMs(quint64 elapsed_ms, bool show_days = false) const;
static std::string GetStringFromU32(const u32& key, const std::map<u32, QString>& map, bool combined = false);
const struct category // (see PARAM.SFO in psdevwiki.com) TODO: Disc Categories
{
// PS3 bootable
const QString app_music = tr("Music App");
const QString app_photo = tr("Photo App");
const QString app_store = tr("Store App");
const QString app_tv = tr("TV App");
const QString app_video = tr("Video App");
const QString bc_video = tr("Broadcast Video");
const QString disc_game = tr("Disc Game");
const QString hdd_game = tr("HDD Game");
const QString home = tr("Home");
const QString network = tr("Network");
const QString store_fe = tr("Store");
const QString web_tv = tr("Web TV");
const QString os_app = tr("Operating System");
// PS2 bootable
const QString ps2_game = tr("PS2 Classics");
const QString ps2_inst = tr("PS2 Game");
// PS1 bootable
const QString ps1_game = tr("PS1 Classics");
// PSP bootable
const QString psp_game = tr("PSP Game");
const QString psp_mini = tr("PSP Minis");
const QString psp_rema = tr("PSP Remasters");
// Data
const QString ps3_data = tr("PS3 Game Data");
const QString ps2_data = tr("PS2 Emulator Data");
// Save
const QString ps3_save = tr("PS3 Save Data");
const QString psp_save = tr("PSP Minis Save Data");
// others
const QString trophy = tr("Trophy");
const QString unknown = tr("Unknown");
const QString other = tr("Other");
const localized_cat cat_boot =
{
{ cat::cat_app_music, app_music }, // media
{ cat::cat_app_photo, app_photo }, // media
{ cat::cat_app_store, app_store }, // media
{ cat::cat_app_tv , app_tv }, // media
{ cat::cat_app_video, app_video }, // media
{ cat::cat_bc_video , bc_video }, // media
{ cat::cat_web_tv , web_tv }, // media
{ cat::cat_home , home }, // home
{ cat::cat_network , network }, // other
{ cat::cat_store_fe , store_fe }, // other
{ cat::cat_disc_game, disc_game }, // disc_game
{ cat::cat_hdd_game , hdd_game }, // hdd_game
{ cat::cat_ps2_game , ps2_game }, // ps2_games
{ cat::cat_ps2_inst , ps2_inst }, // ps2_games
{ cat::cat_ps1_game , ps1_game }, // ps1_game
{ cat::cat_psp_game , psp_game }, // psp_games
{ cat::cat_psp_mini , psp_mini }, // psp_games
{ cat::cat_psp_rema , psp_rema }, // psp_games
{ cat::cat_ps3_os , os_app }, // other
};
const localized_cat cat_data =
{
{ cat::cat_ps3_data, ps3_data }, // data
{ cat::cat_ps2_data, ps2_data }, // data
{ cat::cat_ps3_save, ps3_save }, // data
{ cat::cat_psp_save, psp_save } // data
};
} category;
const struct parental
{
// These values are partly generalized. They can vary between country and category
// Normally only values 1,2,3,5,7 and 9 are used
const std::map<u32, QString> level
{
{ 1, tr("0+") },
{ 2, tr("3+") },
{ 3, tr("7+") },
{ 4, tr("10+") },
{ 5, tr("12+") },
{ 6, tr("15+") },
{ 7, tr("16+") },
{ 8, tr("17+") },
{ 9, tr("18+") },
{ 10, tr("Level 10") },
{ 11, tr("Level 11") }
};
} parental;
const struct resolution
{
// there might be different values for other categories
resolution();
const std::map<u32, QString> mode;
} resolution;
const struct sound
{
sound();
const std::map<u32, QString> format;
} sound;
const struct title_t
{
title_t();
const std::map<std::string, QString> titles;
} title;
};
| 3,802
|
C++
|
.h
| 114
| 30.219298
| 111
| 0.623773
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,713
|
game_list_grid.h
|
RPCS3_rpcs3/rpcs3/rpcs3qt/game_list_grid.h
|
#pragma once
#include "game_list_base.h"
#include "flow_widget.h"
#include <QKeyEvent>
class game_list_grid : public flow_widget, public game_list_base
{
Q_OBJECT
public:
explicit game_list_grid();
void clear_list() override;
void populate(
const std::vector<game_info>& game_data,
const std::map<QString, QString>& notes_map,
const std::map<QString, QString>& title_map,
const std::string& selected_item_id,
bool play_hover_movies) override;
void repaint_icons(std::vector<game_info>& game_data, const QColor& icon_color, const QSize& icon_size, qreal device_pixel_ratio) override;
bool eventFilter(QObject* watched, QEvent* event) override;
void keyPressEvent(QKeyEvent* event) override;
public Q_SLOTS:
void FocusAndSelectFirstEntryIfNoneIs();
Q_SIGNALS:
void FocusToSearchBar();
void ItemDoubleClicked(const game_info& game);
void ItemSelectionChanged(const game_info& game);
void IconReady(const game_info& game);
};
| 954
|
C++
|
.h
| 27
| 33.148148
| 140
| 0.776445
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,714
|
save_data_info_dialog.h
|
RPCS3_rpcs3/rpcs3/rpcs3qt/save_data_info_dialog.h
|
#pragma once
// I just want the struct for the save data.
#include "Emu/Cell/Modules/cellSaveData.h"
#include <QDialog>
#include <QTableWidget>
//Used to display the information of a savedata.
class save_data_info_dialog :public QDialog
{
Q_OBJECT
public:
explicit save_data_info_dialog(SaveDataEntry save, QWidget* parent = nullptr);
private:
void UpdateData();
SaveDataEntry m_entry;
QTableWidget* m_list;
};
| 421
|
C++
|
.h
| 16
| 24.6875
| 79
| 0.79
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.