diff options
Diffstat (limited to 'src')
55 files changed, 705 insertions, 141 deletions
diff --git a/src/citra/citra.cpp b/src/citra/citra.cpp index 14574e56c..e524c5535 100644 --- a/src/citra/citra.cpp +++ b/src/citra/citra.cpp @@ -165,6 +165,8 @@ int main(int argc, char** argv) { break; // Expected case } + Core::Telemetry().AddField(Telemetry::FieldType::App, "Frontend", "SDL"); + while (emu_window->IsOpen()) { system.RunLoop(); } diff --git a/src/citra/config.cpp b/src/citra/config.cpp index 73846ed91..a48ef08c7 100644 --- a/src/citra/config.cpp +++ b/src/citra/config.cpp @@ -78,6 +78,8 @@ void Config::ReadValues() { Settings::values.motion_device = sdl2_config->Get( "Controls", "motion_device", "engine:motion_emu,update_period:100,sensitivity:0.01"); + Settings::values.touch_device = + sdl2_config->Get("Controls", "touch_device", "engine:emu_window"); // Core Settings::values.use_cpu_jit = sdl2_config->GetBoolean("Core", "use_cpu_jit", true); @@ -156,8 +158,12 @@ void Config::ReadValues() { static_cast<u16>(sdl2_config->GetInteger("Debugging", "gdbstub_port", 24689)); // Web Service + Settings::values.enable_telemetry = + sdl2_config->GetBoolean("WebService", "enable_telemetry", true); Settings::values.telemetry_endpoint_url = sdl2_config->Get( "WebService", "telemetry_endpoint_url", "https://services.citra-emu.org/api/telemetry"); + Settings::values.citra_username = sdl2_config->Get("WebService", "citra_username", ""); + Settings::values.citra_token = sdl2_config->Get("WebService", "citra_token", ""); } void Config::Reload() { diff --git a/src/citra/default_ini.h b/src/citra/default_ini.h index 9ea779dd8..4b13a2e1b 100644 --- a/src/citra/default_ini.h +++ b/src/citra/default_ini.h @@ -62,6 +62,10 @@ c_stick= # - "sensitivity": the coefficient converting mouse movement to tilting angle (default to 0.01) motion_device= +# for touch input, the following devices are available: +# - "emu_window" (default) for emulating touch input from mouse input to the emulation window. No parameters required +touch_device= + [Core] # Whether to use the Just-In-Time (JIT) compiler for CPU emulation # 0: Interpreter (slow), 1 (default): JIT (fast) @@ -176,7 +180,14 @@ use_gdbstub=false gdbstub_port=24689 [WebService] +# Whether or not to enable telemetry +# 0: No, 1 (default): Yes +enable_telemetry = # Endpoint URL for submitting telemetry data -telemetry_endpoint_url = +telemetry_endpoint_url = https://services.citra-emu.org/api/telemetry +# Username and token for Citra Web Service +# See https://services.citra-emu.org/ for more info +citra_username = +citra_token = )"; } diff --git a/src/citra_qt/CMakeLists.txt b/src/citra_qt/CMakeLists.txt index f364b2284..e0a19fd9e 100644 --- a/src/citra_qt/CMakeLists.txt +++ b/src/citra_qt/CMakeLists.txt @@ -12,6 +12,7 @@ set(SRCS configuration/configure_graphics.cpp configuration/configure_input.cpp configuration/configure_system.cpp + configuration/configure_web.cpp debugger/graphics/graphics.cpp debugger/graphics/graphics_breakpoint_observer.cpp debugger/graphics/graphics_breakpoints.cpp @@ -42,6 +43,7 @@ set(HEADERS configuration/configure_graphics.h configuration/configure_input.h configuration/configure_system.h + configuration/configure_web.h debugger/graphics/graphics.h debugger/graphics/graphics_breakpoint_observer.h debugger/graphics/graphics_breakpoints.h @@ -71,6 +73,7 @@ set(UIS configuration/configure_graphics.ui configuration/configure_input.ui configuration/configure_system.ui + configuration/configure_web.ui debugger/registers.ui hotkeys.ui main.ui diff --git a/src/citra_qt/configuration/config.cpp b/src/citra_qt/configuration/config.cpp index 6e42db007..ef114aad3 100644 --- a/src/citra_qt/configuration/config.cpp +++ b/src/citra_qt/configuration/config.cpp @@ -61,6 +61,8 @@ void Config::ReadValues() { qt_config->value("motion_device", "engine:motion_emu,update_period:100,sensitivity:0.01") .toString() .toStdString(); + Settings::values.touch_device = + qt_config->value("touch_device", "engine:emu_window").toString().toStdString(); qt_config->endGroup(); @@ -139,10 +141,13 @@ void Config::ReadValues() { qt_config->endGroup(); qt_config->beginGroup("WebService"); + Settings::values.enable_telemetry = qt_config->value("enable_telemetry", true).toBool(); Settings::values.telemetry_endpoint_url = qt_config->value("telemetry_endpoint_url", "https://services.citra-emu.org/api/telemetry") .toString() .toStdString(); + Settings::values.citra_username = qt_config->value("citra_username").toString().toStdString(); + Settings::values.citra_token = qt_config->value("citra_token").toString().toStdString(); qt_config->endGroup(); qt_config->beginGroup("UI"); @@ -194,6 +199,7 @@ void Config::ReadValues() { UISettings::values.show_status_bar = qt_config->value("showStatusBar", true).toBool(); UISettings::values.confirm_before_closing = qt_config->value("confirmClose", true).toBool(); UISettings::values.first_start = qt_config->value("firstStart", true).toBool(); + UISettings::values.callout_flags = qt_config->value("calloutFlags", 0).toUInt(); qt_config->endGroup(); } @@ -209,6 +215,7 @@ void Config::SaveValues() { QString::fromStdString(Settings::values.analogs[i])); } qt_config->setValue("motion_device", QString::fromStdString(Settings::values.motion_device)); + qt_config->setValue("touch_device", QString::fromStdString(Settings::values.touch_device)); qt_config->endGroup(); qt_config->beginGroup("Core"); @@ -283,8 +290,11 @@ void Config::SaveValues() { qt_config->endGroup(); qt_config->beginGroup("WebService"); + qt_config->setValue("enable_telemetry", Settings::values.enable_telemetry); qt_config->setValue("telemetry_endpoint_url", QString::fromStdString(Settings::values.telemetry_endpoint_url)); + qt_config->setValue("citra_username", QString::fromStdString(Settings::values.citra_username)); + qt_config->setValue("citra_token", QString::fromStdString(Settings::values.citra_token)); qt_config->endGroup(); qt_config->beginGroup("UI"); @@ -320,6 +330,7 @@ void Config::SaveValues() { qt_config->setValue("showStatusBar", UISettings::values.show_status_bar); qt_config->setValue("confirmClose", UISettings::values.confirm_before_closing); qt_config->setValue("firstStart", UISettings::values.first_start); + qt_config->setValue("calloutFlags", UISettings::values.callout_flags); qt_config->endGroup(); } diff --git a/src/citra_qt/configuration/configure.ui b/src/citra_qt/configuration/configure.ui index 85e206e42..6abd1917e 100644 --- a/src/citra_qt/configuration/configure.ui +++ b/src/citra_qt/configuration/configure.ui @@ -6,8 +6,8 @@ <rect> <x>0</x> <y>0</y> - <width>441</width> - <height>501</height> + <width>740</width> + <height>500</height> </rect> </property> <property name="windowTitle"> @@ -49,6 +49,11 @@ <string>Debug</string> </attribute> </widget> + <widget class="ConfigureWeb" name="webTab"> + <attribute name="title"> + <string>Web</string> + </attribute> + </widget> </widget> </item> <item> @@ -97,6 +102,12 @@ <header>configuration/configure_graphics.h</header> <container>1</container> </customwidget> + <customwidget> + <class>ConfigureWeb</class> + <extends>QWidget</extends> + <header>configuration/configure_web.h</header> + <container>1</container> + </customwidget> </customwidgets> <resources/> <connections> diff --git a/src/citra_qt/configuration/configure_dialog.cpp b/src/citra_qt/configuration/configure_dialog.cpp index dfc8c03a7..b87dc0e6c 100644 --- a/src/citra_qt/configuration/configure_dialog.cpp +++ b/src/citra_qt/configuration/configure_dialog.cpp @@ -23,5 +23,6 @@ void ConfigureDialog::applyConfiguration() { ui->graphicsTab->applyConfiguration(); ui->audioTab->applyConfiguration(); ui->debugTab->applyConfiguration(); + ui->webTab->applyConfiguration(); Settings::Apply(); } diff --git a/src/citra_qt/configuration/configure_graphics.ui b/src/citra_qt/configuration/configure_graphics.ui index 228f2a869..b340149d5 100644 --- a/src/citra_qt/configuration/configure_graphics.ui +++ b/src/citra_qt/configuration/configure_graphics.ui @@ -146,17 +146,22 @@ <widget class="QComboBox" name="layout_combobox"> <item> <property name="text"> - <string notr="true">Default</string> + <string>Default</string> </property> </item> <item> <property name="text"> - <string notr="true">Single Screen</string> + <string>Single Screen</string> </property> </item> <item> <property name="text"> - <string notr="true">Large Screen</string> + <string>Large Screen</string> + </property> + </item> + <item> + <property name="text"> + <string>Side by Side</string> </property> </item> </widget> diff --git a/src/citra_qt/configuration/configure_web.cpp b/src/citra_qt/configuration/configure_web.cpp new file mode 100644 index 000000000..8715fb018 --- /dev/null +++ b/src/citra_qt/configuration/configure_web.cpp @@ -0,0 +1,52 @@ +// Copyright 2017 Citra Emulator Project +// Licensed under GPLv2 or any later version +// Refer to the license.txt file included. + +#include "citra_qt/configuration/configure_web.h" +#include "core/settings.h" +#include "core/telemetry_session.h" +#include "ui_configure_web.h" + +ConfigureWeb::ConfigureWeb(QWidget* parent) + : QWidget(parent), ui(std::make_unique<Ui::ConfigureWeb>()) { + ui->setupUi(this); + connect(ui->button_regenerate_telemetry_id, &QPushButton::clicked, this, + &ConfigureWeb::refreshTelemetryID); + + this->setConfiguration(); +} + +ConfigureWeb::~ConfigureWeb() {} + +void ConfigureWeb::setConfiguration() { + ui->web_credentials_disclaimer->setWordWrap(true); + ui->telemetry_learn_more->setOpenExternalLinks(true); + ui->telemetry_learn_more->setText("<a " + "href='https://citra-emu.org/entry/" + "telemetry-and-why-thats-a-good-thing/'>Learn more</a>"); + + ui->web_signup_link->setOpenExternalLinks(true); + ui->web_signup_link->setText("<a href='https://services.citra-emu.org/'>Sign up</a>"); + ui->web_token_info_link->setOpenExternalLinks(true); + ui->web_token_info_link->setText( + "<a href='https://citra-emu.org/wiki/citra-web-service/'>What is my token?</a>"); + + ui->toggle_telemetry->setChecked(Settings::values.enable_telemetry); + ui->edit_username->setText(QString::fromStdString(Settings::values.citra_username)); + ui->edit_token->setText(QString::fromStdString(Settings::values.citra_token)); + ui->label_telemetry_id->setText("Telemetry ID: 0x" + + QString::number(Core::GetTelemetryId(), 16).toUpper()); +} + +void ConfigureWeb::applyConfiguration() { + Settings::values.enable_telemetry = ui->toggle_telemetry->isChecked(); + Settings::values.citra_username = ui->edit_username->text().toStdString(); + Settings::values.citra_token = ui->edit_token->text().toStdString(); + Settings::Apply(); +} + +void ConfigureWeb::refreshTelemetryID() { + const u64 new_telemetry_id{Core::RegenerateTelemetryId()}; + ui->label_telemetry_id->setText("Telemetry ID: 0x" + + QString::number(new_telemetry_id, 16).toUpper()); +} diff --git a/src/citra_qt/configuration/configure_web.h b/src/citra_qt/configuration/configure_web.h new file mode 100644 index 000000000..20bc254b9 --- /dev/null +++ b/src/citra_qt/configuration/configure_web.h @@ -0,0 +1,30 @@ +// Copyright 2017 Citra Emulator Project +// Licensed under GPLv2 or any later version +// Refer to the license.txt file included. + +#pragma once + +#include <memory> +#include <QWidget> + +namespace Ui { +class ConfigureWeb; +} + +class ConfigureWeb : public QWidget { + Q_OBJECT + +public: + explicit ConfigureWeb(QWidget* parent = nullptr); + ~ConfigureWeb(); + + void applyConfiguration(); + +public slots: + void refreshTelemetryID(); + +private: + void setConfiguration(); + + std::unique_ptr<Ui::ConfigureWeb> ui; +}; diff --git a/src/citra_qt/configuration/configure_web.ui b/src/citra_qt/configuration/configure_web.ui new file mode 100644 index 000000000..d8d283fad --- /dev/null +++ b/src/citra_qt/configuration/configure_web.ui @@ -0,0 +1,153 @@ +<?xml version="1.0" encoding="UTF-8"?> +<ui version="4.0"> + <class>ConfigureWeb</class> + <widget class="QWidget" name="ConfigureWeb"> + <property name="geometry"> + <rect> + <x>0</x> + <y>0</y> + <width>400</width> + <height>300</height> + </rect> + </property> + <property name="windowTitle"> + <string>Form</string> + </property> + <layout class="QVBoxLayout" name="verticalLayout"> + <item> + <layout class="QVBoxLayout" name="verticalLayout_3"> + <item> + <widget class="QGroupBox" name="groupBoxWebConfig"> + <property name="title"> + <string>Citra Web Service</string> + </property> + <layout class="QVBoxLayout" name="verticalLayoutCitraWebService"> + <item> + <widget class="QLabel" name="web_credentials_disclaimer"> + <property name="text"> + <string>By providing your username and token, you agree to allow Citra to collect additional usage data, which may include user identifying information.</string> + </property> + </widget> + </item> + <item> + <layout class="QGridLayout" name="gridLayoutCitraUsername"> + <item row="0" column="0"> + <widget class="QLabel" name="label_username"> + <property name="text"> + <string>Username: </string> + </property> + </widget> + </item> + <item row="0" column="1"> + <widget class="QLineEdit" name="edit_username"> + <property name="maxLength"> + <number>36</number> + </property> + </widget> + </item> + <item row="1" column="0"> + <widget class="QLabel" name="label_token"> + <property name="text"> + <string>Token: </string> + </property> + </widget> + </item> + <item row="1" column="1"> + <widget class="QLineEdit" name="edit_token"> + <property name="maxLength"> + <number>36</number> + </property> + <property name="echoMode"> + <enum>QLineEdit::Password</enum> + </property> + </widget> + </item> + <item row="2" column="0"> + <widget class="QLabel" name="web_signup_link"> + <property name="text"> + <string>Sign up</string> + </property> + </widget> + </item> + <item row="2" column="1"> + <widget class="QLabel" name="web_token_info_link"> + <property name="text"> + <string>What is my token?</string> + </property> + </widget> + </item> + </layout> + </item> + </layout> + </widget> + </item> + <item> + <widget class="QGroupBox" name="groupBox"> + <property name="title"> + <string>Telemetry</string> + </property> + <layout class="QVBoxLayout" name="verticalLayout_2"> + <item> + <widget class="QCheckBox" name="toggle_telemetry"> + <property name="text"> + <string>Share anonymous usage data with the Citra team</string> + </property> + </widget> + </item> + <item> + <widget class="QLabel" name="telemetry_learn_more"> + <property name="text"> + <string>Learn more</string> + </property> + </widget> + </item> + <item> + <layout class="QGridLayout" name="gridLayoutTelemetryId"> + <item row="0" column="0"> + <widget class="QLabel" name="label_telemetry_id"> + <property name="text"> + <string>Telemetry ID:</string> + </property> + </widget> + </item> + <item row="0" column="1"> + <widget class="QPushButton" name="button_regenerate_telemetry_id"> + <property name="sizePolicy"> + <sizepolicy hsizetype="Fixed" vsizetype="Fixed"> + <horstretch>0</horstretch> + <verstretch>0</verstretch> + </sizepolicy> + </property> + <property name="layoutDirection"> + <enum>Qt::RightToLeft</enum> + </property> + <property name="text"> + <string>Regenerate</string> + </property> + </widget> + </item> + </layout> + </item> + </layout> + </widget> + </item> + </layout> + </item> + <item> + <spacer name="verticalSpacer"> + <property name="orientation"> + <enum>Qt::Vertical</enum> + </property> + <property name="sizeHint" stdset="0"> + <size> + <width>20</width> + <height>40</height> + </size> + </property> + </spacer> + </item> + </layout> + </widget> + <resources/> + <connections/> +</ui> diff --git a/src/citra_qt/main.cpp b/src/citra_qt/main.cpp index c1ae0ccc8..8adbcfe86 100644 --- a/src/citra_qt/main.cpp +++ b/src/citra_qt/main.cpp @@ -48,6 +48,47 @@ Q_IMPORT_PLUGIN(QWindowsIntegrationPlugin); #endif +/** + * "Callouts" are one-time instructional messages shown to the user. In the config settings, there + * is a bitfield "callout_flags" options, used to track if a message has already been shown to the + * user. This is 32-bits - if we have more than 32 callouts, we should retire and recyle old ones. + */ +enum class CalloutFlag : uint32_t { + Telemetry = 0x1, +}; + +static void ShowCalloutMessage(const QString& message, CalloutFlag flag) { + if (UISettings::values.callout_flags & static_cast<uint32_t>(flag)) { + return; + } + + UISettings::values.callout_flags |= static_cast<uint32_t>(flag); + + QMessageBox msg; + msg.setText(message); + msg.setStandardButtons(QMessageBox::Ok); + msg.setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); + msg.setStyleSheet("QLabel{min-width: 900px;}"); + msg.exec(); +} + +void GMainWindow::ShowCallouts() { + static const QString telemetry_message = + tr("To help improve Citra, the Citra Team collects anonymous usage data. No private or " + "personally identifying information is collected. This data helps us to understand how " + "people use Citra and prioritize our efforts. Furthermore, it helps us to more easily " + "identify emulation bugs and performance issues. This data includes:<ul><li>Information" + " about the version of Citra you are using</li><li>Performance data about the games you " + "play</li><li>Your configuration settings</li><li>Information about your computer " + "hardware</li><li>Emulation errors and crash information</li></ul>By default, this " + "feature is enabled. To disable this feature, click 'Emulation' from the menu and then " + "select 'Configure...'. Then, on the 'Web' tab, uncheck 'Share anonymous usage data with" + " the Citra team'. <br/><br/>By using this software, you agree to the above terms.<br/>" + "<br/><a href='https://citra-emu.org/entry/telemetry-and-why-thats-a-good-thing/'>Learn " + "more</a>"); + ShowCalloutMessage(telemetry_message, CalloutFlag::Telemetry); +} + GMainWindow::GMainWindow() : config(new Config()), emu_thread(nullptr) { Pica::g_debug_context = Pica::DebugContext::Construct(); setAcceptDrops(true); @@ -73,6 +114,9 @@ GMainWindow::GMainWindow() : config(new Config()), emu_thread(nullptr) { UpdateUITheme(); + // Show one-time "callout" messages to the user + ShowCallouts(); + QStringList args = QApplication::arguments(); if (args.length() >= 2) { BootGame(args[1]); @@ -320,6 +364,8 @@ bool GMainWindow::LoadROM(const QString& filename) { const Core::System::ResultStatus result{system.Load(render_window, filename.toStdString())}; + Core::Telemetry().AddField(Telemetry::FieldType::App, "Frontend", "Qt"); + if (result != Core::System::ResultStatus::Success) { switch (result) { case Core::System::ResultStatus::ErrorGetLoader: diff --git a/src/citra_qt/main.h b/src/citra_qt/main.h index 360de2ced..d59a6d67d 100644 --- a/src/citra_qt/main.h +++ b/src/citra_qt/main.h @@ -80,6 +80,8 @@ private: void BootGame(const QString& filename); void ShutdownGame(); + void ShowCallouts(); + /** * Stores the filename in the recently loaded files list. * The new filename is stored at the beginning of the recently loaded files list. diff --git a/src/citra_qt/ui_settings.h b/src/citra_qt/ui_settings.h index 025c73f84..d85c92765 100644 --- a/src/citra_qt/ui_settings.h +++ b/src/citra_qt/ui_settings.h @@ -48,6 +48,8 @@ struct Values { // Shortcut name <Shortcut, context> std::vector<Shortcut> shortcuts; + + uint32_t callout_flags; }; extern Values values; diff --git a/src/core/CMakeLists.txt b/src/core/CMakeLists.txt index 53bd50eb2..662030782 100644 --- a/src/core/CMakeLists.txt +++ b/src/core/CMakeLists.txt @@ -59,6 +59,7 @@ set(SRCS hle/kernel/timer.cpp hle/kernel/vm_manager.cpp hle/kernel/wait_object.cpp + hle/lock.cpp hle/romfs.cpp hle/service/ac/ac.cpp hle/service/ac/ac_i.cpp @@ -256,6 +257,7 @@ set(HEADERS hle/kernel/timer.h hle/kernel/vm_manager.h hle/kernel/wait_object.h + hle/lock.h hle/result.h hle/romfs.h hle/service/ac/ac.h diff --git a/src/core/arm/dynarmic/arm_dynarmic.cpp b/src/core/arm/dynarmic/arm_dynarmic.cpp index 7d2790b08..0a0b91590 100644 --- a/src/core/arm/dynarmic/arm_dynarmic.cpp +++ b/src/core/arm/dynarmic/arm_dynarmic.cpp @@ -136,7 +136,7 @@ MICROPROFILE_DEFINE(ARM_Jit, "ARM JIT", "ARM JIT", MP_RGB(255, 64, 64)); void ARM_Dynarmic::ExecuteInstructions(int num_instructions) { MICROPROFILE_SCOPE(ARM_Jit); - unsigned ticks_executed = jit->Run(static_cast<unsigned>(num_instructions)); + std::size_t ticks_executed = jit->Run(static_cast<unsigned>(num_instructions)); AddTicks(ticks_executed); } diff --git a/src/core/arm/dyncom/arm_dyncom_interpreter.cpp b/src/core/arm/dyncom/arm_dyncom_interpreter.cpp index f4fbb8d04..3522d1e82 100644 --- a/src/core/arm/dyncom/arm_dyncom_interpreter.cpp +++ b/src/core/arm/dyncom/arm_dyncom_interpreter.cpp @@ -759,7 +759,7 @@ static ThumbDecodeStatus DecodeThumbInstruction(u32 inst, u32 addr, u32* arm_ins ThumbDecodeStatus ret = TranslateThumbInstruction(addr, inst, arm_inst, inst_size); if (ret == ThumbDecodeStatus::BRANCH) { int inst_index; - int table_length = arm_instruction_trans_len; + int table_length = static_cast<int>(arm_instruction_trans_len); u32 tinstr = GetThumbInstruction(inst, addr); switch ((tinstr & 0xF800) >> 11) { @@ -838,7 +838,7 @@ static unsigned int InterpreterTranslateInstruction(const ARMul_State* cpu, cons return inst_size; } -static int InterpreterTranslateBlock(ARMul_State* cpu, int& bb_start, u32 addr) { +static int InterpreterTranslateBlock(ARMul_State* cpu, std::size_t& bb_start, u32 addr) { MICROPROFILE_SCOPE(DynCom_Decode); // Decode instruction, get index @@ -871,7 +871,7 @@ static int InterpreterTranslateBlock(ARMul_State* cpu, int& bb_start, u32 addr) return KEEP_GOING; } -static int InterpreterTranslateSingle(ARMul_State* cpu, int& bb_start, u32 addr) { +static int InterpreterTranslateSingle(ARMul_State* cpu, std::size_t& bb_start, u32 addr) { MICROPROFILE_SCOPE(DynCom_Decode); ARM_INST_PTR inst_base = nullptr; @@ -1620,7 +1620,7 @@ unsigned InterpreterMainLoop(ARMul_State* cpu) { unsigned int addr; unsigned int num_instrs = 0; - int ptr; + std::size_t ptr; LOAD_NZCVT; DISPATCH : { diff --git a/src/core/arm/skyeye_common/armstate.h b/src/core/arm/skyeye_common/armstate.h index 1a707ff7e..893877797 100644 --- a/src/core/arm/skyeye_common/armstate.h +++ b/src/core/arm/skyeye_common/armstate.h @@ -230,7 +230,7 @@ public: // TODO(bunnei): Move this cache to a better place - it should be per codeset (likely per // process for our purposes), not per ARMul_State (which tracks CPU core state). - std::unordered_map<u32, int> instruction_cache; + std::unordered_map<u32, std::size_t> instruction_cache; private: void ResetMPCoreCP15Registers(); diff --git a/src/core/file_sys/archive_backend.cpp b/src/core/file_sys/archive_backend.cpp index 1fae0ede0..87a240d7a 100644 --- a/src/core/file_sys/archive_backend.cpp +++ b/src/core/file_sys/archive_backend.cpp @@ -90,6 +90,8 @@ std::u16string Path::AsU16Str() const { LOG_ERROR(Service_FS, "LowPathType cannot be converted to u16string!"); return {}; } + + UNREACHABLE(); } std::vector<u8> Path::AsBinary() const { diff --git a/src/core/frontend/emu_window.cpp b/src/core/frontend/emu_window.cpp index 60b20d4e2..e67394177 100644 --- a/src/core/frontend/emu_window.cpp +++ b/src/core/frontend/emu_window.cpp @@ -2,14 +2,55 @@ // Licensed under GPLv2 or any later version // Refer to the license.txt file included. -#include <algorithm> #include <cmath> -#include "common/assert.h" -#include "core/3ds.h" -#include "core/core.h" +#include <mutex> #include "core/frontend/emu_window.h" +#include "core/frontend/input.h" #include "core/settings.h" +class EmuWindow::TouchState : public Input::Factory<Input::TouchDevice>, + public std::enable_shared_from_this<TouchState> { +public: + std::unique_ptr<Input::TouchDevice> Create(const Common::ParamPackage&) override { + return std::make_unique<Device>(shared_from_this()); + } + + std::mutex mutex; + + bool touch_pressed = false; ///< True if touchpad area is currently pressed, otherwise false + + float touch_x = 0.0f; ///< Touchpad X-position + float touch_y = 0.0f; ///< Touchpad Y-position + +private: + class Device : public Input::TouchDevice { + public: + explicit Device(std::weak_ptr<TouchState>&& touch_state) : touch_state(touch_state) {} + std::tuple<float, float, bool> GetStatus() const override { + if (auto state = touch_state.lock()) { + std::lock_guard<std::mutex> guard(state->mutex); + return std::make_tuple(state->touch_x, state->touch_y, state->touch_pressed); + } + return std::make_tuple(0.0f, 0.0f, false); + } + + private: + std::weak_ptr<TouchState> touch_state; + }; +}; + +EmuWindow::EmuWindow() { + // TODO: Find a better place to set this. + config.min_client_area_size = std::make_pair(400u, 480u); + active_config = config; + touch_state = std::make_shared<TouchState>(); + Input::RegisterFactory<Input::TouchDevice>("emu_window", touch_state); +} + +EmuWindow::~EmuWindow() { + Input::UnregisterFactory<Input::TouchDevice>("emu_window"); +} + /** * Check if the given x/y coordinates are within the touchpad specified by the framebuffer layout * @param layout FramebufferLayout object describing the framebuffer size and screen positions @@ -38,22 +79,26 @@ void EmuWindow::TouchPressed(unsigned framebuffer_x, unsigned framebuffer_y) { if (!IsWithinTouchscreen(framebuffer_layout, framebuffer_x, framebuffer_y)) return; - touch_x = Core::kScreenBottomWidth * (framebuffer_x - framebuffer_layout.bottom_screen.left) / - (framebuffer_layout.bottom_screen.right - framebuffer_layout.bottom_screen.left); - touch_y = Core::kScreenBottomHeight * (framebuffer_y - framebuffer_layout.bottom_screen.top) / - (framebuffer_layout.bottom_screen.bottom - framebuffer_layout.bottom_screen.top); + std::lock_guard<std::mutex> guard(touch_state->mutex); + touch_state->touch_x = + static_cast<float>(framebuffer_x - framebuffer_layout.bottom_screen.left) / + (framebuffer_layout.bottom_screen.right - framebuffer_layout.bottom_screen.left); + touch_state->touch_y = + static_cast<float>(framebuffer_y - framebuffer_layout.bottom_screen.top) / + (framebuffer_layout.bottom_screen.bottom - framebuffer_layout.bottom_screen.top); - touch_pressed = true; + touch_state->touch_pressed = true; } void EmuWindow::TouchReleased() { - touch_pressed = false; - touch_x = 0; - touch_y = 0; + std::lock_guard<std::mutex> guard(touch_state->mutex); + touch_state->touch_pressed = false; + touch_state->touch_x = 0; + touch_state->touch_y = 0; } void EmuWindow::TouchMoved(unsigned framebuffer_x, unsigned framebuffer_y) { - if (!touch_pressed) + if (!touch_state->touch_pressed) return; if (!IsWithinTouchscreen(framebuffer_layout, framebuffer_x, framebuffer_y)) @@ -74,6 +119,9 @@ void EmuWindow::UpdateCurrentFramebufferLayout(unsigned width, unsigned height) case Settings::LayoutOption::LargeScreen: layout = Layout::LargeFrameLayout(width, height, Settings::values.swap_screen); break; + case Settings::LayoutOption::SideScreen: + layout = Layout::SideFrameLayout(width, height, Settings::values.swap_screen); + break; case Settings::LayoutOption::Default: default: layout = Layout::DefaultFrameLayout(width, height, Settings::values.swap_screen); diff --git a/src/core/frontend/emu_window.h b/src/core/frontend/emu_window.h index 7bdee251c..c10dee51b 100644 --- a/src/core/frontend/emu_window.h +++ b/src/core/frontend/emu_window.h @@ -4,11 +4,10 @@ #pragma once -#include <mutex> +#include <memory> #include <tuple> #include <utility> #include "common/common_types.h" -#include "common/math_util.h" #include "core/frontend/framebuffer_layout.h" /** @@ -69,17 +68,6 @@ public: void TouchMoved(unsigned framebuffer_x, unsigned framebuffer_y); /** - * Gets the current touch screen state (touch X/Y coordinates and whether or not it is pressed). - * @note This should be called by the core emu thread to get a state set by the window thread. - * @todo Fix this function to be thread-safe. - * @return std::tuple of (x, y, pressed) where `x` and `y` are the touch coordinates and - * `pressed` is true if the touch screen is currently being pressed - */ - std::tuple<u16, u16, bool> GetTouchState() const { - return std::make_tuple(touch_x, touch_y, touch_pressed); - } - - /** * Returns currently active configuration. * @note Accesses to the returned object need not be consistent because it may be modified in * another thread @@ -113,15 +101,8 @@ public: void UpdateCurrentFramebufferLayout(unsigned width, unsigned height); protected: - EmuWindow() { - // TODO: Find a better place to set this. - config.min_client_area_size = std::make_pair(400u, 480u); - active_config = config; - touch_x = 0; - touch_y = 0; - touch_pressed = false; - } - virtual ~EmuWindow() {} + EmuWindow(); + virtual ~EmuWindow(); /** * Processes any pending configuration changes from the last SetConfig call. @@ -177,10 +158,8 @@ private: /// ProcessConfigurationChanges) WindowConfig active_config; ///< Internal active configuration - bool touch_pressed; ///< True if touchpad area is currently pressed, otherwise false - - u16 touch_x; ///< Touchpad X-position in native 3DS pixel coordinates (0-320) - u16 touch_y; ///< Touchpad Y-position in native 3DS pixel coordinates (0-240) + class TouchState; + std::shared_ptr<TouchState> touch_state; /** * Clip the provided coordinates to be inside the touchscreen area. diff --git a/src/core/frontend/framebuffer_layout.cpp b/src/core/frontend/framebuffer_layout.cpp index d2d02f9ff..e9f778fcb 100644 --- a/src/core/frontend/framebuffer_layout.cpp +++ b/src/core/frontend/framebuffer_layout.cpp @@ -141,6 +141,40 @@ FramebufferLayout LargeFrameLayout(unsigned width, unsigned height, bool swapped return res; } +FramebufferLayout SideFrameLayout(unsigned width, unsigned height, bool swapped) { + ASSERT(width > 0); + ASSERT(height > 0); + + FramebufferLayout res{width, height, true, true, {}, {}}; + // Aspect ratio of both screens side by side + const float emulation_aspect_ratio = static_cast<float>(Core::kScreenTopHeight) / + (Core::kScreenTopWidth + Core::kScreenBottomWidth); + float window_aspect_ratio = static_cast<float>(height) / width; + MathUtil::Rectangle<unsigned> screen_window_area{0, 0, width, height}; + // Find largest Rectangle that can fit in the window size with the given aspect ratio + MathUtil::Rectangle<unsigned> screen_rect = + maxRectangle(screen_window_area, emulation_aspect_ratio); + // Find sizes of top and bottom screen + MathUtil::Rectangle<unsigned> top_screen = maxRectangle(screen_rect, TOP_SCREEN_ASPECT_RATIO); + MathUtil::Rectangle<unsigned> bot_screen = maxRectangle(screen_rect, BOT_SCREEN_ASPECT_RATIO); + + if (window_aspect_ratio < emulation_aspect_ratio) { + // Apply borders to the left and right sides of the window. + u32 shift_horizontal = (screen_window_area.GetWidth() - screen_rect.GetWidth()) / 2; + top_screen = top_screen.TranslateX(shift_horizontal); + bot_screen = bot_screen.TranslateX(shift_horizontal); + } else { + // Window is narrower than the emulation content => apply borders to the top and bottom + u32 shift_vertical = (screen_window_area.GetHeight() - screen_rect.GetHeight()) / 2; + top_screen = top_screen.TranslateY(shift_vertical); + bot_screen = bot_screen.TranslateY(shift_vertical); + } + // Move the top screen to the right if we are swapped. + res.top_screen = swapped ? top_screen.TranslateX(bot_screen.GetWidth()) : top_screen; + res.bottom_screen = swapped ? bot_screen : bot_screen.TranslateX(top_screen.GetWidth()); + return res; +} + FramebufferLayout CustomFrameLayout(unsigned width, unsigned height) { ASSERT(width > 0); ASSERT(height > 0); @@ -158,4 +192,4 @@ FramebufferLayout CustomFrameLayout(unsigned width, unsigned height) { res.bottom_screen = bot_screen; return res; } -} +} // namespace Layout diff --git a/src/core/frontend/framebuffer_layout.h b/src/core/frontend/framebuffer_layout.h index 9a7738969..4983cf103 100644 --- a/src/core/frontend/framebuffer_layout.h +++ b/src/core/frontend/framebuffer_layout.h @@ -54,6 +54,17 @@ FramebufferLayout SingleFrameLayout(unsigned width, unsigned height, bool is_swa FramebufferLayout LargeFrameLayout(unsigned width, unsigned height, bool is_swapped); /** +* Factory method for constructing a Frame with the Top screen and bottom +* screen side by side +* This is useful for devices with small screens, like the GPDWin +* @param width Window framebuffer width in pixels +* @param height Window framebuffer height in pixels +* @param is_swapped if true, the bottom screen will be the left display +* @return Newly created FramebufferLayout object with default screen regions initialized +*/ +FramebufferLayout SideFrameLayout(unsigned width, unsigned height, bool is_swapped); + +/** * Factory method for constructing a custom FramebufferLayout * @param width Window framebuffer width in pixels * @param height Window framebuffer height in pixels diff --git a/src/core/frontend/input.h b/src/core/frontend/input.h index 5916a901d..8c256beb5 100644 --- a/src/core/frontend/input.h +++ b/src/core/frontend/input.h @@ -126,4 +126,10 @@ using AnalogDevice = InputDevice<std::tuple<float, float>>; */ using MotionDevice = InputDevice<std::tuple<Math::Vec3<float>, Math::Vec3<float>>>; +/** + * A touch device is an input device that returns a tuple of two floats and a bool. The floats are + * x and y coordinates in the range 0.0 - 1.0, and the bool indicates whether it is pressed. + */ +using TouchDevice = InputDevice<std::tuple<float, float, bool>>; + } // namespace Input diff --git a/src/core/hle/applets/erreula.cpp b/src/core/hle/applets/erreula.cpp index 75d7fd9fc..518f371f5 100644 --- a/src/core/hle/applets/erreula.cpp +++ b/src/core/hle/applets/erreula.cpp @@ -31,8 +31,8 @@ ResultCode ErrEula::ReceiveParameter(const Service::APT::MessageParameter& param heap_memory = std::make_shared<std::vector<u8>>(capture_info.size); // Create a SharedMemory that directly points to this heap block. framebuffer_memory = Kernel::SharedMemory::CreateForApplet( - heap_memory, 0, heap_memory->size(), MemoryPermission::ReadWrite, - MemoryPermission::ReadWrite, "ErrEula Memory"); + heap_memory, 0, capture_info.size, MemoryPermission::ReadWrite, MemoryPermission::ReadWrite, + "ErrEula Memory"); // Send the response message with the newly created SharedMemory Service::APT::MessageParameter result; diff --git a/src/core/hle/applets/mii_selector.cpp b/src/core/hle/applets/mii_selector.cpp index 89f08daa2..705859f1e 100644 --- a/src/core/hle/applets/mii_selector.cpp +++ b/src/core/hle/applets/mii_selector.cpp @@ -38,8 +38,8 @@ ResultCode MiiSelector::ReceiveParameter(const Service::APT::MessageParameter& p heap_memory = std::make_shared<std::vector<u8>>(capture_info.size); // Create a SharedMemory that directly points to this heap block. framebuffer_memory = Kernel::SharedMemory::CreateForApplet( - heap_memory, 0, heap_memory->size(), MemoryPermission::ReadWrite, - MemoryPermission::ReadWrite, "MiiSelector Memory"); + heap_memory, 0, capture_info.size, MemoryPermission::ReadWrite, MemoryPermission::ReadWrite, + "MiiSelector Memory"); // Send the response message with the newly created SharedMemory Service::APT::MessageParameter result; diff --git a/src/core/hle/applets/mint.cpp b/src/core/hle/applets/mint.cpp index 31a79ea17..50d79190b 100644 --- a/src/core/hle/applets/mint.cpp +++ b/src/core/hle/applets/mint.cpp @@ -31,8 +31,8 @@ ResultCode Mint::ReceiveParameter(const Service::APT::MessageParameter& paramete heap_memory = std::make_shared<std::vector<u8>>(capture_info.size); // Create a SharedMemory that directly points to this heap block. framebuffer_memory = Kernel::SharedMemory::CreateForApplet( - heap_memory, 0, heap_memory->size(), MemoryPermission::ReadWrite, - MemoryPermission::ReadWrite, "Mint Memory"); + heap_memory, 0, capture_info.size, MemoryPermission::ReadWrite, MemoryPermission::ReadWrite, + "Mint Memory"); // Send the response message with the newly created SharedMemory Service::APT::MessageParameter result; diff --git a/src/core/hle/applets/swkbd.cpp b/src/core/hle/applets/swkbd.cpp index fdf8807b0..0bc471a3a 100644 --- a/src/core/hle/applets/swkbd.cpp +++ b/src/core/hle/applets/swkbd.cpp @@ -41,8 +41,8 @@ ResultCode SoftwareKeyboard::ReceiveParameter(Service::APT::MessageParameter con heap_memory = std::make_shared<std::vector<u8>>(capture_info.size); // Create a SharedMemory that directly points to this heap block. framebuffer_memory = Kernel::SharedMemory::CreateForApplet( - heap_memory, 0, heap_memory->size(), MemoryPermission::ReadWrite, - MemoryPermission::ReadWrite, "SoftwareKeyboard Memory"); + heap_memory, 0, capture_info.size, MemoryPermission::ReadWrite, MemoryPermission::ReadWrite, + "SoftwareKeyboard Memory"); // Send the response message with the newly created SharedMemory Service::APT::MessageParameter result; diff --git a/src/core/hle/kernel/kernel.h b/src/core/hle/kernel/kernel.h index 9cf288b08..73fab3981 100644 --- a/src/core/hle/kernel/kernel.h +++ b/src/core/hle/kernel/kernel.h @@ -8,6 +8,7 @@ #include <string> #include <utility> #include <boost/smart_ptr/intrusive_ptr.hpp> +#include "common/assert.h" #include "common/common_types.h" namespace Kernel { @@ -84,6 +85,8 @@ public: case HandleType::ClientSession: return false; } + + UNREACHABLE(); } public: @@ -129,4 +132,4 @@ void Init(u32 system_mode); /// Shutdown the kernel void Shutdown(); -} // namespace +} // namespace Kernel diff --git a/src/core/hle/kernel/thread.cpp b/src/core/hle/kernel/thread.cpp index f5f2eb2f7..b957c45dd 100644 --- a/src/core/hle/kernel/thread.cpp +++ b/src/core/hle/kernel/thread.cpp @@ -478,8 +478,6 @@ void Thread::BoostPriority(s32 priority) { } SharedPtr<Thread> SetupMainThread(u32 entry_point, s32 priority) { - DEBUG_ASSERT(!GetCurrentThread()); - // Initialize new "main" thread auto thread_res = Thread::Create("main", entry_point, priority, 0, THREADPROCESSORID_0, Memory::HEAP_VADDR_END); @@ -489,9 +487,7 @@ SharedPtr<Thread> SetupMainThread(u32 entry_point, s32 priority) { thread->context.fpscr = FPSCR_DEFAULT_NAN | FPSCR_FLUSH_TO_ZERO | FPSCR_ROUND_TOZERO | FPSCR_IXC; // 0x03C00010 - // Run new "main" thread - SwitchContext(thread.get()); - + // Note: The newly created thread will be run when the scheduler fires. return thread; } diff --git a/src/core/hle/lock.cpp b/src/core/hle/lock.cpp new file mode 100644 index 000000000..1c24c7ce9 --- /dev/null +++ b/src/core/hle/lock.cpp @@ -0,0 +1,11 @@ +// Copyright 2017 Citra Emulator Project +// Licensed under GPLv2 or any later version +// Refer to the license.txt file included. + +#pragma once + +#include <core/hle/lock.h> + +namespace HLE { +std::recursive_mutex g_hle_lock; +} diff --git a/src/core/hle/lock.h b/src/core/hle/lock.h new file mode 100644 index 000000000..5c99fe996 --- /dev/null +++ b/src/core/hle/lock.h @@ -0,0 +1,18 @@ +// Copyright 2017 Citra Emulator Project +// Licensed under GPLv2 or any later version +// Refer to the license.txt file included. + +#pragma once + +#include <mutex> + +namespace HLE { +/* + * Synchronizes access to the internal HLE kernel structures, it is acquired when a guest + * application thread performs a syscall. It should be acquired by any host threads that read or + * modify the HLE kernel state. Note: Any operation that directly or indirectly reads from or writes + * to the emulated memory is not protected by this mutex, and should be avoided in any threads other + * than the CPU thread. + */ +extern std::recursive_mutex g_hle_lock; +} // namespace HLE diff --git a/src/core/hle/service/hid/hid.cpp b/src/core/hle/service/hid/hid.cpp index 31f34a7ae..aa5d821f9 100644 --- a/src/core/hle/service/hid/hid.cpp +++ b/src/core/hle/service/hid/hid.cpp @@ -7,9 +7,9 @@ #include <cmath> #include <memory> #include "common/logging/log.h" +#include "core/3ds.h" #include "core/core.h" #include "core/core_timing.h" -#include "core/frontend/emu_window.h" #include "core/frontend/input.h" #include "core/hle/ipc.h" #include "core/hle/kernel/event.h" @@ -19,7 +19,6 @@ #include "core/hle/service/hid/hid_spvr.h" #include "core/hle/service/hid/hid_user.h" #include "core/hle/service/service.h" -#include "video_core/video_core.h" namespace Service { namespace HID { @@ -59,6 +58,7 @@ static std::array<std::unique_ptr<Input::ButtonDevice>, Settings::NativeButton:: buttons; static std::unique_ptr<Input::AnalogDevice> circle_pad; static std::unique_ptr<Input::MotionDevice> motion_device; +static std::unique_ptr<Input::TouchDevice> touch_device; DirectionState GetStickDirectionState(s16 circle_pad_x, s16 circle_pad_y) { // 30 degree and 60 degree are angular thresholds for directions @@ -96,6 +96,7 @@ static void LoadInputDevices() { circle_pad = Input::CreateDevice<Input::AnalogDevice>( Settings::values.analogs[Settings::NativeAnalog::CirclePad]); motion_device = Input::CreateDevice<Input::MotionDevice>(Settings::values.motion_device); + touch_device = Input::CreateDevice<Input::TouchDevice>(Settings::values.touch_device); } static void UnloadInputDevices() { @@ -104,6 +105,7 @@ static void UnloadInputDevices() { } circle_pad.reset(); motion_device.reset(); + touch_device.reset(); } static void UpdatePadCallback(u64 userdata, int cycles_late) { @@ -172,8 +174,10 @@ static void UpdatePadCallback(u64 userdata, int cycles_late) { // Get the current touch entry TouchDataEntry& touch_entry = mem->touch.entries[mem->touch.index]; bool pressed = false; - - std::tie(touch_entry.x, touch_entry.y, pressed) = VideoCore::g_emu_window->GetTouchState(); + float x, y; + std::tie(x, y, pressed) = touch_device->GetStatus(); + touch_entry.x = static_cast<u16>(x * Core::kScreenBottomWidth); + touch_entry.y = static_cast<u16>(y * Core::kScreenBottomHeight); touch_entry.valid.Assign(pressed ? 1 : 0); // TODO(bunnei): We're not doing anything with offset 0xA8 + 0x18 of HID SharedMemory, which diff --git a/src/core/hle/svc.cpp b/src/core/hle/svc.cpp index e4b803046..dfc36748c 100644 --- a/src/core/hle/svc.cpp +++ b/src/core/hle/svc.cpp @@ -31,6 +31,7 @@ #include "core/hle/kernel/timer.h" #include "core/hle/kernel/vm_manager.h" #include "core/hle/kernel/wait_object.h" +#include "core/hle/lock.h" #include "core/hle/result.h" #include "core/hle/service/service.h" @@ -1188,7 +1189,7 @@ struct FunctionDef { Func* func; const char* name; }; -} +} // namespace static const FunctionDef SVC_Table[] = { {0x00, nullptr, "Unknown"}, @@ -1332,6 +1333,9 @@ MICROPROFILE_DEFINE(Kernel_SVC, "Kernel", "SVC", MP_RGB(70, 200, 70)); void CallSVC(u32 immediate) { MICROPROFILE_SCOPE(Kernel_SVC); + // Lock the global kernel mutex when we enter the kernel HLE. + std::lock_guard<std::recursive_mutex> lock(HLE::g_hle_lock); + const FunctionDef* info = GetSVCInfo(immediate); if (info) { if (info->func) { @@ -1342,4 +1346,4 @@ void CallSVC(u32 immediate) { } } -} // namespace +} // namespace SVC diff --git a/src/core/hw/gpu.cpp b/src/core/hw/gpu.cpp index 6838e449c..83ad9d898 100644 --- a/src/core/hw/gpu.cpp +++ b/src/core/hw/gpu.cpp @@ -29,7 +29,7 @@ namespace GPU { Regs g_regs; /// 268MHz CPU clocks / 60Hz frames per second -const u64 frame_ticks = BASE_CLOCK_RATE_ARM11 / SCREEN_REFRESH_RATE; +const u64 frame_ticks = static_cast<u64>(BASE_CLOCK_RATE_ARM11 / SCREEN_REFRESH_RATE); /// Event id for CoreTiming static int vblank_event; diff --git a/src/core/hw/gpu.h b/src/core/hw/gpu.h index 21b127fee..e3d0a0e08 100644 --- a/src/core/hw/gpu.h +++ b/src/core/hw/gpu.h @@ -74,9 +74,9 @@ struct Regs { case PixelFormat::RGB5A1: case PixelFormat::RGBA4: return 2; - default: - UNIMPLEMENTED(); } + + UNREACHABLE(); } INSERT_PADDING_WORDS(0x4); diff --git a/src/core/memory.cpp b/src/core/memory.cpp index 65649d9d7..097bc5b47 100644 --- a/src/core/memory.cpp +++ b/src/core/memory.cpp @@ -9,6 +9,7 @@ #include "common/logging/log.h" #include "common/swap.h" #include "core/hle/kernel/process.h" +#include "core/hle/lock.h" #include "core/memory.h" #include "core/memory_setup.h" #include "core/mmio.h" @@ -181,6 +182,9 @@ T Read(const VAddr vaddr) { return value; } + // The memory access might do an MMIO or cached access, so we have to lock the HLE kernel state + std::lock_guard<std::recursive_mutex> lock(HLE::g_hle_lock); + PageType type = current_page_table->attributes[vaddr >> PAGE_BITS]; switch (type) { case PageType::Unmapped: @@ -219,6 +223,9 @@ void Write(const VAddr vaddr, const T data) { return; } + // The memory access might do an MMIO or cached access, so we have to lock the HLE kernel state + std::lock_guard<std::recursive_mutex> lock(HLE::g_hle_lock); + PageType type = current_page_table->attributes[vaddr >> PAGE_BITS]; switch (type) { case PageType::Unmapped: @@ -746,4 +753,4 @@ boost::optional<VAddr> PhysicalToVirtualAddress(const PAddr addr) { return boost::none; } -} // namespace +} // namespace Memory diff --git a/src/core/settings.cpp b/src/core/settings.cpp index d4f0429d1..efcf1267d 100644 --- a/src/core/settings.cpp +++ b/src/core/settings.cpp @@ -36,4 +36,4 @@ void Apply() { Service::IR::ReloadInputDevices(); } -} // namespace +} // namespace Settings diff --git a/src/core/settings.h b/src/core/settings.h index 7e15b119b..024f14666 100644 --- a/src/core/settings.h +++ b/src/core/settings.h @@ -15,6 +15,7 @@ enum class LayoutOption { Default, SingleScreen, LargeScreen, + SideScreen, }; namespace NativeButton { @@ -70,7 +71,7 @@ enum Values { static const std::array<const char*, NumAnalogs> mapping = {{ "circle_pad", "c_stick", }}; -} // namespace NumAnalog +} // namespace NativeAnalog struct Values { // CheckNew3DS @@ -80,6 +81,7 @@ struct Values { std::array<std::string, NativeButton::NumButtons> buttons; std::array<std::string, NativeAnalog::NumAnalogs> analogs; std::string motion_device; + std::string touch_device; // Core bool use_cpu_jit; @@ -129,7 +131,10 @@ struct Values { u16 gdbstub_port; // WebService + bool enable_telemetry; std::string telemetry_endpoint_url; + std::string citra_username; + std::string citra_token; } extern values; // a special value for Values::region_value indicating that citra will automatically select a region @@ -137,4 +142,4 @@ struct Values { static constexpr int REGION_VALUE_AUTO_SELECT = -1; void Apply(); -} +} // namespace Settings diff --git a/src/core/telemetry_session.cpp b/src/core/telemetry_session.cpp index 94483f385..104a16cc9 100644 --- a/src/core/telemetry_session.cpp +++ b/src/core/telemetry_session.cpp @@ -3,8 +3,10 @@ // Refer to the license.txt file included. #include <cstring> +#include <cryptopp/osrng.h> #include "common/assert.h" +#include "common/file_util.h" #include "common/scm_rev.h" #include "common/x64/cpu_detect.h" #include "core/core.h" @@ -29,12 +31,65 @@ static const char* CpuVendorToStr(Common::CPUVendor vendor) { UNREACHABLE(); } +static u64 GenerateTelemetryId() { + u64 telemetry_id{}; + CryptoPP::AutoSeededRandomPool rng; + rng.GenerateBlock(reinterpret_cast<CryptoPP::byte*>(&telemetry_id), sizeof(u64)); + return telemetry_id; +} + +u64 GetTelemetryId() { + u64 telemetry_id{}; + static const std::string& filename{FileUtil::GetUserPath(D_CONFIG_IDX) + "telemetry_id"}; + + if (FileUtil::Exists(filename)) { + FileUtil::IOFile file(filename, "rb"); + if (!file.IsOpen()) { + LOG_ERROR(Core, "failed to open telemetry_id: %s", filename.c_str()); + return {}; + } + file.ReadBytes(&telemetry_id, sizeof(u64)); + } else { + FileUtil::IOFile file(filename, "wb"); + if (!file.IsOpen()) { + LOG_ERROR(Core, "failed to open telemetry_id: %s", filename.c_str()); + return {}; + } + telemetry_id = GenerateTelemetryId(); + file.WriteBytes(&telemetry_id, sizeof(u64)); + } + + return telemetry_id; +} + +u64 RegenerateTelemetryId() { + const u64 new_telemetry_id{GenerateTelemetryId()}; + static const std::string& filename{FileUtil::GetUserPath(D_CONFIG_IDX) + "telemetry_id"}; + + FileUtil::IOFile file(filename, "wb"); + if (!file.IsOpen()) { + LOG_ERROR(Core, "failed to open telemetry_id: %s", filename.c_str()); + return {}; + } + file.WriteBytes(&new_telemetry_id, sizeof(u64)); + return new_telemetry_id; +} + TelemetrySession::TelemetrySession() { #ifdef ENABLE_WEB_SERVICE - backend = std::make_unique<WebService::TelemetryJson>(); + if (Settings::values.enable_telemetry) { + backend = std::make_unique<WebService::TelemetryJson>( + Settings::values.telemetry_endpoint_url, Settings::values.citra_username, + Settings::values.citra_token); + } else { + backend = std::make_unique<Telemetry::NullVisitor>(); + } #else backend = std::make_unique<Telemetry::NullVisitor>(); #endif + // Log one-time top-level information + AddField(Telemetry::FieldType::None, "TelemetryId", GetTelemetryId()); + // Log one-time session start information const s64 init_time{std::chrono::duration_cast<std::chrono::milliseconds>( std::chrono::system_clock::now().time_since_epoch()) diff --git a/src/core/telemetry_session.h b/src/core/telemetry_session.h index cf53835c3..65613daae 100644 --- a/src/core/telemetry_session.h +++ b/src/core/telemetry_session.h @@ -35,4 +35,16 @@ private: std::unique_ptr<Telemetry::VisitorInterface> backend; ///< Backend interface that logs fields }; +/** + * Gets TelemetryId, a unique identifier used for the user's telemetry sessions. + * @returns The current TelemetryId for the session. + */ +u64 GetTelemetryId(); + +/** + * Regenerates TelemetryId, a unique identifier used for the user's telemetry sessions. + * @returns The new TelemetryId that was generated. + */ +u64 RegenerateTelemetryId(); + } // namespace Core diff --git a/src/input_common/motion_emu.cpp b/src/input_common/motion_emu.cpp index a1761f184..59a035e70 100644 --- a/src/input_common/motion_emu.cpp +++ b/src/input_common/motion_emu.cpp @@ -74,11 +74,14 @@ private: bool is_tilting = false; Common::Event shutdown_event; - std::thread motion_emu_thread; std::tuple<Math::Vec3<float>, Math::Vec3<float>> status; std::mutex status_mutex; + // Note: always keep the thread declaration at the end so that other objects are initialized + // before this! + std::thread motion_emu_thread; + void MotionEmuThread() { auto update_time = std::chrono::steady_clock::now(); Math::Quaternion<float> q = MakeQuaternion(Math::Vec3<float>(), 0); diff --git a/src/video_core/regs_framebuffer.h b/src/video_core/regs_framebuffer.h index a50bd4111..7b565f911 100644 --- a/src/video_core/regs_framebuffer.h +++ b/src/video_core/regs_framebuffer.h @@ -256,10 +256,9 @@ struct FramebufferRegs { return 3; case DepthFormat::D24S8: return 4; - default: - LOG_CRITICAL(HW_GPU, "Unknown depth format %u", format); - UNIMPLEMENTED(); } + + ASSERT_MSG(false, "Unknown depth format %u", format); } // Returns the number of bits per depth component of the specified depth format @@ -270,10 +269,9 @@ struct FramebufferRegs { case DepthFormat::D24: case DepthFormat::D24S8: return 24; - default: - LOG_CRITICAL(HW_GPU, "Unknown depth format %u", format); - UNIMPLEMENTED(); } + + ASSERT_MSG(false, "Unknown depth format %u", format); } INSERT_PADDING_WORDS(0x20); diff --git a/src/video_core/renderer_opengl/gl_rasterizer.cpp b/src/video_core/renderer_opengl/gl_rasterizer.cpp index 1c6c15a58..aa95ef21d 100644 --- a/src/video_core/renderer_opengl/gl_rasterizer.cpp +++ b/src/video_core/renderer_opengl/gl_rasterizer.cpp @@ -28,6 +28,9 @@ MICROPROFILE_DEFINE(OpenGL_Blits, "OpenGL", "Blits", MP_RGB(100, 100, 255)); MICROPROFILE_DEFINE(OpenGL_CacheManagement, "OpenGL", "Cache Mgmt", MP_RGB(100, 255, 100)); RasterizerOpenGL::RasterizerOpenGL() : shader_dirty(true) { + // Clipping plane 0 is always enabled for PICA fixed clip plane z <= 0 + state.clip_distance[0] = true; + // Create sampler objects for (size_t i = 0; i < texture_samplers.size(); ++i) { texture_samplers[i].Create(); diff --git a/src/video_core/renderer_opengl/gl_shader_gen.cpp b/src/video_core/renderer_opengl/gl_shader_gen.cpp index d85f281e5..3f390491a 100644 --- a/src/video_core/renderer_opengl/gl_shader_gen.cpp +++ b/src/video_core/renderer_opengl/gl_shader_gen.cpp @@ -1112,7 +1112,10 @@ vec4 secondary_fragment_color = vec4(0.0); "gl_FragCoord.y < scissor_y2)) discard;\n"; } - out += "float z_over_w = 1.0 - gl_FragCoord.z * 2.0;\n"; + // After perspective divide, OpenGL transform z_over_w from [-1, 1] to [near, far]. Here we use + // default near = 0 and far = 1, and undo the transformation to get the original z_over_w, then + // do our own transformation according to PICA specification. + out += "float z_over_w = 2.0 * gl_FragCoord.z - 1.0;\n"; out += "float depth = z_over_w * depth_scale + depth_offset;\n"; if (state.depthmap_enable == RasterizerRegs::DepthBuffering::WBuffering) { out += "depth /= gl_FragCoord.w;\n"; @@ -1195,7 +1198,9 @@ void main() { texcoord0_w = vert_texcoord0_w; normquat = vert_normquat; view = vert_view; - gl_Position = vec4(vert_position.x, vert_position.y, -vert_position.z, vert_position.w); + gl_Position = vert_position; + gl_ClipDistance[0] = -vert_position.z; // fixed PICA clipping plane z <= 0 + // TODO (wwylele): calculate gl_ClipDistance[1] from user-defined clipping plane } )"; diff --git a/src/video_core/renderer_opengl/gl_state.cpp b/src/video_core/renderer_opengl/gl_state.cpp index bc9d34b84..06a905766 100644 --- a/src/video_core/renderer_opengl/gl_state.cpp +++ b/src/video_core/renderer_opengl/gl_state.cpp @@ -68,6 +68,8 @@ OpenGLState::OpenGLState() { draw.vertex_buffer = 0; draw.uniform_buffer = 0; draw.shader_program = 0; + + clip_distance = {}; } void OpenGLState::Apply() const { @@ -261,6 +263,17 @@ void OpenGLState::Apply() const { glUseProgram(draw.shader_program); } + // Clip distance + for (size_t i = 0; i < clip_distance.size(); ++i) { + if (clip_distance[i] != cur_state.clip_distance[i]) { + if (clip_distance[i]) { + glEnable(GL_CLIP_DISTANCE0 + i); + } else { + glDisable(GL_CLIP_DISTANCE0 + i); + } + } + } + cur_state = *this; } diff --git a/src/video_core/renderer_opengl/gl_state.h b/src/video_core/renderer_opengl/gl_state.h index 745a74479..437fe34c4 100644 --- a/src/video_core/renderer_opengl/gl_state.h +++ b/src/video_core/renderer_opengl/gl_state.h @@ -4,6 +4,7 @@ #pragma once +#include <array> #include <glad/glad.h> namespace TextureUnits { @@ -123,6 +124,8 @@ public: GLuint shader_program; // GL_CURRENT_PROGRAM } draw; + std::array<bool, 2> clip_distance; // GL_CLIP_DISTANCE + OpenGLState(); /// Get the currently active OpenGL state diff --git a/src/video_core/swrasterizer/clipper.cpp b/src/video_core/swrasterizer/clipper.cpp index 7537689b7..cdbc71502 100644 --- a/src/video_core/swrasterizer/clipper.cpp +++ b/src/video_core/swrasterizer/clipper.cpp @@ -125,10 +125,6 @@ void ProcessTriangle(const OutputVertex& v0, const OutputVertex& v1, const Outpu {Math::MakeVec(f0, f0, f0, -f1), Math::Vec4<float24>(f0, f0, f0, EPSILON)}, // w = EPSILON }}; - // TODO: If one vertex lies outside one of the depth clipping planes, some platforms (e.g. Wii) - // drop the whole primitive instead of clipping the primitive properly. We should test if - // this happens on the 3DS, too. - // Simple implementation of the Sutherland-Hodgman clipping algorithm. // TODO: Make this less inefficient (currently lots of useless buffering overhead happens here) for (auto edge : clipping_edges) { diff --git a/src/video_core/swrasterizer/framebuffer.cpp b/src/video_core/swrasterizer/framebuffer.cpp index 7de3aac75..f34eab6cf 100644 --- a/src/video_core/swrasterizer/framebuffer.cpp +++ b/src/video_core/swrasterizer/framebuffer.cpp @@ -352,6 +352,8 @@ u8 LogicOp(u8 src, u8 dest, FramebufferRegs::LogicOp op) { case FramebufferRegs::LogicOp::OrInverted: return ~src | dest; } + + UNREACHABLE(); }; } // namespace Rasterizer diff --git a/src/video_core/swrasterizer/rasterizer.h b/src/video_core/swrasterizer/rasterizer.h index 2f0877581..66cd6cfd4 100644 --- a/src/video_core/swrasterizer/rasterizer.h +++ b/src/video_core/swrasterizer/rasterizer.h @@ -19,10 +19,9 @@ struct Vertex : Shader::OutputVertex { // Linear interpolation // factor: 0=this, 1=vtx + // Note: This function cannot be called after perspective divide void Lerp(float24 factor, const Vertex& vtx) { pos = pos * factor + vtx.pos * (float24::FromFloat32(1) - factor); - - // TODO: Should perform perspective correct interpolation here... quat = quat * factor + vtx.quat * (float24::FromFloat32(1) - factor); color = color * factor + vtx.color * (float24::FromFloat32(1) - factor); tc0 = tc0 * factor + vtx.tc0 * (float24::FromFloat32(1) - factor); @@ -30,12 +29,11 @@ struct Vertex : Shader::OutputVertex { tc0_w = tc0_w * factor + vtx.tc0_w * (float24::FromFloat32(1) - factor); view = view * factor + vtx.view * (float24::FromFloat32(1) - factor); tc2 = tc2 * factor + vtx.tc2 * (float24::FromFloat32(1) - factor); - - screenpos = screenpos * factor + vtx.screenpos * (float24::FromFloat32(1) - factor); } // Linear interpolation // factor: 0=v0, 1=v1 + // Note: This function cannot be called after perspective divide static Vertex Lerp(float24 factor, const Vertex& v0, const Vertex& v1) { Vertex ret = v0; ret.Lerp(factor, v1); diff --git a/src/video_core/swrasterizer/texturing.cpp b/src/video_core/swrasterizer/texturing.cpp index 4f02b93f2..79b1ce841 100644 --- a/src/video_core/swrasterizer/texturing.cpp +++ b/src/video_core/swrasterizer/texturing.cpp @@ -89,6 +89,8 @@ Math::Vec3<u8> GetColorModifier(TevStageConfig::ColorModifier factor, case ColorModifier::OneMinusSourceBlue: return (Math::Vec3<u8>(255, 255, 255) - values.bbb()).Cast<u8>(); } + + UNREACHABLE(); }; u8 GetAlphaModifier(TevStageConfig::AlphaModifier factor, const Math::Vec4<u8>& values) { @@ -119,6 +121,8 @@ u8 GetAlphaModifier(TevStageConfig::AlphaModifier factor, const Math::Vec4<u8>& case AlphaModifier::OneMinusSourceBlue: return 255 - values.b(); } + + UNREACHABLE(); }; Math::Vec3<u8> ColorCombine(TevStageConfig::Operation op, const Math::Vec3<u8> input[3]) { diff --git a/src/web_service/telemetry_json.cpp b/src/web_service/telemetry_json.cpp index a2d007e77..6ad2ffcd4 100644 --- a/src/web_service/telemetry_json.cpp +++ b/src/web_service/telemetry_json.cpp @@ -3,7 +3,6 @@ // Refer to the license.txt file included. #include "common/assert.h" -#include "core/settings.h" #include "web_service/telemetry_json.h" #include "web_service/web_backend.h" @@ -81,7 +80,7 @@ void TelemetryJson::Complete() { SerializeSection(Telemetry::FieldType::UserFeedback, "UserFeedback"); SerializeSection(Telemetry::FieldType::UserConfig, "UserConfig"); SerializeSection(Telemetry::FieldType::UserSystem, "UserSystem"); - PostJson(Settings::values.telemetry_endpoint_url, TopSection().dump()); + PostJson(endpoint_url, TopSection().dump(), true, username, token); } } // namespace WebService diff --git a/src/web_service/telemetry_json.h b/src/web_service/telemetry_json.h index 39038b4f9..9e78c6803 100644 --- a/src/web_service/telemetry_json.h +++ b/src/web_service/telemetry_json.h @@ -17,7 +17,9 @@ namespace WebService { */ class TelemetryJson : public Telemetry::VisitorInterface { public: - TelemetryJson() = default; + TelemetryJson(const std::string& endpoint_url, const std::string& username, + const std::string& token) + : endpoint_url(endpoint_url), username(username), token(token) {} ~TelemetryJson() = default; void Visit(const Telemetry::Field<bool>& field) override; @@ -49,6 +51,9 @@ private: nlohmann::json output; std::array<nlohmann::json, 7> sections; + std::string endpoint_url; + std::string username; + std::string token; }; } // namespace WebService diff --git a/src/web_service/web_backend.cpp b/src/web_service/web_backend.cpp index 13e4555ac..d28a3f757 100644 --- a/src/web_service/web_backend.cpp +++ b/src/web_service/web_backend.cpp @@ -2,51 +2,62 @@ // Licensed under GPLv2 or any later version // Refer to the license.txt file included. +#ifdef _WIN32 +#include <winsock.h> +#endif + +#include <cstdlib> +#include <thread> #include <cpr/cpr.h> -#include <stdlib.h> #include "common/logging/log.h" #include "web_service/web_backend.h" namespace WebService { static constexpr char API_VERSION[]{"1"}; -static constexpr char ENV_VAR_USERNAME[]{"CITRA_WEB_SERVICES_USERNAME"}; -static constexpr char ENV_VAR_TOKEN[]{"CITRA_WEB_SERVICES_TOKEN"}; - -static std::string GetEnvironmentVariable(const char* name) { - const char* value{getenv(name)}; - if (value) { - return value; - } - return {}; -} - -const std::string& GetUsername() { - static const std::string username{GetEnvironmentVariable(ENV_VAR_USERNAME)}; - return username; -} -const std::string& GetToken() { - static const std::string token{GetEnvironmentVariable(ENV_VAR_TOKEN)}; - return token; -} +static std::unique_ptr<cpr::Session> g_session; -void PostJson(const std::string& url, const std::string& data) { +void PostJson(const std::string& url, const std::string& data, bool allow_anonymous, + const std::string& username, const std::string& token) { if (url.empty()) { LOG_ERROR(WebService, "URL is invalid"); return; } - if (GetUsername().empty() || GetToken().empty()) { - LOG_ERROR(WebService, "Environment variables %s and %s must be set to POST JSON", - ENV_VAR_USERNAME, ENV_VAR_TOKEN); + const bool are_credentials_provided{!token.empty() && !username.empty()}; + if (!allow_anonymous && !are_credentials_provided) { + LOG_ERROR(WebService, "Credentials must be provided for authenticated requests"); return; } - cpr::PostAsync(cpr::Url{url}, cpr::Body{data}, cpr::Header{{"Content-Type", "application/json"}, - {"x-username", GetUsername()}, - {"x-token", GetToken()}, - {"api-version", API_VERSION}}); +#ifdef _WIN32 + // On Windows, CPR/libcurl does not properly initialize Winsock. The below code is used to + // initialize Winsock globally, which fixes this problem. Without this, only the first CPR + // session will properly be created, and subsequent ones will fail. + WSADATA wsa_data; + const int wsa_result{WSAStartup(MAKEWORD(2, 2), &wsa_data)}; + if (wsa_result) { + LOG_CRITICAL(WebService, "WSAStartup failed: %d", wsa_result); + } +#endif + + // Built request header + cpr::Header header; + if (are_credentials_provided) { + // Authenticated request if credentials are provided + header = {{"Content-Type", "application/json"}, + {"x-username", username.c_str()}, + {"x-token", token.c_str()}, + {"api-version", API_VERSION}}; + } else { + // Otherwise, anonymous request + header = cpr::Header{{"Content-Type", "application/json"}, {"api-version", API_VERSION}}; + } + + // Post JSON asynchronously + static cpr::AsyncResponse future; + future = cpr::PostAsync(cpr::Url{url.c_str()}, cpr::Body{data.c_str()}, header); } } // namespace WebService diff --git a/src/web_service/web_backend.h b/src/web_service/web_backend.h index 2753d3b68..d17100398 100644 --- a/src/web_service/web_backend.h +++ b/src/web_service/web_backend.h @@ -10,22 +10,14 @@ namespace WebService { /** - * Gets the current username for accessing services.citra-emu.org. - * @returns Username as a string, empty if not set. - */ -const std::string& GetUsername(); - -/** - * Gets the current token for accessing services.citra-emu.org. - * @returns Token as a string, empty if not set. - */ -const std::string& GetToken(); - -/** * Posts JSON to services.citra-emu.org. * @param url URL of the services.citra-emu.org endpoint to post data to. * @param data String of JSON data to use for the body of the POST request. + * @param allow_anonymous If true, allow anonymous unauthenticated requests. + * @param username Citra username to use for authentication. + * @param token Citra token to use for authentication. */ -void PostJson(const std::string& url, const std::string& data); +void PostJson(const std::string& url, const std::string& data, bool allow_anonymous, + const std::string& username = {}, const std::string& token = {}); } // namespace WebService |