From 426c4a2a5b65ce04a767e4c514aafc182b8d5a56 Mon Sep 17 00:00:00 2001 From: LittleWhite Date: Sun, 24 Jan 2016 18:34:05 +0100 Subject: [PATCH 001/104] Add Configure widget --- src/citra_qt/CMakeLists.txt | 15 +++- src/citra_qt/configure.ui | 109 +++++++++++++++++++++++++++++ src/citra_qt/configure_debug.cpp | 33 +++++++++ src/citra_qt/configure_debug.h | 31 ++++++++ src/citra_qt/configure_debug.ui | 76 ++++++++++++++++++++ src/citra_qt/configure_dialog.cpp | 32 +++++++++ src/citra_qt/configure_dialog.h | 31 ++++++++ src/citra_qt/configure_general.cpp | 40 +++++++++++ src/citra_qt/configure_general.h | 31 ++++++++ src/citra_qt/configure_general.ui | 96 +++++++++++++++++++++++++ src/citra_qt/hotkeys.cpp | 2 +- src/citra_qt/hotkeys.h | 2 +- src/citra_qt/hotkeys.ui | 47 +------------ src/citra_qt/main.cpp | 48 +++---------- src/citra_qt/main.h | 4 -- src/citra_qt/main.ui | 51 +------------- src/citra_qt/ui_settings.cpp | 11 +++ src/citra_qt/ui_settings.h | 16 +++++ 18 files changed, 533 insertions(+), 142 deletions(-) create mode 100644 src/citra_qt/configure.ui create mode 100644 src/citra_qt/configure_debug.cpp create mode 100644 src/citra_qt/configure_debug.h create mode 100644 src/citra_qt/configure_debug.ui create mode 100644 src/citra_qt/configure_dialog.cpp create mode 100644 src/citra_qt/configure_dialog.h create mode 100644 src/citra_qt/configure_general.cpp create mode 100644 src/citra_qt/configure_general.h create mode 100644 src/citra_qt/configure_general.ui create mode 100644 src/citra_qt/ui_settings.cpp create mode 100644 src/citra_qt/ui_settings.h diff --git a/src/citra_qt/CMakeLists.txt b/src/citra_qt/CMakeLists.txt index 9b3eb2cd6..6660d9879 100644 --- a/src/citra_qt/CMakeLists.txt +++ b/src/citra_qt/CMakeLists.txt @@ -17,12 +17,16 @@ set(SRCS debugger/profiler.cpp debugger/ramview.cpp debugger/registers.cpp - game_list.cpp util/spinbox.cpp util/util.cpp bootmanager.cpp + configure_debug.cpp + configure_dialog.cpp + configure_general.cpp + game_list.cpp hotkeys.cpp main.cpp + ui_settings.cpp citra-qt.rc Info.plist ) @@ -44,12 +48,16 @@ set(HEADERS debugger/profiler.h debugger/ramview.h debugger/registers.h - game_list.h util/spinbox.h util/util.h bootmanager.h + configure_debug.h + configure_dialog.h + configure_general.h + game_list.h hotkeys.h main.h + ui_settings.h version.h ) @@ -59,6 +67,9 @@ set(UIS debugger/disassembler.ui debugger/profiler.ui debugger/registers.ui + configure.ui + configure_debug.ui + configure_general.ui hotkeys.ui main.ui ) diff --git a/src/citra_qt/configure.ui b/src/citra_qt/configure.ui new file mode 100644 index 000000000..e4ac9a7d8 --- /dev/null +++ b/src/citra_qt/configure.ui @@ -0,0 +1,109 @@ + + + ConfigureDialog + + + + 0 + 0 + 441 + 401 + + + + + 370 + 219 + + + + Dialog + + + + + + + 371 + 221 + + + + 0 + + + + General + + + + + Input + + + + + Debug + + + + + + + + QDialogButtonBox::Cancel|QDialogButtonBox::Ok + + + + + + + + ConfigureGeneral + QWidget +
configure_general.h
+ 1 +
+ + ConfigureDebug + QWidget +
configure_debug.h
+ 1 +
+
+ + + + buttonBox + accepted() + ConfigureDialog + accept() + + + 220 + 380 + + + 220 + 200 + + + + + buttonBox + rejected() + ConfigureDialog + reject() + + + 220 + 380 + + + 220 + 200 + + + + +
diff --git a/src/citra_qt/configure_debug.cpp b/src/citra_qt/configure_debug.cpp new file mode 100644 index 000000000..f8ff804b2 --- /dev/null +++ b/src/citra_qt/configure_debug.cpp @@ -0,0 +1,33 @@ +// Copyright 2016 Citra Emulator Project +// Licensed under GPLv2 or any later version +// Refer to the license.txt file included. + +#include "core/core.h" +#include "core/gdbstub/gdbstub.h" // TODO: can't include gdbstub without core.h +#include "core/settings.h" + +#include "configure_debug.h" +#include "ui_configure_debug.h" + +ConfigureDebug::ConfigureDebug(QWidget *parent) : + QWidget(parent), + ui(new Ui::ConfigureDebug) +{ + ui->setupUi(this); + this->setConfiguration(); +} + +ConfigureDebug::~ConfigureDebug() { + delete ui; +} + +void ConfigureDebug::setConfiguration() { + ui->toogleGDBStub->setChecked(Settings::values.use_gdbstub); + ui->GDBPortSpinBox->setValue(Settings::values.gdbstub_port); +} + +void ConfigureDebug::applyConfiguration() { + GDBStub::ToggleServer(ui->toogleGDBStub->isChecked()); + Settings::values.use_gdbstub = ui->toogleGDBStub->isChecked(); + Settings::values.gdbstub_port = ui->GDBPortSpinBox->value(); +} diff --git a/src/citra_qt/configure_debug.h b/src/citra_qt/configure_debug.h new file mode 100644 index 000000000..9b7080d92 --- /dev/null +++ b/src/citra_qt/configure_debug.h @@ -0,0 +1,31 @@ +// Copyright 2016 Citra Emulator Project +// Licensed under GPLv2 or any later version +// Refer to the license.txt file included. + +#ifndef CONFIGURE_DEBUG_H +#define CONFIGURE_DEBUG_H + +#include + +namespace Ui { +class ConfigureDebug; +} + +class ConfigureDebug : public QWidget +{ + Q_OBJECT + +public: + explicit ConfigureDebug(QWidget *parent = 0); + ~ConfigureDebug(); + + void applyConfiguration(); + +private: + void setConfiguration(); + +private: + Ui::ConfigureDebug *ui; +}; + +#endif // CONFIGURE_DEBUG_H diff --git a/src/citra_qt/configure_debug.ui b/src/citra_qt/configure_debug.ui new file mode 100644 index 000000000..80acf6e31 --- /dev/null +++ b/src/citra_qt/configure_debug.ui @@ -0,0 +1,76 @@ + + + ConfigureDebug + + + + 0 + 0 + 400 + 300 + + + + Form + + + + + + + + GDB + + + + + + + + + + Enable GDB Stub + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + Port: + + + + + + + 65536 + + + + + + + + + + + + + + + + + diff --git a/src/citra_qt/configure_dialog.cpp b/src/citra_qt/configure_dialog.cpp new file mode 100644 index 000000000..ae442adcd --- /dev/null +++ b/src/citra_qt/configure_dialog.cpp @@ -0,0 +1,32 @@ +// Copyright 2016 Citra Emulator Project +// Licensed under GPLv2 or any later version +// Refer to the license.txt file included. + +#include "configure_dialog.h" +#include "ui_configure.h" + +#include "config.h" + +#include "core/settings.h" + +ConfigureDialog::ConfigureDialog(QWidget *parent) : + QDialog(parent), + ui(new Ui::ConfigureDialog) +{ + ui->setupUi(this); + this->setConfiguration(); +} + +ConfigureDialog::~ConfigureDialog() { + delete ui; +} + +void ConfigureDialog::setConfiguration() { +} + +void ConfigureDialog::applyConfiguration() { + Config config; + ui->generalTab->applyConfiguration(); + ui->debugTab->applyConfiguration(); + config.Save(); +} diff --git a/src/citra_qt/configure_dialog.h b/src/citra_qt/configure_dialog.h new file mode 100644 index 000000000..d66049340 --- /dev/null +++ b/src/citra_qt/configure_dialog.h @@ -0,0 +1,31 @@ +// Copyright 2016 Citra Emulator Project +// Licensed under GPLv2 or any later version +// Refer to the license.txt file included. + +#ifndef CONFIGURE_DIALOG_H +#define CONFIGURE_DIALOG_H + +#include + +namespace Ui { +class ConfigureDialog; +} + +class ConfigureDialog : public QDialog +{ + Q_OBJECT + +public: + explicit ConfigureDialog(QWidget *parent = 0); + ~ConfigureDialog(); + + void applyConfiguration(); + +private: + void setConfiguration(); + +private: + Ui::ConfigureDialog *ui; +}; + +#endif // CONFIGURE_DIALOG_H diff --git a/src/citra_qt/configure_general.cpp b/src/citra_qt/configure_general.cpp new file mode 100644 index 000000000..71d992ebe --- /dev/null +++ b/src/citra_qt/configure_general.cpp @@ -0,0 +1,40 @@ +// Copyright 2016 Citra Emulator Project +// Licensed under GPLv2 or any later version +// Refer to the license.txt file included. + +#include "citra_qt/configure_general.h" +#include "citra_qt/ui_configure_general.h" +#include "citra_qt/ui_settings.h" + +#include "core/settings.h" + +#include "video_core/video_core.h" + +ConfigureGeneral::ConfigureGeneral(QWidget *parent) : + QWidget(parent), + ui(new Ui::ConfigureGeneral) +{ + ui->setupUi(this); + this->setConfiguration(); +} + +ConfigureGeneral::~ConfigureGeneral() +{ + delete ui; +} + +void ConfigureGeneral::setConfiguration() { + ui->toogleCheckExit->setChecked(UISettings::values.check_closure); + ui->toogleHWRenderer->setChecked(Settings::values.use_hw_renderer); + ui->toogleShaderJIT->setChecked(Settings::values.use_shader_jit); +} + +void ConfigureGeneral::applyConfiguration() { + UISettings::values.check_closure = ui->toogleCheckExit->isChecked(); + + VideoCore::g_hw_renderer_enabled = + Settings::values.use_hw_renderer = ui->toogleHWRenderer->isChecked(); + + VideoCore::g_shader_jit_enabled = + Settings::values.use_shader_jit = ui->toogleShaderJIT->isChecked(); +} diff --git a/src/citra_qt/configure_general.h b/src/citra_qt/configure_general.h new file mode 100644 index 000000000..0f3b69332 --- /dev/null +++ b/src/citra_qt/configure_general.h @@ -0,0 +1,31 @@ +// Copyright 2016 Citra Emulator Project +// Licensed under GPLv2 or any later version +// Refer to the license.txt file included. + +#ifndef CONFIGURE_GENERAL_H +#define CONFIGURE_GENERAL_H + +#include + +namespace Ui { +class ConfigureGeneral; +} + +class ConfigureGeneral : public QWidget +{ + Q_OBJECT + +public: + explicit ConfigureGeneral(QWidget *parent = 0); + ~ConfigureGeneral(); + + void applyConfiguration(); + +private: + void setConfiguration(); + +private: + Ui::ConfigureGeneral *ui; +}; + +#endif // CONFIGURE_GENERAL_H diff --git a/src/citra_qt/configure_general.ui b/src/citra_qt/configure_general.ui new file mode 100644 index 000000000..f847d3c6c --- /dev/null +++ b/src/citra_qt/configure_general.ui @@ -0,0 +1,96 @@ + + + ConfigureGeneral + + + + 0 + 0 + 284 + 377 + + + + Form + + + + + + + + General + + + + + + + + Confirm exit while emulation is running + + + + + + + + + + + + Performance + + + + + + + + Enable hardware renderer + + + + + + + Enable Shader JIT + + + + + + + + + + + + Hotkeys + + + + + + + + + + + + + + + + + + + GHotkeysDialog + QWidget +
hotkeys.h
+ 1 +
+
+ + +
diff --git a/src/citra_qt/hotkeys.cpp b/src/citra_qt/hotkeys.cpp index ed6b12fc4..929ba6f0e 100644 --- a/src/citra_qt/hotkeys.cpp +++ b/src/citra_qt/hotkeys.cpp @@ -94,7 +94,7 @@ QShortcut* GetHotkey(const QString& group, const QString& action, QWidget* widge } -GHotkeysDialog::GHotkeysDialog(QWidget* parent): QDialog(parent) +GHotkeysDialog::GHotkeysDialog(QWidget* parent): QWidget(parent) { ui.setupUi(this); diff --git a/src/citra_qt/hotkeys.h b/src/citra_qt/hotkeys.h index 2fe635882..50e6cbc21 100644 --- a/src/citra_qt/hotkeys.h +++ b/src/citra_qt/hotkeys.h @@ -42,7 +42,7 @@ void SaveHotkeys(QSettings& settings); */ void LoadHotkeys(QSettings& settings); -class GHotkeysDialog : public QDialog +class GHotkeysDialog : public QWidget { Q_OBJECT diff --git a/src/citra_qt/hotkeys.ui b/src/citra_qt/hotkeys.ui index 38a9a14d1..050fe064e 100644 --- a/src/citra_qt/hotkeys.ui +++ b/src/citra_qt/hotkeys.ui @@ -1,7 +1,7 @@ hotkeys - + 0 @@ -39,51 +39,8 @@ - - - - Qt::Horizontal - - - QDialogButtonBox::Cancel|QDialogButtonBox::Ok|QDialogButtonBox::Reset - - - - - - buttonBox - accepted() - hotkeys - accept() - - - 248 - 254 - - - 157 - 274 - - - - - buttonBox - rejected() - hotkeys - reject() - - - 316 - 260 - - - 286 - 274 - - - - + diff --git a/src/citra_qt/main.cpp b/src/citra_qt/main.cpp index 32cceaf7e..573036a2a 100644 --- a/src/citra_qt/main.cpp +++ b/src/citra_qt/main.cpp @@ -13,6 +13,7 @@ #include "citra_qt/bootmanager.h" #include "citra_qt/config.h" +#include "citra_qt/configure_dialog.h" #include "citra_qt/game_list.h" #include "citra_qt/hotkeys.h" #include "citra_qt/main.h" @@ -145,17 +146,9 @@ GMainWindow::GMainWindow() : emu_thread(nullptr) game_list->LoadInterfaceLayout(settings); - ui.action_Use_Gdbstub->setChecked(Settings::values.use_gdbstub); - SetGdbstubEnabled(ui.action_Use_Gdbstub->isChecked()); - + GDBStub::ToggleServer(Settings::values.use_gdbstub); GDBStub::SetServerPort(static_cast(Settings::values.gdbstub_port)); - ui.action_Use_Hardware_Renderer->setChecked(Settings::values.use_hw_renderer); - SetHardwareRendererEnabled(ui.action_Use_Hardware_Renderer->isChecked()); - - ui.action_Use_Shader_JIT->setChecked(Settings::values.use_shader_jit); - SetShaderJITEnabled(ui.action_Use_Shader_JIT->isChecked()); - ui.action_Single_Window_Mode->setChecked(settings.value("singleWindowMode", true).toBool()); ToggleWindowMode(); @@ -176,17 +169,14 @@ GMainWindow::GMainWindow() : emu_thread(nullptr) // Setup connections connect(game_list, SIGNAL(GameChosen(QString)), this, SLOT(OnGameListLoadFile(QString))); + connect(ui.action_Configure, SIGNAL(triggered()), this, SLOT(OnConfigure())); connect(ui.action_Load_File, SIGNAL(triggered()), this, SLOT(OnMenuLoadFile())); connect(ui.action_Load_Symbol_Map, SIGNAL(triggered()), this, SLOT(OnMenuLoadSymbolMap())); connect(ui.action_Select_Game_List_Root, SIGNAL(triggered()), this, SLOT(OnMenuSelectGameListRoot())); connect(ui.action_Start, SIGNAL(triggered()), this, SLOT(OnStartGame())); connect(ui.action_Pause, SIGNAL(triggered()), this, SLOT(OnPauseGame())); connect(ui.action_Stop, SIGNAL(triggered()), this, SLOT(OnStopGame())); - connect(ui.action_Use_Hardware_Renderer, SIGNAL(triggered(bool)), this, SLOT(SetHardwareRendererEnabled(bool))); - connect(ui.action_Use_Shader_JIT, SIGNAL(triggered(bool)), this, SLOT(SetShaderJITEnabled(bool))); - connect(ui.action_Use_Gdbstub, SIGNAL(triggered(bool)), this, SLOT(SetGdbstubEnabled(bool))); connect(ui.action_Single_Window_Mode, SIGNAL(triggered(bool)), this, SLOT(ToggleWindowMode())); - connect(ui.action_Hotkeys, SIGNAL(triggered()), this, SLOT(OnOpenHotkeysDialog())); connect(this, SIGNAL(EmulationStarting(EmuThread*)), disasmWidget, SLOT(OnEmulationStarting(EmuThread*))); connect(this, SIGNAL(EmulationStopping()), disasmWidget, SLOT(OnEmulationStopping())); @@ -496,31 +486,6 @@ void GMainWindow::OnStopGame() { ShutdownGame(); } -void GMainWindow::OnOpenHotkeysDialog() { - GHotkeysDialog dialog(this); - dialog.exec(); -} - -void GMainWindow::SetHardwareRendererEnabled(bool enabled) { - VideoCore::g_hw_renderer_enabled = enabled; - - Config config; - Settings::values.use_hw_renderer = enabled; - config.Save(); -} - -void GMainWindow::SetGdbstubEnabled(bool enabled) { - GDBStub::ToggleServer(enabled); -} - -void GMainWindow::SetShaderJITEnabled(bool enabled) { - VideoCore::g_shader_jit_enabled = enabled; - - Config config; - Settings::values.use_shader_jit = enabled; - config.Save(); -} - void GMainWindow::ToggleWindowMode() { if (ui.action_Single_Window_Mode->isChecked()) { // Render in the main window... @@ -547,7 +512,12 @@ void GMainWindow::ToggleWindowMode() { } void GMainWindow::OnConfigure() { - //GControllerConfigDialog* dialog = new GControllerConfigDialog(controller_ports, this); + ConfigureDialog configureDialog(this); + auto result = configureDialog.exec(); + if ( result == QDialog::Accepted) + { + configureDialog.applyConfiguration(); + } } bool GMainWindow::ConfirmClose() { diff --git a/src/citra_qt/main.h b/src/citra_qt/main.h index 6e4e56689..7fe425b40 100644 --- a/src/citra_qt/main.h +++ b/src/citra_qt/main.h @@ -104,12 +104,8 @@ private slots: /// Called whenever a user selects the "File->Select Game List Root" menu item void OnMenuSelectGameListRoot(); void OnMenuRecentFile(); - void OnOpenHotkeysDialog(); void OnConfigure(); void OnDisplayTitleBars(bool); - void SetHardwareRendererEnabled(bool); - void SetGdbstubEnabled(bool); - void SetShaderJITEnabled(bool); void ToggleWindowMode(); private: diff --git a/src/citra_qt/main.ui b/src/citra_qt/main.ui index 1e8a07cfb..441e0b81e 100644 --- a/src/citra_qt/main.ui +++ b/src/citra_qt/main.ui @@ -45,7 +45,7 @@ 0 0 1081 - 22 + 19 @@ -73,9 +73,6 @@ - - - @@ -84,7 +81,6 @@ - @@ -150,35 +146,6 @@ Single Window Mode - - - Configure &Hotkeys ... - - - - - true - - - Use Hardware Renderer - - - - - true - - - Use Shader JIT - - - - - true - - - Use Gdbstub - - Configure ... @@ -219,22 +186,6 @@ - - action_Configure - triggered() - MainWindow - OnConfigure() - - - -1 - -1 - - - 540 - 364 - - - actionDisplay_widget_title_bars triggered(bool) diff --git a/src/citra_qt/ui_settings.cpp b/src/citra_qt/ui_settings.cpp new file mode 100644 index 000000000..5f2215899 --- /dev/null +++ b/src/citra_qt/ui_settings.cpp @@ -0,0 +1,11 @@ +// Copyright 2016 Citra Emulator Project +// Licensed under GPLv2 or any later version +// Refer to the license.txt file included. + +#include "ui_settings.h" + +namespace UISettings { + +Values values = {}; + +} diff --git a/src/citra_qt/ui_settings.h b/src/citra_qt/ui_settings.h new file mode 100644 index 000000000..f0afbf2d3 --- /dev/null +++ b/src/citra_qt/ui_settings.h @@ -0,0 +1,16 @@ +// Copyright 2016 Citra Emulator Project +// Licensed under GPLv2 or any later version +// Refer to the license.txt file included. + +#ifndef UISETTINGS_H +#define UISETTINGS_H + +namespace UISettings { + +struct Values { + bool check_closure; +} extern values; + +} + +#endif // UISETTINGS_H From e33b9385054169c2850717e9c969a2531ee9b6f2 Mon Sep 17 00:00:00 2001 From: LittleWhite Date: Sun, 24 Jan 2016 21:23:55 +0100 Subject: [PATCH 002/104] Whole config is handled by Config class. This also means : we have only one config file, now --- src/citra_qt/config.cpp | 80 +++++++++++++++++++++++++- src/citra_qt/game_list.cpp | 13 ++--- src/citra_qt/game_list.h | 4 +- src/citra_qt/hotkeys.cpp | 51 ++++++----------- src/citra_qt/hotkeys.h | 4 +- src/citra_qt/main.cpp | 112 +++++++++++++------------------------ src/citra_qt/main.h | 3 + src/citra_qt/ui_settings.h | 32 +++++++++++ 8 files changed, 181 insertions(+), 118 deletions(-) diff --git a/src/citra_qt/config.cpp b/src/citra_qt/config.cpp index 8e247ff5c..981d92a9c 100644 --- a/src/citra_qt/config.cpp +++ b/src/citra_qt/config.cpp @@ -7,12 +7,12 @@ #include #include "citra_qt/config.h" +#include "citra_qt/ui_settings.h" #include "common/file_util.h" #include "core/settings.h" Config::Config() { - // TODO: Don't hardcode the path; let the frontend decide where to put the config files. qt_config_loc = FileUtil::GetUserPath(D_CONFIG_IDX) + "qt-config.ini"; FileUtil::CreateFullPath(qt_config_loc); @@ -67,6 +67,51 @@ void Config::ReadValues() { Settings::values.use_gdbstub = qt_config->value("use_gdbstub", false).toBool(); Settings::values.gdbstub_port = qt_config->value("gdbstub_port", 24689).toInt(); qt_config->endGroup(); + + qt_config->beginGroup("UI"); + + qt_config->beginGroup("UILayout"); + UISettings::values.geometry = qt_config->value("geometry").toByteArray(); + UISettings::values.state = qt_config->value("state").toByteArray(); + UISettings::values.renderwindow_geometry = qt_config->value("geometryRenderWindow").toByteArray(); + UISettings::values.gamelist_header_state = qt_config->value("gameListHeaderState").toByteArray(); + UISettings::values.microprofile_geometry = qt_config->value("microProfileDialogGeometry").toByteArray(); + UISettings::values.microprofile_visible = qt_config->value("microProfileDialogVisible", false).toBool(); + qt_config->endGroup(); + + qt_config->beginGroup("Paths"); + UISettings::values.roms_path = qt_config->value("romsPath").toString(); + UISettings::values.symbols_path = qt_config->value("symbolsPath").toString(); + UISettings::values.gamedir_path = qt_config->value("gameListRootDir", ".").toString(); + UISettings::values.gamedir_deepscan = qt_config->value("gameListDeepScan", false).toBool(); + UISettings::values.recent_files = qt_config->value("recentFiles").toStringList(); + qt_config->endGroup(); + + qt_config->beginGroup("Shortcuts"); + QStringList groups = qt_config->childGroups(); + for (auto group : groups) + { + qt_config->beginGroup(group); + + QStringList hotkeys = qt_config->childGroups(); + for (auto hotkey : hotkeys) + { + qt_config->beginGroup(hotkey); + UISettings::values.shortcuts.push_back(UISettings::Shortcut(group + "/" + hotkey, + UISettings::ContextedShortcut(qt_config->value("KeySeq").toString(), + qt_config->value("Context").toInt()))); + qt_config->endGroup(); + } + + qt_config->endGroup(); + } + qt_config->endGroup(); + + UISettings::values.single_window_mode = qt_config->value("singleWindowMode", true).toBool(); + UISettings::values.display_titlebar = qt_config->value("displayTitleBars", true).toBool(); + UISettings::values.first_start = qt_config->value("firstStart", true).toBool(); + + qt_config->endGroup(); } void Config::SaveValues() { @@ -107,6 +152,39 @@ void Config::SaveValues() { qt_config->setValue("use_gdbstub", Settings::values.use_gdbstub); qt_config->setValue("gdbstub_port", Settings::values.gdbstub_port); qt_config->endGroup(); + + qt_config->beginGroup("UI"); + + qt_config->beginGroup("UILayout"); + qt_config->setValue("geometry", UISettings::values.geometry); + qt_config->setValue("state", UISettings::values.state); + qt_config->setValue("geometryRenderWindow", UISettings::values.renderwindow_geometry); + qt_config->setValue("gameListHeaderState", UISettings::values.gamelist_header_state); + qt_config->setValue("microProfileDialogGeometry", UISettings::values.microprofile_geometry); + qt_config->setValue("microProfileDialogVisible", UISettings::values.microprofile_visible); + qt_config->endGroup(); + + qt_config->beginGroup("Paths"); + qt_config->setValue("romsPath", UISettings::values.roms_path); + qt_config->setValue("symbolsPath", UISettings::values.symbols_path); + qt_config->setValue("gameListRootDir", UISettings::values.gamedir_path); + qt_config->setValue("gameListDeepScan", UISettings::values.gamedir_deepscan); + qt_config->setValue("recentFiles", UISettings::values.recent_files); + qt_config->endGroup(); + + qt_config->beginGroup("Shortcuts"); + for (auto shortcut : UISettings::values.shortcuts ) + { + qt_config->setValue(shortcut.first + "/KeySeq", shortcut.second.first); + qt_config->setValue(shortcut.first + "/Context", shortcut.second.second); + } + qt_config->endGroup(); + + qt_config->setValue("singleWindowMode", UISettings::values.single_window_mode); + qt_config->setValue("displayTitleBars", UISettings::values.display_titlebar); + qt_config->setValue("firstStart", UISettings::values.first_start); + + qt_config->endGroup(); } void Config::Reload() { diff --git a/src/citra_qt/game_list.cpp b/src/citra_qt/game_list.cpp index 1f8d69a03..faf057269 100644 --- a/src/citra_qt/game_list.cpp +++ b/src/citra_qt/game_list.cpp @@ -8,6 +8,7 @@ #include "game_list.h" #include "game_list_p.h" +#include "ui_settings.h" #include "core/loader/loader.h" @@ -100,19 +101,15 @@ void GameList::PopulateAsync(const QString& dir_path, bool deep_scan) current_worker = std::move(worker); } -void GameList::SaveInterfaceLayout(QSettings& settings) +void GameList::SaveInterfaceLayout() { - settings.beginGroup("UILayout"); - settings.setValue("gameListHeaderState", tree_view->header()->saveState()); - settings.endGroup(); + UISettings::values.gamelist_header_state = tree_view->header()->saveState(); } -void GameList::LoadInterfaceLayout(QSettings& settings) +void GameList::LoadInterfaceLayout() { auto header = tree_view->header(); - settings.beginGroup("UILayout"); - header->restoreState(settings.value("gameListHeaderState").toByteArray()); - settings.endGroup(); + header->restoreState(UISettings::values.gamelist_header_state); item_model->sort(header->sortIndicatorSection(), header->sortIndicatorOrder()); } diff --git a/src/citra_qt/game_list.h b/src/citra_qt/game_list.h index 0950d9622..48febdc60 100644 --- a/src/citra_qt/game_list.h +++ b/src/citra_qt/game_list.h @@ -31,8 +31,8 @@ public: void PopulateAsync(const QString& dir_path, bool deep_scan); - void SaveInterfaceLayout(QSettings& settings); - void LoadInterfaceLayout(QSettings& settings); + void SaveInterfaceLayout(); + void LoadInterfaceLayout(); public slots: void AddEntry(QList entry_items); diff --git a/src/citra_qt/hotkeys.cpp b/src/citra_qt/hotkeys.cpp index 929ba6f0e..92525d53c 100644 --- a/src/citra_qt/hotkeys.cpp +++ b/src/citra_qt/hotkeys.cpp @@ -4,11 +4,12 @@ #include +#include #include -#include #include #include "citra_qt/hotkeys.h" +#include "citra_qt/ui_settings.h" struct Hotkey { @@ -24,54 +25,38 @@ typedef std::map HotkeyGroupMap; HotkeyGroupMap hotkey_groups; -void SaveHotkeys(QSettings& settings) +void SaveHotkeys() { - settings.beginGroup("Shortcuts"); - + UISettings::values.shortcuts.clear(); for (auto group : hotkey_groups) { - settings.beginGroup(group.first); for (auto hotkey : group.second) { - settings.beginGroup(hotkey.first); - settings.setValue(QString("KeySeq"), hotkey.second.keyseq.toString()); - settings.setValue(QString("Context"), hotkey.second.context); - settings.endGroup(); + UISettings::values.shortcuts.push_back(UISettings::Shortcut(group.first + "/" + hotkey.first, + UISettings::ContextedShortcut(hotkey.second.keyseq.toString(), + hotkey.second.context))); } - settings.endGroup(); } - settings.endGroup(); } -void LoadHotkeys(QSettings& settings) +void LoadHotkeys() { - settings.beginGroup("Shortcuts"); - // Make sure NOT to use a reference here because it would become invalid once we call beginGroup() - QStringList groups = settings.childGroups(); - for (auto group : groups) + for (auto shortcut : UISettings::values.shortcuts) { - settings.beginGroup(group); + QStringList cat = shortcut.first.split("/"); + Q_ASSERT(cat.size() >= 2); - QStringList hotkeys = settings.childGroups(); - for (auto hotkey : hotkeys) + // RegisterHotkey assigns default keybindings, so use old values as default parameters + Hotkey& hk = hotkey_groups[cat[0]][cat[1]]; + if (!shortcut.second.first.isEmpty()) { - settings.beginGroup(hotkey); - - // RegisterHotkey assigns default keybindings, so use old values as default parameters - Hotkey& hk = hotkey_groups[group][hotkey]; - hk.keyseq = QKeySequence::fromString(settings.value("KeySeq", hk.keyseq.toString()).toString()); - hk.context = (Qt::ShortcutContext)settings.value("Context", hk.context).toInt(); - if (hk.shortcut) - hk.shortcut->setKey(hk.keyseq); - - settings.endGroup(); + hk.keyseq = QKeySequence::fromString(shortcut.second.first); + hk.context = (Qt::ShortcutContext)shortcut.second.second; } - - settings.endGroup(); + if (hk.shortcut) + hk.shortcut->setKey(hk.keyseq); } - - settings.endGroup(); } void RegisterHotkey(const QString& group, const QString& action, const QKeySequence& default_keyseq, Qt::ShortcutContext default_context) diff --git a/src/citra_qt/hotkeys.h b/src/citra_qt/hotkeys.h index 50e6cbc21..79a685074 100644 --- a/src/citra_qt/hotkeys.h +++ b/src/citra_qt/hotkeys.h @@ -33,14 +33,14 @@ QShortcut* GetHotkey(const QString& group, const QString& action, QWidget* widge * * @note Each hotkey group will be stored a settings group; For each hotkey inside that group, a settings group will be created to store the key sequence and the hotkey context. */ -void SaveHotkeys(QSettings& settings); +void SaveHotkeys(); /** * Loads hotkeys from the settings file. * * @note Yet unregistered hotkeys which are present in the settings will automatically be registered. */ -void LoadHotkeys(QSettings& settings); +void LoadHotkeys(); class GHotkeysDialog : public QWidget { diff --git a/src/citra_qt/main.cpp b/src/citra_qt/main.cpp index 573036a2a..26904c71d 100644 --- a/src/citra_qt/main.cpp +++ b/src/citra_qt/main.cpp @@ -17,6 +17,7 @@ #include "citra_qt/game_list.h" #include "citra_qt/hotkeys.h" #include "citra_qt/main.h" +#include "citra_qt/ui_settings.h" // Debugger #include "citra_qt/debugger/callstack.h" @@ -51,12 +52,10 @@ #include "video_core/video_core.h" -GMainWindow::GMainWindow() : emu_thread(nullptr) +GMainWindow::GMainWindow() : config(new Config()), emu_thread(nullptr) { Pica::g_debug_context = Pica::DebugContext::Construct(); - Config config; - ui.setupUi(this); statusBar()->hide(); @@ -134,25 +133,21 @@ GMainWindow::GMainWindow() : emu_thread(nullptr) setGeometry(x, y, w, h); // Restore UI state - QSettings settings; + restoreGeometry(UISettings::values.geometry); + restoreState(UISettings::values.state); + render_window->restoreGeometry(UISettings::values.renderwindow_geometry); + microProfileDialog->restoreGeometry(UISettings::values.microprofile_geometry); + microProfileDialog->setVisible(UISettings::values.microprofile_visible); - settings.beginGroup("UILayout"); - restoreGeometry(settings.value("geometry").toByteArray()); - restoreState(settings.value("state").toByteArray()); - render_window->restoreGeometry(settings.value("geometryRenderWindow").toByteArray()); - microProfileDialog->restoreGeometry(settings.value("microProfileDialogGeometry").toByteArray()); - microProfileDialog->setVisible(settings.value("microProfileDialogVisible").toBool()); - settings.endGroup(); - - game_list->LoadInterfaceLayout(settings); + game_list->LoadInterfaceLayout(); GDBStub::ToggleServer(Settings::values.use_gdbstub); GDBStub::SetServerPort(static_cast(Settings::values.gdbstub_port)); - ui.action_Single_Window_Mode->setChecked(settings.value("singleWindowMode", true).toBool()); + ui.action_Single_Window_Mode->setChecked(UISettings::values.single_window_mode); ToggleWindowMode(); - ui.actionDisplay_widget_title_bars->setChecked(settings.value("displayTitleBars", true).toBool()); + ui.actionDisplay_widget_title_bars->setChecked(UISettings::values.display_titlebar); OnDisplayTitleBars(ui.actionDisplay_widget_title_bars->isChecked()); // Prepare actions for recent files @@ -165,12 +160,10 @@ GMainWindow::GMainWindow() : emu_thread(nullptr) } UpdateRecentFiles(); - confirm_before_closing = settings.value("confirmClose", true).toBool(); - // Setup connections - connect(game_list, SIGNAL(GameChosen(QString)), this, SLOT(OnGameListLoadFile(QString))); + connect(game_list, SIGNAL(GameChosen(QString)), this, SLOT(OnGameListLoadFile(QString)), Qt::DirectConnection); connect(ui.action_Configure, SIGNAL(triggered()), this, SLOT(OnConfigure())); - connect(ui.action_Load_File, SIGNAL(triggered()), this, SLOT(OnMenuLoadFile())); + connect(ui.action_Load_File, SIGNAL(triggered()), this, SLOT(OnMenuLoadFile()),Qt::DirectConnection); connect(ui.action_Load_Symbol_Map, SIGNAL(triggered()), this, SLOT(OnMenuLoadSymbolMap())); connect(ui.action_Select_Game_List_Root, SIGNAL(triggered()), this, SLOT(OnMenuSelectGameListRoot())); connect(ui.action_Start, SIGNAL(triggered()), this, SLOT(OnStartGame())); @@ -191,7 +184,7 @@ GMainWindow::GMainWindow() : emu_thread(nullptr) // Setup hotkeys RegisterHotkey("Main Window", "Load File", QKeySequence::Open); RegisterHotkey("Main Window", "Start Emulation"); - LoadHotkeys(settings); + LoadHotkeys(); connect(GetHotkey("Main Window", "Load File", this), SIGNAL(activated()), this, SLOT(OnMenuLoadFile())); connect(GetHotkey("Main Window", "Start Emulation", this), SIGNAL(activated()), this, SLOT(OnStartGame())); @@ -201,7 +194,7 @@ GMainWindow::GMainWindow() : emu_thread(nullptr) show(); - game_list->PopulateAsync(settings.value("gameListRootDir", ".").toString(), settings.value("gameListDeepScan", false).toBool()); + game_list->PopulateAsync(UISettings::values.gamedir_path, UISettings::values.gamedir_deepscan); QStringList args = QApplication::arguments(); if (args.length() >= 2) { @@ -365,32 +358,24 @@ void GMainWindow::ShutdownGame() { emulation_running = false; } -void GMainWindow::StoreRecentFile(const std::string& filename) -{ - QSettings settings; - QStringList recent_files = settings.value("recentFiles").toStringList(); - recent_files.prepend(QString::fromStdString(filename)); - recent_files.removeDuplicates(); - while (recent_files.size() > max_recent_files_item) { - recent_files.removeLast(); +void GMainWindow::StoreRecentFile(const std::string& filename) { + UISettings::values.recent_files.prepend(QString::fromStdString(filename)); + UISettings::values.recent_files.removeDuplicates(); + while (UISettings::values.recent_files.size() > max_recent_files_item) { + UISettings::values.recent_files.removeLast(); } - settings.setValue("recentFiles", recent_files); - UpdateRecentFiles(); } void GMainWindow::UpdateRecentFiles() { - QSettings settings; - QStringList recent_files = settings.value("recentFiles").toStringList(); - - unsigned int num_recent_files = std::min(recent_files.size(), static_cast(max_recent_files_item)); + unsigned int num_recent_files = std::min(UISettings::values.recent_files.size(), static_cast(max_recent_files_item)); for (unsigned int i = 0; i < num_recent_files; i++) { - QString text = QString("&%1. %2").arg(i + 1).arg(QFileInfo(recent_files[i]).fileName()); + QString text = QString("&%1. %2").arg(i + 1).arg(QFileInfo(UISettings::values.recent_files[i]).fileName()); actions_recent_files[i]->setText(text); - actions_recent_files[i]->setData(recent_files[i]); - actions_recent_files[i]->setToolTip(recent_files[i]); + actions_recent_files[i]->setData(UISettings::values.recent_files[i]); + actions_recent_files[i]->setToolTip(UISettings::values.recent_files[i]); actions_recent_files[i]->setVisible(true); } @@ -411,36 +396,28 @@ void GMainWindow::OnGameListLoadFile(QString game_path) { } void GMainWindow::OnMenuLoadFile() { - QSettings settings; - QString rom_path = settings.value("romsPath", QString()).toString(); - - QString filename = QFileDialog::getOpenFileName(this, tr("Load File"), rom_path, tr("3DS executable (*.3ds *.3dsx *.elf *.axf *.cci *.cxi)")); + QString filename = QFileDialog::getOpenFileName(this, tr("Load File"), UISettings::values.roms_path, tr("3DS executable (*.3ds *.3dsx *.elf *.axf *.cci *.cxi)")); if (!filename.isEmpty()) { - settings.setValue("romsPath", QFileInfo(filename).path()); + UISettings::values.roms_path = QFileInfo(filename).path(); BootGame(filename.toLocal8Bit().data()); } } void GMainWindow::OnMenuLoadSymbolMap() { - QSettings settings; - QString symbol_path = settings.value("symbolsPath", QString()).toString(); - - QString filename = QFileDialog::getOpenFileName(this, tr("Load Symbol Map"), symbol_path, tr("Symbol map (*)")); + QString filename = QFileDialog::getOpenFileName(this, tr("Load Symbol Map"), UISettings::values.symbols_path, tr("Symbol map (*)")); if (!filename.isEmpty()) { - settings.setValue("symbolsPath", QFileInfo(filename).path()); + UISettings::values.symbols_path = QFileInfo(filename).path(); LoadSymbolMap(filename.toLocal8Bit().data()); } } void GMainWindow::OnMenuSelectGameListRoot() { - QSettings settings; - QString dir_path = QFileDialog::getExistingDirectory(this, tr("Select Directory")); if (!dir_path.isEmpty()) { - settings.setValue("gameListRootDir", dir_path); - game_list->PopulateAsync(dir_path, settings.value("gameListDeepScan").toBool()); + UISettings::values.gamedir_path = dir_path; + game_list->PopulateAsync(dir_path, UISettings::values.gamedir_deepscan); } } @@ -456,10 +433,7 @@ void GMainWindow::OnMenuRecentFile() { // Display an error message and remove the file from the list. QMessageBox::information(this, tr("File not found"), tr("File \"%1\" not found").arg(filename)); - QSettings settings; - QStringList recent_files = settings.value("recentFiles").toStringList(); - recent_files.removeOne(filename); - settings.setValue("recentFiles", recent_files); + UISettings::values.recent_files.removeOne(filename); UpdateRecentFiles(); } } @@ -536,23 +510,18 @@ void GMainWindow::closeEvent(QCloseEvent* event) { return; } - // Save window layout - QSettings settings(QSettings::IniFormat, QSettings::UserScope, "Citra team", "Citra"); + UISettings::values.geometry = saveGeometry(); + UISettings::values.state = saveState(); + UISettings::values.renderwindow_geometry = render_window->saveGeometry(); + UISettings::values.microprofile_geometry = microProfileDialog->saveGeometry(); + UISettings::values.microprofile_visible = microProfileDialog->isVisible(); - settings.beginGroup("UILayout"); - settings.setValue("geometry", saveGeometry()); - settings.setValue("state", saveState()); - settings.setValue("geometryRenderWindow", render_window->saveGeometry()); - settings.setValue("microProfileDialogGeometry", microProfileDialog->saveGeometry()); - settings.setValue("microProfileDialogVisible", microProfileDialog->isVisible()); - settings.endGroup(); + UISettings::values.single_window_mode = ui.action_Single_Window_Mode->isChecked(); + UISettings::values.display_titlebar = ui.actionDisplay_widget_title_bars->isChecked(); + UISettings::values.first_start = false; - settings.setValue("singleWindowMode", ui.action_Single_Window_Mode->isChecked()); - settings.setValue("displayTitleBars", ui.actionDisplay_widget_title_bars->isChecked()); - settings.setValue("firstStart", false); - settings.setValue("confirmClose", confirm_before_closing); - game_list->SaveInterfaceLayout(settings); - SaveHotkeys(settings); + game_list->SaveInterfaceLayout(); + SaveHotkeys(); // Shutdown session if the emu thread is active... if (emu_thread != nullptr) @@ -577,7 +546,6 @@ int main(int argc, char* argv[]) { }); // Init settings params - QSettings::setDefaultFormat(QSettings::IniFormat); QCoreApplication::setOrganizationName("Citra team"); QCoreApplication::setApplicationName("Citra"); diff --git a/src/citra_qt/main.h b/src/citra_qt/main.h index 7fe425b40..bd620676b 100644 --- a/src/citra_qt/main.h +++ b/src/citra_qt/main.h @@ -10,6 +10,7 @@ #include "ui_main.h" +class Config; class GameList; class GImageInfo; class GRenderWindow; @@ -114,6 +115,8 @@ private: GRenderWindow* render_window; GameList* game_list; + std::unique_ptr config; + // Whether emulation is currently running in Citra. bool emulation_running = false; std::unique_ptr emu_thread; diff --git a/src/citra_qt/ui_settings.h b/src/citra_qt/ui_settings.h index f0afbf2d3..729866d56 100644 --- a/src/citra_qt/ui_settings.h +++ b/src/citra_qt/ui_settings.h @@ -5,10 +5,42 @@ #ifndef UISETTINGS_H #define UISETTINGS_H +#include +#include +#include + +#include + namespace UISettings { + typedef std::pair ContextedShortcut; + typedef std::pair Shortcut; + struct Values { + QByteArray geometry; + QByteArray state; + + QByteArray renderwindow_geometry; + + QByteArray gamelist_header_state; + + QByteArray microprofile_geometry; + bool microprofile_visible; + + bool single_window_mode; + bool display_titlebar; + bool check_closure; + bool first_start; + + QString roms_path; + QString symbols_path; + QString gamedir_path; + bool gamedir_deepscan; + QStringList recent_files; + + // Shortcut name + std::vector shortcuts; } extern values; } From 3eb737a5f5b199fd3f9951a7060255f46011e9ff Mon Sep 17 00:00:00 2001 From: LittleWhite Date: Sun, 24 Jan 2016 21:54:04 +0100 Subject: [PATCH 003/104] Add more stuff to configure. --- src/citra_qt/config.cpp | 22 +++--- src/citra_qt/configure.ui | 4 +- src/citra_qt/configure_debug.cpp | 21 +++--- src/citra_qt/configure_debug.h | 10 ++- src/citra_qt/configure_debug.ui | 108 ++++++++++++++++++----------- src/citra_qt/configure_dialog.cpp | 7 +- src/citra_qt/configure_dialog.h | 10 ++- src/citra_qt/configure_general.cpp | 23 +++--- src/citra_qt/configure_general.h | 10 ++- src/citra_qt/configure_general.ui | 80 +++++++++++++++++++-- src/citra_qt/hotkeys.cpp | 7 +- src/citra_qt/hotkeys.h | 2 + src/citra_qt/main.cpp | 9 +-- src/citra_qt/main.h | 1 - src/citra_qt/ui_settings.h | 17 +++-- 15 files changed, 211 insertions(+), 120 deletions(-) diff --git a/src/citra_qt/config.cpp b/src/citra_qt/config.cpp index 981d92a9c..ecf5c5a75 100644 --- a/src/citra_qt/config.cpp +++ b/src/citra_qt/config.cpp @@ -82,24 +82,23 @@ void Config::ReadValues() { qt_config->beginGroup("Paths"); UISettings::values.roms_path = qt_config->value("romsPath").toString(); UISettings::values.symbols_path = qt_config->value("symbolsPath").toString(); - UISettings::values.gamedir_path = qt_config->value("gameListRootDir", ".").toString(); + UISettings::values.gamedir = qt_config->value("gameListRootDir", ".").toString(); UISettings::values.gamedir_deepscan = qt_config->value("gameListDeepScan", false).toBool(); UISettings::values.recent_files = qt_config->value("recentFiles").toStringList(); qt_config->endGroup(); qt_config->beginGroup("Shortcuts"); QStringList groups = qt_config->childGroups(); - for (auto group : groups) - { + for (auto group : groups) { qt_config->beginGroup(group); QStringList hotkeys = qt_config->childGroups(); - for (auto hotkey : hotkeys) - { + for (auto hotkey : hotkeys) { qt_config->beginGroup(hotkey); - UISettings::values.shortcuts.push_back(UISettings::Shortcut(group + "/" + hotkey, - UISettings::ContextedShortcut(qt_config->value("KeySeq").toString(), - qt_config->value("Context").toInt()))); + UISettings::values.shortcuts.emplace_back( + UISettings::Shortcut(group + "/" + hotkey, + UISettings::ContextualShortcut(qt_config->value("KeySeq").toString(), + qt_config->value("Context").toInt()))); qt_config->endGroup(); } @@ -109,6 +108,7 @@ void Config::ReadValues() { UISettings::values.single_window_mode = qt_config->value("singleWindowMode", true).toBool(); UISettings::values.display_titlebar = qt_config->value("displayTitleBars", true).toBool(); + UISettings::values.confirm_before_closing = qt_config->value("confirmClose",true).toBool(); UISettings::values.first_start = qt_config->value("firstStart", true).toBool(); qt_config->endGroup(); @@ -167,14 +167,13 @@ void Config::SaveValues() { qt_config->beginGroup("Paths"); qt_config->setValue("romsPath", UISettings::values.roms_path); qt_config->setValue("symbolsPath", UISettings::values.symbols_path); - qt_config->setValue("gameListRootDir", UISettings::values.gamedir_path); + qt_config->setValue("gameListRootDir", UISettings::values.gamedir); qt_config->setValue("gameListDeepScan", UISettings::values.gamedir_deepscan); qt_config->setValue("recentFiles", UISettings::values.recent_files); qt_config->endGroup(); qt_config->beginGroup("Shortcuts"); - for (auto shortcut : UISettings::values.shortcuts ) - { + for (auto shortcut : UISettings::values.shortcuts ) { qt_config->setValue(shortcut.first + "/KeySeq", shortcut.second.first); qt_config->setValue(shortcut.first + "/Context", shortcut.second.second); } @@ -182,6 +181,7 @@ void Config::SaveValues() { qt_config->setValue("singleWindowMode", UISettings::values.single_window_mode); qt_config->setValue("displayTitleBars", UISettings::values.display_titlebar); + qt_config->setValue("confirmClose", UISettings::values.confirm_before_closing); qt_config->setValue("firstStart", UISettings::values.first_start); qt_config->endGroup(); diff --git a/src/citra_qt/configure.ui b/src/citra_qt/configure.ui index e4ac9a7d8..3c1f2ebba 100644 --- a/src/citra_qt/configure.ui +++ b/src/citra_qt/configure.ui @@ -7,7 +7,7 @@ 0 0 441 - 401 + 501 @@ -17,7 +17,7 @@ - Dialog + Citra Configuration diff --git a/src/citra_qt/configure_debug.cpp b/src/citra_qt/configure_debug.cpp index f8ff804b2..ba66d0833 100644 --- a/src/citra_qt/configure_debug.cpp +++ b/src/citra_qt/configure_debug.cpp @@ -2,13 +2,12 @@ // Licensed under GPLv2 or any later version // Refer to the license.txt file included. -#include "core/core.h" -#include "core/gdbstub/gdbstub.h" // TODO: can't include gdbstub without core.h -#include "core/settings.h" - -#include "configure_debug.h" +#include "citra_qt/configure_debug.h" #include "ui_configure_debug.h" +#include "core/gdbstub/gdbstub.h" +#include "core/settings.h" + ConfigureDebug::ConfigureDebug(QWidget *parent) : QWidget(parent), ui(new Ui::ConfigureDebug) @@ -18,16 +17,16 @@ ConfigureDebug::ConfigureDebug(QWidget *parent) : } ConfigureDebug::~ConfigureDebug() { - delete ui; } void ConfigureDebug::setConfiguration() { - ui->toogleGDBStub->setChecked(Settings::values.use_gdbstub); - ui->GDBPortSpinBox->setValue(Settings::values.gdbstub_port); + ui->toogle_gdbstub->setChecked(Settings::values.use_gdbstub); + ui->gdbport_spinbox->setEnabled(Settings::values.use_gdbstub); + ui->gdbport_spinbox->setValue(Settings::values.gdbstub_port); } void ConfigureDebug::applyConfiguration() { - GDBStub::ToggleServer(ui->toogleGDBStub->isChecked()); - Settings::values.use_gdbstub = ui->toogleGDBStub->isChecked(); - Settings::values.gdbstub_port = ui->GDBPortSpinBox->value(); + GDBStub::ToggleServer(ui->toogle_gdbstub->isChecked()); + Settings::values.use_gdbstub = ui->toogle_gdbstub->isChecked(); + Settings::values.gdbstub_port = ui->gdbport_spinbox->value(); } diff --git a/src/citra_qt/configure_debug.h b/src/citra_qt/configure_debug.h index 9b7080d92..ab58ebbdc 100644 --- a/src/citra_qt/configure_debug.h +++ b/src/citra_qt/configure_debug.h @@ -2,9 +2,9 @@ // Licensed under GPLv2 or any later version // Refer to the license.txt file included. -#ifndef CONFIGURE_DEBUG_H -#define CONFIGURE_DEBUG_H +#pragma once +#include #include namespace Ui { @@ -16,7 +16,7 @@ class ConfigureDebug : public QWidget Q_OBJECT public: - explicit ConfigureDebug(QWidget *parent = 0); + explicit ConfigureDebug(QWidget *parent = nullptr); ~ConfigureDebug(); void applyConfiguration(); @@ -25,7 +25,5 @@ private: void setConfiguration(); private: - Ui::ConfigureDebug *ui; + std::unique_ptr ui; }; - -#endif // CONFIGURE_DEBUG_H diff --git a/src/citra_qt/configure_debug.ui b/src/citra_qt/configure_debug.ui index 80acf6e31..3ba7f44da 100644 --- a/src/citra_qt/configure_debug.ui +++ b/src/citra_qt/configure_debug.ui @@ -13,54 +13,50 @@ Form - + - + GDB - + - + - - - - - Enable GDB Stub - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - Port: - - - - - - - 65536 - - - - + + + Enable GDB Stub + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + Port: + + + + + + + 65536 + + @@ -69,8 +65,38 @@ + + + + Qt::Vertical + + + + 20 + 40 + + + + - + + + toogle_gdbstub + toggled(bool) + gdbport_spinbox + setEnabled(bool) + + + 84 + 157 + + + 342 + 158 + + + + diff --git a/src/citra_qt/configure_dialog.cpp b/src/citra_qt/configure_dialog.cpp index ae442adcd..87c26c715 100644 --- a/src/citra_qt/configure_dialog.cpp +++ b/src/citra_qt/configure_dialog.cpp @@ -2,10 +2,10 @@ // Licensed under GPLv2 or any later version // Refer to the license.txt file included. -#include "configure_dialog.h" +#include "citra_qt/config.h" +#include "citra_qt/configure_dialog.h" #include "ui_configure.h" -#include "config.h" #include "core/settings.h" @@ -18,15 +18,12 @@ ConfigureDialog::ConfigureDialog(QWidget *parent) : } ConfigureDialog::~ConfigureDialog() { - delete ui; } void ConfigureDialog::setConfiguration() { } void ConfigureDialog::applyConfiguration() { - Config config; ui->generalTab->applyConfiguration(); ui->debugTab->applyConfiguration(); - config.Save(); } diff --git a/src/citra_qt/configure_dialog.h b/src/citra_qt/configure_dialog.h index d66049340..89020eeb4 100644 --- a/src/citra_qt/configure_dialog.h +++ b/src/citra_qt/configure_dialog.h @@ -2,9 +2,9 @@ // Licensed under GPLv2 or any later version // Refer to the license.txt file included. -#ifndef CONFIGURE_DIALOG_H -#define CONFIGURE_DIALOG_H +#pragma once +#include #include namespace Ui { @@ -16,7 +16,7 @@ class ConfigureDialog : public QDialog Q_OBJECT public: - explicit ConfigureDialog(QWidget *parent = 0); + explicit ConfigureDialog(QWidget *parent = nullptr); ~ConfigureDialog(); void applyConfiguration(); @@ -25,7 +25,5 @@ private: void setConfiguration(); private: - Ui::ConfigureDialog *ui; + std::unique_ptr ui; }; - -#endif // CONFIGURE_DIALOG_H diff --git a/src/citra_qt/configure_general.cpp b/src/citra_qt/configure_general.cpp index 71d992ebe..350bd794d 100644 --- a/src/citra_qt/configure_general.cpp +++ b/src/citra_qt/configure_general.cpp @@ -3,8 +3,8 @@ // Refer to the license.txt file included. #include "citra_qt/configure_general.h" -#include "citra_qt/ui_configure_general.h" #include "citra_qt/ui_settings.h" +#include "ui_configure_general.h" #include "core/settings.h" @@ -18,23 +18,26 @@ ConfigureGeneral::ConfigureGeneral(QWidget *parent) : this->setConfiguration(); } -ConfigureGeneral::~ConfigureGeneral() -{ - delete ui; +ConfigureGeneral::~ConfigureGeneral() { } void ConfigureGeneral::setConfiguration() { - ui->toogleCheckExit->setChecked(UISettings::values.check_closure); - ui->toogleHWRenderer->setChecked(Settings::values.use_hw_renderer); - ui->toogleShaderJIT->setChecked(Settings::values.use_shader_jit); + ui->toogle_deepscan->setChecked(UISettings::values.gamedir_deepscan); + ui->toogle_check_exit->setChecked(UISettings::values.confirm_before_closing); + ui->region_combobox->setCurrentIndex(Settings::values.region_value); + ui->toogle_hw_renderer->setChecked(Settings::values.use_hw_renderer); + ui->toogle_shader_jit->setChecked(Settings::values.use_shader_jit); } void ConfigureGeneral::applyConfiguration() { - UISettings::values.check_closure = ui->toogleCheckExit->isChecked(); + UISettings::values.gamedir_deepscan = ui->toogle_deepscan->isChecked(); + UISettings::values.confirm_before_closing = ui->toogle_check_exit->isChecked(); + + Settings::values.region_value = ui->region_combobox->currentIndex(); VideoCore::g_hw_renderer_enabled = - Settings::values.use_hw_renderer = ui->toogleHWRenderer->isChecked(); + Settings::values.use_hw_renderer = ui->toogle_hw_renderer->isChecked(); VideoCore::g_shader_jit_enabled = - Settings::values.use_shader_jit = ui->toogleShaderJIT->isChecked(); + Settings::values.use_shader_jit = ui->toogle_shader_jit->isChecked(); } diff --git a/src/citra_qt/configure_general.h b/src/citra_qt/configure_general.h index 0f3b69332..a6c68e62d 100644 --- a/src/citra_qt/configure_general.h +++ b/src/citra_qt/configure_general.h @@ -2,9 +2,9 @@ // Licensed under GPLv2 or any later version // Refer to the license.txt file included. -#ifndef CONFIGURE_GENERAL_H -#define CONFIGURE_GENERAL_H +#pragma once +#include #include namespace Ui { @@ -16,7 +16,7 @@ class ConfigureGeneral : public QWidget Q_OBJECT public: - explicit ConfigureGeneral(QWidget *parent = 0); + explicit ConfigureGeneral(QWidget *parent = nullptr); ~ConfigureGeneral(); void applyConfiguration(); @@ -25,7 +25,5 @@ private: void setConfiguration(); private: - Ui::ConfigureGeneral *ui; + std::unique_ptr ui; }; - -#endif // CONFIGURE_GENERAL_H diff --git a/src/citra_qt/configure_general.ui b/src/citra_qt/configure_general.ui index f847d3c6c..47184c5c6 100644 --- a/src/citra_qt/configure_general.ui +++ b/src/citra_qt/configure_general.ui @@ -6,7 +6,7 @@ 0 0 - 284 + 300 377 @@ -25,7 +25,14 @@ - + + + Recursive scan for game folder + + + + + Confirm exit while emulation is running @@ -36,6 +43,69 @@ + + + + Emulation + + + + + + + + + + Region: + + + + + + + + JPN + + + + + USA + + + + + EUR + + + + + AUS + + + + + CHN + + + + + KOR + + + + + TWN + + + + + + + + + + + @@ -45,16 +115,16 @@ - + Enable hardware renderer - + - Enable Shader JIT + Enable shader JIT diff --git a/src/citra_qt/hotkeys.cpp b/src/citra_qt/hotkeys.cpp index 92525d53c..41f95c63d 100644 --- a/src/citra_qt/hotkeys.cpp +++ b/src/citra_qt/hotkeys.cpp @@ -32,9 +32,10 @@ void SaveHotkeys() { for (auto hotkey : group.second) { - UISettings::values.shortcuts.push_back(UISettings::Shortcut(group.first + "/" + hotkey.first, - UISettings::ContextedShortcut(hotkey.second.keyseq.toString(), - hotkey.second.context))); + UISettings::values.shortcuts.emplace_back( + UISettings::Shortcut(group.first + "/" + hotkey.first, + UISettings::ContextualShortcut(hotkey.second.keyseq.toString(), + hotkey.second.context))); } } } diff --git a/src/citra_qt/hotkeys.h b/src/citra_qt/hotkeys.h index 79a685074..38aa5f012 100644 --- a/src/citra_qt/hotkeys.h +++ b/src/citra_qt/hotkeys.h @@ -2,6 +2,8 @@ // Licensed under GPLv2 or any later version // Refer to the license.txt file included. +#pragma once + #include "ui_hotkeys.h" class QDialog; diff --git a/src/citra_qt/main.cpp b/src/citra_qt/main.cpp index 26904c71d..a81c6db3f 100644 --- a/src/citra_qt/main.cpp +++ b/src/citra_qt/main.cpp @@ -194,7 +194,7 @@ GMainWindow::GMainWindow() : config(new Config()), emu_thread(nullptr) show(); - game_list->PopulateAsync(UISettings::values.gamedir_path, UISettings::values.gamedir_deepscan); + game_list->PopulateAsync(UISettings::values.gamedir, UISettings::values.gamedir_deepscan); QStringList args = QApplication::arguments(); if (args.length() >= 2) { @@ -416,7 +416,7 @@ void GMainWindow::OnMenuLoadSymbolMap() { void GMainWindow::OnMenuSelectGameListRoot() { QString dir_path = QFileDialog::getExistingDirectory(this, tr("Select Directory")); if (!dir_path.isEmpty()) { - UISettings::values.gamedir_path = dir_path; + UISettings::values.gamedir = dir_path; game_list->PopulateAsync(dir_path, UISettings::values.gamedir_deepscan); } } @@ -488,14 +488,15 @@ void GMainWindow::ToggleWindowMode() { void GMainWindow::OnConfigure() { ConfigureDialog configureDialog(this); auto result = configureDialog.exec(); - if ( result == QDialog::Accepted) + if (result == QDialog::Accepted) { configureDialog.applyConfiguration(); + config->Save(); } } bool GMainWindow::ConfirmClose() { - if (emu_thread == nullptr || !confirm_before_closing) + if (emu_thread == nullptr || !UISettings::values.confirm_before_closing) return true; auto answer = QMessageBox::question(this, tr("Citra"), diff --git a/src/citra_qt/main.h b/src/citra_qt/main.h index bd620676b..477db5c5c 100644 --- a/src/citra_qt/main.h +++ b/src/citra_qt/main.h @@ -130,7 +130,6 @@ private: GPUCommandListWidget* graphicsCommandsWidget; QAction* actions_recent_files[max_recent_files_item]; - bool confirm_before_closing; }; #endif // _CITRA_QT_MAIN_HXX_ diff --git a/src/citra_qt/ui_settings.h b/src/citra_qt/ui_settings.h index 729866d56..62db4a73e 100644 --- a/src/citra_qt/ui_settings.h +++ b/src/citra_qt/ui_settings.h @@ -2,8 +2,7 @@ // Licensed under GPLv2 or any later version // Refer to the license.txt file included. -#ifndef UISETTINGS_H -#define UISETTINGS_H +#pragma once #include #include @@ -13,8 +12,8 @@ namespace UISettings { - typedef std::pair ContextedShortcut; - typedef std::pair Shortcut; +using ContextualShortcut = std::pair ; +using Shortcut = std::pair; struct Values { QByteArray geometry; @@ -30,19 +29,19 @@ struct Values { bool single_window_mode; bool display_titlebar; - bool check_closure; + bool confirm_before_closing; bool first_start; QString roms_path; QString symbols_path; - QString gamedir_path; + QString gamedir; bool gamedir_deepscan; QStringList recent_files; // Shortcut name std::vector shortcuts; -} extern values; +}; + +extern Values values; } - -#endif // UISETTINGS_H From 81d988b0225c91dfda6f73a60d2a2b9b4db37ba1 Mon Sep 17 00:00:00 2001 From: mailwl Date: Tue, 1 Mar 2016 20:41:40 +0300 Subject: [PATCH 004/104] frd:u: Initial stub some functions --- src/common/logging/backend.cpp | 1 + src/common/logging/log.h | 1 + src/core/hle/service/frd/frd.cpp | 91 ++++++++++++++++++++++++ src/core/hle/service/frd/frd.h | 88 ++++++++++++++++++++++++ src/core/hle/service/frd/frd_u.cpp | 107 +++++++++++++++-------------- src/core/hle/service/service.cpp | 3 +- 6 files changed, 236 insertions(+), 55 deletions(-) diff --git a/src/common/logging/backend.cpp b/src/common/logging/backend.cpp index 4c86151ab..757e0cf47 100644 --- a/src/common/logging/backend.cpp +++ b/src/common/logging/backend.cpp @@ -34,6 +34,7 @@ namespace Log { SUB(Kernel, SVC) \ CLS(Service) \ SUB(Service, SRV) \ + SUB(Service, FRD) \ SUB(Service, FS) \ SUB(Service, ERR) \ SUB(Service, APT) \ diff --git a/src/common/logging/log.h b/src/common/logging/log.h index e4c39c308..4da4831c3 100644 --- a/src/common/logging/log.h +++ b/src/common/logging/log.h @@ -49,6 +49,7 @@ enum class Class : ClassType { Service, ///< HLE implementation of system services. Each major service /// should have its own subclass. Service_SRV, ///< The SRV (Service Directory) implementation + Service_FRD, ///< The FRD (Friends) service Service_FS, ///< The FS (Filesystem) service implementation Service_ERR, ///< The ERR (Error) port implementation Service_APT, ///< The APT (Applets) service diff --git a/src/core/hle/service/frd/frd.cpp b/src/core/hle/service/frd/frd.cpp index c13ffd9d2..15d604bb6 100644 --- a/src/core/hle/service/frd/frd.cpp +++ b/src/core/hle/service/frd/frd.cpp @@ -2,6 +2,8 @@ // Licensed under GPLv2 or any later version // Refer to the license.txt file included. +#include "common/string_util.h" + #include "core/hle/service/service.h" #include "core/hle/service/frd/frd.h" #include "core/hle/service/frd/frd_a.h" @@ -10,6 +12,95 @@ namespace Service { namespace FRD { +static FriendKey my_friend_key = {0, 0, 0ull}; +static MyPresence my_presence = {}; + +void GetMyPresence(Service::Interface* self) { + u32* cmd_buff = Kernel::GetCommandBuffer(); + + u32 shifted_out_size = cmd_buff[64]; + u32 my_presence_addr = cmd_buff[65]; + + ASSERT(shifted_out_size == ((sizeof(MyPresence) << 14) | 2)); + + Memory::WriteBlock(my_presence_addr, reinterpret_cast(&my_presence), sizeof(MyPresence)); + + cmd_buff[1] = RESULT_SUCCESS.raw; // No error + + LOG_WARNING(Service_FRD, "(STUBBED) called"); +} + +void GetFriendKeyList(Service::Interface* self) { + u32* cmd_buff = Kernel::GetCommandBuffer(); + + u32 unknown = cmd_buff[1]; + u32 frd_count = cmd_buff[2]; + u32 frd_key_addr = cmd_buff[65]; + + FriendKey zero_key = {}; + for (u32 i = 0; i < frd_count; ++i) { + Memory::WriteBlock(frd_key_addr + i * sizeof(FriendKey), + reinterpret_cast(&zero_key), sizeof(FriendKey)); + } + + cmd_buff[1] = RESULT_SUCCESS.raw; // No error + cmd_buff[2] = 0; // 0 friends + LOG_WARNING(Service_FRD, "(STUBBED) called, unknown=%d, frd_count=%d, frd_key_addr=0x%08X", + unknown, frd_count, frd_key_addr); +} + +void GetFriendProfile(Service::Interface* self) { + u32* cmd_buff = Kernel::GetCommandBuffer(); + + u32 count = cmd_buff[1]; + u32 frd_key_addr = cmd_buff[3]; + u32 profiles_addr = cmd_buff[65]; + + Profile zero_profile = {}; + for (u32 i = 0; i < count; ++i) { + Memory::WriteBlock(profiles_addr + i * sizeof(Profile), + reinterpret_cast(&zero_profile), sizeof(Profile)); + } + + cmd_buff[1] = RESULT_SUCCESS.raw; // No error + LOG_WARNING(Service_FRD, "(STUBBED) called, count=%d, frd_key_addr=0x%08X, profiles_addr=0x%08X", + count, frd_key_addr, profiles_addr); +} + +void GetFriendAttributeFlags(Service::Interface* self) { + u32* cmd_buff = Kernel::GetCommandBuffer(); + + u32 count = cmd_buff[1]; + u32 frd_key_addr = cmd_buff[3]; + u32 attr_flags_addr = cmd_buff[65]; + + for (u32 i = 0; i < count; ++i) { + //TODO:(mailwl) figure out AttributeFlag size and zero all buffer. Assume 1 byte + Memory::Write8(attr_flags_addr + i, 0); + } + + cmd_buff[1] = RESULT_SUCCESS.raw; // No error + LOG_WARNING(Service_FRD, "(STUBBED) called, count=%d, frd_key_addr=0x%08X, attr_flags_addr=0x%08X", + count, frd_key_addr, attr_flags_addr); +} + +void GetMyFriendKey(Service::Interface* self) { + u32* cmd_buff = Kernel::GetCommandBuffer(); + + cmd_buff[1] = RESULT_SUCCESS.raw; // No error + Memory::WriteBlock(cmd_buff[2], reinterpret_cast(&my_friend_key), sizeof(FriendKey)); + LOG_WARNING(Service_FRD, "(STUBBED) called"); +} + +void GetMyScreenName(Service::Interface* self) { + u32* cmd_buff = Kernel::GetCommandBuffer(); + + cmd_buff[1] = RESULT_SUCCESS.raw; // No error + // TODO: (mailwl) get the name from config + Common::UTF8ToUTF16("Citra").copy(reinterpret_cast(&cmd_buff[2]), 11); + LOG_WARNING(Service_FRD, "(STUBBED) called"); +} + void Init() { using namespace Kernel; diff --git a/src/core/hle/service/frd/frd.h b/src/core/hle/service/frd/frd.h index f9f88b444..c8283a7f3 100644 --- a/src/core/hle/service/frd/frd.h +++ b/src/core/hle/service/frd/frd.h @@ -4,9 +4,97 @@ #pragma once +#include "common/common_types.h" + namespace Service { + +class Interface; + namespace FRD { +struct FriendKey { + u32 friend_id; + u32 unknown; + u64 friend_code; +}; + +struct MyPresence { + u8 unknown[0x12C]; +}; + +struct Profile { + u8 region; + u8 country; + u8 area; + u8 language; + u32 unknown; +}; + +/** + * FRD::GetMyPresence service function + * Inputs: + * 64 : sizeof (MyPresence) << 14 | 2 + * 65 : Address of MyPresence structure + * Outputs: + * 1 : Result of function, 0 on success, otherwise error code + */ +void GetMyPresence(Service::Interface* self); + +/** + * FRD::GetFriendKeyList service function + * Inputs: + * 1 : Unknown + * 2 : Max friends count + * 65 : Address of FriendKey List + * Outputs: + * 1 : Result of function, 0 on success, otherwise error code + * 2 : FriendKey count filled + */ +void GetFriendKeyList(Service::Interface* self); + +/** + * FRD::GetFriendProfile service function + * Inputs: + * 1 : Friends count + * 2 : Friends count << 18 | 2 + * 3 : Address of FriendKey List + * 64 : (count * sizeof (Profile)) << 10 | 2 + * 65 : Address of Profiles List + * Outputs: + * 1 : Result of function, 0 on success, otherwise error code + */ +void GetFriendProfile(Service::Interface* self); + +/** + * FRD::GetFriendAttributeFlags service function + * Inputs: + * 1 : Friends count + * 2 : Friends count << 18 | 2 + * 3 : Address of FriendKey List + * 65 : Address of AttributeFlags + * Outputs: + * 1 : Result of function, 0 on success, otherwise error code + */ +void GetFriendAttributeFlags(Service::Interface* self); + +/** + * FRD::GetMyFriendKey service function + * Inputs: + * none + * Outputs: + * 1 : Result of function, 0 on success, otherwise error code + * 2-5 : FriendKey + */ +void GetMyFriendKey(Service::Interface* self); + +/** + * FRD::GetMyScreenName service function + * Outputs: + * 1 : Result of function, 0 on success, otherwise error code + * 2 : UTF16 encoded name (max 11 symbols) + */ +void GetMyScreenName(Service::Interface* self); + /// Initialize FRD service(s) void Init(); diff --git a/src/core/hle/service/frd/frd_u.cpp b/src/core/hle/service/frd/frd_u.cpp index 2c6885377..db8666416 100644 --- a/src/core/hle/service/frd/frd_u.cpp +++ b/src/core/hle/service/frd/frd_u.cpp @@ -2,65 +2,66 @@ // Licensed under GPLv2 or any later version // Refer to the license.txt file included. +#include "core/hle/service/frd/frd.h" #include "core/hle/service/frd/frd_u.h" namespace Service { namespace FRD { const Interface::FunctionInfo FunctionTable[] = { - {0x00010000, nullptr, "HasLoggedIn"}, - {0x00020000, nullptr, "IsOnline"}, - {0x00030000, nullptr, "Login"}, - {0x00040000, nullptr, "Logout"}, - {0x00050000, nullptr, "GetMyFriendKey"}, - {0x00060000, nullptr, "GetMyPreference"}, - {0x00070000, nullptr, "GetMyProfile"}, - {0x00080000, nullptr, "GetMyPresence"}, - {0x00090000, nullptr, "GetMyScreenName"}, - {0x000A0000, nullptr, "GetMyMii"}, - {0x000B0000, nullptr, "GetMyLocalAccountId"}, - {0x000C0000, nullptr, "GetMyPlayingGame"}, - {0x000D0000, nullptr, "GetMyFavoriteGame"}, - {0x000E0000, nullptr, "GetMyNcPrincipalId"}, - {0x000F0000, nullptr, "GetMyComment"}, - {0x00100040, nullptr, "GetMyPassword"}, - {0x00110080, nullptr, "GetFriendKeyList"}, - {0x00120042, nullptr, "GetFriendPresence"}, - {0x00130142, nullptr, "GetFriendScreenName"}, - {0x00140044, nullptr, "GetFriendMii"}, - {0x00150042, nullptr, "GetFriendProfile"}, - {0x00160042, nullptr, "GetFriendRelationship"}, - {0x00170042, nullptr, "GetFriendAttributeFlags"}, - {0x00180044, nullptr, "GetFriendPlayingGame"}, - {0x00190042, nullptr, "GetFriendFavoriteGame"}, - {0x001A00C4, nullptr, "GetFriendInfo"}, - {0x001B0080, nullptr, "IsIncludedInFriendList"}, - {0x001C0042, nullptr, "UnscrambleLocalFriendCode"}, - {0x001D0002, nullptr, "UpdateGameModeDescription"}, - {0x001E02C2, nullptr, "UpdateGameMode"}, - {0x001F0042, nullptr, "SendInvitation"}, - {0x00200002, nullptr, "AttachToEventNotification"}, - {0x00210040, nullptr, "SetNotificationMask"}, - {0x00220040, nullptr, "GetEventNotification"}, - {0x00230000, nullptr, "GetLastResponseResult"}, - {0x00240040, nullptr, "PrincipalIdToFriendCode"}, - {0x00250080, nullptr, "FriendCodeToPrincipalId"}, - {0x00260080, nullptr, "IsValidFriendCode"}, - {0x00270040, nullptr, "ResultToErrorCode"}, - {0x00280244, nullptr, "RequestGameAuthentication"}, - {0x00290000, nullptr, "GetGameAuthenticationData"}, - {0x002A0204, nullptr, "RequestServiceLocator"}, - {0x002B0000, nullptr, "GetServiceLocatorData"}, - {0x002C0002, nullptr, "DetectNatProperties"}, - {0x002D0000, nullptr, "GetNatProperties"}, - {0x002E0000, nullptr, "GetServerTimeInterval"}, - {0x002F0040, nullptr, "AllowHalfAwake"}, - {0x00300000, nullptr, "GetServerTypes"}, - {0x00310082, nullptr, "GetFriendComment"}, - {0x00320042, nullptr, "SetClientSdkVersion"}, - {0x00330000, nullptr, "GetMyApproachContext"}, - {0x00340046, nullptr, "AddFriendWithApproach"}, - {0x00350082, nullptr, "DecryptApproachContext"}, + {0x00010000, nullptr, "HasLoggedIn"}, + {0x00020000, nullptr, "IsOnline"}, + {0x00030000, nullptr, "Login"}, + {0x00040000, nullptr, "Logout"}, + {0x00050000, GetMyFriendKey, "GetMyFriendKey"}, + {0x00060000, nullptr, "GetMyPreference"}, + {0x00070000, nullptr, "GetMyProfile"}, + {0x00080000, GetMyPresence, "GetMyPresence"}, + {0x00090000, GetMyScreenName, "GetMyScreenName"}, + {0x000A0000, nullptr, "GetMyMii"}, + {0x000B0000, nullptr, "GetMyLocalAccountId"}, + {0x000C0000, nullptr, "GetMyPlayingGame"}, + {0x000D0000, nullptr, "GetMyFavoriteGame"}, + {0x000E0000, nullptr, "GetMyNcPrincipalId"}, + {0x000F0000, nullptr, "GetMyComment"}, + {0x00100040, nullptr, "GetMyPassword"}, + {0x00110080, GetFriendKeyList, "GetFriendKeyList"}, + {0x00120042, nullptr, "GetFriendPresence"}, + {0x00130142, nullptr, "GetFriendScreenName"}, + {0x00140044, nullptr, "GetFriendMii"}, + {0x00150042, GetFriendProfile, "GetFriendProfile"}, + {0x00160042, nullptr, "GetFriendRelationship"}, + {0x00170042, GetFriendAttributeFlags, "GetFriendAttributeFlags"}, + {0x00180044, nullptr, "GetFriendPlayingGame"}, + {0x00190042, nullptr, "GetFriendFavoriteGame"}, + {0x001A00C4, nullptr, "GetFriendInfo"}, + {0x001B0080, nullptr, "IsIncludedInFriendList"}, + {0x001C0042, nullptr, "UnscrambleLocalFriendCode"}, + {0x001D0002, nullptr, "UpdateGameModeDescription"}, + {0x001E02C2, nullptr, "UpdateGameMode"}, + {0x001F0042, nullptr, "SendInvitation"}, + {0x00200002, nullptr, "AttachToEventNotification"}, + {0x00210040, nullptr, "SetNotificationMask"}, + {0x00220040, nullptr, "GetEventNotification"}, + {0x00230000, nullptr, "GetLastResponseResult"}, + {0x00240040, nullptr, "PrincipalIdToFriendCode"}, + {0x00250080, nullptr, "FriendCodeToPrincipalId"}, + {0x00260080, nullptr, "IsValidFriendCode"}, + {0x00270040, nullptr, "ResultToErrorCode"}, + {0x00280244, nullptr, "RequestGameAuthentication"}, + {0x00290000, nullptr, "GetGameAuthenticationData"}, + {0x002A0204, nullptr, "RequestServiceLocator"}, + {0x002B0000, nullptr, "GetServiceLocatorData"}, + {0x002C0002, nullptr, "DetectNatProperties"}, + {0x002D0000, nullptr, "GetNatProperties"}, + {0x002E0000, nullptr, "GetServerTimeInterval"}, + {0x002F0040, nullptr, "AllowHalfAwake"}, + {0x00300000, nullptr, "GetServerTypes"}, + {0x00310082, nullptr, "GetFriendComment"}, + {0x00320042, nullptr, "SetClientSdkVersion"}, + {0x00330000, nullptr, "GetMyApproachContext"}, + {0x00340046, nullptr, "AddFriendWithApproach"}, + {0x00350082, nullptr, "DecryptApproachContext"}, }; FRD_U_Interface::FRD_U_Interface() { diff --git a/src/core/hle/service/service.cpp b/src/core/hle/service/service.cpp index 35b648409..833a68f05 100644 --- a/src/core/hle/service/service.cpp +++ b/src/core/hle/service/service.cpp @@ -70,9 +70,8 @@ ResultVal Interface::SyncRequest() { // TODO(bunnei): Hack - ignore error cmd_buff[1] = 0; return MakeResult(false); - } else { - LOG_TRACE(Service, "%s", MakeFunctionString(itr->second.name, GetPortName().c_str(), cmd_buff).c_str()); } + LOG_TRACE(Service, "%s", MakeFunctionString(itr->second.name, GetPortName().c_str(), cmd_buff).c_str()); itr->second.func(this); From 91dbebbcc5007c3286f0f9948c2225ff5b5c8260 Mon Sep 17 00:00:00 2001 From: Ryan Loebs Date: Mon, 28 Mar 2016 23:34:34 -0700 Subject: [PATCH 005/104] SOC Updates -Implement GetSockOpt / SetSockOpt -Fix bug in RecvFrom where sending from localhost does not fill in src_addr/src_addr_len on Linux --- src/core/hle/service/soc_u.cpp | 49 +++++++++++++++++++++++++++++++--- 1 file changed, 46 insertions(+), 3 deletions(-) diff --git a/src/core/hle/service/soc_u.cpp b/src/core/hle/service/soc_u.cpp index ff0af8f12..efda8bd4f 100644 --- a/src/core/hle/service/soc_u.cpp +++ b/src/core/hle/service/soc_u.cpp @@ -568,7 +568,7 @@ static void RecvFrom(Service::Interface* self) { socklen_t src_addr_len = sizeof(src_addr); int ret = ::recvfrom(socket_handle, (char*)output_buff, len, flags, &src_addr, &src_addr_len); - if (buffer_parameters.output_src_address_buffer != 0) { + if (buffer_parameters.output_src_address_buffer != 0 && src_addr_len > 0) { CTRSockAddr* ctr_src_addr = reinterpret_cast(Memory::GetPointer(buffer_parameters.output_src_address_buffer)); *ctr_src_addr = CTRSockAddr::FromPlatform(src_addr); } @@ -724,6 +724,49 @@ static void ShutdownSockets(Service::Interface* self) { cmd_buffer[1] = 0; } +static void GetSockOpt(Service::Interface* self) { + u32* cmd_buffer = Kernel::GetCommandBuffer(); + u32 socket_handle = cmd_buffer[1]; + u32 level = cmd_buffer[2]; + u32 optname = cmd_buffer[3]; + u32 optlen = cmd_buffer[4]; + + // 0x100 = static buffer offset (bytes) + // + 0x4 = 2nd pointer (u32) position + // >> 2 = convert to u32 offset instead of byte offset (cmd_buffer = u32*) + u8* optval = Memory::GetPointer(cmd_buffer[0x104 >> 2]); + + int ret = ::getsockopt(socket_handle, level, optname, &optval, &optlen); + int err = 0; + if(ret == SOCKET_ERROR_VALUE) { + err = TranslateError(GET_ERRNO); + } + + cmd_buffer[0] = IPC::MakeHeader(0x11, 4, 2); + cmd_buffer[1] = ret; + cmd_buffer[2] = err; + cmd_buffer[3] = optlen; +} + +static void SetSockOpt(Service::Interface* self) { + u32* cmd_buffer = Kernel::GetCommandBuffer(); + u32 socket_handle = cmd_buffer[1]; + u32 level = cmd_buffer[2]; + u32 optname = cmd_buffer[3]; + socklen_t optlen = static_cast(cmd_buffer[4]); + void *optval = Memory::GetPointer(cmd_buffer[8]); + + int ret = static_cast(::setsockopt(socket_handle, level, optname, optval, optlen)); + int err = 0; + if(ret == SOCKET_ERROR_VALUE) { + err = TranslateError(GET_ERRNO); + } + + cmd_buffer[0] = IPC::MakeHeader(0x12, 4, 4); + cmd_buffer[1] = ret; + cmd_buffer[2] = err; +} + const Interface::FunctionInfo FunctionTable[] = { {0x00010044, InitializeSockets, "InitializeSockets"}, {0x000200C2, Socket, "Socket"}, @@ -741,8 +784,8 @@ const Interface::FunctionInfo FunctionTable[] = { {0x000E00C2, nullptr, "GetHostByAddr"}, {0x000F0106, nullptr, "GetAddrInfo"}, {0x00100102, nullptr, "GetNameInfo"}, - {0x00110102, nullptr, "GetSockOpt"}, - {0x00120104, nullptr, "SetSockOpt"}, + {0x00110102, GetSockOpt, "GetSockOpt"}, + {0x00120104, SetSockOpt, "SetSockOpt"}, {0x001300C2, Fcntl, "Fcntl"}, {0x00140084, Poll, "Poll"}, {0x00150042, nullptr, "SockAtMark"}, From 65883d9327030adb33938c9b0de276b4cfd74a46 Mon Sep 17 00:00:00 2001 From: Ryan Loebs Date: Tue, 29 Mar 2016 04:42:58 -0700 Subject: [PATCH 006/104] Addressing PR comments --- src/core/hle/service/soc_u.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/core/hle/service/soc_u.cpp b/src/core/hle/service/soc_u.cpp index efda8bd4f..ea301f71f 100644 --- a/src/core/hle/service/soc_u.cpp +++ b/src/core/hle/service/soc_u.cpp @@ -568,7 +568,7 @@ static void RecvFrom(Service::Interface* self) { socklen_t src_addr_len = sizeof(src_addr); int ret = ::recvfrom(socket_handle, (char*)output_buff, len, flags, &src_addr, &src_addr_len); - if (buffer_parameters.output_src_address_buffer != 0 && src_addr_len > 0) { + if (ret >= 0 && buffer_parameters.output_src_address_buffer != 0 && src_addr_len > 0) { CTRSockAddr* ctr_src_addr = reinterpret_cast(Memory::GetPointer(buffer_parameters.output_src_address_buffer)); *ctr_src_addr = CTRSockAddr::FromPlatform(src_addr); } @@ -736,7 +736,7 @@ static void GetSockOpt(Service::Interface* self) { // >> 2 = convert to u32 offset instead of byte offset (cmd_buffer = u32*) u8* optval = Memory::GetPointer(cmd_buffer[0x104 >> 2]); - int ret = ::getsockopt(socket_handle, level, optname, &optval, &optlen); + int ret = ::getsockopt(socket_handle, level, optname, optval, &optlen); int err = 0; if(ret == SOCKET_ERROR_VALUE) { err = TranslateError(GET_ERRNO); @@ -754,11 +754,11 @@ static void SetSockOpt(Service::Interface* self) { u32 level = cmd_buffer[2]; u32 optname = cmd_buffer[3]; socklen_t optlen = static_cast(cmd_buffer[4]); - void *optval = Memory::GetPointer(cmd_buffer[8]); + u8 *optval = Memory::GetPointer(cmd_buffer[8]); int ret = static_cast(::setsockopt(socket_handle, level, optname, optval, optlen)); int err = 0; - if(ret == SOCKET_ERROR_VALUE) { + if (ret == SOCKET_ERROR_VALUE) { err = TranslateError(GET_ERRNO); } From aa5bb3b997d56b33ea9de8c7435f06d3849b61fd Mon Sep 17 00:00:00 2001 From: Ryan Loebs Date: Tue, 29 Mar 2016 04:45:17 -0700 Subject: [PATCH 007/104] Formatting... --- src/core/hle/service/soc_u.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/core/hle/service/soc_u.cpp b/src/core/hle/service/soc_u.cpp index ea301f71f..43194345c 100644 --- a/src/core/hle/service/soc_u.cpp +++ b/src/core/hle/service/soc_u.cpp @@ -738,7 +738,7 @@ static void GetSockOpt(Service::Interface* self) { int ret = ::getsockopt(socket_handle, level, optname, optval, &optlen); int err = 0; - if(ret == SOCKET_ERROR_VALUE) { + if (ret == SOCKET_ERROR_VALUE) { err = TranslateError(GET_ERRNO); } From b8422b24bd733c745c519ddd0e1d45a9191aca76 Mon Sep 17 00:00:00 2001 From: Ryan Loebs Date: Tue, 29 Mar 2016 14:24:03 -0700 Subject: [PATCH 008/104] Compiling on Windows now --- src/core/hle/service/soc_u.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/core/hle/service/soc_u.cpp b/src/core/hle/service/soc_u.cpp index 43194345c..4606ad743 100644 --- a/src/core/hle/service/soc_u.cpp +++ b/src/core/hle/service/soc_u.cpp @@ -729,12 +729,12 @@ static void GetSockOpt(Service::Interface* self) { u32 socket_handle = cmd_buffer[1]; u32 level = cmd_buffer[2]; u32 optname = cmd_buffer[3]; - u32 optlen = cmd_buffer[4]; + int optlen = (int)cmd_buffer[4]; // 0x100 = static buffer offset (bytes) // + 0x4 = 2nd pointer (u32) position // >> 2 = convert to u32 offset instead of byte offset (cmd_buffer = u32*) - u8* optval = Memory::GetPointer(cmd_buffer[0x104 >> 2]); + char* optval = reinterpret_cast(Memory::GetPointer(cmd_buffer[0x104 >> 2])); int ret = ::getsockopt(socket_handle, level, optname, optval, &optlen); int err = 0; @@ -754,7 +754,7 @@ static void SetSockOpt(Service::Interface* self) { u32 level = cmd_buffer[2]; u32 optname = cmd_buffer[3]; socklen_t optlen = static_cast(cmd_buffer[4]); - u8 *optval = Memory::GetPointer(cmd_buffer[8]); + const char *optval = reinterpret_cast(Memory::GetPointer(cmd_buffer[8])); int ret = static_cast(::setsockopt(socket_handle, level, optname, optval, optlen)); int err = 0; From 64815a8b1609e874d5e3f403c93c8456bd4a9ccb Mon Sep 17 00:00:00 2001 From: Ryan Loebs Date: Tue, 29 Mar 2016 14:33:32 -0700 Subject: [PATCH 009/104] But of course, Windows uses 'int' while Linux uses 'socklen_t' --- src/core/hle/service/soc_u.cpp | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/core/hle/service/soc_u.cpp b/src/core/hle/service/soc_u.cpp index 4606ad743..b7c8eff57 100644 --- a/src/core/hle/service/soc_u.cpp +++ b/src/core/hle/service/soc_u.cpp @@ -729,7 +729,11 @@ static void GetSockOpt(Service::Interface* self) { u32 socket_handle = cmd_buffer[1]; u32 level = cmd_buffer[2]; u32 optname = cmd_buffer[3]; +#ifdef _WIN32 int optlen = (int)cmd_buffer[4]; +#else + socklen_t optlen = (socklen_t)cmd_buffer[4]; +#endif // 0x100 = static buffer offset (bytes) // + 0x4 = 2nd pointer (u32) position From 0a7d53692adb1eae98a2935a445efea327370d9f Mon Sep 17 00:00:00 2001 From: Ryan Loebs Date: Tue, 29 Mar 2016 14:48:25 -0700 Subject: [PATCH 010/104] Derp: win32: typedef int socklen_t; --- src/core/hle/service/soc_u.cpp | 4 ---- 1 file changed, 4 deletions(-) diff --git a/src/core/hle/service/soc_u.cpp b/src/core/hle/service/soc_u.cpp index b7c8eff57..9d836349a 100644 --- a/src/core/hle/service/soc_u.cpp +++ b/src/core/hle/service/soc_u.cpp @@ -729,11 +729,7 @@ static void GetSockOpt(Service::Interface* self) { u32 socket_handle = cmd_buffer[1]; u32 level = cmd_buffer[2]; u32 optname = cmd_buffer[3]; -#ifdef _WIN32 - int optlen = (int)cmd_buffer[4]; -#else socklen_t optlen = (socklen_t)cmd_buffer[4]; -#endif // 0x100 = static buffer offset (bytes) // + 0x4 = 2nd pointer (u32) position From b1f89408dd0072a4fc7baac1384dc9744374107c Mon Sep 17 00:00:00 2001 From: Ryan Loebs Date: Wed, 30 Mar 2016 00:25:19 -0700 Subject: [PATCH 011/104] Added GetSockOptName Filter out and translate invalid sockopt names. --- src/core/hle/service/soc_u.cpp | 73 +++++++++++++++++++++++++++------- 1 file changed, 58 insertions(+), 15 deletions(-) diff --git a/src/core/hle/service/soc_u.cpp b/src/core/hle/service/soc_u.cpp index 9d836349a..1c3ea03a2 100644 --- a/src/core/hle/service/soc_u.cpp +++ b/src/core/hle/service/soc_u.cpp @@ -295,6 +295,26 @@ union CTRSockAddr { } }; +/// Filters valid sockopt names and converts from platform-specific name if necessary +static int GetSockOptName(u32 name) { + switch(name) { + case SO_RCVLOWAT: +#ifdef _WIN32 + // LOWAT not supported by WinSock + return -1; +#endif + case SO_REUSEADDR: + case SO_SNDBUF: + case SO_RCVBUF: + case SO_TYPE: + case SO_ERROR: + return name; + default: + // all other options are either ineffectual or unsupported + return -1; + } +} + /// Holds info about the currently open sockets static std::unordered_map open_sockets; @@ -728,18 +748,29 @@ static void GetSockOpt(Service::Interface* self) { u32* cmd_buffer = Kernel::GetCommandBuffer(); u32 socket_handle = cmd_buffer[1]; u32 level = cmd_buffer[2]; - u32 optname = cmd_buffer[3]; + int optname = GetSockOptName(cmd_buffer[3]); socklen_t optlen = (socklen_t)cmd_buffer[4]; - // 0x100 = static buffer offset (bytes) - // + 0x4 = 2nd pointer (u32) position - // >> 2 = convert to u32 offset instead of byte offset (cmd_buffer = u32*) - char* optval = reinterpret_cast(Memory::GetPointer(cmd_buffer[0x104 >> 2])); - - int ret = ::getsockopt(socket_handle, level, optname, optval, &optlen); + int ret = -1; int err = 0; - if (ret == SOCKET_ERROR_VALUE) { - err = TranslateError(GET_ERRNO); + + if(optname < 0) { +#ifdef _WIN32 + err = WSAEINVAL; +#else + err = EINVAL; +#endif + } else { + // 0x100 = static buffer offset (bytes) + // + 0x4 = 2nd pointer (u32) position + // >> 2 = convert to u32 offset instead of byte offset (cmd_buffer = u32*) + char *optval = reinterpret_cast(Memory::GetPointer(cmd_buffer[0x104 >> 2])); + + ret = ::getsockopt(socket_handle, level, optname, optval, &optlen); + err = 0; + if (ret == SOCKET_ERROR_VALUE) { + err = TranslateError(GET_ERRNO); + } } cmd_buffer[0] = IPC::MakeHeader(0x11, 4, 2); @@ -752,14 +783,26 @@ static void SetSockOpt(Service::Interface* self) { u32* cmd_buffer = Kernel::GetCommandBuffer(); u32 socket_handle = cmd_buffer[1]; u32 level = cmd_buffer[2]; - u32 optname = cmd_buffer[3]; - socklen_t optlen = static_cast(cmd_buffer[4]); - const char *optval = reinterpret_cast(Memory::GetPointer(cmd_buffer[8])); + int optname = GetSockOptName(cmd_buffer[3]); - int ret = static_cast(::setsockopt(socket_handle, level, optname, optval, optlen)); + int ret = -1; int err = 0; - if (ret == SOCKET_ERROR_VALUE) { - err = TranslateError(GET_ERRNO); + + if(optname < 0) { +#ifdef _WIN32 + err = WSAEINVAL; +#else + err = EINVAL; +#endif + } else { + socklen_t optlen = static_cast(cmd_buffer[4]); + const char *optval = reinterpret_cast(Memory::GetPointer(cmd_buffer[8])); + + ret = static_cast(::setsockopt(socket_handle, level, optname, optval, optlen)); + err = 0; + if (ret == SOCKET_ERROR_VALUE) { + err = TranslateError(GET_ERRNO); + } } cmd_buffer[0] = IPC::MakeHeader(0x12, 4, 4); From 2faafff1b961ce735a1e8ffb46f175bd0f993af3 Mon Sep 17 00:00:00 2001 From: Ryan Loebs Date: Wed, 30 Mar 2016 13:51:34 -0700 Subject: [PATCH 012/104] Code style --- src/core/hle/service/soc_u.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/core/hle/service/soc_u.cpp b/src/core/hle/service/soc_u.cpp index 1c3ea03a2..6ab246ba8 100644 --- a/src/core/hle/service/soc_u.cpp +++ b/src/core/hle/service/soc_u.cpp @@ -764,7 +764,7 @@ static void GetSockOpt(Service::Interface* self) { // 0x100 = static buffer offset (bytes) // + 0x4 = 2nd pointer (u32) position // >> 2 = convert to u32 offset instead of byte offset (cmd_buffer = u32*) - char *optval = reinterpret_cast(Memory::GetPointer(cmd_buffer[0x104 >> 2])); + char* optval = reinterpret_cast(Memory::GetPointer(cmd_buffer[0x104 >> 2])); ret = ::getsockopt(socket_handle, level, optname, optval, &optlen); err = 0; @@ -796,7 +796,7 @@ static void SetSockOpt(Service::Interface* self) { #endif } else { socklen_t optlen = static_cast(cmd_buffer[4]); - const char *optval = reinterpret_cast(Memory::GetPointer(cmd_buffer[8])); + const char* optval = reinterpret_cast(Memory::GetPointer(cmd_buffer[8])); ret = static_cast(::setsockopt(socket_handle, level, optname, optval, optlen)); err = 0; From acfa76aa381f7220606962777510809fa55a6a04 Mon Sep 17 00:00:00 2001 From: LFsWang Date: Thu, 31 Mar 2016 18:58:37 +0800 Subject: [PATCH 013/104] Fix encode problem On Windows --- src/citra_qt/game_list.cpp | 4 ++-- src/citra_qt/main.cpp | 8 ++++---- src/common/file_util.cpp | 29 +++++++++++++++++------------ src/common/string_util.cpp | 26 +++++++++++++------------- src/common/string_util.h | 2 +- 5 files changed, 37 insertions(+), 32 deletions(-) diff --git a/src/citra_qt/game_list.cpp b/src/citra_qt/game_list.cpp index a0b216b0a..ffcab1f03 100644 --- a/src/citra_qt/game_list.cpp +++ b/src/citra_qt/game_list.cpp @@ -66,7 +66,7 @@ void GameList::ValidateEntry(const QModelIndex& item) if (file_path.isEmpty()) return; - std::string std_file_path(file_path.toLocal8Bit()); + std::string std_file_path(file_path.toStdString()); if (!FileUtil::Exists(std_file_path) || FileUtil::IsDirectory(std_file_path)) return; emit GameChosen(file_path); @@ -148,7 +148,7 @@ void GameListWorker::AddFstEntriesToGameList(const std::string& dir_path, bool d emit EntryReady({ new GameListItem(QString::fromStdString(Loader::GetFileTypeString(filetype))), - new GameListItemPath(QString::fromLocal8Bit(physical_name.c_str())), + new GameListItemPath(QString::fromStdString(physical_name)), new GameListItemSize(FileUtil::GetSize(physical_name)), }); } diff --git a/src/citra_qt/main.cpp b/src/citra_qt/main.cpp index 32cceaf7e..f621f5d66 100644 --- a/src/citra_qt/main.cpp +++ b/src/citra_qt/main.cpp @@ -417,7 +417,7 @@ void GMainWindow::UpdateRecentFiles() { } void GMainWindow::OnGameListLoadFile(QString game_path) { - BootGame(game_path.toLocal8Bit().data()); + BootGame(game_path.toStdString()); } void GMainWindow::OnMenuLoadFile() { @@ -428,7 +428,7 @@ void GMainWindow::OnMenuLoadFile() { if (!filename.isEmpty()) { settings.setValue("romsPath", QFileInfo(filename).path()); - BootGame(filename.toLocal8Bit().data()); + BootGame(filename.toStdString()); } } @@ -440,7 +440,7 @@ void GMainWindow::OnMenuLoadSymbolMap() { if (!filename.isEmpty()) { settings.setValue("symbolsPath", QFileInfo(filename).path()); - LoadSymbolMap(filename.toLocal8Bit().data()); + LoadSymbolMap(filename.toStdString()); } } @@ -461,7 +461,7 @@ void GMainWindow::OnMenuRecentFile() { QString filename = action->data().toString(); QFileInfo file_info(filename); if (file_info.exists()) { - BootGame(filename.toLocal8Bit().data()); + BootGame(filename.toStdString()); } else { // Display an error message and remove the file from the list. QMessageBox::information(this, tr("File not found"), tr("File \"%1\" not found").arg(filename)); diff --git a/src/common/file_util.cpp b/src/common/file_util.cpp index c3061479a..c3ae03052 100644 --- a/src/common/file_util.cpp +++ b/src/common/file_util.cpp @@ -85,7 +85,7 @@ bool Exists(const std::string &filename) StripTailDirSlashes(copy); #ifdef _WIN32 - int result = _tstat64(Common::UTF8ToTStr(copy).c_str(), &file_info); + int result = _wstat64(Common::UTF8ToUTF16W(copy).c_str(), &file_info); #else int result = stat64(copy.c_str(), &file_info); #endif @@ -102,7 +102,7 @@ bool IsDirectory(const std::string &filename) StripTailDirSlashes(copy); #ifdef _WIN32 - int result = _tstat64(Common::UTF8ToTStr(copy).c_str(), &file_info); + int result = _wstat64(Common::UTF8ToUTF16W(copy).c_str(), &file_info); #else int result = stat64(copy.c_str(), &file_info); #endif @@ -138,7 +138,7 @@ bool Delete(const std::string &filename) } #ifdef _WIN32 - if (!DeleteFile(Common::UTF8ToTStr(filename).c_str())) + if (!DeleteFileW(Common::UTF8ToUTF16W(filename).c_str())) { LOG_ERROR(Common_Filesystem, "DeleteFile failed on %s: %s", filename.c_str(), GetLastErrorMsg()); @@ -160,7 +160,7 @@ bool CreateDir(const std::string &path) { LOG_TRACE(Common_Filesystem, "directory %s", path.c_str()); #ifdef _WIN32 - if (::CreateDirectory(Common::UTF8ToTStr(path).c_str(), nullptr)) + if (::CreateDirectoryW(Common::UTF8ToUTF16W(path).c_str(), nullptr)) return true; DWORD error = GetLastError(); if (error == ERROR_ALREADY_EXISTS) @@ -241,7 +241,7 @@ bool DeleteDir(const std::string &filename) } #ifdef _WIN32 - if (::RemoveDirectory(Common::UTF8ToTStr(filename).c_str())) + if (::RemoveDirectoryW(Common::UTF8ToUTF16W(filename).c_str())) return true; #else if (rmdir(filename.c_str()) == 0) @@ -257,8 +257,13 @@ bool Rename(const std::string &srcFilename, const std::string &destFilename) { LOG_TRACE(Common_Filesystem, "%s --> %s", srcFilename.c_str(), destFilename.c_str()); +#ifdef _WIN32 + if (_wrename(Common::UTF8ToUTF16W(srcFilename).c_str(), Common::UTF8ToUTF16W(destFilename).c_str()) == 0) + return true; +#else if (rename(srcFilename.c_str(), destFilename.c_str()) == 0) return true; +#endif LOG_ERROR(Common_Filesystem, "failed %s --> %s: %s", srcFilename.c_str(), destFilename.c_str(), GetLastErrorMsg()); return false; @@ -270,7 +275,7 @@ bool Copy(const std::string &srcFilename, const std::string &destFilename) LOG_TRACE(Common_Filesystem, "%s --> %s", srcFilename.c_str(), destFilename.c_str()); #ifdef _WIN32 - if (CopyFile(Common::UTF8ToTStr(srcFilename).c_str(), Common::UTF8ToTStr(destFilename).c_str(), FALSE)) + if (CopyFileW(Common::UTF8ToUTF16W(srcFilename).c_str(), Common::UTF8ToUTF16W(destFilename).c_str(), FALSE)) return true; LOG_ERROR(Common_Filesystem, "failed %s --> %s: %s", @@ -358,7 +363,7 @@ u64 GetSize(const std::string &filename) struct stat64 buf; #ifdef _WIN32 - if (_tstat64(Common::UTF8ToTStr(filename).c_str(), &buf) == 0) + if (_wstat64(Common::UTF8ToUTF16W(filename).c_str(), &buf) == 0) #else if (stat64(filename.c_str(), &buf) == 0) #endif @@ -432,16 +437,16 @@ bool ForeachDirectoryEntry(unsigned* num_entries_out, const std::string &directo #ifdef _WIN32 // Find the first file in the directory. - WIN32_FIND_DATA ffd; + WIN32_FIND_DATAW ffd; - HANDLE handle_find = FindFirstFile(Common::UTF8ToTStr(directory + "\\*").c_str(), &ffd); + HANDLE handle_find = FindFirstFileW(Common::UTF8ToUTF16W(directory + "\\*").c_str(), &ffd); if (handle_find == INVALID_HANDLE_VALUE) { FindClose(handle_find); return false; } // windows loop do { - const std::string virtual_name(Common::TStrToUTF8(ffd.cFileName)); + const std::string virtual_name(Common::UTF16ToUTF8(ffd.cFileName)); #else struct dirent dirent, *result = nullptr; @@ -465,7 +470,7 @@ bool ForeachDirectoryEntry(unsigned* num_entries_out, const std::string &directo found_entries += ret_entries; #ifdef _WIN32 - } while (FindNextFile(handle_find, &ffd) != 0); + } while (FindNextFileW(handle_find, &ffd) != 0); FindClose(handle_find); #else } @@ -900,7 +905,7 @@ bool IOFile::Open(const std::string& filename, const char openmode[]) { Close(); #ifdef _WIN32 - _tfopen_s(&m_file, Common::UTF8ToTStr(filename).c_str(), Common::UTF8ToTStr(openmode).c_str()); + _wfopen_s(&m_file, Common::UTF8ToUTF16W(filename).c_str(), Common::UTF8ToUTF16W(openmode).c_str()); #else m_file = fopen(filename.c_str(), openmode); #endif diff --git a/src/common/string_util.cpp b/src/common/string_util.cpp index 6d6fc591f..f0aa072db 100644 --- a/src/common/string_util.cpp +++ b/src/common/string_util.cpp @@ -320,19 +320,6 @@ std::u16string UTF8ToUTF16(const std::string& input) #endif } -static std::string UTF16ToUTF8(const std::wstring& input) -{ - auto const size = WideCharToMultiByte(CP_UTF8, 0, input.data(), static_cast(input.size()), nullptr, 0, nullptr, nullptr); - - std::string output; - output.resize(size); - - if (size == 0 || size != WideCharToMultiByte(CP_UTF8, 0, input.data(), static_cast(input.size()), &output[0], static_cast(output.size()), nullptr, nullptr)) - output.clear(); - - return output; -} - static std::wstring CPToUTF16(u32 code_page, const std::string& input) { auto const size = MultiByteToWideChar(code_page, 0, input.data(), static_cast(input.size()), nullptr, 0); @@ -346,6 +333,19 @@ static std::wstring CPToUTF16(u32 code_page, const std::string& input) return output; } +std::string UTF16ToUTF8(const std::wstring& input) +{ + auto const size = WideCharToMultiByte(CP_UTF8, 0, input.data(), static_cast(input.size()), nullptr, 0, nullptr, nullptr); + + std::string output; + output.resize(size); + + if (size == 0 || size != WideCharToMultiByte(CP_UTF8, 0, input.data(), static_cast(input.size()), &output[0], static_cast(output.size()), nullptr, nullptr)) + output.clear(); + + return output; +} + std::wstring UTF8ToUTF16W(const std::string &input) { return CPToUTF16(CP_UTF8, input); diff --git a/src/common/string_util.h b/src/common/string_util.h index c5c474c6f..89d9f133e 100644 --- a/src/common/string_util.h +++ b/src/common/string_util.h @@ -95,7 +95,7 @@ std::string CP1252ToUTF8(const std::string& str); std::string SHIFTJISToUTF8(const std::string& str); #ifdef _WIN32 - +std::string UTF16ToUTF8(const std::wstring& input); std::wstring UTF8ToUTF16W(const std::string& str); #ifdef _UNICODE From be019125392fd2ac39e482dc928c2710e6fbc685 Mon Sep 17 00:00:00 2001 From: LFsWang Date: Thu, 31 Mar 2016 19:21:03 +0800 Subject: [PATCH 014/104] fix unicode url problem on windows --- src/common/file_util.cpp | 24 ++++++++++++++++++------ 1 file changed, 18 insertions(+), 6 deletions(-) diff --git a/src/common/file_util.cpp b/src/common/file_util.cpp index c3ae03052..89eac1380 100644 --- a/src/common/file_util.cpp +++ b/src/common/file_util.cpp @@ -192,7 +192,7 @@ bool CreateFullPath(const std::string &fullPath) { int panicCounter = 100; LOG_TRACE(Common_Filesystem, "path %s", fullPath.c_str()); - + LOG_WARNING(Common_Filesystem, "path %s", fullPath.c_str()); if (FileUtil::Exists(fullPath)) { LOG_WARNING(Common_Filesystem, "path exists %s", fullPath.c_str()); @@ -577,15 +577,23 @@ void CopyDir(const std::string &source_path, const std::string &dest_path) // Returns the current directory std::string GetCurrentDir() { - char *dir; // Get the current working directory (getcwd uses malloc) +#ifdef _WIN32 + wchar_t *dir; + if (!(dir = _wgetcwd(nullptr, 0))) { +#else + char *dir; if (!(dir = getcwd(nullptr, 0))) { - +#endif LOG_ERROR(Common_Filesystem, "GetCurrentDirectory failed: %s", GetLastErrorMsg()); return nullptr; } +#ifdef _WIN32 + std::string strDir = Common::UTF16ToUTF8(dir); +#else std::string strDir = dir; +#endif free(dir); return strDir; } @@ -593,7 +601,11 @@ std::string GetCurrentDir() // Sets the current directory to the given directory bool SetCurrentDir(const std::string &directory) { +#ifdef _WIN32 + return _wchdir(Common::UTF8ToUTF16W(directory).c_str()) == 0; +#else return chdir(directory.c_str()) == 0; +#endif } #if defined(__APPLE__) @@ -618,9 +630,9 @@ std::string& GetExeDirectory() static std::string exe_path; if (exe_path.empty()) { - TCHAR tchar_exe_path[2048]; - GetModuleFileName(nullptr, tchar_exe_path, 2048); - exe_path = Common::TStrToUTF8(tchar_exe_path); + wchar_t wchar_exe_path[2048]; + GetModuleFileNameW(nullptr, wchar_exe_path, 2048); + exe_path = Common::UTF16ToUTF8(wchar_exe_path); exe_path = exe_path.substr(0, exe_path.find_last_of('\\')); } return exe_path; From 87afef73b1825426ec43f36e2da4915dea632489 Mon Sep 17 00:00:00 2001 From: LFsWang Date: Thu, 31 Mar 2016 20:29:39 +0800 Subject: [PATCH 015/104] remove debug code --- src/citra_qt/config.cpp | 2 +- src/common/file_util.cpp | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/citra_qt/config.cpp b/src/citra_qt/config.cpp index d1a19ade9..8e247ff5c 100644 --- a/src/citra_qt/config.cpp +++ b/src/citra_qt/config.cpp @@ -16,7 +16,7 @@ Config::Config() { // TODO: Don't hardcode the path; let the frontend decide where to put the config files. qt_config_loc = FileUtil::GetUserPath(D_CONFIG_IDX) + "qt-config.ini"; FileUtil::CreateFullPath(qt_config_loc); - qt_config = new QSettings(QString::fromLocal8Bit(qt_config_loc.c_str()), QSettings::IniFormat); + qt_config = new QSettings(QString::fromStdString(qt_config_loc), QSettings::IniFormat); Reload(); } diff --git a/src/common/file_util.cpp b/src/common/file_util.cpp index 89eac1380..9ada09f8a 100644 --- a/src/common/file_util.cpp +++ b/src/common/file_util.cpp @@ -192,7 +192,7 @@ bool CreateFullPath(const std::string &fullPath) { int panicCounter = 100; LOG_TRACE(Common_Filesystem, "path %s", fullPath.c_str()); - LOG_WARNING(Common_Filesystem, "path %s", fullPath.c_str()); + if (FileUtil::Exists(fullPath)) { LOG_WARNING(Common_Filesystem, "path exists %s", fullPath.c_str()); From 58ee548ed88122086712f58bf05495655b5fd3f7 Mon Sep 17 00:00:00 2001 From: Ryan Loebs Date: Fri, 1 Apr 2016 22:19:21 -0700 Subject: [PATCH 016/104] Rework sockopt translation to match the error translation code already in place --- src/core/hle/service/soc_u.cpp | 52 ++++++++++++++++++++-------------- 1 file changed, 30 insertions(+), 22 deletions(-) diff --git a/src/core/hle/service/soc_u.cpp b/src/core/hle/service/soc_u.cpp index 6ab246ba8..d3e5d4bca 100644 --- a/src/core/hle/service/soc_u.cpp +++ b/src/core/hle/service/soc_u.cpp @@ -151,6 +151,34 @@ static int TranslateError(int error) { return error; } +/// Holds the translation from system network socket options to 3DS network socket options +/// Note: -1 = No effect/unavailable +static const std::unordered_map sockopt_map = { { + { 0x0004, SO_REUSEADDR }, + { 0x0080, -1 }, + { 0x0100, -1 }, + { 0x1001, SO_SNDBUF }, + { 0x1002, SO_RCVBUF }, + { 0x1003, -1 }, +#ifdef _WIN32 + /// Unsupported in WinSock2 + { 0x1004, -1 }, +#else + { 0x1004, SO_RCVLOWAT }, +#endif + { 0x1008, SO_TYPE }, + { 0x1009, SO_ERROR }, +}}; + +/// Converts a socket option from 3ds-specific to platform-specific +static int TranslateSockOpt(int console_opt_name) { + auto found = sockopt_map.find(console_opt_name); + if (found != sockopt_map.end()) { + return found->second; + } + return console_opt_name; +} + /// Holds information about a particular socket struct SocketHolder { u32 socket_fd; ///< The socket descriptor @@ -295,26 +323,6 @@ union CTRSockAddr { } }; -/// Filters valid sockopt names and converts from platform-specific name if necessary -static int GetSockOptName(u32 name) { - switch(name) { - case SO_RCVLOWAT: -#ifdef _WIN32 - // LOWAT not supported by WinSock - return -1; -#endif - case SO_REUSEADDR: - case SO_SNDBUF: - case SO_RCVBUF: - case SO_TYPE: - case SO_ERROR: - return name; - default: - // all other options are either ineffectual or unsupported - return -1; - } -} - /// Holds info about the currently open sockets static std::unordered_map open_sockets; @@ -748,7 +756,7 @@ static void GetSockOpt(Service::Interface* self) { u32* cmd_buffer = Kernel::GetCommandBuffer(); u32 socket_handle = cmd_buffer[1]; u32 level = cmd_buffer[2]; - int optname = GetSockOptName(cmd_buffer[3]); + int optname = TranslateSockOpt(cmd_buffer[3]); socklen_t optlen = (socklen_t)cmd_buffer[4]; int ret = -1; @@ -783,7 +791,7 @@ static void SetSockOpt(Service::Interface* self) { u32* cmd_buffer = Kernel::GetCommandBuffer(); u32 socket_handle = cmd_buffer[1]; u32 level = cmd_buffer[2]; - int optname = GetSockOptName(cmd_buffer[3]); + int optname = TranslateSockOpt(cmd_buffer[3]); int ret = -1; int err = 0; From 3219be8ee0efe0ad9e2d7399fe78a545aa263078 Mon Sep 17 00:00:00 2001 From: Emmanuel Gil Peyrot Date: Sun, 3 Apr 2016 17:00:44 +0100 Subject: [PATCH 017/104] OpenGL: Fix a double framebuffer completeness checks. --- src/video_core/renderer_opengl/gl_rasterizer.cpp | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/src/video_core/renderer_opengl/gl_rasterizer.cpp b/src/video_core/renderer_opengl/gl_rasterizer.cpp index 21ad9ee77..ff44dfcfe 100644 --- a/src/video_core/renderer_opengl/gl_rasterizer.cpp +++ b/src/video_core/renderer_opengl/gl_rasterizer.cpp @@ -140,8 +140,9 @@ void RasterizerOpenGL::InitObjects() { } state.Apply(); - ASSERT_MSG(glCheckFramebufferStatus(GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE, - "OpenGL rasterizer framebuffer setup failed, status %X", glCheckFramebufferStatus(GL_FRAMEBUFFER)); + GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER); + ASSERT_MSG(status == GL_FRAMEBUFFER_COMPLETE, + "OpenGL rasterizer framebuffer setup failed, status %X", status); } void RasterizerOpenGL::Reset() { @@ -809,8 +810,9 @@ void RasterizerOpenGL::SyncFramebuffer() { ReloadDepthBuffer(); } - ASSERT_MSG(glCheckFramebufferStatus(GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE, - "OpenGL rasterizer framebuffer setup failed, status %X", glCheckFramebufferStatus(GL_FRAMEBUFFER)); + GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER); + ASSERT_MSG(status == GL_FRAMEBUFFER_COMPLETE, + "OpenGL rasterizer framebuffer setup failed, status %X", status); } void RasterizerOpenGL::SyncCullMode() { From ef47d855cee7d3c3de62c9c8c63449357ec02011 Mon Sep 17 00:00:00 2001 From: JamePeng Date: Sun, 27 Mar 2016 18:15:48 +0800 Subject: [PATCH 018/104] Append the missing function name"GetAppletInfo" to APT:A --- src/core/hle/service/apt/apt_a.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/core/hle/service/apt/apt_a.cpp b/src/core/hle/service/apt/apt_a.cpp index 0c6a77305..61f660f55 100644 --- a/src/core/hle/service/apt/apt_a.cpp +++ b/src/core/hle/service/apt/apt_a.cpp @@ -14,7 +14,7 @@ const Interface::FunctionInfo FunctionTable[] = { {0x00030040, Enable, "Enable?"}, {0x00040040, nullptr, "Finalize?"}, {0x00050040, nullptr, "GetAppletManInfo?"}, - {0x00060040, nullptr, "GetAppletInfo?"}, + {0x00060040, GetAppletInfo, "GetAppletInfo"}, {0x00090040, IsRegistered, "IsRegistered"}, {0x000C0104, SendParameter, "SendParameter"}, {0x000D0080, ReceiveParameter, "ReceiveParameter"}, @@ -24,6 +24,7 @@ const Interface::FunctionInfo FunctionTable[] = { {0x00180040, PrepareToStartLibraryApplet, "PrepareToStartLibraryApplet"}, {0x001E0084, StartLibraryApplet, "StartLibraryApplet"}, {0x003B0040, nullptr, "CancelLibraryApplet?"}, + {0x003E0080, nullptr, "ReplySleepQuery"}, {0x00430040, NotifyToWait, "NotifyToWait?"}, {0x00440000, GetSharedFont, "GetSharedFont?"}, {0x004B00C2, AppletUtility, "AppletUtility?"}, From af9a8258b93e4fd6a0fc1980fadfd07330d00de2 Mon Sep 17 00:00:00 2001 From: JamePeng Date: Tue, 29 Mar 2016 05:25:05 +0800 Subject: [PATCH 019/104] implement APT::GetStartupArgument --- src/core/hle/service/apt/apt.cpp | 17 +++++++++++++++++ src/core/hle/service/apt/apt.h | 17 +++++++++++++++++ src/core/hle/service/apt/apt_a.cpp | 1 + src/core/hle/service/apt/apt_s.cpp | 2 +- src/core/hle/service/apt/apt_u.cpp | 2 +- 5 files changed, 37 insertions(+), 2 deletions(-) diff --git a/src/core/hle/service/apt/apt.cpp b/src/core/hle/service/apt/apt.cpp index a49365287..6d72e8188 100644 --- a/src/core/hle/service/apt/apt.cpp +++ b/src/core/hle/service/apt/apt.cpp @@ -397,6 +397,23 @@ void GetAppletInfo(Service::Interface* self) { LOG_WARNING(Service_APT, "(stubbed) called appid=%u", app_id); } +void GetStartupArgument(Service::Interface* self) { + u32* cmd_buff = Kernel::GetCommandBuffer(); + u32 parameter_size = cmd_buff[1]; + StartupArgumentType startup_argument_type = static_cast(cmd_buff[2]); + + if (parameter_size >= 0x300) { + LOG_ERROR(Service_APT, "Parameter size is outside the valid range (capped to 0x300): parameter_size=0x%08x", parameter_size); + return; + } + + LOG_WARNING(Service_APT,"(stubbed) called startup_argument_type=%u , parameter_size=0x%08x , parameter_value=0x%08x", + startup_argument_type, parameter_size, Memory::Read32(cmd_buff[41])); + + cmd_buff[1] = RESULT_SUCCESS.raw; + cmd_buff[2] = (parameter_size > 0) ? 1 : 0; +} + void Init() { AddService(new APT_A_Interface); AddService(new APT_S_Interface); diff --git a/src/core/hle/service/apt/apt.h b/src/core/hle/service/apt/apt.h index 47a97c1a1..e4f96855b 100644 --- a/src/core/hle/service/apt/apt.h +++ b/src/core/hle/service/apt/apt.h @@ -67,6 +67,12 @@ enum class AppletId : u32 { Ed2 = 0x402, }; +enum class StartupArgumentType : u32 { + OtherApp = 0, + Restart = 1, + OtherMedia = 2, +}; + /// Send a parameter to the currently-running application, which will read it via ReceiveParameter void SendParameter(const MessageParameter& parameter); @@ -344,6 +350,17 @@ void PreloadLibraryApplet(Service::Interface* self); */ void StartLibraryApplet(Service::Interface* self); +/** +* APT::GetStartupArgument service function +* Inputs: +* 1 : Parameter Size (capped to 0x300) +* 2 : StartupArgumentType +* Outputs: +* 0 : Return header +* 1 : u8, Exists (0 = does not exist, 1 = exists) +*/ +void GetStartupArgument(Service::Interface* self); + /// Initialize the APT service void Init(); diff --git a/src/core/hle/service/apt/apt_a.cpp b/src/core/hle/service/apt/apt_a.cpp index 61f660f55..c0bbf7dd4 100644 --- a/src/core/hle/service/apt/apt_a.cpp +++ b/src/core/hle/service/apt/apt_a.cpp @@ -28,6 +28,7 @@ const Interface::FunctionInfo FunctionTable[] = { {0x00430040, NotifyToWait, "NotifyToWait?"}, {0x00440000, GetSharedFont, "GetSharedFont?"}, {0x004B00C2, AppletUtility, "AppletUtility?"}, + {0x00510080, GetStartupArgument, "GetStartupArgument"}, {0x00550040, nullptr, "WriteInputToNsState?"}, }; diff --git a/src/core/hle/service/apt/apt_s.cpp b/src/core/hle/service/apt/apt_s.cpp index 7f6e81a63..b978b8f67 100644 --- a/src/core/hle/service/apt/apt_s.cpp +++ b/src/core/hle/service/apt/apt_s.cpp @@ -89,7 +89,7 @@ const Interface::FunctionInfo FunctionTable[] = { {0x004E0000, nullptr, "HardwareResetAsync"}, {0x004F0080, nullptr, "SetApplicationCpuTimeLimit"}, {0x00500040, nullptr, "GetApplicationCpuTimeLimit"}, - {0x00510080, nullptr, "GetStartupArgument"}, + {0x00510080, GetStartupArgument, "GetStartupArgument"}, {0x00520104, nullptr, "Wrap1"}, {0x00530104, nullptr, "Unwrap1"}, {0x00580002, nullptr, "GetProgramID"}, diff --git a/src/core/hle/service/apt/apt_u.cpp b/src/core/hle/service/apt/apt_u.cpp index b13b51549..0e85c6d08 100644 --- a/src/core/hle/service/apt/apt_u.cpp +++ b/src/core/hle/service/apt/apt_u.cpp @@ -89,7 +89,7 @@ const Interface::FunctionInfo FunctionTable[] = { {0x004E0000, nullptr, "HardwareResetAsync"}, {0x004F0080, SetAppCpuTimeLimit, "SetAppCpuTimeLimit"}, {0x00500040, GetAppCpuTimeLimit, "GetAppCpuTimeLimit"}, - {0x00510080, nullptr, "GetStartupArgument"}, + {0x00510080, GetStartupArgument, "GetStartupArgument"}, {0x00520104, nullptr, "Wrap1"}, {0x00530104, nullptr, "Unwrap1"}, {0x00580002, nullptr, "GetProgramID"}, From a06dcfeb61d6769c562d6d50cfa3c0024176ae82 Mon Sep 17 00:00:00 2001 From: MerryMage Date: Tue, 5 Apr 2016 13:29:55 +0100 Subject: [PATCH 020/104] Common: Remove Common::make_unique, use std::make_unique --- src/citra/citra.cpp | 4 ++-- src/citra/config.cpp | 7 ++++--- src/citra_qt/main.cpp | 4 ++-- src/common/CMakeLists.txt | 1 - src/common/make_unique.h | 17 ----------------- src/core/arm/dyncom/arm_dyncom.cpp | 5 ++--- src/core/core.cpp | 5 ++--- src/core/file_sys/archive_extsavedata.cpp | 4 ++-- src/core/file_sys/archive_romfs.cpp | 3 +-- src/core/file_sys/archive_savedata.cpp | 4 ++-- src/core/file_sys/archive_savedatacheck.cpp | 4 ++-- src/core/file_sys/archive_sdmc.cpp | 4 ++-- src/core/file_sys/archive_systemsavedata.cpp | 4 ++-- src/core/file_sys/disk_archive.cpp | 8 ++++---- src/core/file_sys/ivfc_archive.cpp | 5 ++--- src/core/hle/kernel/process.cpp | 3 ++- src/core/hle/service/fs/archive.cpp | 13 ++++++------- src/core/loader/loader.cpp | 5 ++--- src/core/loader/ncch.cpp | 1 - src/video_core/renderer_base.cpp | 6 ++---- .../renderer_opengl/gl_rasterizer.cpp | 3 +-- .../renderer_opengl/gl_rasterizer_cache.cpp | 5 +++-- src/video_core/shader/shader.cpp | 1 - src/video_core/video_core.cpp | 3 +-- 24 files changed, 46 insertions(+), 73 deletions(-) delete mode 100644 src/common/make_unique.h diff --git a/src/citra/citra.cpp b/src/citra/citra.cpp index 40e40f192..b12369136 100644 --- a/src/citra/citra.cpp +++ b/src/citra/citra.cpp @@ -5,6 +5,7 @@ #include #include #include +#include // This needs to be included before getopt.h because the latter #defines symbols used by it #include "common/microprofile.h" @@ -19,7 +20,6 @@ #include "common/logging/log.h" #include "common/logging/backend.h" #include "common/logging/filter.h" -#include "common/make_unique.h" #include "common/scope_exit.h" #include "core/settings.h" @@ -79,7 +79,7 @@ int main(int argc, char **argv) { GDBStub::ToggleServer(Settings::values.use_gdbstub); GDBStub::SetServerPort(static_cast(Settings::values.gdbstub_port)); - std::unique_ptr emu_window = Common::make_unique(); + std::unique_ptr emu_window = std::make_unique(); VideoCore::g_hw_renderer_enabled = Settings::values.use_hw_renderer; VideoCore::g_shader_jit_enabled = Settings::values.use_shader_jit; diff --git a/src/citra/config.cpp b/src/citra/config.cpp index 9034b188e..6b6617352 100644 --- a/src/citra/config.cpp +++ b/src/citra/config.cpp @@ -2,6 +2,8 @@ // Licensed under GPLv2 or any later version // Refer to the license.txt file included. +#include + #include #include @@ -10,7 +12,6 @@ #include "common/file_util.h" #include "common/logging/log.h" -#include "common/make_unique.h" #include "core/settings.h" @@ -19,7 +20,7 @@ Config::Config() { // TODO: Don't hardcode the path; let the frontend decide where to put the config files. sdl2_config_loc = FileUtil::GetUserPath(D_CONFIG_IDX) + "sdl2-config.ini"; - sdl2_config = Common::make_unique(sdl2_config_loc); + sdl2_config = std::make_unique(sdl2_config_loc); Reload(); } @@ -31,7 +32,7 @@ bool Config::LoadINI(const std::string& default_contents, bool retry) { LOG_WARNING(Config, "Failed to load %s. Creating file from defaults...", location); FileUtil::CreateFullPath(location); FileUtil::WriteStringToFile(true, default_contents, location); - sdl2_config = Common::make_unique(location); // Reopen file + sdl2_config = std::make_unique(location); // Reopen file return LoadINI(default_contents, false); } diff --git a/src/citra_qt/main.cpp b/src/citra_qt/main.cpp index 32cceaf7e..ebd52a7b3 100644 --- a/src/citra_qt/main.cpp +++ b/src/citra_qt/main.cpp @@ -3,6 +3,7 @@ // Refer to the license.txt file included. #include +#include #include #include @@ -30,7 +31,6 @@ #include "citra_qt/debugger/ramview.h" #include "citra_qt/debugger/registers.h" -#include "common/make_unique.h" #include "common/microprofile.h" #include "common/platform.h" #include "common/scm_rev.h" @@ -319,7 +319,7 @@ void GMainWindow::BootGame(const std::string& filename) { return; // Create and start the emulation thread - emu_thread = Common::make_unique(render_window); + emu_thread = std::make_unique(render_window); emit EmulationStarting(emu_thread.get()); render_window->moveContext(); emu_thread->start(); diff --git a/src/common/CMakeLists.txt b/src/common/CMakeLists.txt index 1c9be718f..c839ce173 100644 --- a/src/common/CMakeLists.txt +++ b/src/common/CMakeLists.txt @@ -42,7 +42,6 @@ set(HEADERS logging/filter.h logging/log.h logging/backend.h - make_unique.h math_util.h memory_util.h microprofile.h diff --git a/src/common/make_unique.h b/src/common/make_unique.h deleted file mode 100644 index f6e7f017c..000000000 --- a/src/common/make_unique.h +++ /dev/null @@ -1,17 +0,0 @@ -// Copyright 2014 Citra Emulator Project -// Licensed under GPLv2 or any later version -// Refer to the license.txt file included. - -#pragma once - -#include -#include - -namespace Common { - -template -std::unique_ptr make_unique(Args&&... args) { - return std::unique_ptr(new T(std::forward(args)...)); -} - -} // namespace diff --git a/src/core/arm/dyncom/arm_dyncom.cpp b/src/core/arm/dyncom/arm_dyncom.cpp index f3be2c857..947f5094b 100644 --- a/src/core/arm/dyncom/arm_dyncom.cpp +++ b/src/core/arm/dyncom/arm_dyncom.cpp @@ -3,8 +3,7 @@ // Refer to the license.txt file included. #include - -#include "common/make_unique.h" +#include #include "core/arm/skyeye_common/armstate.h" #include "core/arm/skyeye_common/armsupp.h" @@ -18,7 +17,7 @@ #include "core/core_timing.h" ARM_DynCom::ARM_DynCom(PrivilegeMode initial_mode) { - state = Common::make_unique(initial_mode); + state = std::make_unique(initial_mode); } ARM_DynCom::~ARM_DynCom() { diff --git a/src/core/core.cpp b/src/core/core.cpp index 84d6c392e..3bb843aab 100644 --- a/src/core/core.cpp +++ b/src/core/core.cpp @@ -4,7 +4,6 @@ #include -#include "common/make_unique.h" #include "common/logging/log.h" #include "core/core.h" @@ -74,8 +73,8 @@ void Stop() { /// Initialize the core void Init() { - g_sys_core = Common::make_unique(USER32MODE); - g_app_core = Common::make_unique(USER32MODE); + g_sys_core = std::make_unique(USER32MODE); + g_app_core = std::make_unique(USER32MODE); LOG_DEBUG(Core, "Initialized OK"); } diff --git a/src/core/file_sys/archive_extsavedata.cpp b/src/core/file_sys/archive_extsavedata.cpp index 961264fe5..1d9eaefcb 100644 --- a/src/core/file_sys/archive_extsavedata.cpp +++ b/src/core/file_sys/archive_extsavedata.cpp @@ -3,12 +3,12 @@ // Refer to the license.txt file included. #include +#include #include #include "common/common_types.h" #include "common/file_util.h" #include "common/logging/log.h" -#include "common/make_unique.h" #include "common/string_util.h" #include "core/file_sys/archive_extsavedata.h" @@ -84,7 +84,7 @@ ResultVal> ArchiveFactory_ExtSaveData::Open(cons ErrorSummary::InvalidState, ErrorLevel::Status); } } - auto archive = Common::make_unique(fullpath); + auto archive = std::make_unique(fullpath); return MakeResult>(std::move(archive)); } diff --git a/src/core/file_sys/archive_romfs.cpp b/src/core/file_sys/archive_romfs.cpp index a9a29ebde..38828b546 100644 --- a/src/core/file_sys/archive_romfs.cpp +++ b/src/core/file_sys/archive_romfs.cpp @@ -7,7 +7,6 @@ #include "common/common_types.h" #include "common/logging/log.h" -#include "common/make_unique.h" #include "core/file_sys/archive_romfs.h" #include "core/file_sys/ivfc_archive.h" @@ -25,7 +24,7 @@ ArchiveFactory_RomFS::ArchiveFactory_RomFS(Loader::AppLoader& app_loader) { } ResultVal> ArchiveFactory_RomFS::Open(const Path& path) { - auto archive = Common::make_unique(romfs_file, data_offset, data_size); + auto archive = std::make_unique(romfs_file, data_offset, data_size); return MakeResult>(std::move(archive)); } diff --git a/src/core/file_sys/archive_savedata.cpp b/src/core/file_sys/archive_savedata.cpp index fe020d21c..fd5711e14 100644 --- a/src/core/file_sys/archive_savedata.cpp +++ b/src/core/file_sys/archive_savedata.cpp @@ -3,11 +3,11 @@ // Refer to the license.txt file included. #include +#include #include "common/common_types.h" #include "common/file_util.h" #include "common/logging/log.h" -#include "common/make_unique.h" #include "common/string_util.h" #include "core/file_sys/archive_savedata.h" @@ -53,7 +53,7 @@ ResultVal> ArchiveFactory_SaveData::Open(const P ErrorSummary::InvalidState, ErrorLevel::Status); } - auto archive = Common::make_unique(std::move(concrete_mount_point)); + auto archive = std::make_unique(std::move(concrete_mount_point)); return MakeResult>(std::move(archive)); } diff --git a/src/core/file_sys/archive_savedatacheck.cpp b/src/core/file_sys/archive_savedatacheck.cpp index 3db11c500..9f65e5455 100644 --- a/src/core/file_sys/archive_savedatacheck.cpp +++ b/src/core/file_sys/archive_savedatacheck.cpp @@ -3,12 +3,12 @@ // Refer to the license.txt file included. #include +#include #include #include "common/common_types.h" #include "common/file_util.h" #include "common/logging/log.h" -#include "common/make_unique.h" #include "common/string_util.h" #include "core/file_sys/archive_savedatacheck.h" @@ -44,7 +44,7 @@ ResultVal> ArchiveFactory_SaveDataCheck::Open(co } auto size = file->GetSize(); - auto archive = Common::make_unique(file, 0, size); + auto archive = std::make_unique(file, 0, size); return MakeResult>(std::move(archive)); } diff --git a/src/core/file_sys/archive_sdmc.cpp b/src/core/file_sys/archive_sdmc.cpp index 657221cbf..9b218af58 100644 --- a/src/core/file_sys/archive_sdmc.cpp +++ b/src/core/file_sys/archive_sdmc.cpp @@ -3,10 +3,10 @@ // Refer to the license.txt file included. #include +#include #include "common/file_util.h" #include "common/logging/log.h" -#include "common/make_unique.h" #include "core/file_sys/archive_sdmc.h" #include "core/file_sys/disk_archive.h" @@ -36,7 +36,7 @@ bool ArchiveFactory_SDMC::Initialize() { } ResultVal> ArchiveFactory_SDMC::Open(const Path& path) { - auto archive = Common::make_unique(sdmc_directory); + auto archive = std::make_unique(sdmc_directory); return MakeResult>(std::move(archive)); } diff --git a/src/core/file_sys/archive_systemsavedata.cpp b/src/core/file_sys/archive_systemsavedata.cpp index e1780de2f..1bcc228a1 100644 --- a/src/core/file_sys/archive_systemsavedata.cpp +++ b/src/core/file_sys/archive_systemsavedata.cpp @@ -3,11 +3,11 @@ // Refer to the license.txt file included. #include +#include #include #include "common/common_types.h" #include "common/file_util.h" -#include "common/make_unique.h" #include "common/string_util.h" #include "core/file_sys/archive_systemsavedata.h" @@ -59,7 +59,7 @@ ResultVal> ArchiveFactory_SystemSaveData::Open(c return ResultCode(ErrorDescription::FS_NotFormatted, ErrorModule::FS, ErrorSummary::InvalidState, ErrorLevel::Status); } - auto archive = Common::make_unique(fullpath); + auto archive = std::make_unique(fullpath); return MakeResult>(std::move(archive)); } diff --git a/src/core/file_sys/disk_archive.cpp b/src/core/file_sys/disk_archive.cpp index 8e4ea01c5..489cc96fb 100644 --- a/src/core/file_sys/disk_archive.cpp +++ b/src/core/file_sys/disk_archive.cpp @@ -4,11 +4,11 @@ #include #include +#include #include "common/common_types.h" #include "common/file_util.h" #include "common/logging/log.h" -#include "common/make_unique.h" #include "core/file_sys/disk_archive.h" @@ -19,7 +19,7 @@ namespace FileSys { ResultVal> DiskArchive::OpenFile(const Path& path, const Mode mode) const { LOG_DEBUG(Service_FS, "called path=%s mode=%01X", path.DebugStr().c_str(), mode.hex); - auto file = Common::make_unique(*this, path, mode); + auto file = std::make_unique(*this, path, mode); ResultCode result = file->Open(); if (result.IsError()) return result; @@ -83,7 +83,7 @@ bool DiskArchive::RenameDirectory(const Path& src_path, const Path& dest_path) c std::unique_ptr DiskArchive::OpenDirectory(const Path& path) const { LOG_DEBUG(Service_FS, "called path=%s", path.DebugStr().c_str()); - auto directory = Common::make_unique(*this, path); + auto directory = std::make_unique(*this, path); if (!directory->Open()) return nullptr; return std::move(directory); @@ -132,7 +132,7 @@ ResultCode DiskFile::Open() { // Open the file in binary mode, to avoid problems with CR/LF on Windows systems mode_string += "b"; - file = Common::make_unique(path, mode_string.c_str()); + file = std::make_unique(path, mode_string.c_str()); if (file->IsOpen()) return RESULT_SUCCESS; return ResultCode(ErrorDescription::FS_NotFound, ErrorModule::FS, ErrorSummary::NotFound, ErrorLevel::Status); diff --git a/src/core/file_sys/ivfc_archive.cpp b/src/core/file_sys/ivfc_archive.cpp index a8e9a72ef..c61791ef7 100644 --- a/src/core/file_sys/ivfc_archive.cpp +++ b/src/core/file_sys/ivfc_archive.cpp @@ -7,7 +7,6 @@ #include "common/common_types.h" #include "common/logging/log.h" -#include "common/make_unique.h" #include "core/file_sys/ivfc_archive.h" @@ -21,7 +20,7 @@ std::string IVFCArchive::GetName() const { } ResultVal> IVFCArchive::OpenFile(const Path& path, const Mode mode) const { - return MakeResult>(Common::make_unique(romfs_file, data_offset, data_size)); + return MakeResult>(std::make_unique(romfs_file, data_offset, data_size)); } ResultCode IVFCArchive::DeleteFile(const Path& path) const { @@ -58,7 +57,7 @@ bool IVFCArchive::RenameDirectory(const Path& src_path, const Path& dest_path) c } std::unique_ptr IVFCArchive::OpenDirectory(const Path& path) const { - return Common::make_unique(); + return std::make_unique(); } u64 IVFCArchive::GetFreeBytes() const { diff --git a/src/core/hle/kernel/process.cpp b/src/core/hle/kernel/process.cpp index 24b266eae..0546f6e16 100644 --- a/src/core/hle/kernel/process.cpp +++ b/src/core/hle/kernel/process.cpp @@ -2,10 +2,11 @@ // Licensed under GPLv2 or any later version // Refer to the license.txt file included. +#include + #include "common/assert.h" #include "common/common_funcs.h" #include "common/logging/log.h" -#include "common/make_unique.h" #include "core/hle/kernel/memory.h" #include "core/hle/kernel/process.h" diff --git a/src/core/hle/service/fs/archive.cpp b/src/core/hle/service/fs/archive.cpp index 590697e76..e9588cb72 100644 --- a/src/core/hle/service/fs/archive.cpp +++ b/src/core/hle/service/fs/archive.cpp @@ -15,7 +15,6 @@ #include "common/common_types.h" #include "common/file_util.h" #include "common/logging/log.h" -#include "common/make_unique.h" #include "core/file_sys/archive_backend.h" #include "core/file_sys/archive_extsavedata.h" @@ -521,23 +520,23 @@ void ArchiveInit() { std::string sdmc_directory = FileUtil::GetUserPath(D_SDMC_IDX); std::string nand_directory = FileUtil::GetUserPath(D_NAND_IDX); - auto sdmc_factory = Common::make_unique(sdmc_directory); + auto sdmc_factory = std::make_unique(sdmc_directory); if (sdmc_factory->Initialize()) RegisterArchiveType(std::move(sdmc_factory), ArchiveIdCode::SDMC); else LOG_ERROR(Service_FS, "Can't instantiate SDMC archive with path %s", sdmc_directory.c_str()); // Create the SaveData archive - auto savedata_factory = Common::make_unique(sdmc_directory); + auto savedata_factory = std::make_unique(sdmc_directory); RegisterArchiveType(std::move(savedata_factory), ArchiveIdCode::SaveData); - auto extsavedata_factory = Common::make_unique(sdmc_directory, false); + auto extsavedata_factory = std::make_unique(sdmc_directory, false); if (extsavedata_factory->Initialize()) RegisterArchiveType(std::move(extsavedata_factory), ArchiveIdCode::ExtSaveData); else LOG_ERROR(Service_FS, "Can't instantiate ExtSaveData archive with path %s", extsavedata_factory->GetMountPoint().c_str()); - auto sharedextsavedata_factory = Common::make_unique(nand_directory, true); + auto sharedextsavedata_factory = std::make_unique(nand_directory, true); if (sharedextsavedata_factory->Initialize()) RegisterArchiveType(std::move(sharedextsavedata_factory), ArchiveIdCode::SharedExtSaveData); else @@ -545,10 +544,10 @@ void ArchiveInit() { sharedextsavedata_factory->GetMountPoint().c_str()); // Create the SaveDataCheck archive, basically a small variation of the RomFS archive - auto savedatacheck_factory = Common::make_unique(nand_directory); + auto savedatacheck_factory = std::make_unique(nand_directory); RegisterArchiveType(std::move(savedatacheck_factory), ArchiveIdCode::SaveDataCheck); - auto systemsavedata_factory = Common::make_unique(nand_directory); + auto systemsavedata_factory = std::make_unique(nand_directory); RegisterArchiveType(std::move(systemsavedata_factory), ArchiveIdCode::SystemSaveData); } diff --git a/src/core/loader/loader.cpp b/src/core/loader/loader.cpp index b1907cd55..886501c41 100644 --- a/src/core/loader/loader.cpp +++ b/src/core/loader/loader.cpp @@ -6,7 +6,6 @@ #include #include "common/logging/log.h" -#include "common/make_unique.h" #include "common/string_util.h" #include "core/file_sys/archive_romfs.h" @@ -120,7 +119,7 @@ ResultStatus LoadFile(const std::string& filename) { AppLoader_THREEDSX app_loader(std::move(file), filename_filename, filename); // Load application and RomFS if (ResultStatus::Success == app_loader.Load()) { - Service::FS::RegisterArchiveType(Common::make_unique(app_loader), Service::FS::ArchiveIdCode::RomFS); + Service::FS::RegisterArchiveType(std::make_unique(app_loader), Service::FS::ArchiveIdCode::RomFS); return ResultStatus::Success; } break; @@ -139,7 +138,7 @@ ResultStatus LoadFile(const std::string& filename) { // Load application and RomFS ResultStatus result = app_loader.Load(); if (ResultStatus::Success == result) { - Service::FS::RegisterArchiveType(Common::make_unique(app_loader), Service::FS::ArchiveIdCode::RomFS); + Service::FS::RegisterArchiveType(std::make_unique(app_loader), Service::FS::ArchiveIdCode::RomFS); } return result; } diff --git a/src/core/loader/ncch.cpp b/src/core/loader/ncch.cpp index 93f21bec2..e63cab33f 100644 --- a/src/core/loader/ncch.cpp +++ b/src/core/loader/ncch.cpp @@ -7,7 +7,6 @@ #include #include "common/logging/log.h" -#include "common/make_unique.h" #include "common/string_util.h" #include "common/swap.h" diff --git a/src/video_core/renderer_base.cpp b/src/video_core/renderer_base.cpp index 6467ff723..101f84eb9 100644 --- a/src/video_core/renderer_base.cpp +++ b/src/video_core/renderer_base.cpp @@ -4,8 +4,6 @@ #include -#include "common/make_unique.h" - #include "core/settings.h" #include "video_core/renderer_base.h" @@ -19,9 +17,9 @@ void RendererBase::RefreshRasterizerSetting() { opengl_rasterizer_active = hw_renderer_enabled; if (hw_renderer_enabled) { - rasterizer = Common::make_unique(); + rasterizer = std::make_unique(); } else { - rasterizer = Common::make_unique(); + rasterizer = std::make_unique(); } rasterizer->InitObjects(); rasterizer->Reset(); diff --git a/src/video_core/renderer_opengl/gl_rasterizer.cpp b/src/video_core/renderer_opengl/gl_rasterizer.cpp index b3dc6aa19..5d91aac00 100644 --- a/src/video_core/renderer_opengl/gl_rasterizer.cpp +++ b/src/video_core/renderer_opengl/gl_rasterizer.cpp @@ -9,7 +9,6 @@ #include "common/color.h" #include "common/file_util.h" -#include "common/make_unique.h" #include "common/math_util.h" #include "common/microprofile.h" #include "common/profiler.h" @@ -674,7 +673,7 @@ void RasterizerOpenGL::ReconfigureDepthTexture(DepthTextureInfo& texture, Pica:: void RasterizerOpenGL::SetShader() { PicaShaderConfig config = PicaShaderConfig::CurrentConfig(); - std::unique_ptr shader = Common::make_unique(); + std::unique_ptr shader = std::make_unique(); // Find (or generate) the GLSL shader for the current TEV state auto cached_shader = shader_cache.find(config); diff --git a/src/video_core/renderer_opengl/gl_rasterizer_cache.cpp b/src/video_core/renderer_opengl/gl_rasterizer_cache.cpp index a9ad46fe0..1323c12e4 100644 --- a/src/video_core/renderer_opengl/gl_rasterizer_cache.cpp +++ b/src/video_core/renderer_opengl/gl_rasterizer_cache.cpp @@ -2,8 +2,9 @@ // Licensed under GPLv2 or any later version // Refer to the license.txt file included. +#include + #include "common/hash.h" -#include "common/make_unique.h" #include "common/math_util.h" #include "common/microprofile.h" #include "common/vector_math.h" @@ -29,7 +30,7 @@ void RasterizerCacheOpenGL::LoadAndBindTexture(OpenGLState &state, unsigned text } else { MICROPROFILE_SCOPE(OpenGL_TextureUpload); - std::unique_ptr new_texture = Common::make_unique(); + std::unique_ptr new_texture = std::make_unique(); new_texture->texture.Create(); state.texture_units[texture_unit].texture_2d = new_texture->texture.handle; diff --git a/src/video_core/shader/shader.cpp b/src/video_core/shader/shader.cpp index 509558fc0..045e7d5bd 100644 --- a/src/video_core/shader/shader.cpp +++ b/src/video_core/shader/shader.cpp @@ -8,7 +8,6 @@ #include #include "common/hash.h" -#include "common/make_unique.h" #include "common/microprofile.h" #include "common/profiler.h" diff --git a/src/video_core/video_core.cpp b/src/video_core/video_core.cpp index ee5e50df1..256899c89 100644 --- a/src/video_core/video_core.cpp +++ b/src/video_core/video_core.cpp @@ -5,7 +5,6 @@ #include #include "common/emu_window.h" -#include "common/make_unique.h" #include "common/logging/log.h" #include "core/core.h" @@ -32,7 +31,7 @@ bool Init(EmuWindow* emu_window) { Pica::Init(); g_emu_window = emu_window; - g_renderer = Common::make_unique(); + g_renderer = std::make_unique(); g_renderer->SetWindow(g_emu_window); if (g_renderer->Init()) { LOG_DEBUG(Render, "initialized OK"); From 857bf9cd0963675605fc1cd3db0575335c902f7b Mon Sep 17 00:00:00 2001 From: JamePeng Date: Tue, 5 Apr 2016 02:24:02 +0800 Subject: [PATCH 021/104] append SetAppCpuTimeLimit and GetAppCpuTimeLimit to APT:A --- src/core/hle/service/apt/apt.h | 16 ++++++++-------- src/core/hle/service/apt/apt_a.cpp | 5 ++++- src/core/hle/service/apt/apt_s.cpp | 8 ++++---- 3 files changed, 16 insertions(+), 13 deletions(-) diff --git a/src/core/hle/service/apt/apt.h b/src/core/hle/service/apt/apt.h index e4f96855b..668b4a66f 100644 --- a/src/core/hle/service/apt/apt.h +++ b/src/core/hle/service/apt/apt.h @@ -351,14 +351,14 @@ void PreloadLibraryApplet(Service::Interface* self); void StartLibraryApplet(Service::Interface* self); /** -* APT::GetStartupArgument service function -* Inputs: -* 1 : Parameter Size (capped to 0x300) -* 2 : StartupArgumentType -* Outputs: -* 0 : Return header -* 1 : u8, Exists (0 = does not exist, 1 = exists) -*/ + * APT::GetStartupArgument service function + * Inputs: + * 1 : Parameter Size (capped to 0x300) + * 2 : StartupArgumentType + * Outputs: + * 0 : Return header + * 1 : u8, Exists (0 = does not exist, 1 = exists) + */ void GetStartupArgument(Service::Interface* self); /// Initialize the APT service diff --git a/src/core/hle/service/apt/apt_a.cpp b/src/core/hle/service/apt/apt_a.cpp index c0bbf7dd4..9ff47701a 100644 --- a/src/core/hle/service/apt/apt_a.cpp +++ b/src/core/hle/service/apt/apt_a.cpp @@ -13,9 +13,10 @@ const Interface::FunctionInfo FunctionTable[] = { {0x00020080, Initialize, "Initialize?"}, {0x00030040, Enable, "Enable?"}, {0x00040040, nullptr, "Finalize?"}, - {0x00050040, nullptr, "GetAppletManInfo?"}, + {0x00050040, GetAppletManInfo, "GetAppletManInfo"}, {0x00060040, GetAppletInfo, "GetAppletInfo"}, {0x00090040, IsRegistered, "IsRegistered"}, + {0x000B0040, InquireNotification, "InquireNotification"}, {0x000C0104, SendParameter, "SendParameter"}, {0x000D0080, ReceiveParameter, "ReceiveParameter"}, {0x000E0080, GlanceParameter, "GlanceParameter"}, @@ -28,6 +29,8 @@ const Interface::FunctionInfo FunctionTable[] = { {0x00430040, NotifyToWait, "NotifyToWait?"}, {0x00440000, GetSharedFont, "GetSharedFont?"}, {0x004B00C2, AppletUtility, "AppletUtility?"}, + {0x004F0080, SetAppCpuTimeLimit, "SetAppCpuTimeLimit"}, + {0x00500040, GetAppCpuTimeLimit, "GetAppCpuTimeLimit"}, {0x00510080, GetStartupArgument, "GetStartupArgument"}, {0x00550040, nullptr, "WriteInputToNsState?"}, }; diff --git a/src/core/hle/service/apt/apt_s.cpp b/src/core/hle/service/apt/apt_s.cpp index b978b8f67..ca54e593c 100644 --- a/src/core/hle/service/apt/apt_s.cpp +++ b/src/core/hle/service/apt/apt_s.cpp @@ -13,8 +13,8 @@ const Interface::FunctionInfo FunctionTable[] = { {0x00020080, Initialize, "Initialize"}, {0x00030040, Enable, "Enable"}, {0x00040040, nullptr, "Finalize"}, - {0x00050040, nullptr, "GetAppletManInfo"}, - {0x00060040, nullptr, "GetAppletInfo"}, + {0x00050040, GetAppletManInfo, "GetAppletManInfo"}, + {0x00060040, GetAppletInfo, "GetAppletInfo"}, {0x00070000, nullptr, "GetLastSignaledAppletId"}, {0x00080000, nullptr, "CountRegisteredApplet"}, {0x00090040, nullptr, "IsRegistered"}, @@ -87,8 +87,8 @@ const Interface::FunctionInfo FunctionTable[] = { {0x004C0000, nullptr, "SetFatalErrDispMode"}, {0x004D0080, nullptr, "GetAppletProgramInfo"}, {0x004E0000, nullptr, "HardwareResetAsync"}, - {0x004F0080, nullptr, "SetApplicationCpuTimeLimit"}, - {0x00500040, nullptr, "GetApplicationCpuTimeLimit"}, + {0x004F0080, SetAppCpuTimeLimit, "SetAppCpuTimeLimit"}, + {0x00500040, GetAppCpuTimeLimit, "GetAppCpuTimeLimit"}, {0x00510080, GetStartupArgument, "GetStartupArgument"}, {0x00520104, nullptr, "Wrap1"}, {0x00530104, nullptr, "Unwrap1"}, From 44d746fc92718c39629e64dbfb8555690d3af0fc Mon Sep 17 00:00:00 2001 From: polaris- Date: Wed, 6 Apr 2016 07:01:00 -0400 Subject: [PATCH 022/104] Adopted WinterMute's gdbstub changes This fixes the comments left on the PR (whitespace, SO_REUSEADDR, comment changes). --- src/citra/citra.cpp | 25 ++++++-- src/core/gdbstub/gdbstub.cpp | 108 +++++++++++++++++++++++++++-------- 2 files changed, 106 insertions(+), 27 deletions(-) diff --git a/src/citra/citra.cpp b/src/citra/citra.cpp index b12369136..045c5fe8c 100644 --- a/src/citra/citra.cpp +++ b/src/citra/citra.cpp @@ -36,25 +36,40 @@ static void PrintHelp() { - std::cout << "Usage: citra " << std::endl; + std::cout << "Usage: citra [options] " << std::endl; + std::cout << "--help, -h Display this information" << std::endl; + std::cout << "--gdbport, -g number Enable gdb stub on port number" << std::endl; } /// Application entry point int main(int argc, char **argv) { int option_index = 0; + u32 gdb_port = 0; + char *endarg; std::string boot_filename; + static struct option long_options[] = { { "help", no_argument, 0, 'h' }, + { "gdbport", required_argument, 0, 'g' }, { 0, 0, 0, 0 } }; while (optind < argc) { - char arg = getopt_long(argc, argv, ":h", long_options, &option_index); + char arg = getopt_long(argc, argv, ":hg:", long_options, &option_index); if (arg != -1) { switch (arg) { case 'h': PrintHelp(); return 0; + case 'g': + errno = 0; + gdb_port = strtoul(optarg, &endarg, 0); + if (endarg == optarg) errno = EINVAL; + if (errno != 0) { + perror("--gdbport"); + exit(1); + } + break; } } else { boot_filename = argv[optind]; @@ -76,8 +91,10 @@ int main(int argc, char **argv) { Config config; log_filter.ParseFilterString(Settings::values.log_filter); - GDBStub::ToggleServer(Settings::values.use_gdbstub); - GDBStub::SetServerPort(static_cast(Settings::values.gdbstub_port)); + if (gdb_port != 0) { + GDBStub::ToggleServer(true); + GDBStub::SetServerPort(gdb_port); + } std::unique_ptr emu_window = std::make_unique(); diff --git a/src/core/gdbstub/gdbstub.cpp b/src/core/gdbstub/gdbstub.cpp index 3a2445241..c1a7ec5bf 100644 --- a/src/core/gdbstub/gdbstub.cpp +++ b/src/core/gdbstub/gdbstub.cpp @@ -60,6 +60,59 @@ const u32 R15_REGISTER = 15; const u32 CPSR_REGISTER = 25; const u32 FPSCR_REGISTER = 58; +// For sample XML files see the GDB source /gdb/features +// GDB also wants the l character at the start +// This XML defines what the registers are for this specific ARM device +static const char* target_xml = +R"(l + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +)"; + namespace GDBStub { static int gdbserver_socket = -1; @@ -211,7 +264,7 @@ static u8 ReadByte() { } /// Calculate the checksum of the current command buffer. -static u8 CalculateChecksum(u8 *buffer, u32 length) { +static u8 CalculateChecksum(u8* buffer, u32 length) { return static_cast(std::accumulate(buffer, buffer + length, 0, std::plus())); } @@ -353,8 +406,15 @@ static void SendReply(const char* reply) { static void HandleQuery() { LOG_DEBUG(Debug_GDBStub, "gdb: query '%s'\n", command_buffer + 1); - if (!strcmp(reinterpret_cast(command_buffer + 1), "TStatus")) { + const char* query = reinterpret_cast(command_buffer + 1); + + if (strcmp(query, "TStatus") == 0 ) { SendReply("T0"); + } else if (strncmp(query, "Supported:", strlen("Supported:")) == 0) { + // PacketSize needs to be large enough for target xml + SendReply("PacketSize=800;qXfer:features:read+"); + } else if (strncmp(query, "Xfer:features:read:target.xml:", strlen("Xfer:features:read:target.xml:")) == 0) { + SendReply(target_xml); } else { SendReply(""); } @@ -491,29 +551,25 @@ static void ReadRegisters() { memset(buffer, 0, sizeof(buffer)); u8* bufptr = buffer; - for (int i = 0, reg = 0; reg <= FPSCR_REGISTER; i++, reg++) { - if (reg <= R15_REGISTER) { - IntToGdbHex(bufptr + i * CHAR_BIT, Core::g_app_core->GetReg(reg)); - } else if (reg == CPSR_REGISTER) { - IntToGdbHex(bufptr + i * CHAR_BIT, Core::g_app_core->GetCPSR()); - } else if (reg == CPSR_REGISTER - 1) { - // Dummy FPA register, ignore - IntToGdbHex(bufptr + i * CHAR_BIT, 0); - } else if (reg < CPSR_REGISTER) { - // Dummy FPA registers, ignore - IntToGdbHex(bufptr + i * CHAR_BIT, 0); - IntToGdbHex(bufptr + (i + 1) * CHAR_BIT, 0); - IntToGdbHex(bufptr + (i + 2) * CHAR_BIT, 0); - i += 2; - } else if (reg > CPSR_REGISTER && reg < FPSCR_REGISTER) { - IntToGdbHex(bufptr + i * CHAR_BIT, Core::g_app_core->GetVFPReg(reg - CPSR_REGISTER - 1)); - IntToGdbHex(bufptr + (i + 1) * CHAR_BIT, 0); - i++; - } else if (reg == FPSCR_REGISTER) { - IntToGdbHex(bufptr + i * CHAR_BIT, Core::g_app_core->GetVFPSystemReg(VFP_FPSCR)); - } + + for (int reg = 0; reg <= R15_REGISTER; reg++) { + IntToGdbHex(bufptr + reg * CHAR_BIT, Core::g_app_core->GetReg(reg)); } + bufptr += (16 * CHAR_BIT); + + IntToGdbHex(bufptr, Core::g_app_core->GetCPSR()); + + bufptr += CHAR_BIT; + + for (int reg = 0; reg <= 31; reg++) { + IntToGdbHex(bufptr + reg * CHAR_BIT, Core::g_app_core->GetVFPReg(reg)); + } + + bufptr += (32 * CHAR_BIT); + + IntToGdbHex(bufptr, Core::g_app_core->GetVFPSystemReg(VFP_FPSCR)); + SendReply(reinterpret_cast(buffer)); } @@ -885,6 +941,12 @@ void Init(u16 port) { LOG_ERROR(Debug_GDBStub, "Failed to create gdb socket"); } + // Set socket to SO_REUSEADDR so it can always bind on the same port + int reuse_enabled = 1; + if (setsockopt(tmpsock, SOL_SOCKET, SO_REUSEADDR, (const char*)&reuse_enabled, sizeof(reuse_enabled)) < 0) { + LOG_ERROR(Debug_GDBStub, "Failed to set gdb socket option"); + } + const sockaddr* server_addr = reinterpret_cast(&saddr_server); socklen_t server_addrlen = sizeof(saddr_server); if (bind(tmpsock, server_addr, server_addrlen) < 0) { From 06a4369f75e2791bd62426329b84e979c68f3279 Mon Sep 17 00:00:00 2001 From: mailwl Date: Wed, 6 Apr 2016 14:57:43 +0300 Subject: [PATCH 023/104] Fix thumb ADR instruction alignment --- src/core/arm/dyncom/arm_dyncom_interpreter.cpp | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/src/core/arm/dyncom/arm_dyncom_interpreter.cpp b/src/core/arm/dyncom/arm_dyncom_interpreter.cpp index 9ed61947e..a6faf42b9 100644 --- a/src/core/arm/dyncom/arm_dyncom_interpreter.cpp +++ b/src/core/arm/dyncom/arm_dyncom_interpreter.cpp @@ -3955,9 +3955,7 @@ unsigned InterpreterMainLoop(ARMul_State* cpu) { if (inst_base->cond == ConditionCode::AL || CondPassed(cpu, inst_base->cond)) { add_inst* const inst_cream = (add_inst*)inst_base->component; - u32 rn_val = RN; - if (inst_cream->Rn == 15) - rn_val += 2 * cpu->GetInstructionSize(); + u32 rn_val = CHECK_READ_REG15_WA(cpu, inst_cream->Rn); bool carry; bool overflow; @@ -6167,9 +6165,7 @@ unsigned InterpreterMainLoop(ARMul_State* cpu) { if (inst_base->cond == ConditionCode::AL || CondPassed(cpu, inst_base->cond)) { sub_inst* const inst_cream = (sub_inst*)inst_base->component; - u32 rn_val = RN; - if (inst_cream->Rn == 15) - rn_val += 2 * cpu->GetInstructionSize(); + u32 rn_val = CHECK_READ_REG15_WA(cpu, inst_cream->Rn); bool carry; bool overflow; From 64ec5ac356cfc1ac433bce9d93ca6a9c2edba79f Mon Sep 17 00:00:00 2001 From: polaris- Date: Wed, 6 Apr 2016 22:27:28 -0400 Subject: [PATCH 024/104] Default to settings from ini for gdbstub --- src/citra/citra.cpp | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/src/citra/citra.cpp b/src/citra/citra.cpp index 045c5fe8c..3a1fbe3f7 100644 --- a/src/citra/citra.cpp +++ b/src/citra/citra.cpp @@ -43,8 +43,10 @@ static void PrintHelp() /// Application entry point int main(int argc, char **argv) { + Config config; int option_index = 0; - u32 gdb_port = 0; + bool use_gdbstub = Settings::values.use_gdbstub; + u32 gdb_port = static_cast(Settings::values.gdbstub_port); char *endarg; std::string boot_filename; @@ -64,6 +66,7 @@ int main(int argc, char **argv) { case 'g': errno = 0; gdb_port = strtoul(optarg, &endarg, 0); + use_gdbstub = true; if (endarg == optarg) errno = EINVAL; if (errno != 0) { perror("--gdbport"); @@ -88,13 +91,10 @@ int main(int argc, char **argv) { return -1; } - Config config; log_filter.ParseFilterString(Settings::values.log_filter); - if (gdb_port != 0) { - GDBStub::ToggleServer(true); - GDBStub::SetServerPort(gdb_port); - } + GDBStub::ToggleServer(use_gdbstub); + GDBStub::SetServerPort(gdb_port); std::unique_ptr emu_window = std::make_unique(); From 4630209c4ce99bb05d5493ff16d9ec666d88dbc9 Mon Sep 17 00:00:00 2001 From: mailwl Date: Fri, 8 Apr 2016 18:41:09 +0300 Subject: [PATCH 025/104] Update cpsr (T)humb bit while creating thread --- src/core/arm/dyncom/arm_dyncom.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/core/arm/dyncom/arm_dyncom.cpp b/src/core/arm/dyncom/arm_dyncom.cpp index 947f5094b..a3581132c 100644 --- a/src/core/arm/dyncom/arm_dyncom.cpp +++ b/src/core/arm/dyncom/arm_dyncom.cpp @@ -93,7 +93,7 @@ void ARM_DynCom::ResetContext(Core::ThreadContext& context, u32 stack_top, u32 e context.cpu_registers[0] = arg; context.pc = entry_point; context.sp = stack_top; - context.cpsr = 0x1F; // Usermode + context.cpsr = 0x1F | ((entry_point & 1) << 5); // Usermode and THUMB mode } void ARM_DynCom::SaveContext(Core::ThreadContext& ctx) { From 61ec5fa776ee14115e2c3c755c730c44cb0cfd20 Mon Sep 17 00:00:00 2001 From: mailwl Date: Fri, 8 Apr 2016 22:39:52 +0300 Subject: [PATCH 026/104] cecd:u: stub GetCecStateAbbreviated (#1648) --- src/common/logging/log.h | 2 +- src/core/hle/service/cecd/cecd.cpp | 9 +++++++++ src/core/hle/service/cecd/cecd.h | 18 ++++++++++++++++++ src/core/hle/service/cecd/cecd_u.cpp | 1 + 4 files changed, 29 insertions(+), 1 deletion(-) diff --git a/src/common/logging/log.h b/src/common/logging/log.h index b8eede3b8..521362317 100644 --- a/src/common/logging/log.h +++ b/src/common/logging/log.h @@ -62,7 +62,7 @@ enum class Class : ClassType { Service_NIM, ///< The NIM (Network interface manager) service Service_NWM, ///< The NWM (Network wlan manager) service Service_CAM, ///< The CAM (Camera) service - Service_CECD, ///< The CECD service + Service_CECD, ///< The CECD (StreetPass) service Service_CFG, ///< The CFG (Configuration) service Service_DSP, ///< The DSP (DSP control) service Service_DLP, ///< The DLP (Download Play) service diff --git a/src/core/hle/service/cecd/cecd.cpp b/src/core/hle/service/cecd/cecd.cpp index e6e36e7ec..50c03495e 100644 --- a/src/core/hle/service/cecd/cecd.cpp +++ b/src/core/hle/service/cecd/cecd.cpp @@ -16,6 +16,15 @@ namespace CECD { static Kernel::SharedPtr cecinfo_event; static Kernel::SharedPtr change_state_event; +void GetCecStateAbbreviated(Service::Interface* self) { + u32* cmd_buff = Kernel::GetCommandBuffer(); + + cmd_buff[1] = RESULT_SUCCESS.raw; // No error + cmd_buff[2] = static_cast(CecStateAbbreviated::CEC_STATE_ABBREV_IDLE); + + LOG_WARNING(Service_CECD, "(STUBBED) called"); +} + void GetCecInfoEventHandle(Service::Interface* self) { u32* cmd_buff = Kernel::GetCommandBuffer(); diff --git a/src/core/hle/service/cecd/cecd.h b/src/core/hle/service/cecd/cecd.h index 89a8d67bb..435611363 100644 --- a/src/core/hle/service/cecd/cecd.h +++ b/src/core/hle/service/cecd/cecd.h @@ -10,6 +10,24 @@ class Interface; namespace CECD { +enum class CecStateAbbreviated { + CEC_STATE_ABBREV_IDLE = 1, ///< Corresponds to CEC_STATE_IDLE + CEC_STATE_ABBREV_NOT_LOCAL = 2, ///< Corresponds to CEC_STATEs *FINISH*, *POST, and OVER_BOSS + CEC_STATE_ABBREV_SCANNING = 3, ///< Corresponds to CEC_STATE_SCANNING + CEC_STATE_ABBREV_WLREADY = 4, ///< Corresponds to CEC_STATE_WIRELESS_READY when some unknown bool is true + CEC_STATE_ABBREV_OTHER = 5, ///< Corresponds to CEC_STATEs besides *FINISH*, *POST, and OVER_BOSS and those listed here +}; + +/** + * GetCecStateAbbreviated service function + * Inputs: + * 0: 0x000E0000 + * Outputs: + * 1: ResultCode + * 2: CecStateAbbreviated + */ +void GetCecStateAbbreviated(Service::Interface* self); + /** * GetCecInfoEventHandle service function * Inputs: diff --git a/src/core/hle/service/cecd/cecd_u.cpp b/src/core/hle/service/cecd/cecd_u.cpp index ace1c73c0..be6d4d8f6 100644 --- a/src/core/hle/service/cecd/cecd_u.cpp +++ b/src/core/hle/service/cecd/cecd_u.cpp @@ -9,6 +9,7 @@ namespace Service { namespace CECD { static const Interface::FunctionInfo FunctionTable[] = { + {0x000E0000, GetCecStateAbbreviated, "GetCecStateAbbreviated"}, {0x000F0000, GetCecInfoEventHandle, "GetCecInfoEventHandle"}, {0x00100000, GetChangeStateEventHandle, "GetChangeStateEventHandle"}, {0x00120104, nullptr, "ReadSavedData"}, From 9045c57d6f88b8c828e325e8db75b19c4b4097bc Mon Sep 17 00:00:00 2001 From: JamePeng Date: Sat, 9 Apr 2016 03:44:00 +0800 Subject: [PATCH 027/104] update the code of AM service! (#1623) --- src/core/hle/service/am/am.cpp | 144 ++++++++++++++++++++++++++--- src/core/hle/service/am/am.h | 126 ++++++++++++++++++++++--- src/core/hle/service/am/am_app.cpp | 16 ++-- src/core/hle/service/am/am_net.cpp | 18 ++-- src/core/hle/service/am/am_sys.cpp | 22 +++-- src/core/hle/service/am/am_u.cpp | 18 ++-- 6 files changed, 291 insertions(+), 53 deletions(-) diff --git a/src/core/hle/service/am/am.cpp b/src/core/hle/service/am/am.cpp index 06be9940e..9591522e5 100644 --- a/src/core/hle/service/am/am.cpp +++ b/src/core/hle/service/am/am.cpp @@ -2,6 +2,8 @@ // Licensed under GPLv2 or any later version // Refer to the license.txt file included. +#include + #include "common/logging/log.h" #include "core/hle/service/service.h" @@ -9,30 +11,119 @@ #include "core/hle/service/am/am_app.h" #include "core/hle/service/am/am_net.h" #include "core/hle/service/am/am_sys.h" +#include "core/hle/service/am/am_u.h" namespace Service { namespace AM { -void TitleIDListGetTotal(Service::Interface* self) { +static std::array am_content_count = { 0, 0, 0 }; +static std::array am_titles_count = { 0, 0, 0 }; +static std::array am_titles_list_count = { 0, 0, 0 }; +static u32 am_ticket_count = 0; +static u32 am_ticket_list_count = 0; + +void GetTitleCount(Service::Interface* self) { u32* cmd_buff = Kernel::GetCommandBuffer(); + u32 media_type = cmd_buff[1] & 0xFF; cmd_buff[1] = RESULT_SUCCESS.raw; - cmd_buff[2] = 0; - - LOG_WARNING(Service_AM, "(STUBBED) media_type %u", media_type); + cmd_buff[2] = am_titles_count[media_type]; + LOG_WARNING(Service_AM, "(STUBBED) media_type=%u, title_count=0x%08x", media_type, am_titles_count[media_type]); } -void GetTitleIDList(Service::Interface* self) { +void FindContentInfos(Service::Interface* self) { u32* cmd_buff = Kernel::GetCommandBuffer(); - u32 num_titles = cmd_buff[1]; - u32 media_type = cmd_buff[2] & 0xFF; - u32 addr = cmd_buff[4]; + + u32 media_type = cmd_buff[1] & 0xFF; + u64 title_id = (static_cast(cmd_buff[3]) << 32) | cmd_buff[2]; + u32 content_ids_pointer = cmd_buff[6]; + u32 content_info_pointer = cmd_buff[8]; + + am_content_count[media_type] = cmd_buff[4]; cmd_buff[1] = RESULT_SUCCESS.raw; - cmd_buff[2] = 0; + LOG_WARNING(Service_AM, "(STUBBED) media_type=%u, title_id=0x%016lx, content_cound=%u, content_ids_pointer=0x%08x, content_info_pointer=0x%08x", + media_type, title_id, am_content_count[media_type], content_ids_pointer, content_info_pointer); +} - LOG_WARNING(Service_AM, "(STUBBED) Requested %u titles from media type %u. Address=0x%08X", num_titles, media_type, addr); +void ListContentInfos(Service::Interface* self) { + u32* cmd_buff = Kernel::GetCommandBuffer(); + + u32 media_type = cmd_buff[2] & 0xFF; + u64 title_id = (static_cast(cmd_buff[4]) << 32) | cmd_buff[3]; + u32 start_index = cmd_buff[5]; + u32 content_info_pointer = cmd_buff[7]; + + am_content_count[media_type] = cmd_buff[1]; + + cmd_buff[1] = RESULT_SUCCESS.raw; + cmd_buff[2] = am_content_count[media_type]; + LOG_WARNING(Service_AM, "(STUBBED) media_type=%u, content_count=%u, title_id=0x%016" PRIx64 ", start_index=0x%08x, content_info_pointer=0x%08X", + media_type, am_content_count[media_type], title_id, start_index, content_info_pointer); +} + +void DeleteContents(Service::Interface* self) { + u32* cmd_buff = Kernel::GetCommandBuffer(); + + u32 media_type = cmd_buff[1] & 0xFF; + u64 title_id = (static_cast(cmd_buff[3]) << 32) | cmd_buff[2]; + u32 content_ids_pointer = cmd_buff[6]; + + am_content_count[media_type] = cmd_buff[4]; + + cmd_buff[1] = RESULT_SUCCESS.raw; + LOG_WARNING(Service_AM, "(STUBBED) media_type=%u, title_id=0x%016" PRIx64 ", content_count=%u, content_ids_pointer=0x%08x", + media_type, title_id, am_content_count[media_type], content_ids_pointer); +} + +void GetTitleList(Service::Interface* self) { + u32* cmd_buff = Kernel::GetCommandBuffer(); + + u32 media_type = cmd_buff[2] & 0xFF; + u32 title_ids_output_pointer = cmd_buff[4]; + + am_titles_list_count[media_type] = cmd_buff[1]; + + cmd_buff[1] = RESULT_SUCCESS.raw; + cmd_buff[2] = am_titles_list_count[media_type]; + LOG_WARNING(Service_AM, "(STUBBED) media_type=%u, titles_list_count=0x%08X, title_ids_output_pointer=0x%08X", + media_type, am_titles_list_count[media_type], title_ids_output_pointer); +} + +void GetTitleInfo(Service::Interface* self) { + u32* cmd_buff = Kernel::GetCommandBuffer(); + + u32 media_type = cmd_buff[1] & 0xFF; + u32 title_id_list_pointer = cmd_buff[4]; + u32 title_list_pointer = cmd_buff[6]; + + am_titles_count[media_type] = cmd_buff[2]; + + cmd_buff[1] = RESULT_SUCCESS.raw; + LOG_WARNING(Service_AM, "(STUBBED) media_type=%u, total_titles=0x%08X, title_id_list_pointer=0x%08X, title_list_pointer=0x%08X", + media_type, am_titles_count[media_type], title_id_list_pointer, title_list_pointer); +} + +void GetDataTitleInfos(Service::Interface* self) { + GetTitleInfo(self); + + LOG_WARNING(Service_AM, "(STUBBED) called"); +} + +void ListDataTitleTicketInfos(Service::Interface* self) { + u32* cmd_buff = Kernel::GetCommandBuffer(); + + u64 title_id = (static_cast(cmd_buff[3]) << 32) | cmd_buff[2]; + u32 start_index = cmd_buff[4]; + u32 ticket_info_pointer = cmd_buff[6]; + + am_ticket_count = cmd_buff[1]; + + cmd_buff[1] = RESULT_SUCCESS.raw; + cmd_buff[2] = am_ticket_count; + LOG_WARNING(Service_AM, "(STUBBED) ticket_count=0x%08X, title_id=0x%016" PRIx64 ", start_index=0x%08X, ticket_info_pointer=0x%08X", + am_ticket_count, title_id, start_index, ticket_info_pointer); } void GetNumContentInfos(Service::Interface* self) { @@ -40,16 +131,47 @@ void GetNumContentInfos(Service::Interface* self) { cmd_buff[1] = RESULT_SUCCESS.raw; cmd_buff[2] = 1; // Number of content infos plus one - LOG_WARNING(Service_AM, "(STUBBED) called"); } +void DeleteTicket(Service::Interface* self) { + u32* cmd_buff = Kernel::GetCommandBuffer(); + + u64 title_id = (static_cast(cmd_buff[2]) << 32) | cmd_buff[1]; + + cmd_buff[1] = RESULT_SUCCESS.raw; + LOG_WARNING(Service_AM, "(STUBBED) called title_id=0x%016" PRIx64 "",title_id); +} + +void GetTicketCount(Service::Interface* self) { + u32* cmd_buff = Kernel::GetCommandBuffer(); + + cmd_buff[1] = RESULT_SUCCESS.raw; + cmd_buff[2] = am_ticket_count; + LOG_WARNING(Service_AM, "(STUBBED) called ticket_count=0x%08x",am_ticket_count); +} + +void GetTicketList(Service::Interface* self) { + u32* cmd_buff = Kernel::GetCommandBuffer(); + + u32 num_of_skip = cmd_buff[2]; + u32 ticket_list_pointer = cmd_buff[4]; + + am_ticket_list_count = cmd_buff[1]; + + cmd_buff[1] = RESULT_SUCCESS.raw; + cmd_buff[2] = am_ticket_list_count; + LOG_WARNING(Service_AM, "(STUBBED) ticket_list_count=0x%08x, num_of_skip=0x%08x, ticket_list_pointer=0x%08x", + am_ticket_list_count, num_of_skip, ticket_list_pointer); +} + void Init() { using namespace Kernel; AddService(new AM_APP_Interface); AddService(new AM_NET_Interface); AddService(new AM_SYS_Interface); + AddService(new AM_U_Interface); } void Shutdown() { diff --git a/src/core/hle/service/am/am.h b/src/core/hle/service/am/am.h index 15e63bc7b..5676cdd5f 100644 --- a/src/core/hle/service/am/am.h +++ b/src/core/hle/service/am/am.h @@ -11,7 +11,7 @@ class Interface; namespace AM { /** - * AM::TitleIDListGetTotal service function + * AM::GetTitleCount service function * Gets the number of installed titles in the requested media type * Inputs: * 0 : Command header (0x00010040) @@ -20,36 +20,140 @@ namespace AM { * 1 : Result, 0 on success, otherwise error code * 2 : The number of titles in the requested media type */ -void TitleIDListGetTotal(Service::Interface* self); +void GetTitleCount(Service::Interface* self); /** - * AM::GetTitleIDList service function + * AM::FindContentInfos service function + * Inputs: + * 1 : MediaType + * 2-3 : u64, Title ID + * 4 : Content count + * 6 : Content IDs pointer + * 8 : Content Infos pointer + * Outputs: + * 1 : Result, 0 on success, otherwise error code + */ +void FindContentInfos(Service::Interface* self); + +/** + * AM::ListContentInfos service function + * Inputs: + * 1 : Content count + * 2 : MediaType + * 3-4 : u64, Title ID + * 5 : Start Index + * 7 : Content Infos pointer + * Outputs: + * 1 : Result, 0 on success, otherwise error code + * 2 : Number of content infos returned + */ +void ListContentInfos(Service::Interface* self); + +/** + * AM::DeleteContents service function + * Inputs: + * 1 : MediaType + * 2-3 : u64, Title ID + * 4 : Content count + * 6 : Content IDs pointer + * Outputs: + * 1 : Result, 0 on success, otherwise error code + */ +void DeleteContents(Service::Interface* self); + +/** + * AM::GetTitleList service function * Loads information about the desired number of titles from the desired media type into an array * Inputs: - * 0 : Command header (0x00020082) - * 1 : The maximum number of titles to load + * 1 : Title count * 2 : Media type to load the titles from - * 3 : Descriptor of the output buffer pointer - * 4 : Address of the output buffer + * 4 : Title IDs output pointer * Outputs: * 1 : Result, 0 on success, otherwise error code * 2 : The number of titles loaded from the requested media type */ -void GetTitleIDList(Service::Interface* self); +void GetTitleList(Service::Interface* self); + +/** + * AM::GetTitleInfo service function + * Inputs: + * 1 : u8 Mediatype + * 2 : Total titles + * 4 : TitleIDList pointer + * 6 : TitleList pointer + * Outputs: + * 1 : Result, 0 on success, otherwise error code + */ +void GetTitleInfo(Service::Interface* self); + +/** + * AM::GetDataTitleInfos service function + * Wrapper for AM::GetTitleInfo + * Inputs: + * 1 : u8 Mediatype + * 2 : Total titles + * 4 : TitleIDList pointer + * 6 : TitleList pointer + * Outputs: + * 1 : Result, 0 on success, otherwise error code + */ +void GetDataTitleInfos(Service::Interface* self); + +/** + * AM::ListDataTitleTicketInfos service function + * Inputs: + * 1 : Ticket count + * 2-3 : u64, Title ID + * 4 : Start Index? + * 5 : (TicketCount * 24) << 8 | 0x4 + * 6 : Ticket Infos pointer + * Outputs: + * 1 : Result, 0 on success, otherwise error code + * 2 : Number of ticket infos returned + */ +void ListDataTitleTicketInfos(Service::Interface* self); /** * AM::GetNumContentInfos service function * Inputs: * 0 : Command header (0x100100C0) - * 1 : Unknown - * 2 : Unknown - * 3 : Unknown + * 1 : MediaType + * 2-3 : u64, Title ID * Outputs: * 1 : Result, 0 on success, otherwise error code * 2 : Number of content infos plus one */ void GetNumContentInfos(Service::Interface* self); +/** + * AM::DeleteTicket service function + * Inputs: + * 1-2 : u64, Title ID + * Outputs: + * 1 : Result, 0 on success, otherwise error code + */ +void DeleteTicket(Service::Interface* self); + +/** + * AM::GetTicketCount service function + * Outputs: + * 1 : Result, 0 on success, otherwise error code + * 2 : Total titles + */ +void GetTicketCount(Service::Interface* self); + +/** + * AM::GetTicketList service function + * Inputs: + * 1 : Number of TicketList + * 2 : Number to skip + * 4 : TicketList pointer + * Outputs: + * 1 : Result, 0 on success, otherwise error code + * 2 : Total TicketList + */ +void GetTicketList(Service::Interface* self); + /// Initialize AM service void Init(); diff --git a/src/core/hle/service/am/am_app.cpp b/src/core/hle/service/am/am_app.cpp index 16c76a1eb..d27b3defd 100644 --- a/src/core/hle/service/am/am_app.cpp +++ b/src/core/hle/service/am/am_app.cpp @@ -9,14 +9,14 @@ namespace Service { namespace AM { const Interface::FunctionInfo FunctionTable[] = { - {0x100100C0, GetNumContentInfos, "GetNumContentInfos"}, - {0x10020104, nullptr, "FindContentInfos"}, - {0x10030142, nullptr, "ListContentInfos"}, - {0x10040102, nullptr, "DeleteContents"}, - {0x10050084, nullptr, "GetDataTitleInfos"}, - {0x10070102, nullptr, "ListDataTitleTicketInfos"}, - {0x100900C0, nullptr, "IsDataTitleInUse"}, - {0x100A0000, nullptr, "IsExternalTitleDatabaseInitialized"}, + {0x100100C0, GetNumContentInfos, "GetNumContentInfos"}, + {0x10020104, FindContentInfos, "FindContentInfos"}, + {0x10030142, ListContentInfos, "ListContentInfos"}, + {0x10040102, DeleteContents, "DeleteContents"}, + {0x10050084, GetDataTitleInfos, "GetDataTitleInfos"}, + {0x10070102, ListDataTitleTicketInfos, "ListDataTitleTicketInfos"}, + {0x100900C0, nullptr, "IsDataTitleInUse"}, + {0x100A0000, nullptr, "IsExternalTitleDatabaseInitialized"}, }; AM_APP_Interface::AM_APP_Interface() { diff --git a/src/core/hle/service/am/am_net.cpp b/src/core/hle/service/am/am_net.cpp index 065e04118..e75755245 100644 --- a/src/core/hle/service/am/am_net.cpp +++ b/src/core/hle/service/am/am_net.cpp @@ -9,16 +9,20 @@ namespace Service { namespace AM { const Interface::FunctionInfo FunctionTable[] = { - {0x00010040, TitleIDListGetTotal, "TitleIDListGetTotal"}, - {0x00020082, GetTitleIDList, "GetTitleIDList"}, - {0x00030084, nullptr, "ListTitles"}, + {0x00010040, GetTitleCount, "GetTitleCount"}, + {0x00020082, GetTitleList, "GetTitleList"}, + {0x00030084, GetTitleInfo, "GetTitleInfo"}, {0x000400C0, nullptr, "DeleteApplicationTitle"}, {0x000500C0, nullptr, "GetTitleProductCode"}, - {0x00080000, nullptr, "TitleIDListGetTotal3"}, - {0x00090082, nullptr, "GetTitleIDList3"}, + {0x000600C0, nullptr, "GetTitleExtDataId"}, + {0x00070080, DeleteTicket, "DeleteTicket"}, + {0x00080000, GetTicketCount, "GetTicketCount"}, + {0x00090082, GetTicketList, "GetTicketList"}, {0x000A0000, nullptr, "GetDeviceID"}, - {0x000D0084, nullptr, "ListTitles2"}, - {0x00140040, nullptr, "FinishInstallToMedia"}, + {0x000D0084, nullptr, "GetPendingTitleInfo"}, + {0x000E00C0, nullptr, "DeletePendingTitle"}, + {0x00140040, nullptr, "FinalizePendingTitles"}, + {0x00150040, nullptr, "DeleteAllPendingTitles"}, {0x00180080, nullptr, "InitializeTitleDatabase"}, {0x00190040, nullptr, "ReloadDBS"}, {0x001A00C0, nullptr, "GetDSiWareExportSize"}, diff --git a/src/core/hle/service/am/am_sys.cpp b/src/core/hle/service/am/am_sys.cpp index e38812297..8bad5e1c9 100644 --- a/src/core/hle/service/am/am_sys.cpp +++ b/src/core/hle/service/am/am_sys.cpp @@ -9,23 +9,27 @@ namespace Service { namespace AM { const Interface::FunctionInfo FunctionTable[] = { - {0x00010040, TitleIDListGetTotal, "TitleIDListGetTotal"}, - {0x00020082, GetTitleIDList, "GetTitleIDList"}, - {0x00030084, nullptr, "ListTitles"}, + {0x00010040, GetTitleCount, "GetTitleCount"}, + {0x00020082, GetTitleList, "GetTitleList"}, + {0x00030084, GetTitleInfo, "GetTitleInfo"}, {0x000400C0, nullptr, "DeleteApplicationTitle"}, {0x000500C0, nullptr, "GetTitleProductCode"}, - {0x00080000, nullptr, "TitleIDListGetTotal3"}, - {0x00090082, nullptr, "GetTitleIDList3"}, + {0x000600C0, nullptr, "GetTitleExtDataId"}, + {0x00070080, DeleteTicket, "DeleteTicket"}, + {0x00080000, GetTicketCount, "GetTicketCount"}, + {0x00090082, GetTicketList, "GetTicketList"}, {0x000A0000, nullptr, "GetDeviceID"}, - {0x000D0084, nullptr, "ListTitles2"}, - {0x00140040, nullptr, "FinishInstallToMedia"}, + {0x000D0084, nullptr, "GetPendingTitleInfo"}, + {0x000E00C0, nullptr, "DeletePendingTitle"}, + {0x00140040, nullptr, "FinalizePendingTitles"}, + {0x00150040, nullptr, "DeleteAllPendingTitles"}, {0x00180080, nullptr, "InitializeTitleDatabase"}, {0x00190040, nullptr, "ReloadDBS"}, {0x001A00C0, nullptr, "GetDSiWareExportSize"}, {0x001B0144, nullptr, "ExportDSiWare"}, {0x001C0084, nullptr, "ImportDSiWare"}, - {0x00230080, nullptr, "TitleIDListGetTotal2"}, - {0x002400C2, nullptr, "GetTitleIDList2"} + {0x00230080, nullptr, "GetPendingTitleCount"}, + {0x002400C2, nullptr, "GetPendingTitleList"} }; AM_SYS_Interface::AM_SYS_Interface() { diff --git a/src/core/hle/service/am/am_u.cpp b/src/core/hle/service/am/am_u.cpp index c0392b754..d583dd9e6 100644 --- a/src/core/hle/service/am/am_u.cpp +++ b/src/core/hle/service/am/am_u.cpp @@ -9,16 +9,20 @@ namespace Service { namespace AM { const Interface::FunctionInfo FunctionTable[] = { - {0x00010040, TitleIDListGetTotal, "TitleIDListGetTotal"}, - {0x00020082, GetTitleIDList, "GetTitleIDList"}, - {0x00030084, nullptr, "ListTitles"}, + {0x00010040, GetTitleCount, "GetTitleCount"}, + {0x00020082, GetTitleList, "GetTitleList"}, + {0x00030084, GetTitleInfo, "GetTitleInfo"}, {0x000400C0, nullptr, "DeleteApplicationTitle"}, {0x000500C0, nullptr, "GetTitleProductCode"}, - {0x00080000, nullptr, "TitleIDListGetTotal3"}, - {0x00090082, nullptr, "GetTitleIDList3"}, + {0x000600C0, nullptr, "GetTitleExtDataId"}, + {0x00070080, DeleteTicket, "DeleteTicket"}, + {0x00080000, GetTicketCount, "GetTicketCount"}, + {0x00090082, GetTicketList, "GetTicketList"}, {0x000A0000, nullptr, "GetDeviceID"}, - {0x000D0084, nullptr, "ListTitles2"}, - {0x00140040, nullptr, "FinishInstallToMedia"}, + {0x000D0084, nullptr, "GetPendingTitleInfo"}, + {0x000E00C0, nullptr, "DeletePendingTitle"}, + {0x00140040, nullptr, "FinalizePendingTitles"}, + {0x00150040, nullptr, "DeleteAllPendingTitles"}, {0x00180080, nullptr, "InitializeTitleDatabase"}, {0x00190040, nullptr, "ReloadDBS"}, {0x001A00C0, nullptr, "GetDSiWareExportSize"}, From d47605b2edcdb02c1f26ca15539c415ce0986490 Mon Sep 17 00:00:00 2001 From: Jannik Vogel Date: Fri, 1 Apr 2016 15:49:16 +0200 Subject: [PATCH 028/104] OpenGL: Keep stencil-test and framebuffer.depth_format in sync --- src/video_core/renderer_opengl/gl_rasterizer.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/src/video_core/renderer_opengl/gl_rasterizer.cpp b/src/video_core/renderer_opengl/gl_rasterizer.cpp index 4fdf93a3e..5a97696bf 100644 --- a/src/video_core/renderer_opengl/gl_rasterizer.cpp +++ b/src/video_core/renderer_opengl/gl_rasterizer.cpp @@ -271,6 +271,7 @@ void RasterizerOpenGL::NotifyPicaRegisterChanged(u32 id) { // Stencil test case PICA_REG_INDEX(output_merger.stencil_test.raw_func): case PICA_REG_INDEX(output_merger.stencil_test.raw_op): + case PICA_REG_INDEX(framebuffer.depth_format): SyncStencilTest(); break; From fa24df73404b1db5e2cff855c2ec88300972be5c Mon Sep 17 00:00:00 2001 From: Jannik Vogel Date: Fri, 1 Apr 2016 15:44:42 +0200 Subject: [PATCH 029/104] Rasterizer: Respect buffer-write allow registers --- src/video_core/pica.h | 12 +++++++++++- src/video_core/rasterizer.cpp | 8 +++++--- 2 files changed, 16 insertions(+), 4 deletions(-) diff --git a/src/video_core/pica.h b/src/video_core/pica.h index 16f9e4006..4552ff81c 100644 --- a/src/video_core/pica.h +++ b/src/video_core/pica.h @@ -578,7 +578,17 @@ struct Regs { } struct { - INSERT_PADDING_WORDS(0x6); + INSERT_PADDING_WORDS(0x3); + + union { + BitField<0, 4, u32> allow_color_write; // 0 = disable, else enable + }; + + INSERT_PADDING_WORDS(0x1); + + union { + BitField<0, 2, u32> allow_depth_stencil_write; // 0 = disable, else enable + }; DepthFormat depth_format; // TODO: Should be a BitField! BitField<16, 3, ColorFormat> color_format; diff --git a/src/video_core/rasterizer.cpp b/src/video_core/rasterizer.cpp index fd02aa652..5b9ed7c64 100644 --- a/src/video_core/rasterizer.cpp +++ b/src/video_core/rasterizer.cpp @@ -809,7 +809,8 @@ static void ProcessTriangleInternal(const Shader::OutputVertex& v0, auto UpdateStencil = [stencil_test, x, y, &old_stencil](Pica::Regs::StencilAction action) { u8 new_stencil = PerformStencilAction(action, old_stencil, stencil_test.reference_value); - SetStencil(x >> 4, y >> 4, (new_stencil & stencil_test.write_mask) | (old_stencil & ~stencil_test.write_mask)); + if (g_state.regs.framebuffer.allow_depth_stencil_write != 0) + SetStencil(x >> 4, y >> 4, (new_stencil & stencil_test.write_mask) | (old_stencil & ~stencil_test.write_mask)); }; if (stencil_action_enable) { @@ -909,7 +910,7 @@ static void ProcessTriangleInternal(const Shader::OutputVertex& v0, } } - if (output_merger.depth_write_enable) + if (regs.framebuffer.allow_depth_stencil_write != 0 && output_merger.depth_write_enable) SetDepth(x >> 4, y >> 4, z); // The stencil depth_pass action is executed even if depth testing is disabled @@ -1133,7 +1134,8 @@ static void ProcessTriangleInternal(const Shader::OutputVertex& v0, output_merger.alpha_enable ? blend_output.a() : dest.a() }; - DrawPixel(x >> 4, y >> 4, result); + if (regs.framebuffer.allow_color_write != 0) + DrawPixel(x >> 4, y >> 4, result); } } } From c6bbc41984d2f48f6002e2953340a6b5b4b1c065 Mon Sep 17 00:00:00 2001 From: Jannik Vogel Date: Thu, 31 Mar 2016 15:36:00 +0200 Subject: [PATCH 030/104] OpenGL: Split buffer-write mask sync into seperate functions --- .../renderer_opengl/gl_rasterizer.cpp | 38 +++++++++++++++---- .../renderer_opengl/gl_rasterizer.h | 9 +++++ 2 files changed, 39 insertions(+), 8 deletions(-) diff --git a/src/video_core/renderer_opengl/gl_rasterizer.cpp b/src/video_core/renderer_opengl/gl_rasterizer.cpp index 5a97696bf..be29ceac1 100644 --- a/src/video_core/renderer_opengl/gl_rasterizer.cpp +++ b/src/video_core/renderer_opengl/gl_rasterizer.cpp @@ -153,6 +153,9 @@ void RasterizerOpenGL::Reset() { SyncLogicOp(); SyncStencilTest(); SyncDepthTest(); + SyncColorWriteMask(); + SyncStencilWriteMask(); + SyncDepthWriteMask(); SetShader(); @@ -268,16 +271,23 @@ void RasterizerOpenGL::NotifyPicaRegisterChanged(u32 id) { state.draw.shader_dirty = true; break; - // Stencil test + // Sync GL stencil test + stencil write mask + // (Pica stencil test function register also contains a stencil write mask) case PICA_REG_INDEX(output_merger.stencil_test.raw_func): + SyncStencilTest(); + SyncStencilWriteMask(); + break; case PICA_REG_INDEX(output_merger.stencil_test.raw_op): case PICA_REG_INDEX(framebuffer.depth_format): SyncStencilTest(); break; - // Depth test + // Sync GL depth test + depth and color write mask + // (Pica depth test function register also contains a depth and color write mask) case PICA_REG_INDEX(output_merger.depth_test_enable): SyncDepthTest(); + SyncDepthWriteMask(); + SyncColorWriteMask(); break; // Logic op @@ -881,13 +891,30 @@ void RasterizerOpenGL::SyncLogicOp() { state.logic_op = PicaToGL::LogicOp(Pica::g_state.regs.output_merger.logic_op); } +void RasterizerOpenGL::SyncColorWriteMask() { + const auto& regs = Pica::g_state.regs; + state.color_mask.red_enabled = regs.output_merger.red_enable; + state.color_mask.green_enabled = regs.output_merger.green_enable; + state.color_mask.blue_enabled = regs.output_merger.blue_enable; + state.color_mask.alpha_enabled = regs.output_merger.alpha_enable; +} + +void RasterizerOpenGL::SyncStencilWriteMask() { + const auto& regs = Pica::g_state.regs; + state.stencil.write_mask = regs.output_merger.stencil_test.write_mask; +} + +void RasterizerOpenGL::SyncDepthWriteMask() { + const auto& regs = Pica::g_state.regs; + state.depth.write_mask = regs.output_merger.depth_write_enable ? GL_TRUE : GL_FALSE; +} + void RasterizerOpenGL::SyncStencilTest() { const auto& regs = Pica::g_state.regs; state.stencil.test_enabled = regs.output_merger.stencil_test.enable && regs.framebuffer.depth_format == Pica::Regs::DepthFormat::D24S8; state.stencil.test_func = PicaToGL::CompareFunc(regs.output_merger.stencil_test.func); state.stencil.test_ref = regs.output_merger.stencil_test.reference_value; state.stencil.test_mask = regs.output_merger.stencil_test.input_mask; - state.stencil.write_mask = regs.output_merger.stencil_test.write_mask; state.stencil.action_stencil_fail = PicaToGL::StencilOp(regs.output_merger.stencil_test.action_stencil_fail); state.stencil.action_depth_fail = PicaToGL::StencilOp(regs.output_merger.stencil_test.action_depth_fail); state.stencil.action_depth_pass = PicaToGL::StencilOp(regs.output_merger.stencil_test.action_depth_pass); @@ -899,11 +926,6 @@ void RasterizerOpenGL::SyncDepthTest() { regs.output_merger.depth_write_enable == 1; state.depth.test_func = regs.output_merger.depth_test_enable == 1 ? PicaToGL::CompareFunc(regs.output_merger.depth_test_func) : GL_ALWAYS; - state.color_mask.red_enabled = regs.output_merger.red_enable; - state.color_mask.green_enabled = regs.output_merger.green_enable; - state.color_mask.blue_enabled = regs.output_merger.blue_enable; - state.color_mask.alpha_enabled = regs.output_merger.alpha_enable; - state.depth.write_mask = regs.output_merger.depth_write_enable ? GL_TRUE : GL_FALSE; } void RasterizerOpenGL::SyncCombinerColor() { diff --git a/src/video_core/renderer_opengl/gl_rasterizer.h b/src/video_core/renderer_opengl/gl_rasterizer.h index fc85aa3ff..390349a0c 100644 --- a/src/video_core/renderer_opengl/gl_rasterizer.h +++ b/src/video_core/renderer_opengl/gl_rasterizer.h @@ -344,6 +344,15 @@ private: /// Syncs the logic op states to match the PICA register void SyncLogicOp(); + /// Syncs the color write mask to match the PICA register state + void SyncColorWriteMask(); + + /// Syncs the stencil write mask to match the PICA register state + void SyncStencilWriteMask(); + + /// Syncs the depth write mask to match the PICA register state + void SyncDepthWriteMask(); + /// Syncs the stencil test states to match the PICA register void SyncStencilTest(); From 35a92b40977f9d2ad4f37c0d93c6cd9bbc57d591 Mon Sep 17 00:00:00 2001 From: Jannik Vogel Date: Fri, 1 Apr 2016 15:50:30 +0200 Subject: [PATCH 031/104] OpenGL: Respect buffer-write allow registers --- .../renderer_opengl/gl_rasterizer.cpp | 34 +++++++++++++++---- 1 file changed, 28 insertions(+), 6 deletions(-) diff --git a/src/video_core/renderer_opengl/gl_rasterizer.cpp b/src/video_core/renderer_opengl/gl_rasterizer.cpp index be29ceac1..6ca9f45e2 100644 --- a/src/video_core/renderer_opengl/gl_rasterizer.cpp +++ b/src/video_core/renderer_opengl/gl_rasterizer.cpp @@ -290,6 +290,19 @@ void RasterizerOpenGL::NotifyPicaRegisterChanged(u32 id) { SyncColorWriteMask(); break; + // Sync GL depth and stencil write mask + // (This is a dedicated combined depth / stencil write-enable register) + case PICA_REG_INDEX(framebuffer.allow_depth_stencil_write): + SyncDepthWriteMask(); + SyncStencilWriteMask(); + break; + + // Sync GL color write mask + // (This is a dedicated color write-enable register) + case PICA_REG_INDEX(framebuffer.allow_color_write): + SyncColorWriteMask(); + break; + // Logic op case PICA_REG_INDEX(output_merger.logic_op): SyncLogicOp(); @@ -893,20 +906,29 @@ void RasterizerOpenGL::SyncLogicOp() { void RasterizerOpenGL::SyncColorWriteMask() { const auto& regs = Pica::g_state.regs; - state.color_mask.red_enabled = regs.output_merger.red_enable; - state.color_mask.green_enabled = regs.output_merger.green_enable; - state.color_mask.blue_enabled = regs.output_merger.blue_enable; - state.color_mask.alpha_enabled = regs.output_merger.alpha_enable; + + auto IsColorWriteEnabled = [&](u32 value) { + return (regs.framebuffer.allow_color_write != 0 && value != 0) ? GL_TRUE : GL_FALSE; + }; + + state.color_mask.red_enabled = IsColorWriteEnabled(regs.output_merger.red_enable); + state.color_mask.green_enabled = IsColorWriteEnabled(regs.output_merger.green_enable); + state.color_mask.blue_enabled = IsColorWriteEnabled(regs.output_merger.blue_enable); + state.color_mask.alpha_enabled = IsColorWriteEnabled(regs.output_merger.alpha_enable); } void RasterizerOpenGL::SyncStencilWriteMask() { const auto& regs = Pica::g_state.regs; - state.stencil.write_mask = regs.output_merger.stencil_test.write_mask; + state.stencil.write_mask = (regs.framebuffer.allow_depth_stencil_write != 0) + ? static_cast(regs.output_merger.stencil_test.write_mask) + : 0; } void RasterizerOpenGL::SyncDepthWriteMask() { const auto& regs = Pica::g_state.regs; - state.depth.write_mask = regs.output_merger.depth_write_enable ? GL_TRUE : GL_FALSE; + state.depth.write_mask = (regs.framebuffer.allow_depth_stencil_write != 0 && regs.output_merger.depth_write_enable) + ? GL_TRUE + : GL_FALSE; } void RasterizerOpenGL::SyncStencilTest() { From 2efc1c93485bb668361447161e55d04257ae3fda Mon Sep 17 00:00:00 2001 From: mailwl Date: Sat, 9 Apr 2016 06:46:03 +0300 Subject: [PATCH 032/104] Fix BLX LR opcode interpretation --- src/core/arm/dyncom/arm_dyncom_interpreter.cpp | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/core/arm/dyncom/arm_dyncom_interpreter.cpp b/src/core/arm/dyncom/arm_dyncom_interpreter.cpp index a6faf42b9..647784208 100644 --- a/src/core/arm/dyncom/arm_dyncom_interpreter.cpp +++ b/src/core/arm/dyncom/arm_dyncom_interpreter.cpp @@ -4080,11 +4080,12 @@ unsigned InterpreterMainLoop(ARMul_State* cpu) { if ((inst_base->cond == ConditionCode::AL) || CondPassed(cpu, inst_base->cond)) { unsigned int inst = inst_cream->inst; if (BITS(inst, 20, 27) == 0x12 && BITS(inst, 4, 7) == 0x3) { + const u32 jump_address = cpu->Reg[inst_cream->val.Rm]; cpu->Reg[14] = (cpu->Reg[15] + cpu->GetInstructionSize()); if(cpu->TFlag) cpu->Reg[14] |= 0x1; - cpu->Reg[15] = cpu->Reg[inst_cream->val.Rm] & 0xfffffffe; - cpu->TFlag = cpu->Reg[inst_cream->val.Rm] & 0x1; + cpu->Reg[15] = jump_address & 0xfffffffe; + cpu->TFlag = jump_address & 0x1; } else { cpu->Reg[14] = (cpu->Reg[15] + cpu->GetInstructionSize()); cpu->TFlag = 0x1; From 0ad050f85d4f5d091b32dacac41b23e0b5b251e2 Mon Sep 17 00:00:00 2001 From: Jannik Vogel Date: Fri, 8 Apr 2016 23:16:51 +0200 Subject: [PATCH 033/104] OpenGL: Implement color combiner Operation::Dot3_RGB --- src/video_core/renderer_opengl/gl_shader_gen.cpp | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/video_core/renderer_opengl/gl_shader_gen.cpp b/src/video_core/renderer_opengl/gl_shader_gen.cpp index ee4b54ab9..646b4eaaf 100644 --- a/src/video_core/renderer_opengl/gl_shader_gen.cpp +++ b/src/video_core/renderer_opengl/gl_shader_gen.cpp @@ -198,6 +198,9 @@ static void AppendColorCombiner(std::string& out, TevStageConfig::Operation oper case Operation::AddThenMultiply: out += "min(" + variable_name + "[0] + " + variable_name + "[1], vec3(1.0)) * " + variable_name + "[2]"; break; + case Operation::Dot3_RGB: + out += "vec3(dot(" + variable_name + "[0] - vec3(0.5), " + variable_name + "[1] - vec3(0.5)) * 4.0)"; + break; default: out += "vec3(0.0)"; LOG_CRITICAL(Render_OpenGL, "Unknown color combiner operation: %u", operation); From ff7c798d8601d59b095e60feea43e98e20054c22 Mon Sep 17 00:00:00 2001 From: Jannik Vogel Date: Sun, 10 Apr 2016 22:07:06 +0200 Subject: [PATCH 034/104] Pica: Remove geometry dumper (PICA_DUMP_GEOMETRY) --- src/video_core/command_processor.cpp | 19 -------------- src/video_core/debug_utils/debug_utils.cpp | 29 ---------------------- src/video_core/debug_utils/debug_utils.h | 21 ---------------- src/video_core/primitive_assembly.cpp | 2 -- 4 files changed, 71 deletions(-) diff --git a/src/video_core/command_processor.cpp b/src/video_core/command_processor.cpp index 028b59348..08ec2907a 100644 --- a/src/video_core/command_processor.cpp +++ b/src/video_core/command_processor.cpp @@ -249,10 +249,6 @@ static void WritePicaReg(u32 id, u32 value, u32 mask) { const u16* index_address_16 = reinterpret_cast(index_address_8); bool index_u16 = index_info.format != 0; -#if PICA_DUMP_GEOMETRY - DebugUtils::GeometryDumper geometry_dumper; - PrimitiveAssembler dumping_primitive_assembler(regs.triangle_topology.Value()); -#endif PrimitiveAssembler& primitive_assembler = g_state.primitive_assembler; if (g_debug_context) { @@ -388,17 +384,6 @@ static void WritePicaReg(u32 id, u32 value, u32 mask) { if (g_debug_context) g_debug_context->OnEvent(DebugContext::Event::VertexLoaded, (void*)&input); -#if PICA_DUMP_GEOMETRY - // NOTE: When dumping geometry, we simply assume that the first input attribute - // corresponds to the position for now. - DebugUtils::GeometryDumper::Vertex dumped_vertex = { - input.attr[0][0].ToFloat32(), input.attr[0][1].ToFloat32(), input.attr[0][2].ToFloat32() - }; - using namespace std::placeholders; - dumping_primitive_assembler.SubmitVertex(dumped_vertex, - std::bind(&DebugUtils::GeometryDumper::AddTriangle, - &geometry_dumper, _1, _2, _3)); -#endif // Send to vertex shader output = Shader::Run(shader_unit, input, attribute_config.GetNumTotalAttributes()); @@ -424,10 +409,6 @@ static void WritePicaReg(u32 id, u32 value, u32 mask) { range.second, range.first); } -#if PICA_DUMP_GEOMETRY - geometry_dumper.Dump(); -#endif - break; } diff --git a/src/video_core/debug_utils/debug_utils.cpp b/src/video_core/debug_utils/debug_utils.cpp index bac6d69c7..693f93597 100644 --- a/src/video_core/debug_utils/debug_utils.cpp +++ b/src/video_core/debug_utils/debug_utils.cpp @@ -85,35 +85,6 @@ std::shared_ptr g_debug_context; // TODO: Get rid of this global namespace DebugUtils { -void GeometryDumper::AddTriangle(Vertex& v0, Vertex& v1, Vertex& v2) { - vertices.push_back(v0); - vertices.push_back(v1); - vertices.push_back(v2); - - int num_vertices = (int)vertices.size(); - faces.push_back({{ num_vertices-3, num_vertices-2, num_vertices-1 }}); -} - -void GeometryDumper::Dump() { - static int index = 0; - std::string filename = std::string("geometry_dump") + std::to_string(++index) + ".obj"; - - std::ofstream file(filename); - - for (const auto& vertex : vertices) { - file << "v " << vertex.pos[0] - << " " << vertex.pos[1] - << " " << vertex.pos[2] << std::endl; - } - - for (const Face& face : faces) { - file << "f " << 1+face.index[0] - << " " << 1+face.index[1] - << " " << 1+face.index[2] << std::endl; - } -} - - void DumpShader(const std::string& filename, const Regs::ShaderConfig& config, const Shader::ShaderSetup& setup, const Regs::VSOutputAttributes* output_attributes) { struct StuffToWrite { diff --git a/src/video_core/debug_utils/debug_utils.h b/src/video_core/debug_utils/debug_utils.h index 795160a32..7df941619 100644 --- a/src/video_core/debug_utils/debug_utils.h +++ b/src/video_core/debug_utils/debug_utils.h @@ -158,30 +158,9 @@ extern std::shared_ptr g_debug_context; // TODO: Get rid of this g namespace DebugUtils { -#define PICA_DUMP_GEOMETRY 0 #define PICA_DUMP_TEXTURES 0 #define PICA_LOG_TEV 0 -// Simple utility class for dumping geometry data to an OBJ file -class GeometryDumper { -public: - struct Vertex { - std::array pos; - }; - - void AddTriangle(Vertex& v0, Vertex& v1, Vertex& v2); - - void Dump(); - -private: - struct Face { - int index[3]; - }; - - std::vector vertices; - std::vector faces; -}; - void DumpShader(const std::string& filename, const Regs::ShaderConfig& config, const Shader::ShaderSetup& setup, const Regs::VSOutputAttributes* output_attributes); diff --git a/src/video_core/primitive_assembly.cpp b/src/video_core/primitive_assembly.cpp index 0061690f1..ff3e2b862 100644 --- a/src/video_core/primitive_assembly.cpp +++ b/src/video_core/primitive_assembly.cpp @@ -68,7 +68,5 @@ void PrimitiveAssembler::Reconfigure(Regs::TriangleTopology topology // explicitly instantiate use cases template struct PrimitiveAssembler; -template -struct PrimitiveAssembler; } // namespace From df0a81621f3c544709ec0f472c3f3c4172b80c92 Mon Sep 17 00:00:00 2001 From: mailwl Date: Tue, 29 Mar 2016 22:29:57 +0300 Subject: [PATCH 035/104] Set Kernel config "Unknown Value" to 0x1 --- src/core/hle/shared_page.cpp | 3 +++ src/core/hle/shared_page.h | 6 ++++-- 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/src/core/hle/shared_page.cpp b/src/core/hle/shared_page.cpp index 50c5bc01b..2a1caeaac 100644 --- a/src/core/hle/shared_page.cpp +++ b/src/core/hle/shared_page.cpp @@ -16,6 +16,9 @@ void Init() { std::memset(&shared_page, 0, sizeof(shared_page)); shared_page.running_hw = 0x1; // product + + // Some games wait until this value becomes 0x1, before asking running_hw + shared_page.unknown_value = 0x1; } } // namespace diff --git a/src/core/hle/shared_page.h b/src/core/hle/shared_page.h index 379bb7b63..35a07c685 100644 --- a/src/core/hle/shared_page.h +++ b/src/core/hle/shared_page.h @@ -39,12 +39,14 @@ struct SharedPageDef { DateTime date_time_0; // 20 DateTime date_time_1; // 40 u8 wifi_macaddr[6]; // 60 - u8 wifi_unknown1; // 66 + u8 wifi_link_level; // 66 u8 wifi_unknown2; // 67 INSERT_PADDING_BYTES(0x80 - 0x68); // 68 float_le sliderstate_3d; // 80 u8 ledstate_3d; // 84 - INSERT_PADDING_BYTES(0xA0 - 0x85); // 85 + INSERT_PADDING_BYTES(1); // 85 + u8 unknown_value; // 86 + INSERT_PADDING_BYTES(0xA0 - 0x87); // 87 u64_le menu_title_id; // A0 u64_le active_menu_title_id; // A8 INSERT_PADDING_BYTES(0x1000 - 0xB0); // B0 From f2c86197042ab3179ce81e4b7e370f3bd7a46b75 Mon Sep 17 00:00:00 2001 From: Jannik Vogel Date: Mon, 11 Apr 2016 14:38:42 +0200 Subject: [PATCH 036/104] CitraQt: Apply config at startup --- src/citra_qt/config.cpp | 1 + src/citra_qt/configure_debug.cpp | 3 +-- src/citra_qt/configure_general.cpp | 8 +------- src/citra_qt/main.cpp | 3 --- src/core/settings.cpp | 14 ++++++++++++++ src/core/settings.h | 2 ++ 6 files changed, 19 insertions(+), 12 deletions(-) diff --git a/src/citra_qt/config.cpp b/src/citra_qt/config.cpp index ecf5c5a75..e363be38a 100644 --- a/src/citra_qt/config.cpp +++ b/src/citra_qt/config.cpp @@ -189,6 +189,7 @@ void Config::SaveValues() { void Config::Reload() { ReadValues(); + Settings::Apply(); } void Config::Save() { diff --git a/src/citra_qt/configure_debug.cpp b/src/citra_qt/configure_debug.cpp index ba66d0833..dc3d7b906 100644 --- a/src/citra_qt/configure_debug.cpp +++ b/src/citra_qt/configure_debug.cpp @@ -5,7 +5,6 @@ #include "citra_qt/configure_debug.h" #include "ui_configure_debug.h" -#include "core/gdbstub/gdbstub.h" #include "core/settings.h" ConfigureDebug::ConfigureDebug(QWidget *parent) : @@ -26,7 +25,7 @@ void ConfigureDebug::setConfiguration() { } void ConfigureDebug::applyConfiguration() { - GDBStub::ToggleServer(ui->toogle_gdbstub->isChecked()); Settings::values.use_gdbstub = ui->toogle_gdbstub->isChecked(); Settings::values.gdbstub_port = ui->gdbport_spinbox->value(); + Settings::Apply(); } diff --git a/src/citra_qt/configure_general.cpp b/src/citra_qt/configure_general.cpp index 350bd794d..a27d0d26c 100644 --- a/src/citra_qt/configure_general.cpp +++ b/src/citra_qt/configure_general.cpp @@ -8,8 +8,6 @@ #include "core/settings.h" -#include "video_core/video_core.h" - ConfigureGeneral::ConfigureGeneral(QWidget *parent) : QWidget(parent), ui(new Ui::ConfigureGeneral) @@ -32,12 +30,8 @@ void ConfigureGeneral::setConfiguration() { void ConfigureGeneral::applyConfiguration() { UISettings::values.gamedir_deepscan = ui->toogle_deepscan->isChecked(); UISettings::values.confirm_before_closing = ui->toogle_check_exit->isChecked(); - Settings::values.region_value = ui->region_combobox->currentIndex(); - - VideoCore::g_hw_renderer_enabled = Settings::values.use_hw_renderer = ui->toogle_hw_renderer->isChecked(); - - VideoCore::g_shader_jit_enabled = Settings::values.use_shader_jit = ui->toogle_shader_jit->isChecked(); + Settings::Apply(); } diff --git a/src/citra_qt/main.cpp b/src/citra_qt/main.cpp index 23eb28259..2ca1e51f6 100644 --- a/src/citra_qt/main.cpp +++ b/src/citra_qt/main.cpp @@ -141,9 +141,6 @@ GMainWindow::GMainWindow() : config(new Config()), emu_thread(nullptr) game_list->LoadInterfaceLayout(); - GDBStub::ToggleServer(Settings::values.use_gdbstub); - GDBStub::SetServerPort(static_cast(Settings::values.gdbstub_port)); - ui.action_Single_Window_Mode->setChecked(UISettings::values.single_window_mode); ToggleWindowMode(); diff --git a/src/core/settings.cpp b/src/core/settings.cpp index 8a14f75aa..1aa26fbd2 100644 --- a/src/core/settings.cpp +++ b/src/core/settings.cpp @@ -4,8 +4,22 @@ #include "settings.h" +#include "core/gdbstub/gdbstub.h" + +#include "video_core/video_core.h" + namespace Settings { Values values = {}; +void Apply() { + + GDBStub::SetServerPort(static_cast(values.gdbstub_port)); + GDBStub::ToggleServer(values.use_gdbstub); + + VideoCore::g_hw_renderer_enabled = values.use_hw_renderer; + VideoCore::g_shader_jit_enabled = values.use_shader_jit; + } + +} // namespace diff --git a/src/core/settings.h b/src/core/settings.h index 97ddcdff9..4933a516d 100644 --- a/src/core/settings.h +++ b/src/core/settings.h @@ -67,4 +67,6 @@ struct Values { u16 gdbstub_port; } extern values; +void Apply(); + } From 997af88ec6ceb5852c03749592c1cd9901d5bad7 Mon Sep 17 00:00:00 2001 From: Jannik Vogel Date: Mon, 11 Apr 2016 15:20:05 +0200 Subject: [PATCH 037/104] Use Settings::Apply in SDL frontend --- src/citra/citra.cpp | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/src/citra/citra.cpp b/src/citra/citra.cpp index 3a1fbe3f7..d6ad13f69 100644 --- a/src/citra/citra.cpp +++ b/src/citra/citra.cpp @@ -93,14 +93,13 @@ int main(int argc, char **argv) { log_filter.ParseFilterString(Settings::values.log_filter); - GDBStub::ToggleServer(use_gdbstub); - GDBStub::SetServerPort(gdb_port); + // Apply the command line arguments + Settings::values.gdbstub_port = gdb_port; + Settings::values.use_gdbstub = use_gdbstub; + Settings::Apply(); std::unique_ptr emu_window = std::make_unique(); - VideoCore::g_hw_renderer_enabled = Settings::values.use_hw_renderer; - VideoCore::g_shader_jit_enabled = Settings::values.use_shader_jit; - System::Init(emu_window.get()); SCOPE_EXIT({ System::Shutdown(); }); From 226c5546e27a66d1278df402abed0c0ac8279f9f Mon Sep 17 00:00:00 2001 From: MerryMage Date: Tue, 12 Apr 2016 14:33:44 +0100 Subject: [PATCH 038/104] FileUtil: Missing #include, Add const to IOFile methods --- src/common/file_util.h | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/src/common/file_util.h b/src/common/file_util.h index a85121aa6..880b8a1e3 100644 --- a/src/common/file_util.h +++ b/src/common/file_util.h @@ -14,6 +14,10 @@ #include "common/common_types.h" +#ifdef _MSC_VER +#include "common/string_util.h" +#endif + // User directory indices for GetUserPath enum { D_USER_IDX, @@ -172,7 +176,7 @@ class IOFile : public NonCopyable { public: IOFile(); - IOFile(std::FILE* file); + explicit IOFile(std::FILE* file); IOFile(const std::string& filename, const char openmode[]); ~IOFile(); @@ -235,10 +239,10 @@ public: return WriteArray(&object, 1); } - bool IsOpen() { return nullptr != m_file; } + bool IsOpen() const { return nullptr != m_file; } // m_good is set to false when a read, write or other function fails - bool IsGood() { return m_good; } + bool IsGood() const { return m_good; } operator void*() { return m_good ? m_file : nullptr; } std::FILE* ReleaseHandle(); @@ -258,9 +262,6 @@ public: std::FILE* m_file; bool m_good; -private: - IOFile(IOFile&); - IOFile& operator=(IOFile& other); }; } // namespace From 3ee4432fe391282ac2a5ab5492ff915b0c2adf28 Mon Sep 17 00:00:00 2001 From: Lioncash Date: Wed, 13 Apr 2016 19:10:54 -0400 Subject: [PATCH 039/104] file_util: Make IOFile data members private --- src/common/file_util.h | 1 + 1 file changed, 1 insertion(+) diff --git a/src/common/file_util.h b/src/common/file_util.h index 880b8a1e3..80e618aca 100644 --- a/src/common/file_util.h +++ b/src/common/file_util.h @@ -260,6 +260,7 @@ public: // clear error state void Clear() { m_good = true; std::clearerr(m_file); } +private: std::FILE* m_file; bool m_good; }; From bf9945b81bf7d41c197ac8b190cab9e1c7176733 Mon Sep 17 00:00:00 2001 From: Lioncash Date: Wed, 13 Apr 2016 19:20:23 -0400 Subject: [PATCH 040/104] file_util: Check for is_trivially_copyable Also applies the template checks to ReadArray as well. --- src/common/file_util.h | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/src/common/file_util.h b/src/common/file_util.h index 80e618aca..dd151575f 100644 --- a/src/common/file_util.h +++ b/src/common/file_util.h @@ -192,6 +192,9 @@ public: template size_t ReadArray(T* data, size_t length) { + static_assert(std::is_standard_layout(), "Given array does not consist of standard layout objects"); + static_assert(std::is_trivially_copyable(), "Given array does not consist of trivially copyable objects"); + if (!IsOpen()) { m_good = false; return -1; @@ -207,9 +210,8 @@ public: template size_t WriteArray(const T* data, size_t length) { - static_assert(std::is_standard_layout::value, "Given array does not consist of standard layout objects"); - // TODO: gcc 4.8 does not support is_trivially_copyable, but we really should check for it here. - //static_assert(std::is_trivially_copyable::value, "Given array does not consist of trivially copyable objects"); + static_assert(std::is_standard_layout(), "Given array does not consist of standard layout objects"); + static_assert(std::is_trivially_copyable(), "Given array does not consist of trivially copyable objects"); if (!IsOpen()) { m_good = false; From a4120ca66cc6c0f3a8056c6ea247c15f63c7feff Mon Sep 17 00:00:00 2001 From: Lioncash Date: Wed, 13 Apr 2016 19:29:16 -0400 Subject: [PATCH 041/104] file_util: Don't expose IOFile internals through the API --- src/common/file_util.cpp | 25 +++------------------- src/common/file_util.h | 9 +------- src/video_core/debug_utils/debug_utils.cpp | 17 ++++++++++++++- 3 files changed, 20 insertions(+), 31 deletions(-) diff --git a/src/common/file_util.cpp b/src/common/file_util.cpp index 9ada09f8a..578c673b9 100644 --- a/src/common/file_util.cpp +++ b/src/common/file_util.cpp @@ -824,13 +824,12 @@ size_t WriteStringToFile(bool text_file, const std::string &str, const char *fil size_t ReadFileToString(bool text_file, const char *filename, std::string &str) { - FileUtil::IOFile file(filename, text_file ? "r" : "rb"); - auto const f = file.GetHandle(); + IOFile file(filename, text_file ? "r" : "rb"); - if (!f) + if (!file) return false; - str.resize(static_cast(GetSize(f))); + str.resize(static_cast(file.GetSize())); return file.ReadArray(&str[0], str.size()); } @@ -880,10 +879,6 @@ IOFile::IOFile() : m_file(nullptr), m_good(true) {} -IOFile::IOFile(std::FILE* file) - : m_file(file), m_good(true) -{} - IOFile::IOFile(const std::string& filename, const char openmode[]) : m_file(nullptr), m_good(true) { @@ -935,20 +930,6 @@ bool IOFile::Close() return m_good; } -std::FILE* IOFile::ReleaseHandle() -{ - std::FILE* const ret = m_file; - m_file = nullptr; - return ret; -} - -void IOFile::SetHandle(std::FILE* file) -{ - Close(); - Clear(); - m_file = file; -} - u64 IOFile::GetSize() { if (IsOpen()) diff --git a/src/common/file_util.h b/src/common/file_util.h index dd151575f..8f72fb4e2 100644 --- a/src/common/file_util.h +++ b/src/common/file_util.h @@ -176,7 +176,6 @@ class IOFile : public NonCopyable { public: IOFile(); - explicit IOFile(std::FILE* file); IOFile(const std::string& filename, const char openmode[]); ~IOFile(); @@ -245,13 +244,7 @@ public: // m_good is set to false when a read, write or other function fails bool IsGood() const { return m_good; } - operator void*() { return m_good ? m_file : nullptr; } - - std::FILE* ReleaseHandle(); - - std::FILE* GetHandle() { return m_file; } - - void SetHandle(std::FILE* file); + explicit operator bool() const { return IsGood(); } bool Seek(s64 off, int origin); u64 Tell(); diff --git a/src/video_core/debug_utils/debug_utils.cpp b/src/video_core/debug_utils/debug_utils.cpp index 693f93597..c8752c003 100644 --- a/src/video_core/debug_utils/debug_utils.cpp +++ b/src/video_core/debug_utils/debug_utils.cpp @@ -586,6 +586,21 @@ TextureInfo TextureInfo::FromPicaRegister(const Regs::TextureConfig& config, return info; } +#ifdef HAVE_PNG +// Adapter functions to libpng to write/flush to File::IOFile instances. +static void WriteIOFile(png_structp png_ptr, png_bytep data, png_size_t length) { + auto* fp = static_cast(png_get_io_ptr(png_ptr)); + if (!fp->WriteBytes(data, length)) + png_error(png_ptr, "Failed to write to output PNG file."); +} + +static void FlushIOFile(png_structp png_ptr) { + auto* fp = static_cast(png_get_io_ptr(png_ptr)); + if (!fp->Flush()) + png_error(png_ptr, "Failed to flush to output PNG file."); +} +#endif + void DumpTexture(const Pica::Regs::TextureConfig& texture_config, u8* data) { #ifndef HAVE_PNG return; @@ -629,7 +644,7 @@ void DumpTexture(const Pica::Regs::TextureConfig& texture_config, u8* data) { goto finalise; } - png_init_io(png_ptr, fp.GetHandle()); + png_set_write_fn(png_ptr, static_cast(&fp), WriteIOFile, FlushIOFile); // Write header (8 bit color depth) png_set_IHDR(png_ptr, info_ptr, texture_config.width, texture_config.height, From 655623ebb2dd6f3f1451e5b8b92dc755868347c8 Mon Sep 17 00:00:00 2001 From: Lioncash Date: Wed, 13 Apr 2016 19:38:01 -0400 Subject: [PATCH 042/104] file_util: const qualify IOFile's Tell and GetSize functions --- src/common/file_util.cpp | 12 ++++++------ src/common/file_util.h | 4 ++-- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/src/common/file_util.cpp b/src/common/file_util.cpp index 578c673b9..7d96d04d9 100644 --- a/src/common/file_util.cpp +++ b/src/common/file_util.cpp @@ -930,12 +930,12 @@ bool IOFile::Close() return m_good; } -u64 IOFile::GetSize() +u64 IOFile::GetSize() const { if (IsOpen()) return FileUtil::GetSize(m_file); - else - return 0; + + return 0; } bool IOFile::Seek(s64 off, int origin) @@ -946,12 +946,12 @@ bool IOFile::Seek(s64 off, int origin) return m_good; } -u64 IOFile::Tell() +u64 IOFile::Tell() const { if (IsOpen()) return ftello(m_file); - else - return -1; + + return -1; } bool IOFile::Flush() diff --git a/src/common/file_util.h b/src/common/file_util.h index 8f72fb4e2..d520130ce 100644 --- a/src/common/file_util.h +++ b/src/common/file_util.h @@ -247,8 +247,8 @@ public: explicit operator bool() const { return IsGood(); } bool Seek(s64 off, int origin); - u64 Tell(); - u64 GetSize(); + u64 Tell() const; + u64 GetSize() const; bool Resize(u64 size); bool Flush(); From 5f51622e9de0483519f47c749888fe7d5b120c79 Mon Sep 17 00:00:00 2001 From: Lioncash Date: Wed, 13 Apr 2016 19:48:03 -0400 Subject: [PATCH 043/104] file_util: In-class initialize data members --- src/common/file_util.cpp | 6 ++---- src/common/file_util.h | 4 ++-- 2 files changed, 4 insertions(+), 6 deletions(-) diff --git a/src/common/file_util.cpp b/src/common/file_util.cpp index 7d96d04d9..53700c865 100644 --- a/src/common/file_util.cpp +++ b/src/common/file_util.cpp @@ -876,11 +876,10 @@ void SplitFilename83(const std::string& filename, std::array& short_nam } IOFile::IOFile() - : m_file(nullptr), m_good(true) -{} +{ +} IOFile::IOFile(const std::string& filename, const char openmode[]) - : m_file(nullptr), m_good(true) { Open(filename, openmode); } @@ -891,7 +890,6 @@ IOFile::~IOFile() } IOFile::IOFile(IOFile&& other) - : m_file(nullptr), m_good(true) { Swap(other); } diff --git a/src/common/file_util.h b/src/common/file_util.h index d520130ce..b54a9fb72 100644 --- a/src/common/file_util.h +++ b/src/common/file_util.h @@ -256,8 +256,8 @@ public: void Clear() { m_good = true; std::clearerr(m_file); } private: - std::FILE* m_file; - bool m_good; + std::FILE* m_file = nullptr; + bool m_good = true; }; } // namespace From e5d417213ce67bc23ac644132828d125a59c2455 Mon Sep 17 00:00:00 2001 From: bunnei Date: Sat, 19 Mar 2016 15:16:16 -0400 Subject: [PATCH 044/104] emitter: Support arbitrary FixupBranch targets. --- src/common/x64/emitter.cpp | 16 ++++++++++++++++ src/common/x64/emitter.h | 1 + 2 files changed, 17 insertions(+) diff --git a/src/common/x64/emitter.cpp b/src/common/x64/emitter.cpp index 1dcf2416c..6c8d10ea7 100644 --- a/src/common/x64/emitter.cpp +++ b/src/common/x64/emitter.cpp @@ -531,6 +531,22 @@ void XEmitter::SetJumpTarget(const FixupBranch& branch) } } +void XEmitter::SetJumpTarget(const FixupBranch& branch, const u8* target) +{ + if (branch.type == 0) + { + s64 distance = (s64)(target - branch.ptr); + ASSERT_MSG(distance >= -0x80 && distance < 0x80, "Jump target too far away, needs force5Bytes = true"); + branch.ptr[-1] = (u8)(s8)distance; + } + else if (branch.type == 1) + { + s64 distance = (s64)(target - branch.ptr); + ASSERT_MSG(distance >= -0x80000000LL && distance < 0x80000000LL, "Jump target too far away, needs indirect register"); + ((s32*)branch.ptr)[-1] = (s32)distance; + } +} + //Single byte opcodes //There is no PUSHAD/POPAD in 64-bit mode. void XEmitter::INT3() {Write8(0xCC);} diff --git a/src/common/x64/emitter.h b/src/common/x64/emitter.h index 7c6548fb5..80dfa96d2 100644 --- a/src/common/x64/emitter.h +++ b/src/common/x64/emitter.h @@ -431,6 +431,7 @@ public: void J_CC(CCFlags conditionCode, const u8* addr, bool force5Bytes = false); void SetJumpTarget(const FixupBranch& branch); + void SetJumpTarget(const FixupBranch& branch, const u8* target); void SETcc(CCFlags flag, OpArg dest); // Note: CMOV brings small if any benefit on current cpus. From 135aec7beab9e484183565eea9d3cab03fe0b879 Mon Sep 17 00:00:00 2001 From: bunnei Date: Thu, 17 Mar 2016 19:51:43 -0400 Subject: [PATCH 045/104] shader_jit_x64: Fix strict memory aliasing issues. --- src/video_core/shader/shader_jit_x64.cpp | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/video_core/shader/shader_jit_x64.cpp b/src/video_core/shader/shader_jit_x64.cpp index dffe051ef..d74b58d84 100644 --- a/src/video_core/shader/shader_jit_x64.cpp +++ b/src/video_core/shader/shader_jit_x64.cpp @@ -741,7 +741,9 @@ void JitCompiler::Compile_Block(unsigned end) { void JitCompiler::Compile_NextInstr(unsigned* offset) { offset_ptr = offset; - Instruction instr = *(Instruction*)&g_state.vs.program_code[(*offset_ptr)++]; + Instruction instr; + std::memcpy(&instr, &g_state.vs.program_code[(*offset_ptr)++], sizeof(Instruction)); + OpCode::Id opcode = instr.opcode.Value(); auto instr_func = instr_table[static_cast(opcode)]; From 4632791a40f8ec5af7e166ff90fd4f8cd69b2745 Mon Sep 17 00:00:00 2001 From: bunnei Date: Thu, 17 Mar 2016 19:45:09 -0400 Subject: [PATCH 046/104] shader_jit_x64: Rewrite flow control to support arbitrary CALL and JMP instructions. --- src/video_core/shader/shader_jit_x64.cpp | 128 +++++++++++++++++------ src/video_core/shader/shader_jit_x64.h | 32 +++++- 2 files changed, 122 insertions(+), 38 deletions(-) diff --git a/src/video_core/shader/shader_jit_x64.cpp b/src/video_core/shader/shader_jit_x64.cpp index d74b58d84..c798992ec 100644 --- a/src/video_core/shader/shader_jit_x64.cpp +++ b/src/video_core/shader/shader_jit_x64.cpp @@ -137,6 +137,15 @@ static const u8 NO_SRC_REG_SWIZZLE = 0x1b; /// Raw constant for the destination register enable mask that indicates all components are enabled static const u8 NO_DEST_REG_MASK = 0xf; +/** + * Get the vertex shader instruction for a given offset in the current shader program + * @param offset Offset in the current shader program of the instruction + * @return Instruction at the specified offset + */ +static Instruction GetVertexShaderInstruction(size_t offset) { + return { g_state.vs.program_code[offset] }; +} + /** * Loads and swizzles a source register into the specified XMM register. * @param instr VS instruction, used for determining how to load the source register @@ -564,10 +573,23 @@ void JitCompiler::Compile_END(Instruction instr) { } void JitCompiler::Compile_CALL(Instruction instr) { - unsigned offset = instr.flow_control.dest_offset; - while (offset < (instr.flow_control.dest_offset + instr.flow_control.num_instructions)) { - Compile_NextInstr(&offset); - } + // Need to advance the return address past the proceeding instructions, this is the number of bytes to skip + constexpr unsigned SKIP = 21; + const uintptr_t start = reinterpret_cast(GetCodePtr()); + + // Push return address - not using CALL because we also want to push the offset of the return before jumping + MOV(64, R(RAX), ImmPtr(GetCodePtr() + SKIP)); + PUSH(RAX); + + // Push offset of the return + PUSH(32, Imm32(instr.flow_control.dest_offset + instr.flow_control.num_instructions)); + + // Jump + FixupBranch b = J(true); + fixup_branches.push_back({ b, instr.flow_control.dest_offset }); + + // Make sure that if the above code changes, SKIP gets updated + ASSERT(reinterpret_cast(GetCodePtr()) - start == SKIP); } void JitCompiler::Compile_CALLC(Instruction instr) { @@ -645,8 +667,8 @@ void JitCompiler::Compile_MAD(Instruction instr) { } void JitCompiler::Compile_IF(Instruction instr) { - ASSERT_MSG(instr.flow_control.dest_offset > *offset_ptr, "Backwards if-statements (%d -> %d) not supported", - *offset_ptr, instr.flow_control.dest_offset.Value()); + ASSERT_MSG(instr.flow_control.dest_offset > last_program_counter, "Backwards if-statements (%d -> %d) not supported", + last_program_counter, instr.flow_control.dest_offset.Value()); // Evaluate the "IF" condition if (instr.opcode.Value() == OpCode::Id::IFU) { @@ -677,8 +699,8 @@ void JitCompiler::Compile_IF(Instruction instr) { } void JitCompiler::Compile_LOOP(Instruction instr) { - ASSERT_MSG(instr.flow_control.dest_offset > *offset_ptr, "Backwards loops (%d -> %d) not supported", - *offset_ptr, instr.flow_control.dest_offset.Value()); + ASSERT_MSG(instr.flow_control.dest_offset > last_program_counter, "Backwards loops (%d -> %d) not supported", + last_program_counter, instr.flow_control.dest_offset.Value()); ASSERT_MSG(!looping, "Nested loops not supported"); looping = true; @@ -706,9 +728,6 @@ void JitCompiler::Compile_LOOP(Instruction instr) { } void JitCompiler::Compile_JMP(Instruction instr) { - ASSERT_MSG(instr.flow_control.dest_offset > *offset_ptr, "Backwards jumps (%d -> %d) not supported", - *offset_ptr, instr.flow_control.dest_offset.Value()); - if (instr.opcode.Value() == OpCode::Id::JMPC) Compile_EvaluateCondition(instr); else if (instr.opcode.Value() == OpCode::Id::JMPU) @@ -718,31 +737,42 @@ void JitCompiler::Compile_JMP(Instruction instr) { bool inverted_condition = (instr.opcode.Value() == OpCode::Id::JMPU) && (instr.flow_control.num_instructions & 1); + FixupBranch b = J_CC(inverted_condition ? CC_Z : CC_NZ, true); - - Compile_Block(instr.flow_control.dest_offset); - - SetJumpTarget(b); + fixup_branches.push_back({ b, instr.flow_control.dest_offset }); } void JitCompiler::Compile_Block(unsigned end) { - // Save current offset pointer - unsigned* prev_offset_ptr = offset_ptr; - unsigned offset = *prev_offset_ptr; - - while (offset < end) - Compile_NextInstr(&offset); - - // Restore current offset pointer - offset_ptr = prev_offset_ptr; - *offset_ptr = offset; + while (program_counter < end) { + Compile_NextInstr(); + } } -void JitCompiler::Compile_NextInstr(unsigned* offset) { - offset_ptr = offset; +void JitCompiler::Compile_Return() { + // Peek return offset on the stack and check if we're at that offset + MOV(64, R(RAX), MDisp(RSP, 0)); + CMP(32, R(RAX), Imm32(program_counter)); - Instruction instr; - std::memcpy(&instr, &g_state.vs.program_code[(*offset_ptr)++], sizeof(Instruction)); + // If so, jump back to before CALL + FixupBranch b = J_CC(CC_NZ, true); + ADD(64, R(RSP), Imm32(8)); // Ignore return offset that's on the stack + POP(RAX); // Pop off return address + JMPptr(R(RAX)); + SetJumpTarget(b); +} + +void JitCompiler::Compile_NextInstr() { + last_program_counter = program_counter; + + auto search = return_offsets.find(program_counter); + if (search != return_offsets.end()) { + Compile_Return(); + } + + ASSERT_MSG(code_ptr[program_counter] == nullptr, "Tried to compile already compiled shader location!"); + code_ptr[program_counter] = GetCodePtr(); + + Instruction instr = GetVertexShaderInstruction(program_counter++); OpCode::Id opcode = instr.opcode.Value(); auto instr_func = instr_table[static_cast(opcode)]; @@ -757,9 +787,24 @@ void JitCompiler::Compile_NextInstr(unsigned* offset) { } } +void JitCompiler::FindReturnOffsets() { + return_offsets.clear(); + + for (size_t offset = 0; offset < g_state.vs.program_code.size(); ++offset) { + Instruction instr = GetVertexShaderInstruction(offset); + + switch (instr.opcode.Value()) { + case OpCode::Id::CALL: + case OpCode::Id::CALLC: + case OpCode::Id::CALLU: + return_offsets.insert(instr.flow_control.dest_offset + instr.flow_control.num_instructions); + break; + } + } +} + CompiledShader* JitCompiler::Compile() { const u8* start = GetCodePtr(); - unsigned offset = g_state.regs.vs.main_offset; // The stack pointer is 8 modulo 16 at the entry of a procedure ABI_PushRegistersAndAdjustStack(ABI_ALL_CALLEE_SAVED, 8); @@ -782,10 +827,27 @@ CompiledShader* JitCompiler::Compile() { MOV(PTRBITS, R(RAX), ImmPtr(&neg)); MOVAPS(NEGBIT, MatR(RAX)); - looping = false; + // Find all `CALL` instructions and identify return locations + FindReturnOffsets(); - while (offset < g_state.vs.program_code.size()) { - Compile_NextInstr(&offset); + // Reset flow control state + last_program_counter = 0; + program_counter = 0; + looping = false; + code_ptr.fill(nullptr); + fixup_branches.clear(); + + // Jump to start of the shader program + if (g_state.regs.vs.main_offset != 0) { + fixup_branches.push_back({ J(true), g_state.regs.vs.main_offset }); + } + + // Compile entire program + Compile_Block(static_cast(g_state.vs.program_code.size())); + + // Set the target for any incomplete branches now that the entire shader program has been emitted + for (const auto& branch : fixup_branches) { + SetJumpTarget(branch.first, code_ptr[branch.second]); } return (CompiledShader*)start; diff --git a/src/video_core/shader/shader_jit_x64.h b/src/video_core/shader/shader_jit_x64.h index 5357c964b..d6f03892d 100644 --- a/src/video_core/shader/shader_jit_x64.h +++ b/src/video_core/shader/shader_jit_x64.h @@ -4,6 +4,9 @@ #pragma once +#include +#include + #include #include "common/x64/emitter.h" @@ -66,8 +69,9 @@ public: void Compile_MAD(Instruction instr); private: + void Compile_Block(unsigned end); - void Compile_NextInstr(unsigned* offset); + void Compile_NextInstr(); void Compile_SwizzleSrc(Instruction instr, unsigned src_num, SourceRegister src_reg, Gen::X64Reg dest); void Compile_DestEnable(Instruction instr, Gen::X64Reg dest); @@ -81,13 +85,31 @@ private: void Compile_EvaluateCondition(Instruction instr); void Compile_UniformCondition(Instruction instr); + /** + * Emits the code to conditionally return from a subroutine envoked by the `CALL` instruction. + */ + void Compile_Return(); + BitSet32 PersistentCallerSavedRegs(); - /// Pointer to the variable that stores the current Pica code offset. Used to handle nested code blocks. - unsigned* offset_ptr = nullptr; + /** + * Analyzes the entire shader program for `CALL` instructions before emitting any code, + * identifying the locations where a return needs to be inserted. + */ + void FindReturnOffsets(); - /// Set to true if currently in a loop, used to check for the existence of nested loops - bool looping = false; + /// Mapping of Pica VS instructions to pointers in the emitted code + std::array code_ptr; + + /// Offsets in code where a return needs to be inserted + std::set return_offsets; + + unsigned last_program_counter; ///< Offset of the most recent instruction decoded + unsigned program_counter; ///< Offset of the next instruction to decode + bool looping = false; ///< True if compiling a loop, used to check for nested loops + + /// Branches that need to be fixed up once the entire shader program is compiled + std::vector> fixup_branches; }; } // Shader From c9d10de644078a29e2310791ee221f3bc916e923 Mon Sep 17 00:00:00 2001 From: bunnei Date: Sun, 20 Mar 2016 00:37:05 -0400 Subject: [PATCH 047/104] shader_jit_x64: Allocate each program independently and persist for emu session. --- src/video_core/shader/shader.cpp | 29 ++++++++---------------- src/video_core/shader/shader_jit_x64.cpp | 17 +++++++------- src/video_core/shader/shader_jit_x64.h | 20 ++++++++-------- 3 files changed, 28 insertions(+), 38 deletions(-) diff --git a/src/video_core/shader/shader.cpp b/src/video_core/shader/shader.cpp index 78d295c76..e17368a4a 100644 --- a/src/video_core/shader/shader.cpp +++ b/src/video_core/shader/shader.cpp @@ -28,15 +28,8 @@ namespace Pica { namespace Shader { #ifdef ARCHITECTURE_x86_64 -static std::unordered_map shader_map; -static JitCompiler jit; -static CompiledShader* jit_shader; - -static void ClearCache() { - shader_map.clear(); - jit.Clear(); - LOG_INFO(HW_GPU, "Shader JIT cache cleared"); -} +static std::unordered_map> shader_map; +static const JitCompiler* jit_shader; #endif // ARCHITECTURE_x86_64 void Setup(UnitState& state) { @@ -48,16 +41,12 @@ void Setup(UnitState& state) { auto iter = shader_map.find(cache_key); if (iter != shader_map.end()) { - jit_shader = iter->second; + jit_shader = iter->second.get(); } else { - // Check if remaining JIT code space is enough for at least one more (massive) shader - if (jit.GetSpaceLeft() < jit_shader_size) { - // If not, clear the cache of all previously compiled shaders - ClearCache(); - } - - jit_shader = jit.Compile(); - shader_map.emplace(cache_key, jit_shader); + auto shader = std::make_unique(); + shader->Compile(); + jit_shader = shader.get(); + shader_map[cache_key] = std::move(shader); } } #endif // ARCHITECTURE_x86_64 @@ -65,7 +54,7 @@ void Setup(UnitState& state) { void Shutdown() { #ifdef ARCHITECTURE_x86_64 - ClearCache(); + shader_map.clear(); #endif // ARCHITECTURE_x86_64 } @@ -109,7 +98,7 @@ OutputVertex Run(UnitState& state, const InputVertex& input, int num_attr #ifdef ARCHITECTURE_x86_64 if (VideoCore::g_shader_jit_enabled) - jit_shader(&state.registers); + jit_shader->Run(&state.registers); else RunInterpreter(state); #else diff --git a/src/video_core/shader/shader_jit_x64.cpp b/src/video_core/shader/shader_jit_x64.cpp index c798992ec..3da4e51fa 100644 --- a/src/video_core/shader/shader_jit_x64.cpp +++ b/src/video_core/shader/shader_jit_x64.cpp @@ -589,7 +589,7 @@ void JitCompiler::Compile_CALL(Instruction instr) { fixup_branches.push_back({ b, instr.flow_control.dest_offset }); // Make sure that if the above code changes, SKIP gets updated - ASSERT(reinterpret_cast(GetCodePtr()) - start == SKIP); + ASSERT(reinterpret_cast(GetCodePtr()) - start == SKIP); } void JitCompiler::Compile_CALLC(Instruction instr) { @@ -803,8 +803,8 @@ void JitCompiler::FindReturnOffsets() { } } -CompiledShader* JitCompiler::Compile() { - const u8* start = GetCodePtr(); +void JitCompiler::Compile() { + program = (CompiledShader*)GetCodePtr(); // The stack pointer is 8 modulo 16 at the entry of a procedure ABI_PushRegistersAndAdjustStack(ABI_ALL_CALLEE_SAVED, 8); @@ -850,15 +850,14 @@ CompiledShader* JitCompiler::Compile() { SetJumpTarget(branch.first, code_ptr[branch.second]); } - return (CompiledShader*)start; + uintptr_t size = reinterpret_cast(GetCodePtr()) - reinterpret_cast(program); + ASSERT_MSG(size <= MAX_SHADER_SIZE, "Compiled a shader that exceeds the allocated size!"); + + LOG_DEBUG(HW_GPU, "Compiled shader size=%d", size); } JitCompiler::JitCompiler() { - AllocCodeSpace(jit_cache_size); -} - -void JitCompiler::Clear() { - ClearCodeSpace(); + AllocCodeSpace(MAX_SHADER_SIZE); } } // namespace Shader diff --git a/src/video_core/shader/shader_jit_x64.h b/src/video_core/shader/shader_jit_x64.h index d6f03892d..19f9bdb56 100644 --- a/src/video_core/shader/shader_jit_x64.h +++ b/src/video_core/shader/shader_jit_x64.h @@ -22,10 +22,8 @@ namespace Pica { namespace Shader { -/// Memory needed to be available to compile the next shader (otherwise, clear the cache) -constexpr size_t jit_shader_size = 1024 * 512; -/// Memory allocated for the JIT code space cache -constexpr size_t jit_cache_size = 1024 * 1024 * 8; +/// Memory allocated for each compiled shader (64Kb) +constexpr size_t MAX_SHADER_SIZE = 1024 * 64; using CompiledShader = void(void* registers); @@ -37,9 +35,11 @@ class JitCompiler : public Gen::XCodeBlock { public: JitCompiler(); - CompiledShader* Compile(); + void Run(void* registers) const { + program(registers); + } - void Clear(); + void Compile(); void Compile_ADD(Instruction instr); void Compile_DP3(Instruction instr); @@ -104,12 +104,14 @@ private: /// Offsets in code where a return needs to be inserted std::set return_offsets; - unsigned last_program_counter; ///< Offset of the most recent instruction decoded - unsigned program_counter; ///< Offset of the next instruction to decode - bool looping = false; ///< True if compiling a loop, used to check for nested loops + unsigned last_program_counter = 0; ///< Offset of the most recent instruction decoded + unsigned program_counter = 0; ///< Offset of the next instruction to decode + bool looping = false; ///< True if compiling a loop, used to check for nested loops /// Branches that need to be fixed up once the entire shader program is compiled std::vector> fixup_branches; + + CompiledShader* program = nullptr; }; } // Shader From a5a74eb121e0586706c3196d450c088280f996a5 Mon Sep 17 00:00:00 2001 From: bunnei Date: Sat, 26 Mar 2016 21:02:15 -0400 Subject: [PATCH 048/104] shader_jit_x64: Specify shader main offset at runtime. --- src/video_core/shader/shader.cpp | 5 ++--- src/video_core/shader/shader_jit_x64.cpp | 4 +--- src/video_core/shader/shader_jit_x64.h | 7 +++---- 3 files changed, 6 insertions(+), 10 deletions(-) diff --git a/src/video_core/shader/shader.cpp b/src/video_core/shader/shader.cpp index e17368a4a..b35413488 100644 --- a/src/video_core/shader/shader.cpp +++ b/src/video_core/shader/shader.cpp @@ -36,8 +36,7 @@ void Setup(UnitState& state) { #ifdef ARCHITECTURE_x86_64 if (VideoCore::g_shader_jit_enabled) { u64 cache_key = (Common::ComputeHash64(&g_state.vs.program_code, sizeof(g_state.vs.program_code)) ^ - Common::ComputeHash64(&g_state.vs.swizzle_data, sizeof(g_state.vs.swizzle_data)) ^ - g_state.regs.vs.main_offset); + Common::ComputeHash64(&g_state.vs.swizzle_data, sizeof(g_state.vs.swizzle_data))); auto iter = shader_map.find(cache_key); if (iter != shader_map.end()) { @@ -98,7 +97,7 @@ OutputVertex Run(UnitState& state, const InputVertex& input, int num_attr #ifdef ARCHITECTURE_x86_64 if (VideoCore::g_shader_jit_enabled) - jit_shader->Run(&state.registers); + jit_shader->Run(&state.registers, g_state.regs.vs.main_offset); else RunInterpreter(state); #else diff --git a/src/video_core/shader/shader_jit_x64.cpp b/src/video_core/shader/shader_jit_x64.cpp index 3da4e51fa..cbdc1e40f 100644 --- a/src/video_core/shader/shader_jit_x64.cpp +++ b/src/video_core/shader/shader_jit_x64.cpp @@ -838,9 +838,7 @@ void JitCompiler::Compile() { fixup_branches.clear(); // Jump to start of the shader program - if (g_state.regs.vs.main_offset != 0) { - fixup_branches.push_back({ J(true), g_state.regs.vs.main_offset }); - } + JMPptr(R(ABI_PARAM2)); // Compile entire program Compile_Block(static_cast(g_state.vs.program_code.size())); diff --git a/src/video_core/shader/shader_jit_x64.h b/src/video_core/shader/shader_jit_x64.h index 19f9bdb56..1501d13bf 100644 --- a/src/video_core/shader/shader_jit_x64.h +++ b/src/video_core/shader/shader_jit_x64.h @@ -25,8 +25,6 @@ namespace Shader { /// Memory allocated for each compiled shader (64Kb) constexpr size_t MAX_SHADER_SIZE = 1024 * 64; -using CompiledShader = void(void* registers); - /** * This class implements the shader JIT compiler. It recompiles a Pica shader program into x86_64 * code that can be executed on the host machine directly. @@ -35,8 +33,8 @@ class JitCompiler : public Gen::XCodeBlock { public: JitCompiler(); - void Run(void* registers) const { - program(registers); + void Run(void* registers, unsigned offset) const { + program(registers, code_ptr[offset]); } void Compile(); @@ -111,6 +109,7 @@ private: /// Branches that need to be fixed up once the entire shader program is compiled std::vector> fixup_branches; + using CompiledShader = void(void* registers, const u8* start_addr); CompiledShader* program = nullptr; }; From ffcf7ecee9f0b2843783e3678edaffbe1dda8ca2 Mon Sep 17 00:00:00 2001 From: bunnei Date: Fri, 1 Apr 2016 23:33:03 -0400 Subject: [PATCH 049/104] shader: Remove unused 'state' argument from 'Setup' function. --- src/video_core/command_processor.cpp | 4 ++-- src/video_core/shader/shader.cpp | 2 +- src/video_core/shader/shader.h | 3 +-- 3 files changed, 4 insertions(+), 5 deletions(-) diff --git a/src/video_core/command_processor.cpp b/src/video_core/command_processor.cpp index 08ec2907a..3abe79c09 100644 --- a/src/video_core/command_processor.cpp +++ b/src/video_core/command_processor.cpp @@ -140,7 +140,7 @@ static void WritePicaReg(u32 id, u32 value, u32 mask) { immediate_attribute_id = 0; Shader::UnitState shader_unit; - Shader::Setup(shader_unit); + Shader::Setup(); if (g_debug_context) g_debug_context->OnEvent(DebugContext::Event::VertexLoaded, static_cast(&immediate_input)); @@ -300,7 +300,7 @@ static void WritePicaReg(u32 id, u32 value, u32 mask) { vertex_cache_ids.fill(-1); Shader::UnitState shader_unit; - Shader::Setup(shader_unit); + Shader::Setup(); for (unsigned int index = 0; index < regs.num_vertices; ++index) { diff --git a/src/video_core/shader/shader.cpp b/src/video_core/shader/shader.cpp index b35413488..5214864ec 100644 --- a/src/video_core/shader/shader.cpp +++ b/src/video_core/shader/shader.cpp @@ -32,7 +32,7 @@ static std::unordered_map> shader_map; static const JitCompiler* jit_shader; #endif // ARCHITECTURE_x86_64 -void Setup(UnitState& state) { +void Setup() { #ifdef ARCHITECTURE_x86_64 if (VideoCore::g_shader_jit_enabled) { u64 cache_key = (Common::ComputeHash64(&g_state.vs.program_code, sizeof(g_state.vs.program_code)) ^ diff --git a/src/video_core/shader/shader.h b/src/video_core/shader/shader.h index 7af8f1fa1..9c5bd97bd 100644 --- a/src/video_core/shader/shader.h +++ b/src/video_core/shader/shader.h @@ -339,9 +339,8 @@ struct UnitState { /** * Performs any shader unit setup that only needs to happen once per shader (as opposed to once per * vertex, which would happen within the `Run` function). - * @param state Shader unit state, must be setup per shader and per shader unit */ -void Setup(UnitState& state); +void Setup(); /// Performs any cleanup when the emulator is shutdown void Shutdown(); From f3afe24594bad11d7e0fd28902d1ce1e6e22e3a2 Mon Sep 17 00:00:00 2001 From: bunnei Date: Sat, 2 Apr 2016 00:02:03 -0400 Subject: [PATCH 050/104] shader_jit_x64: Execute certain asserts at runtime. - This is because we compile the full shader code space, and therefore its common to compile malformed instructions. --- src/video_core/shader/shader_jit_x64.cpp | 18 +++++++++++++----- src/video_core/shader/shader_jit_x64.h | 6 ++++++ 2 files changed, 19 insertions(+), 5 deletions(-) diff --git a/src/video_core/shader/shader_jit_x64.cpp b/src/video_core/shader/shader_jit_x64.cpp index cbdc1e40f..dda9bcef7 100644 --- a/src/video_core/shader/shader_jit_x64.cpp +++ b/src/video_core/shader/shader_jit_x64.cpp @@ -146,6 +146,16 @@ static Instruction GetVertexShaderInstruction(size_t offset) { return { g_state.vs.program_code[offset] }; } +static void LogCritical(const char* msg) { + LOG_CRITICAL(HW_GPU, msg); +} + +void JitCompiler::RuntimeAssert(bool condition, const char* msg) { + if (!condition) { + ABI_CallFunctionP(reinterpret_cast(LogCritical), const_cast(msg)); + } +} + /** * Loads and swizzles a source register into the specified XMM register. * @param instr VS instruction, used for determining how to load the source register @@ -667,8 +677,7 @@ void JitCompiler::Compile_MAD(Instruction instr) { } void JitCompiler::Compile_IF(Instruction instr) { - ASSERT_MSG(instr.flow_control.dest_offset > last_program_counter, "Backwards if-statements (%d -> %d) not supported", - last_program_counter, instr.flow_control.dest_offset.Value()); + RuntimeAssert(instr.flow_control.dest_offset > last_program_counter, "Backwards if-statements not supported"); // Evaluate the "IF" condition if (instr.opcode.Value() == OpCode::Id::IFU) { @@ -699,9 +708,8 @@ void JitCompiler::Compile_IF(Instruction instr) { } void JitCompiler::Compile_LOOP(Instruction instr) { - ASSERT_MSG(instr.flow_control.dest_offset > last_program_counter, "Backwards loops (%d -> %d) not supported", - last_program_counter, instr.flow_control.dest_offset.Value()); - ASSERT_MSG(!looping, "Nested loops not supported"); + RuntimeAssert(instr.flow_control.dest_offset > last_program_counter, "Backwards loops not supported"); + RuntimeAssert(!looping, "Nested loops not supported"); looping = true; diff --git a/src/video_core/shader/shader_jit_x64.h b/src/video_core/shader/shader_jit_x64.h index 1501d13bf..159b902b2 100644 --- a/src/video_core/shader/shader_jit_x64.h +++ b/src/video_core/shader/shader_jit_x64.h @@ -90,6 +90,12 @@ private: BitSet32 PersistentCallerSavedRegs(); + /** + * Assertion evaluated at compile-time, but only triggered if executed at runtime. + * @param msg Message to be logged if the assertion fails. + */ + void RuntimeAssert(bool condition, const char* msg); + /** * Analyzes the entire shader program for `CALL` instructions before emitting any code, * identifying the locations where a return needs to be inserted. From 6e0319eec91341101505b944a652e0b635a51b6e Mon Sep 17 00:00:00 2001 From: bunnei Date: Sat, 9 Apr 2016 11:24:48 -0400 Subject: [PATCH 051/104] shader_jit_x64: Get rid of unnecessary last_program_counter variable. --- src/video_core/shader/shader_jit_x64.cpp | 7 ++----- src/video_core/shader/shader_jit_x64.h | 1 - 2 files changed, 2 insertions(+), 6 deletions(-) diff --git a/src/video_core/shader/shader_jit_x64.cpp b/src/video_core/shader/shader_jit_x64.cpp index dda9bcef7..fae7e8b41 100644 --- a/src/video_core/shader/shader_jit_x64.cpp +++ b/src/video_core/shader/shader_jit_x64.cpp @@ -677,7 +677,7 @@ void JitCompiler::Compile_MAD(Instruction instr) { } void JitCompiler::Compile_IF(Instruction instr) { - RuntimeAssert(instr.flow_control.dest_offset > last_program_counter, "Backwards if-statements not supported"); + RuntimeAssert(instr.flow_control.dest_offset >= program_counter, "Backwards if-statements not supported"); // Evaluate the "IF" condition if (instr.opcode.Value() == OpCode::Id::IFU) { @@ -708,7 +708,7 @@ void JitCompiler::Compile_IF(Instruction instr) { } void JitCompiler::Compile_LOOP(Instruction instr) { - RuntimeAssert(instr.flow_control.dest_offset > last_program_counter, "Backwards loops not supported"); + RuntimeAssert(instr.flow_control.dest_offset >= program_counter, "Backwards loops not supported"); RuntimeAssert(!looping, "Nested loops not supported"); looping = true; @@ -770,8 +770,6 @@ void JitCompiler::Compile_Return() { } void JitCompiler::Compile_NextInstr() { - last_program_counter = program_counter; - auto search = return_offsets.find(program_counter); if (search != return_offsets.end()) { Compile_Return(); @@ -839,7 +837,6 @@ void JitCompiler::Compile() { FindReturnOffsets(); // Reset flow control state - last_program_counter = 0; program_counter = 0; looping = false; code_ptr.fill(nullptr); diff --git a/src/video_core/shader/shader_jit_x64.h b/src/video_core/shader/shader_jit_x64.h index 159b902b2..920a269e2 100644 --- a/src/video_core/shader/shader_jit_x64.h +++ b/src/video_core/shader/shader_jit_x64.h @@ -108,7 +108,6 @@ private: /// Offsets in code where a return needs to be inserted std::set return_offsets; - unsigned last_program_counter = 0; ///< Offset of the most recent instruction decoded unsigned program_counter = 0; ///< Offset of the next instruction to decode bool looping = false; ///< True if compiling a loop, used to check for nested loops From 1d45b57939b10bc1bc13ee33ad74e968850af703 Mon Sep 17 00:00:00 2001 From: bunnei Date: Sat, 9 Apr 2016 11:39:56 -0400 Subject: [PATCH 052/104] shader_jit_x64: Separate initialization and code generation for readability. --- src/video_core/shader/shader_jit_x64.cpp | 17 ++++++++--------- 1 file changed, 8 insertions(+), 9 deletions(-) diff --git a/src/video_core/shader/shader_jit_x64.cpp b/src/video_core/shader/shader_jit_x64.cpp index fae7e8b41..efea55811 100644 --- a/src/video_core/shader/shader_jit_x64.cpp +++ b/src/video_core/shader/shader_jit_x64.cpp @@ -810,7 +810,15 @@ void JitCompiler::FindReturnOffsets() { } void JitCompiler::Compile() { + // Reset flow control state program = (CompiledShader*)GetCodePtr(); + program_counter = 0; + looping = false; + code_ptr.fill(nullptr); + fixup_branches.clear(); + + // Find all `CALL` instructions and identify return locations + FindReturnOffsets(); // The stack pointer is 8 modulo 16 at the entry of a procedure ABI_PushRegistersAndAdjustStack(ABI_ALL_CALLEE_SAVED, 8); @@ -833,15 +841,6 @@ void JitCompiler::Compile() { MOV(PTRBITS, R(RAX), ImmPtr(&neg)); MOVAPS(NEGBIT, MatR(RAX)); - // Find all `CALL` instructions and identify return locations - FindReturnOffsets(); - - // Reset flow control state - program_counter = 0; - looping = false; - code_ptr.fill(nullptr); - fixup_branches.clear(); - // Jump to start of the shader program JMPptr(R(ABI_PARAM2)); From 507e0b59896779d0276456c780ad2aefc3dbc28a Mon Sep 17 00:00:00 2001 From: bunnei Date: Sat, 9 Apr 2016 17:42:48 -0400 Subject: [PATCH 053/104] emitter: Add CALL that can be fixed up. --- src/common/x64/emitter.cpp | 12 ++++++++++++ src/common/x64/emitter.h | 1 + 2 files changed, 13 insertions(+) diff --git a/src/common/x64/emitter.cpp b/src/common/x64/emitter.cpp index 6c8d10ea7..5662f7f86 100644 --- a/src/common/x64/emitter.cpp +++ b/src/common/x64/emitter.cpp @@ -455,6 +455,18 @@ void XEmitter::CALL(const void* fnptr) Write32(u32(distance)); } +FixupBranch XEmitter::CALL() +{ + FixupBranch branch; + branch.type = 1; + branch.ptr = code + 5; + + Write8(0xE8); + Write32(0); + + return branch; +} + FixupBranch XEmitter::J(bool force5bytes) { FixupBranch branch; diff --git a/src/common/x64/emitter.h b/src/common/x64/emitter.h index 80dfa96d2..a33724146 100644 --- a/src/common/x64/emitter.h +++ b/src/common/x64/emitter.h @@ -425,6 +425,7 @@ public: #undef CALL #endif void CALL(const void* fnptr); + FixupBranch CALL(); void CALLptr(OpArg arg); FixupBranch J_CC(CCFlags conditionCode, bool force5bytes = false); From 60749f2cda38f35a80a144f990d45c9b016ed0e2 Mon Sep 17 00:00:00 2001 From: bunnei Date: Sat, 9 Apr 2016 17:46:13 -0400 Subject: [PATCH 054/104] shader_jit_x64: Use CALL/RET instead of JMP for subroutines. --- src/video_core/shader/shader_jit_x64.cpp | 24 +++++++----------------- 1 file changed, 7 insertions(+), 17 deletions(-) diff --git a/src/video_core/shader/shader_jit_x64.cpp b/src/video_core/shader/shader_jit_x64.cpp index efea55811..503fad158 100644 --- a/src/video_core/shader/shader_jit_x64.cpp +++ b/src/video_core/shader/shader_jit_x64.cpp @@ -583,23 +583,15 @@ void JitCompiler::Compile_END(Instruction instr) { } void JitCompiler::Compile_CALL(Instruction instr) { - // Need to advance the return address past the proceeding instructions, this is the number of bytes to skip - constexpr unsigned SKIP = 21; - const uintptr_t start = reinterpret_cast(GetCodePtr()); - - // Push return address - not using CALL because we also want to push the offset of the return before jumping - MOV(64, R(RAX), ImmPtr(GetCodePtr() + SKIP)); - PUSH(RAX); - // Push offset of the return - PUSH(32, Imm32(instr.flow_control.dest_offset + instr.flow_control.num_instructions)); + PUSH(64, Imm32(instr.flow_control.dest_offset + instr.flow_control.num_instructions)); - // Jump - FixupBranch b = J(true); + // Call the subroutine + FixupBranch b = CALL(); fixup_branches.push_back({ b, instr.flow_control.dest_offset }); - // Make sure that if the above code changes, SKIP gets updated - ASSERT(reinterpret_cast(GetCodePtr()) - start == SKIP); + // Skip over the return offset that's on the stack + ADD(64, R(RSP), Imm32(8)); } void JitCompiler::Compile_CALLC(Instruction instr) { @@ -758,14 +750,12 @@ void JitCompiler::Compile_Block(unsigned end) { void JitCompiler::Compile_Return() { // Peek return offset on the stack and check if we're at that offset - MOV(64, R(RAX), MDisp(RSP, 0)); + MOV(64, R(RAX), MDisp(RSP, 8)); CMP(32, R(RAX), Imm32(program_counter)); // If so, jump back to before CALL FixupBranch b = J_CC(CC_NZ, true); - ADD(64, R(RSP), Imm32(8)); // Ignore return offset that's on the stack - POP(RAX); // Pop off return address - JMPptr(R(RAX)); + RET(); SetJumpTarget(b); } From 60aa72e1177c436351c91be291ef869816df79e0 Mon Sep 17 00:00:00 2001 From: bunnei Date: Tue, 12 Apr 2016 23:24:34 -0400 Subject: [PATCH 055/104] shader_jit_x64: Use a sorted vector instead of a set for keeping track of return addresses. --- src/video_core/shader/shader_jit_x64.cpp | 9 ++++++--- src/video_core/shader/shader_jit_x64.h | 4 ++-- 2 files changed, 8 insertions(+), 5 deletions(-) diff --git a/src/video_core/shader/shader_jit_x64.cpp b/src/video_core/shader/shader_jit_x64.cpp index 503fad158..e32a4e720 100644 --- a/src/video_core/shader/shader_jit_x64.cpp +++ b/src/video_core/shader/shader_jit_x64.cpp @@ -2,6 +2,7 @@ // Licensed under GPLv2 or any later version // Refer to the license.txt file included. +#include #include #include "common/x64/abi.h" @@ -760,8 +761,7 @@ void JitCompiler::Compile_Return() { } void JitCompiler::Compile_NextInstr() { - auto search = return_offsets.find(program_counter); - if (search != return_offsets.end()) { + if (std::binary_search(return_offsets.begin(), return_offsets.end(), program_counter)) { Compile_Return(); } @@ -793,10 +793,13 @@ void JitCompiler::FindReturnOffsets() { case OpCode::Id::CALL: case OpCode::Id::CALLC: case OpCode::Id::CALLU: - return_offsets.insert(instr.flow_control.dest_offset + instr.flow_control.num_instructions); + return_offsets.push_back(instr.flow_control.dest_offset + instr.flow_control.num_instructions); break; } } + + // Sort for efficient binary search later + std::sort(return_offsets.begin(), return_offsets.end()); } void JitCompiler::Compile() { diff --git a/src/video_core/shader/shader_jit_x64.h b/src/video_core/shader/shader_jit_x64.h index 920a269e2..aa5060584 100644 --- a/src/video_core/shader/shader_jit_x64.h +++ b/src/video_core/shader/shader_jit_x64.h @@ -4,8 +4,8 @@ #pragma once -#include #include +#include #include @@ -106,7 +106,7 @@ private: std::array code_ptr; /// Offsets in code where a return needs to be inserted - std::set return_offsets; + std::vector return_offsets; unsigned program_counter = 0; ///< Offset of the next instruction to decode bool looping = false; ///< True if compiling a loop, used to check for nested loops From 847fb951e29bb9bfb2735cf6bb1186e0374f3654 Mon Sep 17 00:00:00 2001 From: bunnei Date: Tue, 12 Apr 2016 23:29:25 -0400 Subject: [PATCH 056/104] shader_jit_x64: Free memory that's no longer needed after compilation. --- src/video_core/shader/shader_jit_x64.cpp | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/src/video_core/shader/shader_jit_x64.cpp b/src/video_core/shader/shader_jit_x64.cpp index e32a4e720..773542283 100644 --- a/src/video_core/shader/shader_jit_x64.cpp +++ b/src/video_core/shader/shader_jit_x64.cpp @@ -845,6 +845,12 @@ void JitCompiler::Compile() { SetJumpTarget(branch.first, code_ptr[branch.second]); } + // Free memory that's no longer needed + return_offsets.clear(); + return_offsets.shrink_to_fit(); + fixup_branches.clear(); + fixup_branches.shrink_to_fit(); + uintptr_t size = reinterpret_cast(GetCodePtr()) - reinterpret_cast(program); ASSERT_MSG(size <= MAX_SHADER_SIZE, "Compiled a shader that exceeds the allocated size!"); From 3f623b2561eb829b5c9c3855cb24a612b12f7d6f Mon Sep 17 00:00:00 2001 From: bunnei Date: Tue, 12 Apr 2016 23:34:03 -0400 Subject: [PATCH 057/104] shader_jit_x64.cpp: Rename JitCompiler to JitShader. --- src/video_core/shader/shader.cpp | 6 +- src/video_core/shader/shader_jit_x64.cpp | 174 +++++++++++------------ src/video_core/shader/shader_jit_x64.h | 4 +- 3 files changed, 92 insertions(+), 92 deletions(-) diff --git a/src/video_core/shader/shader.cpp b/src/video_core/shader/shader.cpp index 5214864ec..75301accd 100644 --- a/src/video_core/shader/shader.cpp +++ b/src/video_core/shader/shader.cpp @@ -28,8 +28,8 @@ namespace Pica { namespace Shader { #ifdef ARCHITECTURE_x86_64 -static std::unordered_map> shader_map; -static const JitCompiler* jit_shader; +static std::unordered_map> shader_map; +static const JitShader* jit_shader; #endif // ARCHITECTURE_x86_64 void Setup() { @@ -42,7 +42,7 @@ void Setup() { if (iter != shader_map.end()) { jit_shader = iter->second.get(); } else { - auto shader = std::make_unique(); + auto shader = std::make_unique(); shader->Compile(); jit_shader = shader.get(); shader_map[cache_key] = std::move(shader); diff --git a/src/video_core/shader/shader_jit_x64.cpp b/src/video_core/shader/shader_jit_x64.cpp index 773542283..9369d2fe5 100644 --- a/src/video_core/shader/shader_jit_x64.cpp +++ b/src/video_core/shader/shader_jit_x64.cpp @@ -20,73 +20,73 @@ namespace Shader { using namespace Gen; -typedef void (JitCompiler::*JitFunction)(Instruction instr); +typedef void (JitShader::*JitFunction)(Instruction instr); const JitFunction instr_table[64] = { - &JitCompiler::Compile_ADD, // add - &JitCompiler::Compile_DP3, // dp3 - &JitCompiler::Compile_DP4, // dp4 - &JitCompiler::Compile_DPH, // dph + &JitShader::Compile_ADD, // add + &JitShader::Compile_DP3, // dp3 + &JitShader::Compile_DP4, // dp4 + &JitShader::Compile_DPH, // dph nullptr, // unknown - &JitCompiler::Compile_EX2, // ex2 - &JitCompiler::Compile_LG2, // lg2 + &JitShader::Compile_EX2, // ex2 + &JitShader::Compile_LG2, // lg2 nullptr, // unknown - &JitCompiler::Compile_MUL, // mul - &JitCompiler::Compile_SGE, // sge - &JitCompiler::Compile_SLT, // slt - &JitCompiler::Compile_FLR, // flr - &JitCompiler::Compile_MAX, // max - &JitCompiler::Compile_MIN, // min - &JitCompiler::Compile_RCP, // rcp - &JitCompiler::Compile_RSQ, // rsq + &JitShader::Compile_MUL, // mul + &JitShader::Compile_SGE, // sge + &JitShader::Compile_SLT, // slt + &JitShader::Compile_FLR, // flr + &JitShader::Compile_MAX, // max + &JitShader::Compile_MIN, // min + &JitShader::Compile_RCP, // rcp + &JitShader::Compile_RSQ, // rsq nullptr, // unknown nullptr, // unknown - &JitCompiler::Compile_MOVA, // mova - &JitCompiler::Compile_MOV, // mov + &JitShader::Compile_MOVA, // mova + &JitShader::Compile_MOV, // mov nullptr, // unknown nullptr, // unknown nullptr, // unknown nullptr, // unknown - &JitCompiler::Compile_DPH, // dphi + &JitShader::Compile_DPH, // dphi nullptr, // unknown - &JitCompiler::Compile_SGE, // sgei - &JitCompiler::Compile_SLT, // slti + &JitShader::Compile_SGE, // sgei + &JitShader::Compile_SLT, // slti nullptr, // unknown nullptr, // unknown nullptr, // unknown nullptr, // unknown nullptr, // unknown - &JitCompiler::Compile_NOP, // nop - &JitCompiler::Compile_END, // end + &JitShader::Compile_NOP, // nop + &JitShader::Compile_END, // end nullptr, // break - &JitCompiler::Compile_CALL, // call - &JitCompiler::Compile_CALLC, // callc - &JitCompiler::Compile_CALLU, // callu - &JitCompiler::Compile_IF, // ifu - &JitCompiler::Compile_IF, // ifc - &JitCompiler::Compile_LOOP, // loop + &JitShader::Compile_CALL, // call + &JitShader::Compile_CALLC, // callc + &JitShader::Compile_CALLU, // callu + &JitShader::Compile_IF, // ifu + &JitShader::Compile_IF, // ifc + &JitShader::Compile_LOOP, // loop nullptr, // emit nullptr, // sete - &JitCompiler::Compile_JMP, // jmpc - &JitCompiler::Compile_JMP, // jmpu - &JitCompiler::Compile_CMP, // cmp - &JitCompiler::Compile_CMP, // cmp - &JitCompiler::Compile_MAD, // madi - &JitCompiler::Compile_MAD, // madi - &JitCompiler::Compile_MAD, // madi - &JitCompiler::Compile_MAD, // madi - &JitCompiler::Compile_MAD, // madi - &JitCompiler::Compile_MAD, // madi - &JitCompiler::Compile_MAD, // madi - &JitCompiler::Compile_MAD, // madi - &JitCompiler::Compile_MAD, // mad - &JitCompiler::Compile_MAD, // mad - &JitCompiler::Compile_MAD, // mad - &JitCompiler::Compile_MAD, // mad - &JitCompiler::Compile_MAD, // mad - &JitCompiler::Compile_MAD, // mad - &JitCompiler::Compile_MAD, // mad - &JitCompiler::Compile_MAD, // mad + &JitShader::Compile_JMP, // jmpc + &JitShader::Compile_JMP, // jmpu + &JitShader::Compile_CMP, // cmp + &JitShader::Compile_CMP, // cmp + &JitShader::Compile_MAD, // madi + &JitShader::Compile_MAD, // madi + &JitShader::Compile_MAD, // madi + &JitShader::Compile_MAD, // madi + &JitShader::Compile_MAD, // madi + &JitShader::Compile_MAD, // madi + &JitShader::Compile_MAD, // madi + &JitShader::Compile_MAD, // madi + &JitShader::Compile_MAD, // mad + &JitShader::Compile_MAD, // mad + &JitShader::Compile_MAD, // mad + &JitShader::Compile_MAD, // mad + &JitShader::Compile_MAD, // mad + &JitShader::Compile_MAD, // mad + &JitShader::Compile_MAD, // mad + &JitShader::Compile_MAD, // mad }; // The following is used to alias some commonly used registers. Generally, RAX-RDX and XMM0-XMM3 can @@ -151,7 +151,7 @@ static void LogCritical(const char* msg) { LOG_CRITICAL(HW_GPU, msg); } -void JitCompiler::RuntimeAssert(bool condition, const char* msg) { +void JitShader::RuntimeAssert(bool condition, const char* msg) { if (!condition) { ABI_CallFunctionP(reinterpret_cast(LogCritical), const_cast(msg)); } @@ -164,7 +164,7 @@ void JitCompiler::RuntimeAssert(bool condition, const char* msg) { * @param src_reg SourceRegister object corresponding to the source register to load * @param dest Destination XMM register to store the loaded, swizzled source register */ -void JitCompiler::Compile_SwizzleSrc(Instruction instr, unsigned src_num, SourceRegister src_reg, X64Reg dest) { +void JitShader::Compile_SwizzleSrc(Instruction instr, unsigned src_num, SourceRegister src_reg, X64Reg dest) { X64Reg src_ptr; size_t src_offset; @@ -236,7 +236,7 @@ void JitCompiler::Compile_SwizzleSrc(Instruction instr, unsigned src_num, Source } } -void JitCompiler::Compile_DestEnable(Instruction instr,X64Reg src) { +void JitShader::Compile_DestEnable(Instruction instr,X64Reg src) { DestRegister dest; unsigned operand_desc_id; if (instr.opcode.Value().EffectiveOpCode() == OpCode::Id::MAD || @@ -283,7 +283,7 @@ void JitCompiler::Compile_DestEnable(Instruction instr,X64Reg src) { } } -void JitCompiler::Compile_SanitizedMul(Gen::X64Reg src1, Gen::X64Reg src2, Gen::X64Reg scratch) { +void JitShader::Compile_SanitizedMul(Gen::X64Reg src1, Gen::X64Reg src2, Gen::X64Reg scratch) { MOVAPS(scratch, R(src1)); CMPPS(scratch, R(src2), CMP_ORD); @@ -296,7 +296,7 @@ void JitCompiler::Compile_SanitizedMul(Gen::X64Reg src1, Gen::X64Reg src2, Gen:: ANDPS(src1, R(scratch)); } -void JitCompiler::Compile_EvaluateCondition(Instruction instr) { +void JitShader::Compile_EvaluateCondition(Instruction instr) { // Note: NXOR is used below to check for equality switch (instr.flow_control.op) { case Instruction::FlowControlType::Or: @@ -327,23 +327,23 @@ void JitCompiler::Compile_EvaluateCondition(Instruction instr) { } } -void JitCompiler::Compile_UniformCondition(Instruction instr) { +void JitShader::Compile_UniformCondition(Instruction instr) { int offset = offsetof(decltype(g_state.vs.uniforms), b) + (instr.flow_control.bool_uniform_id * sizeof(bool)); CMP(sizeof(bool) * 8, MDisp(UNIFORMS, offset), Imm8(0)); } -BitSet32 JitCompiler::PersistentCallerSavedRegs() { +BitSet32 JitShader::PersistentCallerSavedRegs() { return persistent_regs & ABI_ALL_CALLER_SAVED; } -void JitCompiler::Compile_ADD(Instruction instr) { +void JitShader::Compile_ADD(Instruction instr) { Compile_SwizzleSrc(instr, 1, instr.common.src1, SRC1); Compile_SwizzleSrc(instr, 2, instr.common.src2, SRC2); ADDPS(SRC1, R(SRC2)); Compile_DestEnable(instr, SRC1); } -void JitCompiler::Compile_DP3(Instruction instr) { +void JitShader::Compile_DP3(Instruction instr) { Compile_SwizzleSrc(instr, 1, instr.common.src1, SRC1); Compile_SwizzleSrc(instr, 2, instr.common.src2, SRC2); @@ -362,7 +362,7 @@ void JitCompiler::Compile_DP3(Instruction instr) { Compile_DestEnable(instr, SRC1); } -void JitCompiler::Compile_DP4(Instruction instr) { +void JitShader::Compile_DP4(Instruction instr) { Compile_SwizzleSrc(instr, 1, instr.common.src1, SRC1); Compile_SwizzleSrc(instr, 2, instr.common.src2, SRC2); @@ -379,7 +379,7 @@ void JitCompiler::Compile_DP4(Instruction instr) { Compile_DestEnable(instr, SRC1); } -void JitCompiler::Compile_DPH(Instruction instr) { +void JitShader::Compile_DPH(Instruction instr) { if (instr.opcode.Value().EffectiveOpCode() == OpCode::Id::DPHI) { Compile_SwizzleSrc(instr, 1, instr.common.src1i, SRC1); Compile_SwizzleSrc(instr, 2, instr.common.src2i, SRC2); @@ -411,7 +411,7 @@ void JitCompiler::Compile_DPH(Instruction instr) { Compile_DestEnable(instr, SRC1); } -void JitCompiler::Compile_EX2(Instruction instr) { +void JitShader::Compile_EX2(Instruction instr) { Compile_SwizzleSrc(instr, 1, instr.common.src1, SRC1); MOVSS(XMM0, R(SRC1)); @@ -424,7 +424,7 @@ void JitCompiler::Compile_EX2(Instruction instr) { Compile_DestEnable(instr, SRC1); } -void JitCompiler::Compile_LG2(Instruction instr) { +void JitShader::Compile_LG2(Instruction instr) { Compile_SwizzleSrc(instr, 1, instr.common.src1, SRC1); MOVSS(XMM0, R(SRC1)); @@ -437,14 +437,14 @@ void JitCompiler::Compile_LG2(Instruction instr) { Compile_DestEnable(instr, SRC1); } -void JitCompiler::Compile_MUL(Instruction instr) { +void JitShader::Compile_MUL(Instruction instr) { Compile_SwizzleSrc(instr, 1, instr.common.src1, SRC1); Compile_SwizzleSrc(instr, 2, instr.common.src2, SRC2); Compile_SanitizedMul(SRC1, SRC2, SCRATCH); Compile_DestEnable(instr, SRC1); } -void JitCompiler::Compile_SGE(Instruction instr) { +void JitShader::Compile_SGE(Instruction instr) { if (instr.opcode.Value().EffectiveOpCode() == OpCode::Id::SGEI) { Compile_SwizzleSrc(instr, 1, instr.common.src1i, SRC1); Compile_SwizzleSrc(instr, 2, instr.common.src2i, SRC2); @@ -459,7 +459,7 @@ void JitCompiler::Compile_SGE(Instruction instr) { Compile_DestEnable(instr, SRC2); } -void JitCompiler::Compile_SLT(Instruction instr) { +void JitShader::Compile_SLT(Instruction instr) { if (instr.opcode.Value().EffectiveOpCode() == OpCode::Id::SLTI) { Compile_SwizzleSrc(instr, 1, instr.common.src1i, SRC1); Compile_SwizzleSrc(instr, 2, instr.common.src2i, SRC2); @@ -474,7 +474,7 @@ void JitCompiler::Compile_SLT(Instruction instr) { Compile_DestEnable(instr, SRC1); } -void JitCompiler::Compile_FLR(Instruction instr) { +void JitShader::Compile_FLR(Instruction instr) { Compile_SwizzleSrc(instr, 1, instr.common.src1, SRC1); if (Common::GetCPUCaps().sse4_1) { @@ -487,7 +487,7 @@ void JitCompiler::Compile_FLR(Instruction instr) { Compile_DestEnable(instr, SRC1); } -void JitCompiler::Compile_MAX(Instruction instr) { +void JitShader::Compile_MAX(Instruction instr) { Compile_SwizzleSrc(instr, 1, instr.common.src1, SRC1); Compile_SwizzleSrc(instr, 2, instr.common.src2, SRC2); // SSE semantics match PICA200 ones: In case of NaN, SRC2 is returned. @@ -495,7 +495,7 @@ void JitCompiler::Compile_MAX(Instruction instr) { Compile_DestEnable(instr, SRC1); } -void JitCompiler::Compile_MIN(Instruction instr) { +void JitShader::Compile_MIN(Instruction instr) { Compile_SwizzleSrc(instr, 1, instr.common.src1, SRC1); Compile_SwizzleSrc(instr, 2, instr.common.src2, SRC2); // SSE semantics match PICA200 ones: In case of NaN, SRC2 is returned. @@ -503,7 +503,7 @@ void JitCompiler::Compile_MIN(Instruction instr) { Compile_DestEnable(instr, SRC1); } -void JitCompiler::Compile_MOVA(Instruction instr) { +void JitShader::Compile_MOVA(Instruction instr) { SwizzlePattern swiz = { g_state.vs.swizzle_data[instr.common.operand_desc_id] }; if (!swiz.DestComponentEnabled(0) && !swiz.DestComponentEnabled(1)) { @@ -548,12 +548,12 @@ void JitCompiler::Compile_MOVA(Instruction instr) { } } -void JitCompiler::Compile_MOV(Instruction instr) { +void JitShader::Compile_MOV(Instruction instr) { Compile_SwizzleSrc(instr, 1, instr.common.src1, SRC1); Compile_DestEnable(instr, SRC1); } -void JitCompiler::Compile_RCP(Instruction instr) { +void JitShader::Compile_RCP(Instruction instr) { Compile_SwizzleSrc(instr, 1, instr.common.src1, SRC1); // TODO(bunnei): RCPSS is a pretty rough approximation, this might cause problems if Pica @@ -564,7 +564,7 @@ void JitCompiler::Compile_RCP(Instruction instr) { Compile_DestEnable(instr, SRC1); } -void JitCompiler::Compile_RSQ(Instruction instr) { +void JitShader::Compile_RSQ(Instruction instr) { Compile_SwizzleSrc(instr, 1, instr.common.src1, SRC1); // TODO(bunnei): RSQRTSS is a pretty rough approximation, this might cause problems if Pica @@ -575,15 +575,15 @@ void JitCompiler::Compile_RSQ(Instruction instr) { Compile_DestEnable(instr, SRC1); } -void JitCompiler::Compile_NOP(Instruction instr) { +void JitShader::Compile_NOP(Instruction instr) { } -void JitCompiler::Compile_END(Instruction instr) { +void JitShader::Compile_END(Instruction instr) { ABI_PopRegistersAndAdjustStack(ABI_ALL_CALLEE_SAVED, 8); RET(); } -void JitCompiler::Compile_CALL(Instruction instr) { +void JitShader::Compile_CALL(Instruction instr) { // Push offset of the return PUSH(64, Imm32(instr.flow_control.dest_offset + instr.flow_control.num_instructions)); @@ -595,21 +595,21 @@ void JitCompiler::Compile_CALL(Instruction instr) { ADD(64, R(RSP), Imm32(8)); } -void JitCompiler::Compile_CALLC(Instruction instr) { +void JitShader::Compile_CALLC(Instruction instr) { Compile_EvaluateCondition(instr); FixupBranch b = J_CC(CC_Z, true); Compile_CALL(instr); SetJumpTarget(b); } -void JitCompiler::Compile_CALLU(Instruction instr) { +void JitShader::Compile_CALLU(Instruction instr) { Compile_UniformCondition(instr); FixupBranch b = J_CC(CC_Z, true); Compile_CALL(instr); SetJumpTarget(b); } -void JitCompiler::Compile_CMP(Instruction instr) { +void JitShader::Compile_CMP(Instruction instr) { using Op = Instruction::Common::CompareOpType::Op; Op op_x = instr.common.compare_op.x; Op op_y = instr.common.compare_op.y; @@ -652,7 +652,7 @@ void JitCompiler::Compile_CMP(Instruction instr) { SHR(64, R(COND1), Imm8(63)); } -void JitCompiler::Compile_MAD(Instruction instr) { +void JitShader::Compile_MAD(Instruction instr) { Compile_SwizzleSrc(instr, 1, instr.mad.src1, SRC1); if (instr.opcode.Value().EffectiveOpCode() == OpCode::Id::MADI) { @@ -669,7 +669,7 @@ void JitCompiler::Compile_MAD(Instruction instr) { Compile_DestEnable(instr, SRC1); } -void JitCompiler::Compile_IF(Instruction instr) { +void JitShader::Compile_IF(Instruction instr) { RuntimeAssert(instr.flow_control.dest_offset >= program_counter, "Backwards if-statements not supported"); // Evaluate the "IF" condition @@ -700,7 +700,7 @@ void JitCompiler::Compile_IF(Instruction instr) { SetJumpTarget(b2); } -void JitCompiler::Compile_LOOP(Instruction instr) { +void JitShader::Compile_LOOP(Instruction instr) { RuntimeAssert(instr.flow_control.dest_offset >= program_counter, "Backwards loops not supported"); RuntimeAssert(!looping, "Nested loops not supported"); @@ -728,7 +728,7 @@ void JitCompiler::Compile_LOOP(Instruction instr) { looping = false; } -void JitCompiler::Compile_JMP(Instruction instr) { +void JitShader::Compile_JMP(Instruction instr) { if (instr.opcode.Value() == OpCode::Id::JMPC) Compile_EvaluateCondition(instr); else if (instr.opcode.Value() == OpCode::Id::JMPU) @@ -743,13 +743,13 @@ void JitCompiler::Compile_JMP(Instruction instr) { fixup_branches.push_back({ b, instr.flow_control.dest_offset }); } -void JitCompiler::Compile_Block(unsigned end) { +void JitShader::Compile_Block(unsigned end) { while (program_counter < end) { Compile_NextInstr(); } } -void JitCompiler::Compile_Return() { +void JitShader::Compile_Return() { // Peek return offset on the stack and check if we're at that offset MOV(64, R(RAX), MDisp(RSP, 8)); CMP(32, R(RAX), Imm32(program_counter)); @@ -760,7 +760,7 @@ void JitCompiler::Compile_Return() { SetJumpTarget(b); } -void JitCompiler::Compile_NextInstr() { +void JitShader::Compile_NextInstr() { if (std::binary_search(return_offsets.begin(), return_offsets.end(), program_counter)) { Compile_Return(); } @@ -783,7 +783,7 @@ void JitCompiler::Compile_NextInstr() { } } -void JitCompiler::FindReturnOffsets() { +void JitShader::FindReturnOffsets() { return_offsets.clear(); for (size_t offset = 0; offset < g_state.vs.program_code.size(); ++offset) { @@ -802,7 +802,7 @@ void JitCompiler::FindReturnOffsets() { std::sort(return_offsets.begin(), return_offsets.end()); } -void JitCompiler::Compile() { +void JitShader::Compile() { // Reset flow control state program = (CompiledShader*)GetCodePtr(); program_counter = 0; @@ -857,7 +857,7 @@ void JitCompiler::Compile() { LOG_DEBUG(HW_GPU, "Compiled shader size=%d", size); } -JitCompiler::JitCompiler() { +JitShader::JitShader() { AllocCodeSpace(MAX_SHADER_SIZE); } diff --git a/src/video_core/shader/shader_jit_x64.h b/src/video_core/shader/shader_jit_x64.h index aa5060584..005fbdbe3 100644 --- a/src/video_core/shader/shader_jit_x64.h +++ b/src/video_core/shader/shader_jit_x64.h @@ -29,9 +29,9 @@ constexpr size_t MAX_SHADER_SIZE = 1024 * 64; * This class implements the shader JIT compiler. It recompiles a Pica shader program into x86_64 * code that can be executed on the host machine directly. */ -class JitCompiler : public Gen::XCodeBlock { +class JitShader : public Gen::XCodeBlock { public: - JitCompiler(); + JitShader(); void Run(void* registers, unsigned offset) const { program(registers, code_ptr[offset]); From d7fe2784cca9c13d1f79f4063691fc4ced1c4759 Mon Sep 17 00:00:00 2001 From: bunnei Date: Tue, 12 Apr 2016 23:35:36 -0400 Subject: [PATCH 058/104] shader_jit_x64: Rename RuntimeAssert to Compile_Assert. --- src/video_core/shader/shader_jit_x64.cpp | 8 ++++---- src/video_core/shader/shader_jit_x64.h | 2 +- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/src/video_core/shader/shader_jit_x64.cpp b/src/video_core/shader/shader_jit_x64.cpp index 9369d2fe5..b47d3beda 100644 --- a/src/video_core/shader/shader_jit_x64.cpp +++ b/src/video_core/shader/shader_jit_x64.cpp @@ -151,7 +151,7 @@ static void LogCritical(const char* msg) { LOG_CRITICAL(HW_GPU, msg); } -void JitShader::RuntimeAssert(bool condition, const char* msg) { +void JitShader::Compile_Assert(bool condition, const char* msg) { if (!condition) { ABI_CallFunctionP(reinterpret_cast(LogCritical), const_cast(msg)); } @@ -670,7 +670,7 @@ void JitShader::Compile_MAD(Instruction instr) { } void JitShader::Compile_IF(Instruction instr) { - RuntimeAssert(instr.flow_control.dest_offset >= program_counter, "Backwards if-statements not supported"); + Compile_Assert(instr.flow_control.dest_offset >= program_counter, "Backwards if-statements not supported"); // Evaluate the "IF" condition if (instr.opcode.Value() == OpCode::Id::IFU) { @@ -701,8 +701,8 @@ void JitShader::Compile_IF(Instruction instr) { } void JitShader::Compile_LOOP(Instruction instr) { - RuntimeAssert(instr.flow_control.dest_offset >= program_counter, "Backwards loops not supported"); - RuntimeAssert(!looping, "Nested loops not supported"); + Compile_Assert(instr.flow_control.dest_offset >= program_counter, "Backwards loops not supported"); + Compile_Assert(!looping, "Nested loops not supported"); looping = true; diff --git a/src/video_core/shader/shader_jit_x64.h b/src/video_core/shader/shader_jit_x64.h index 005fbdbe3..cd6280ade 100644 --- a/src/video_core/shader/shader_jit_x64.h +++ b/src/video_core/shader/shader_jit_x64.h @@ -94,7 +94,7 @@ private: * Assertion evaluated at compile-time, but only triggered if executed at runtime. * @param msg Message to be logged if the assertion fails. */ - void RuntimeAssert(bool condition, const char* msg); + void Compile_Assert(bool condition, const char* msg); /** * Analyzes the entire shader program for `CALL` instructions before emitting any code, From 8c508334455629ed88bc49fd2c355d4af99f0c6a Mon Sep 17 00:00:00 2001 From: MerryMage Date: Thu, 14 Apr 2016 12:53:05 +0100 Subject: [PATCH 059/104] common/thread: Correct code style --- src/common/thread.h | 40 +++++++++++++++++++--------------------- 1 file changed, 19 insertions(+), 21 deletions(-) diff --git a/src/common/thread.h b/src/common/thread.h index 8255ee6d3..9bd0e8e7f 100644 --- a/src/common/thread.h +++ b/src/common/thread.h @@ -30,8 +30,7 @@ # endif #endif -namespace Common -{ +namespace Common { int CurrentThreadId(); @@ -43,55 +42,55 @@ public: Event() : is_set(false) {} void Set() { - std::lock_guard lk(m_mutex); + std::lock_guard lk(mutex); if (!is_set) { is_set = true; - m_condvar.notify_one(); + condvar.notify_one(); } } void Wait() { - std::unique_lock lk(m_mutex); - m_condvar.wait(lk, [&]{ return is_set; }); + std::unique_lock lk(mutex); + condvar.wait(lk, [&]{ return is_set; }); is_set = false; } void Reset() { - std::unique_lock lk(m_mutex); + std::unique_lock lk(mutex); // no other action required, since wait loops on the predicate and any lingering signal will get cleared on the first iteration is_set = false; } private: bool is_set; - std::condition_variable m_condvar; - std::mutex m_mutex; + std::condition_variable condvar; + std::mutex mutex; }; class Barrier { public: - Barrier(size_t count) : m_count(count), m_waiting(0) {} + explicit Barrier(size_t count_) : count(count_), waiting(0) {} /// Blocks until all "count" threads have called Sync() void Sync() { - std::unique_lock lk(m_mutex); + std::unique_lock lk(mutex); // TODO: broken when next round of Sync()s // is entered before all waiting threads return from the notify_all - if (++m_waiting == m_count) { - m_waiting = 0; - m_condvar.notify_all(); + if (++waiting == count) { + waiting = 0; + condvar.notify_all(); } else { - m_condvar.wait(lk, [&]{ return m_waiting == 0; }); + condvar.wait(lk, [&]{ return waiting == 0; }); } } private: - std::condition_variable m_condvar; - std::mutex m_mutex; - const size_t m_count; - size_t m_waiting; + std::condition_variable condvar; + std::mutex mutex; + const size_t count; + size_t waiting; }; void SleepCurrentThread(int ms); @@ -100,8 +99,7 @@ void SwitchCurrentThread(); // On Linux, this is equal to sleep 1ms // Use this function during a spin-wait to make the current thread // relax while another thread is working. This may be more efficient // than using events because event functions use kernel calls. -inline void YieldCPU() -{ +inline void YieldCPU() { std::this_thread::yield(); } From 3c710f9b104acf218bce1054bd325f9a2515f8ca Mon Sep 17 00:00:00 2001 From: MerryMage Date: Thu, 14 Apr 2016 12:54:06 +0100 Subject: [PATCH 060/104] Thread: Make Barrier reusable --- src/common/thread.h | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/common/thread.h b/src/common/thread.h index 9bd0e8e7f..bbfa8befa 100644 --- a/src/common/thread.h +++ b/src/common/thread.h @@ -69,20 +69,19 @@ private: class Barrier { public: - explicit Barrier(size_t count_) : count(count_), waiting(0) {} + explicit Barrier(size_t count_) : count(count_), waiting(0), generation(0) {} /// Blocks until all "count" threads have called Sync() void Sync() { std::unique_lock lk(mutex); - - // TODO: broken when next round of Sync()s - // is entered before all waiting threads return from the notify_all + const size_t current_generation = generation; if (++waiting == count) { + generation++; waiting = 0; condvar.notify_all(); } else { - condvar.wait(lk, [&]{ return waiting == 0; }); + condvar.wait(lk, [this, current_generation]{ return current_generation != generation; }); } } @@ -91,6 +90,7 @@ private: std::mutex mutex; const size_t count; size_t waiting; + size_t generation; // Incremented once each time the barrier is used }; void SleepCurrentThread(int ms); From 727d508e02415101d1f49a75858e35a49220e81b Mon Sep 17 00:00:00 2001 From: wwylele Date: Thu, 14 Apr 2016 16:53:51 +0300 Subject: [PATCH 061/104] ncch:only decompress .code section --- src/core/loader/ncch.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/core/loader/ncch.cpp b/src/core/loader/ncch.cpp index e63cab33f..a4b47ef8c 100644 --- a/src/core/loader/ncch.cpp +++ b/src/core/loader/ncch.cpp @@ -174,7 +174,7 @@ ResultStatus AppLoader_NCCH::LoadSectionExeFS(const char* name, std::vector& return ResultStatus::Error; LOG_DEBUG(Loader, "%d sections:", kMaxSections); - // Iterate through the ExeFs archive until we find the .code file... + // Iterate through the ExeFs archive until we find a section with the specified name... for (unsigned section_number = 0; section_number < kMaxSections; section_number++) { const auto& section = exefs_header.section[section_number]; @@ -186,7 +186,7 @@ ResultStatus AppLoader_NCCH::LoadSectionExeFS(const char* name, std::vector& s64 section_offset = (section.offset + exefs_offset + sizeof(ExeFs_Header) + ncch_offset); file.Seek(section_offset, SEEK_SET); - if (is_compressed) { + if (strcmp(section.name, ".code") == 0 && is_compressed) { // Section is compressed, read compressed .code section... std::unique_ptr temp_buffer; try { From 4501a9eb5079ab89b5bb06ec0affd0ef9f72e96f Mon Sep 17 00:00:00 2001 From: Lioncash Date: Thu, 14 Apr 2016 22:04:46 -0400 Subject: [PATCH 062/104] debug_utils: use std::make_unique for initializing PicaTrace --- src/video_core/debug_utils/debug_utils.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/video_core/debug_utils/debug_utils.cpp b/src/video_core/debug_utils/debug_utils.cpp index c8752c003..c3a9c9598 100644 --- a/src/video_core/debug_utils/debug_utils.cpp +++ b/src/video_core/debug_utils/debug_utils.cpp @@ -286,7 +286,7 @@ void StartPicaTracing() } std::lock_guard lock(pica_trace_mutex); - pica_trace = std::unique_ptr(new PicaTrace); + pica_trace = std::make_unique(); is_pica_tracing = true; } From 8d5a6110f7e253a525b3d7cd62dafeaf67a9c8f3 Mon Sep 17 00:00:00 2001 From: JamePeng Date: Fri, 15 Apr 2016 12:36:07 +0800 Subject: [PATCH 063/104] Y2R: num_tiles should be allowed when its value is 128 (#1669) --- src/core/hw/y2r.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/core/hw/y2r.cpp b/src/core/hw/y2r.cpp index 48c45564f..083391e83 100644 --- a/src/core/hw/y2r.cpp +++ b/src/core/hw/y2r.cpp @@ -261,7 +261,7 @@ void PerformConversion(ConversionConfiguration& cvt) { ASSERT(cvt.block_alignment != BlockAlignment::Block8x8 || cvt.input_lines % 8 == 0); // Tiles per row size_t num_tiles = cvt.input_line_width / 8; - ASSERT(num_tiles < MAX_TILES); + ASSERT(num_tiles <= MAX_TILES); // Buffer used as a CDMA source/target. std::unique_ptr data_buffer(new u8[cvt.input_line_width * 8 * 4]); From fd771d7a87ba1cd321b68baf48934cdf1d9d9e69 Mon Sep 17 00:00:00 2001 From: MerryMage Date: Fri, 15 Apr 2016 11:34:08 +0100 Subject: [PATCH 064/104] Configure Dialog: Remove minimumSize property --- src/citra_qt/configure.ui | 12 ------------ 1 file changed, 12 deletions(-) diff --git a/src/citra_qt/configure.ui b/src/citra_qt/configure.ui index 3c1f2ebba..6ae056ff9 100644 --- a/src/citra_qt/configure.ui +++ b/src/citra_qt/configure.ui @@ -10,24 +10,12 @@ 501 - - - 370 - 219 - - Citra Configuration - - - 371 - 221 - - 0 From 43b6cbd762aa9158e44484f728aa828f22b7811a Mon Sep 17 00:00:00 2001 From: wwylele Date: Fri, 15 Apr 2016 11:50:50 +0300 Subject: [PATCH 065/104] fix driver root identification on Windows --- src/common/file_util.cpp | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/src/common/file_util.cpp b/src/common/file_util.cpp index 9ada09f8a..687b7ae5a 100644 --- a/src/common/file_util.cpp +++ b/src/common/file_util.cpp @@ -69,9 +69,10 @@ static void StripTailDirSlashes(std::string &fname) { if (fname.length() > 1) { - size_t i = fname.length() - 1; - while (fname[i] == DIR_SEP_CHR) - fname[i--] = '\0'; + size_t i = fname.length(); + while (i > 0 && fname[i - 1] == DIR_SEP_CHR) + --i; + fname.resize(i); } return; } @@ -85,6 +86,10 @@ bool Exists(const std::string &filename) StripTailDirSlashes(copy); #ifdef _WIN32 + // Windows needs a slash to identify a driver root + if (copy.size() != 0 && copy.back() == ':') + copy += DIR_SEP_CHR; + int result = _wstat64(Common::UTF8ToUTF16W(copy).c_str(), &file_info); #else int result = stat64(copy.c_str(), &file_info); @@ -102,6 +107,10 @@ bool IsDirectory(const std::string &filename) StripTailDirSlashes(copy); #ifdef _WIN32 + // Windows needs a slash to identify a driver root + if (copy.size() != 0 && copy.back() == ':') + copy += DIR_SEP_CHR; + int result = _wstat64(Common::UTF8ToUTF16W(copy).c_str(), &file_info); #else int result = stat64(copy.c_str(), &file_info); From 1cc183703af806858f982a4ac2872457790e248f Mon Sep 17 00:00:00 2001 From: Lioncash Date: Sat, 16 Apr 2016 00:06:19 -0400 Subject: [PATCH 066/104] core: Clean out some unnecessary header includes --- src/core/hle/config_mem.cpp | 7 ------- src/core/hle/hle.cpp | 2 -- src/core/loader/3dsx.cpp | 6 +----- 3 files changed, 1 insertion(+), 14 deletions(-) diff --git a/src/core/hle/config_mem.cpp b/src/core/hle/config_mem.cpp index b1a72dc0c..ccd73cfcb 100644 --- a/src/core/hle/config_mem.cpp +++ b/src/core/hle/config_mem.cpp @@ -3,13 +3,6 @@ // Refer to the license.txt file included. #include - -#include "common/assert.h" -#include "common/common_types.h" -#include "common/common_funcs.h" - -#include "core/core.h" -#include "core/memory.h" #include "core/hle/config_mem.h" //////////////////////////////////////////////////////////////////////////////////////////////////// diff --git a/src/core/hle/hle.cpp b/src/core/hle/hle.cpp index 331b1b22a..e545de3b5 100644 --- a/src/core/hle/hle.cpp +++ b/src/core/hle/hle.cpp @@ -8,8 +8,6 @@ #include "core/arm/arm_interface.h" #include "core/core.h" #include "core/hle/hle.h" -#include "core/hle/config_mem.h" -#include "core/hle/shared_page.h" #include "core/hle/service/service.h" //////////////////////////////////////////////////////////////////////////////////////////////////// diff --git a/src/core/loader/3dsx.cpp b/src/core/loader/3dsx.cpp index 8eed6a50a..5fb3b9e2b 100644 --- a/src/core/loader/3dsx.cpp +++ b/src/core/loader/3dsx.cpp @@ -10,13 +10,9 @@ #include "core/file_sys/archive_romfs.h" #include "core/hle/kernel/process.h" #include "core/hle/kernel/resource_limit.h" -#include "core/hle/service/fs/archive.h" -#include "core/loader/elf.h" -#include "core/loader/ncch.h" +#include "core/loader/3dsx.h" #include "core/memory.h" -#include "3dsx.h" - namespace Loader { /* From e2b63a2dd7ed1b2714daf5ff94f7603111ce78c6 Mon Sep 17 00:00:00 2001 From: Jannik Vogel Date: Sat, 2 Apr 2016 03:26:10 +0200 Subject: [PATCH 067/104] Rasterizer: Allow all blend factors for alpha blend-func --- src/video_core/rasterizer.cpp | 105 +++++++++++++++------------------- 1 file changed, 45 insertions(+), 60 deletions(-) diff --git a/src/video_core/rasterizer.cpp b/src/video_core/rasterizer.cpp index 5b9ed7c64..0434ad05a 100644 --- a/src/video_core/rasterizer.cpp +++ b/src/video_core/rasterizer.cpp @@ -923,60 +923,16 @@ static void ProcessTriangleInternal(const Shader::OutputVertex& v0, if (output_merger.alphablend_enable) { auto params = output_merger.alpha_blending; - auto LookupFactorRGB = [&](Regs::BlendFactor factor) -> Math::Vec3 { - switch (factor) { - case Regs::BlendFactor::Zero : - return Math::Vec3(0, 0, 0); + auto LookupFactor = [&](unsigned channel, Regs::BlendFactor factor) -> u8 { + DEBUG_ASSERT(channel < 4); - case Regs::BlendFactor::One : - return Math::Vec3(255, 255, 255); + const Math::Vec4 blend_const = { + static_cast(output_merger.blend_const.r), + static_cast(output_merger.blend_const.g), + static_cast(output_merger.blend_const.b), + static_cast(output_merger.blend_const.a) + }; - case Regs::BlendFactor::SourceColor: - return combiner_output.rgb(); - - case Regs::BlendFactor::OneMinusSourceColor: - return Math::Vec3(255 - combiner_output.r(), 255 - combiner_output.g(), 255 - combiner_output.b()); - - case Regs::BlendFactor::DestColor: - return dest.rgb(); - - case Regs::BlendFactor::OneMinusDestColor: - return Math::Vec3(255 - dest.r(), 255 - dest.g(), 255 - dest.b()); - - case Regs::BlendFactor::SourceAlpha: - return Math::Vec3(combiner_output.a(), combiner_output.a(), combiner_output.a()); - - case Regs::BlendFactor::OneMinusSourceAlpha: - return Math::Vec3(255 - combiner_output.a(), 255 - combiner_output.a(), 255 - combiner_output.a()); - - case Regs::BlendFactor::DestAlpha: - return Math::Vec3(dest.a(), dest.a(), dest.a()); - - case Regs::BlendFactor::OneMinusDestAlpha: - return Math::Vec3(255 - dest.a(), 255 - dest.a(), 255 - dest.a()); - - case Regs::BlendFactor::ConstantColor: - return Math::Vec3(output_merger.blend_const.r, output_merger.blend_const.g, output_merger.blend_const.b); - - case Regs::BlendFactor::OneMinusConstantColor: - return Math::Vec3(255 - output_merger.blend_const.r, 255 - output_merger.blend_const.g, 255 - output_merger.blend_const.b); - - case Regs::BlendFactor::ConstantAlpha: - return Math::Vec3(output_merger.blend_const.a, output_merger.blend_const.a, output_merger.blend_const.a); - - case Regs::BlendFactor::OneMinusConstantAlpha: - return Math::Vec3(255 - output_merger.blend_const.a, 255 - output_merger.blend_const.a, 255 - output_merger.blend_const.a); - - default: - LOG_CRITICAL(HW_GPU, "Unknown color blend factor %x", factor); - UNIMPLEMENTED(); - break; - } - - return {}; - }; - - auto LookupFactorA = [&](Regs::BlendFactor factor) -> u8 { switch (factor) { case Regs::BlendFactor::Zero: return 0; @@ -984,6 +940,18 @@ static void ProcessTriangleInternal(const Shader::OutputVertex& v0, case Regs::BlendFactor::One: return 255; + case Regs::BlendFactor::SourceColor: + return combiner_output[channel]; + + case Regs::BlendFactor::OneMinusSourceColor: + return 255 - combiner_output[channel]; + + case Regs::BlendFactor::DestColor: + return dest[channel]; + + case Regs::BlendFactor::OneMinusDestColor: + return 255 - dest[channel]; + case Regs::BlendFactor::SourceAlpha: return combiner_output.a(); @@ -996,19 +964,31 @@ static void ProcessTriangleInternal(const Shader::OutputVertex& v0, case Regs::BlendFactor::OneMinusDestAlpha: return 255 - dest.a(); + case Regs::BlendFactor::ConstantColor: + return blend_const[channel]; + + case Regs::BlendFactor::OneMinusConstantColor: + return 255 - blend_const[channel]; + case Regs::BlendFactor::ConstantAlpha: - return output_merger.blend_const.a; + return blend_const.a(); case Regs::BlendFactor::OneMinusConstantAlpha: - return 255 - output_merger.blend_const.a; + return 255 - blend_const.a(); + + case Regs::BlendFactor::SourceAlphaSaturate: + // Returns 1.0 for the alpha channel + if (channel == 3) + return 255; + return std::min(combiner_output.a(), static_cast(255 - dest.a())); default: - LOG_CRITICAL(HW_GPU, "Unknown alpha blend factor %x", factor); + LOG_CRITICAL(HW_GPU, "Unknown blend factor %x", factor); UNIMPLEMENTED(); break; } - return {}; + return combiner_output[channel]; }; static auto EvaluateBlendEquation = [](const Math::Vec4& src, const Math::Vec4& srcfactor, @@ -1060,10 +1040,15 @@ static void ProcessTriangleInternal(const Shader::OutputVertex& v0, MathUtil::Clamp(result.a(), 0, 255)); }; - auto srcfactor = Math::MakeVec(LookupFactorRGB(params.factor_source_rgb), - LookupFactorA(params.factor_source_a)); - auto dstfactor = Math::MakeVec(LookupFactorRGB(params.factor_dest_rgb), - LookupFactorA(params.factor_dest_a)); + auto srcfactor = Math::MakeVec(LookupFactor(0, params.factor_source_rgb), + LookupFactor(1, params.factor_source_rgb), + LookupFactor(2, params.factor_source_rgb), + LookupFactor(3, params.factor_source_a)); + + auto dstfactor = Math::MakeVec(LookupFactor(0, params.factor_dest_rgb), + LookupFactor(1, params.factor_dest_rgb), + LookupFactor(2, params.factor_dest_rgb), + LookupFactor(3, params.factor_dest_a)); blend_output = EvaluateBlendEquation(combiner_output, srcfactor, dest, dstfactor, params.blend_equation_rgb); blend_output.a() = EvaluateBlendEquation(combiner_output, srcfactor, dest, dstfactor, params.blend_equation_a).a(); From 164c15f9116dd0f0b1f0a64fd551d10f24024e96 Mon Sep 17 00:00:00 2001 From: Emmanuel Gil Peyrot Date: Tue, 19 Apr 2016 02:24:21 +0100 Subject: [PATCH 068/104] SDL2 Frontend: Use argv[0], add a --version, and reorder options. --- src/citra/citra.cpp | 29 ++++++++++++++++++++--------- 1 file changed, 20 insertions(+), 9 deletions(-) diff --git a/src/citra/citra.cpp b/src/citra/citra.cpp index d6ad13f69..b4501eb2e 100644 --- a/src/citra/citra.cpp +++ b/src/citra/citra.cpp @@ -20,6 +20,7 @@ #include "common/logging/log.h" #include "common/logging/backend.h" #include "common/logging/filter.h" +#include "common/scm_rev.h" #include "common/scope_exit.h" #include "core/settings.h" @@ -34,11 +35,17 @@ #include "video_core/video_core.h" -static void PrintHelp() +static void PrintHelp(const char *argv0) { - std::cout << "Usage: citra [options] " << std::endl; - std::cout << "--help, -h Display this information" << std::endl; - std::cout << "--gdbport, -g number Enable gdb stub on port number" << std::endl; + std::cout << "Usage: " << argv0 << " [options] \n" + "-g, --gdbport=NUMBER Enable gdb stub on port NUMBER\n" + "-h, --help Display this help and exit\n" + "-v, --version Output version information and exit\n"; +} + +static void PrintVersion() +{ + std::cout << "Citra " << Common::g_scm_branch << " " << Common::g_scm_desc << std::endl; } /// Application entry point @@ -51,18 +58,16 @@ int main(int argc, char **argv) { std::string boot_filename; static struct option long_options[] = { - { "help", no_argument, 0, 'h' }, { "gdbport", required_argument, 0, 'g' }, + { "help", no_argument, 0, 'h' }, + { "version", no_argument, 0, 'v' }, { 0, 0, 0, 0 } }; while (optind < argc) { - char arg = getopt_long(argc, argv, ":hg:", long_options, &option_index); + char arg = getopt_long(argc, argv, "g:hv", long_options, &option_index); if (arg != -1) { switch (arg) { - case 'h': - PrintHelp(); - return 0; case 'g': errno = 0; gdb_port = strtoul(optarg, &endarg, 0); @@ -73,6 +78,12 @@ int main(int argc, char **argv) { exit(1); } break; + case 'h': + PrintHelp(argv[0]); + return 0; + case 'v': + PrintVersion(); + return 0; } } else { boot_filename = argv[optind]; From 854912ca5d166cab47f7a2a41f563135889e3c1a Mon Sep 17 00:00:00 2001 From: JamePeng Date: Wed, 20 Apr 2016 18:38:01 +0800 Subject: [PATCH 069/104] Update the code of service y2r! --- src/core/hle/service/y2r_u.cpp | 369 ++++++++++++++++++++++++++++++--- src/core/hle/service/y2r_u.h | 20 ++ 2 files changed, 357 insertions(+), 32 deletions(-) diff --git a/src/core/hle/service/y2r_u.cpp b/src/core/hle/service/y2r_u.cpp index 22f373adf..2c6328a44 100644 --- a/src/core/hle/service/y2r_u.cpp +++ b/src/core/hle/service/y2r_u.cpp @@ -4,6 +4,7 @@ #include +#include "common/common_funcs.h" #include "common/common_types.h" #include "common/logging/log.h" @@ -28,13 +29,17 @@ struct ConversionParameters { u16 input_line_width; u16 input_lines; StandardCoefficient standard_coefficient; - u8 reserved; + u8 padding; u16 alpha; }; static_assert(sizeof(ConversionParameters) == 12, "ConversionParameters struct has incorrect size"); static Kernel::SharedPtr completion_event; static ConversionConfiguration conversion; +static DitheringWeightParams dithering_weight_params; +static u32 temporal_dithering_enabled = 0; +static u32 transfer_end_interrupt_enabled = 0; +static u32 spacial_dithering_enabled = 0; static const CoefficientSet standard_coefficients[4] = { {{ 0x100, 0x166, 0xB6, 0x58, 0x1C5, -0x166F, 0x10EE, -0x1C5B }}, // ITU_Rec601 @@ -73,7 +78,7 @@ ResultCode ConversionConfiguration::SetInputLines(u16 lines) { ResultCode ConversionConfiguration::SetStandardCoefficient(StandardCoefficient standard_coefficient) { size_t index = static_cast(standard_coefficient); - if (index >= 4) { + if (index >= ARRAY_SIZE(standard_coefficients)) { return ResultCode(ErrorDescription::InvalidEnumValue, ErrorModule::CAM, ErrorSummary::InvalidArgument, ErrorLevel::Usage); // 0xE0E053ED } @@ -88,42 +93,167 @@ static void SetInputFormat(Service::Interface* self) { conversion.input_format = static_cast(cmd_buff[1]); LOG_DEBUG(Service_Y2R, "called input_format=%hhu", conversion.input_format); + cmd_buff[0] = IPC::MakeHeader(0x1, 1, 0); cmd_buff[1] = RESULT_SUCCESS.raw; } +static void GetInputFormat(Service::Interface* self) { + u32* cmd_buff = Kernel::GetCommandBuffer(); + + cmd_buff[0] = IPC::MakeHeader(0x2, 2, 0); + cmd_buff[1] = RESULT_SUCCESS.raw; + cmd_buff[2] = static_cast(conversion.input_format); + LOG_DEBUG(Service_Y2R, "called input_format=%hhu", conversion.input_format); +} + static void SetOutputFormat(Service::Interface* self) { u32* cmd_buff = Kernel::GetCommandBuffer(); conversion.output_format = static_cast(cmd_buff[1]); LOG_DEBUG(Service_Y2R, "called output_format=%hhu", conversion.output_format); + cmd_buff[0] = IPC::MakeHeader(0x3, 1, 0); cmd_buff[1] = RESULT_SUCCESS.raw; } +static void GetOutputFormat(Service::Interface* self) { + u32* cmd_buff = Kernel::GetCommandBuffer(); + + cmd_buff[0] = IPC::MakeHeader(0x4, 2, 0); + cmd_buff[1] = RESULT_SUCCESS.raw; + cmd_buff[2] = static_cast(conversion.output_format); + LOG_DEBUG(Service_Y2R, "called output_format=%hhu", conversion.output_format); +} + static void SetRotation(Service::Interface* self) { u32* cmd_buff = Kernel::GetCommandBuffer(); conversion.rotation = static_cast(cmd_buff[1]); LOG_DEBUG(Service_Y2R, "called rotation=%hhu", conversion.rotation); + cmd_buff[0] = IPC::MakeHeader(0x5, 1, 0); cmd_buff[1] = RESULT_SUCCESS.raw; } +static void GetRotation(Service::Interface* self) { + u32* cmd_buff = Kernel::GetCommandBuffer(); + + cmd_buff[0] = IPC::MakeHeader(0x6, 2, 0); + cmd_buff[1] = RESULT_SUCCESS.raw; + cmd_buff[2] = static_cast(conversion.rotation); + LOG_DEBUG(Service_Y2R, "called rotation=%hhu", conversion.rotation); +} + static void SetBlockAlignment(Service::Interface* self) { u32* cmd_buff = Kernel::GetCommandBuffer(); conversion.block_alignment = static_cast(cmd_buff[1]); - LOG_DEBUG(Service_Y2R, "called alignment=%hhu", conversion.block_alignment); + LOG_DEBUG(Service_Y2R, "called block_alignment=%hhu", conversion.block_alignment); + cmd_buff[0] = IPC::MakeHeader(0x7, 1, 0); cmd_buff[1] = RESULT_SUCCESS.raw; } +static void GetBlockAlignment(Service::Interface* self) { + u32* cmd_buff = Kernel::GetCommandBuffer(); + + cmd_buff[0] = IPC::MakeHeader(0x8, 2, 0); + cmd_buff[1] = RESULT_SUCCESS.raw; + cmd_buff[2] = static_cast(conversion.block_alignment); + LOG_DEBUG(Service_Y2R, "called block_alignment=%hhu", conversion.block_alignment); +} + +/** + * Y2R_U::SetSpacialDithering service function + * Inputs: + * 1 : u8, 0 = Disabled, 1 = Enabled + * Outputs: + * 1 : Result of function, 0 on success, otherwise error code + */ +static void SetSpacialDithering(Service::Interface* self) { + u32* cmd_buff = Kernel::GetCommandBuffer(); + spacial_dithering_enabled = cmd_buff[1] & 0xF; + + cmd_buff[0] = IPC::MakeHeader(0x9, 1, 0); + cmd_buff[1] = RESULT_SUCCESS.raw; + LOG_WARNING(Service_Y2R, "(STUBBED) called"); +} + +/** + * Y2R_U::GetSpacialDithering service function + * Outputs: + * 1 : Result of function, 0 on success, otherwise error code + * 2 : u8, 0 = Disabled, 1 = Enabled + */ +static void GetSpacialDithering(Service::Interface* self) { + u32* cmd_buff = Kernel::GetCommandBuffer(); + + cmd_buff[0] = IPC::MakeHeader(0xA, 2, 0); + cmd_buff[1] = RESULT_SUCCESS.raw; + cmd_buff[2] = spacial_dithering_enabled; + LOG_WARNING(Service_Y2R, "(STUBBED) called"); +} + +/** + * Y2R_U::SetTemporalDithering service function + * Inputs: + * 1 : u8, 0 = Disabled, 1 = Enabled + * Outputs: + * 1 : Result of function, 0 on success, otherwise error code + */ +static void SetTemporalDithering(Service::Interface* self) { + u32* cmd_buff = Kernel::GetCommandBuffer(); + temporal_dithering_enabled = cmd_buff[1] & 0xF; + + cmd_buff[0] = IPC::MakeHeader(0xB, 1, 0); + cmd_buff[1] = RESULT_SUCCESS.raw; + LOG_WARNING(Service_Y2R, "(STUBBED) called"); +} + +/** + * Y2R_U::GetTemporalDithering service function + * Outputs: + * 1 : Result of function, 0 on success, otherwise error code + * 2 : u8, 0 = Disabled, 1 = Enabled + */ +static void GetTemporalDithering(Service::Interface* self) { + u32* cmd_buff = Kernel::GetCommandBuffer(); + + cmd_buff[0] = IPC::MakeHeader(0xC, 2, 0); + cmd_buff[1] = RESULT_SUCCESS.raw; + cmd_buff[2] = temporal_dithering_enabled; + LOG_WARNING(Service_Y2R, "(STUBBED) called"); +} + +/** + * Y2R_U::SetTransferEndInterrupt service function + * Inputs: + * 1 : u8, 0 = Disabled, 1 = Enabled + * Outputs: + * 1 : Result of function, 0 on success, otherwise error code + */ static void SetTransferEndInterrupt(Service::Interface* self) { u32* cmd_buff = Kernel::GetCommandBuffer(); + transfer_end_interrupt_enabled = cmd_buff[1] & 0xf; cmd_buff[0] = IPC::MakeHeader(0xD, 1, 0); cmd_buff[1] = RESULT_SUCCESS.raw; - LOG_DEBUG(Service_Y2R, "(STUBBED) called"); + LOG_WARNING(Service_Y2R, "(STUBBED) called"); +} + +/** + * Y2R_U::GetTransferEndInterrupt service function + * Outputs: + * 1 : Result of function, 0 on success, otherwise error code + * 2 : u8, 0 = Disabled, 1 = Enabled + */ +static void GetTransferEndInterrupt(Service::Interface* self) { + u32* cmd_buff = Kernel::GetCommandBuffer(); + + cmd_buff[0] = IPC::MakeHeader(0xE, 2, 0); + cmd_buff[1] = RESULT_SUCCESS.raw; + cmd_buff[2] = transfer_end_interrupt_enabled; + LOG_WARNING(Service_Y2R, "(STUBBED) called"); } /** @@ -135,6 +265,7 @@ static void SetTransferEndInterrupt(Service::Interface* self) { static void GetTransferEndEvent(Service::Interface* self) { u32* cmd_buff = Kernel::GetCommandBuffer(); + cmd_buff[0] = IPC::MakeHeader(0xF, 2, 0); cmd_buff[1] = RESULT_SUCCESS.raw; cmd_buff[3] = Kernel::g_handle_table.Create(completion_event).MoveFrom(); LOG_DEBUG(Service_Y2R, "called"); @@ -152,6 +283,7 @@ static void SetSendingY(Service::Interface* self) { "src_process_handle=0x%08X", conversion.src_Y.image_size, conversion.src_Y.transfer_unit, conversion.src_Y.gap, src_process_handle); + cmd_buff[0] = IPC::MakeHeader(0x10, 1, 0); cmd_buff[1] = RESULT_SUCCESS.raw; } @@ -167,6 +299,7 @@ static void SetSendingU(Service::Interface* self) { "src_process_handle=0x%08X", conversion.src_U.image_size, conversion.src_U.transfer_unit, conversion.src_U.gap, src_process_handle); + cmd_buff[0] = IPC::MakeHeader(0x11, 1, 0); cmd_buff[1] = RESULT_SUCCESS.raw; } @@ -182,6 +315,7 @@ static void SetSendingV(Service::Interface* self) { "src_process_handle=0x%08X", conversion.src_V.image_size, conversion.src_V.transfer_unit, conversion.src_V.gap, src_process_handle); + cmd_buff[0] = IPC::MakeHeader(0x12, 1, 0); cmd_buff[1] = RESULT_SUCCESS.raw; } @@ -197,9 +331,70 @@ static void SetSendingYUYV(Service::Interface* self) { "src_process_handle=0x%08X", conversion.src_YUYV.image_size, conversion.src_YUYV.transfer_unit, conversion.src_YUYV.gap, src_process_handle); + cmd_buff[0] = IPC::MakeHeader(0x13, 1, 0); cmd_buff[1] = RESULT_SUCCESS.raw; } +/** + * Y2R::IsFinishedSendingYuv service function + * Output: + * 1 : Result of the function, 0 on success, otherwise error code + * 2 : u8, 0 = Not Finished, 1 = Finished + */ +static void IsFinishedSendingYuv(Service::Interface* self) { + u32* cmd_buff = Kernel::GetCommandBuffer(); + + cmd_buff[0] = IPC::MakeHeader(0x14, 2, 0); + cmd_buff[1] = RESULT_SUCCESS.raw; + cmd_buff[2] = 1; + LOG_WARNING(Service_Y2R, "(STUBBED) called"); +} + +/** + * Y2R::IsFinishedSendingY service function + * Output: + * 1 : Result of the function, 0 on success, otherwise error code + * 2 : u8, 0 = Not Finished, 1 = Finished + */ +static void IsFinishedSendingY(Service::Interface* self) { + u32* cmd_buff = Kernel::GetCommandBuffer(); + + cmd_buff[0] = IPC::MakeHeader(0x15, 2, 0); + cmd_buff[1] = RESULT_SUCCESS.raw; + cmd_buff[2] = 1; + LOG_WARNING(Service_Y2R, "(STUBBED) called"); +} + +/** + * Y2R::IsFinishedSendingU service function + * Output: + * 1 : Result of the function, 0 on success, otherwise error code + * 2 : u8, 0 = Not Finished, 1 = Finished + */ +static void IsFinishedSendingU(Service::Interface* self) { + u32* cmd_buff = Kernel::GetCommandBuffer(); + + cmd_buff[0] = IPC::MakeHeader(0x16, 2, 0); + cmd_buff[1] = RESULT_SUCCESS.raw; + cmd_buff[2] = 1; + LOG_WARNING(Service_Y2R, "(STUBBED) called"); +} + +/** + * Y2R::IsFinishedSendingV service function + * Output: + * 1 : Result of the function, 0 on success, otherwise error code + * 2 : u8, 0 = Not Finished, 1 = Finished + */ +static void IsFinishedSendingV(Service::Interface* self) { + u32* cmd_buff = Kernel::GetCommandBuffer(); + + cmd_buff[0] = IPC::MakeHeader(0x17, 2, 0); + cmd_buff[1] = RESULT_SUCCESS.raw; + cmd_buff[2] = 1; + LOG_WARNING(Service_Y2R, "(STUBBED) called"); +} + static void SetReceiving(Service::Interface* self) { u32* cmd_buff = Kernel::GetCommandBuffer(); @@ -213,23 +408,59 @@ static void SetReceiving(Service::Interface* self) { conversion.dst.transfer_unit, conversion.dst.gap, dst_process_handle); + cmd_buff[0] = IPC::MakeHeader(0x18, 1, 0); cmd_buff[1] = RESULT_SUCCESS.raw; } +/** + * Y2R::IsFinishedReceiving service function + * Output: + * 1 : Result of the function, 0 on success, otherwise error code + * 2 : u8, 0 = Not Finished, 1 = Finished + */ +static void IsFinishedReceiving(Service::Interface* self) { + u32* cmd_buff = Kernel::GetCommandBuffer(); + + cmd_buff[0] = IPC::MakeHeader(0x19, 2, 0); + cmd_buff[1] = RESULT_SUCCESS.raw; + cmd_buff[2] = 1; + LOG_WARNING(Service_Y2R, "(STUBBED) called"); +} + static void SetInputLineWidth(Service::Interface* self) { u32* cmd_buff = Kernel::GetCommandBuffer(); LOG_DEBUG(Service_Y2R, "called input_line_width=%u", cmd_buff[1]); + cmd_buff[0] = IPC::MakeHeader(0x1A, 1, 0); cmd_buff[1] = conversion.SetInputLineWidth(cmd_buff[1]).raw; } +static void GetInputLineWidth(Service::Interface* self) { + u32* cmd_buff = Kernel::GetCommandBuffer(); + + cmd_buff[0] = IPC::MakeHeader(0x1B, 2, 0); + cmd_buff[1] = RESULT_SUCCESS.raw; + cmd_buff[2] = conversion.input_line_width; + LOG_DEBUG(Service_Y2R, "called input_line_width=%u", conversion.input_line_width); +} + static void SetInputLines(Service::Interface* self) { u32* cmd_buff = Kernel::GetCommandBuffer(); - LOG_DEBUG(Service_Y2R, "called input_line_number=%u", cmd_buff[1]); + LOG_DEBUG(Service_Y2R, "called input_lines=%u", cmd_buff[1]); + cmd_buff[0] = IPC::MakeHeader(0x1C, 1, 0); cmd_buff[1] = conversion.SetInputLines(cmd_buff[1]).raw; } +static void GetInputLines(Service::Interface* self) { + u32* cmd_buff = Kernel::GetCommandBuffer(); + + cmd_buff[0] = IPC::MakeHeader(0x1D, 2, 0); + cmd_buff[1] = RESULT_SUCCESS.raw; + cmd_buff[2] = static_cast(conversion.input_lines); + LOG_DEBUG(Service_Y2R, "called input_lines=%u", conversion.input_lines); +} + static void SetCoefficient(Service::Interface* self) { u32* cmd_buff = Kernel::GetCommandBuffer(); @@ -239,15 +470,45 @@ static void SetCoefficient(Service::Interface* self) { coefficients[0], coefficients[1], coefficients[2], coefficients[3], coefficients[4], coefficients[5], coefficients[6], coefficients[7]); + cmd_buff[0] = IPC::MakeHeader(0x1E, 1, 0); cmd_buff[1] = RESULT_SUCCESS.raw; } +static void GetCoefficient(Service::Interface* self) { + u32* cmd_buff = Kernel::GetCommandBuffer(); + + cmd_buff[0] = IPC::MakeHeader(0x1F, 5, 0); + cmd_buff[1] = RESULT_SUCCESS.raw; + std::memcpy(&cmd_buff[2], conversion.coefficients.data(), sizeof(CoefficientSet)); +} + static void SetStandardCoefficient(Service::Interface* self) { u32* cmd_buff = Kernel::GetCommandBuffer(); - LOG_DEBUG(Service_Y2R, "called standard_coefficient=%u", cmd_buff[1]); + u32 index = cmd_buff[1]; - cmd_buff[1] = conversion.SetStandardCoefficient((StandardCoefficient)cmd_buff[1]).raw; + cmd_buff[0] = IPC::MakeHeader(0x20, 1, 0); + cmd_buff[1] = conversion.SetStandardCoefficient((StandardCoefficient)index).raw; + LOG_DEBUG(Service_Y2R, "called standard_coefficient=%u", index); +} + +static void GetStandardCoefficient(Service::Interface* self) { + u32* cmd_buff = Kernel::GetCommandBuffer(); + + u32 index = cmd_buff[1]; + + if (index < ARRAY_SIZE(standard_coefficients)) { + std::memcpy(&cmd_buff[2], &standard_coefficients[index], sizeof(CoefficientSet)); + + cmd_buff[0] = IPC::MakeHeader(0x21, 5, 0); + cmd_buff[1] = RESULT_SUCCESS.raw; + LOG_DEBUG(Service_Y2R, "called standard_coefficient=%u ", index); + } + else { + cmd_buff[0] = IPC::MakeHeader(0x21, 1, 0); + cmd_buff[1] = -1; + LOG_ERROR(Service_Y2R, "called standard_coefficient=%u The argument is invalid!", index); + } } static void SetAlpha(Service::Interface* self) { @@ -256,9 +517,37 @@ static void SetAlpha(Service::Interface* self) { conversion.alpha = cmd_buff[1]; LOG_DEBUG(Service_Y2R, "called alpha=%hu", conversion.alpha); + cmd_buff[0] = IPC::MakeHeader(0x22, 1, 0); cmd_buff[1] = RESULT_SUCCESS.raw; } +static void GetAlpha(Service::Interface* self) { + u32* cmd_buff = Kernel::GetCommandBuffer(); + + cmd_buff[0] = IPC::MakeHeader(0x23, 2, 0); + cmd_buff[1] = RESULT_SUCCESS.raw; + cmd_buff[2] = conversion.alpha; + LOG_DEBUG(Service_Y2R, "called alpha=%hu", conversion.alpha); +} + +static void SetDitheringWeightParams(Service::Interface* self) { + u32* cmd_buff = Kernel::GetCommandBuffer(); + std::memcpy(&dithering_weight_params, &cmd_buff[1], sizeof(DitheringWeightParams)); + + cmd_buff[0] = IPC::MakeHeader(0x24, 1, 0); + cmd_buff[1] = RESULT_SUCCESS.raw; + LOG_DEBUG(Service_Y2R, "called"); +} + +static void GetDitheringWeightParams(Service::Interface* self) { + u32* cmd_buff = Kernel::GetCommandBuffer(); + + cmd_buff[0] = IPC::MakeHeader(0x25, 9, 0); + cmd_buff[1] = RESULT_SUCCESS.raw; + std::memcpy(&cmd_buff[2], &dithering_weight_params, sizeof(DitheringWeightParams)); + LOG_DEBUG(Service_Y2R, "called"); +} + static void StartConversion(Service::Interface* self) { u32* cmd_buff = Kernel::GetCommandBuffer(); @@ -273,6 +562,7 @@ static void StartConversion(Service::Interface* self) { LOG_DEBUG(Service_Y2R, "called"); completion_event->Signal(); + cmd_buff[0] = IPC::MakeHeader(0x26, 1, 0); cmd_buff[1] = RESULT_SUCCESS.raw; } @@ -293,15 +583,16 @@ static void StopConversion(Service::Interface* self) { static void IsBusyConversion(Service::Interface* self) { u32* cmd_buff = Kernel::GetCommandBuffer(); + cmd_buff[0] = IPC::MakeHeader(0x28, 2, 0); cmd_buff[1] = RESULT_SUCCESS.raw; cmd_buff[2] = 0; // StartConversion always finishes immediately LOG_DEBUG(Service_Y2R, "called"); } /** - * Y2R_U::SetConversionParams service function + * Y2R_U::SetPackageParameter service function */ -static void SetConversionParams(Service::Interface* self) { +static void SetPackageParameter(Service::Interface* self) { u32* cmd_buff = Kernel::GetCommandBuffer(); auto params = reinterpret_cast(&cmd_buff[1]); @@ -311,7 +602,7 @@ static void SetConversionParams(Service::Interface* self) { "reserved=%hhu alpha=%hX", params->input_format, params->output_format, params->rotation, params->block_alignment, params->input_line_width, params->input_lines, params->standard_coefficient, - params->reserved, params->alpha); + params->padding, params->alpha); ResultCode result = RESULT_SUCCESS; @@ -325,6 +616,7 @@ static void SetConversionParams(Service::Interface* self) { if (result.IsError()) goto cleanup; result = conversion.SetStandardCoefficient(params->standard_coefficient); if (result.IsError()) goto cleanup; + conversion.padding = params->padding; conversion.alpha = params->alpha; cleanup: @@ -335,6 +627,7 @@ cleanup: static void PingProcess(Service::Interface* self) { u32* cmd_buff = Kernel::GetCommandBuffer(); + cmd_buff[0] = IPC::MakeHeader(0x2A, 2, 0); cmd_buff[1] = RESULT_SUCCESS.raw; cmd_buff[2] = 0; LOG_WARNING(Service_Y2R, "(STUBBED) called"); @@ -373,51 +666,63 @@ static void DriverFinalize(Service::Interface* self) { LOG_DEBUG(Service_Y2R, "called"); } + +static void GetPackageParameter(Service::Interface* self) { + u32* cmd_buff = Kernel::GetCommandBuffer(); + + cmd_buff[0] = IPC::MakeHeader(0x2D, 4, 0); + cmd_buff[1] = RESULT_SUCCESS.raw; + std::memcpy(&cmd_buff[2], &conversion, sizeof(ConversionParameters)); + + LOG_DEBUG(Service_Y2R, "called"); +} + const Interface::FunctionInfo FunctionTable[] = { {0x00010040, SetInputFormat, "SetInputFormat"}, - {0x00020000, nullptr, "GetInputFormat"}, + {0x00020000, GetInputFormat, "GetInputFormat"}, {0x00030040, SetOutputFormat, "SetOutputFormat"}, - {0x00040000, nullptr, "GetOutputFormat"}, + {0x00040000, GetOutputFormat, "GetOutputFormat"}, {0x00050040, SetRotation, "SetRotation"}, - {0x00060000, nullptr, "GetRotation"}, + {0x00060000, GetRotation, "GetRotation"}, {0x00070040, SetBlockAlignment, "SetBlockAlignment"}, - {0x00080000, nullptr, "GetBlockAlignment"}, - {0x00090040, nullptr, "SetSpacialDithering"}, - {0x000A0000, nullptr, "GetSpacialDithering"}, - {0x000B0040, nullptr, "SetTemporalDithering"}, - {0x000C0000, nullptr, "GetTemporalDithering"}, + {0x00080000, GetBlockAlignment, "GetBlockAlignment"}, + {0x00090040, SetSpacialDithering, "SetSpacialDithering"}, + {0x000A0000, GetSpacialDithering, "GetSpacialDithering"}, + {0x000B0040, SetTemporalDithering, "SetTemporalDithering"}, + {0x000C0000, GetTemporalDithering, "GetTemporalDithering"}, {0x000D0040, SetTransferEndInterrupt, "SetTransferEndInterrupt"}, + {0x000E0000, GetTransferEndInterrupt, "GetTransferEndInterrupt"}, {0x000F0000, GetTransferEndEvent, "GetTransferEndEvent"}, {0x00100102, SetSendingY, "SetSendingY"}, {0x00110102, SetSendingU, "SetSendingU"}, {0x00120102, SetSendingV, "SetSendingV"}, {0x00130102, SetSendingYUYV, "SetSendingYUYV"}, - {0x00140000, nullptr, "IsFinishedSendingYuv"}, - {0x00150000, nullptr, "IsFinishedSendingY"}, - {0x00160000, nullptr, "IsFinishedSendingU"}, - {0x00170000, nullptr, "IsFinishedSendingV"}, + {0x00140000, IsFinishedSendingYuv, "IsFinishedSendingYuv"}, + {0x00150000, IsFinishedSendingY, "IsFinishedSendingY"}, + {0x00160000, IsFinishedSendingU, "IsFinishedSendingU"}, + {0x00170000, IsFinishedSendingV, "IsFinishedSendingV"}, {0x00180102, SetReceiving, "SetReceiving"}, - {0x00190000, nullptr, "IsFinishedReceiving"}, + {0x00190000, IsFinishedReceiving, "IsFinishedReceiving"}, {0x001A0040, SetInputLineWidth, "SetInputLineWidth"}, - {0x001B0000, nullptr, "GetInputLineWidth"}, + {0x001B0000, GetInputLineWidth, "GetInputLineWidth"}, {0x001C0040, SetInputLines, "SetInputLines"}, - {0x001D0000, nullptr, "GetInputLines"}, + {0x001D0000, GetInputLines, "GetInputLines"}, {0x001E0100, SetCoefficient, "SetCoefficient"}, - {0x001F0000, nullptr, "GetCoefficient"}, + {0x001F0000, GetCoefficient, "GetCoefficient"}, {0x00200040, SetStandardCoefficient, "SetStandardCoefficient"}, - {0x00210040, nullptr, "GetStandardCoefficientParams"}, + {0x00210040, GetStandardCoefficient, "GetStandardCoefficient"}, {0x00220040, SetAlpha, "SetAlpha"}, - {0x00230000, nullptr, "GetAlpha"}, - {0x00240200, nullptr, "SetDitheringWeightParams"}, - {0x00250000, nullptr, "GetDitheringWeightParams"}, + {0x00230000, GetAlpha, "GetAlpha"}, + {0x00240200, SetDitheringWeightParams,"SetDitheringWeightParams"}, + {0x00250000, GetDitheringWeightParams,"GetDitheringWeightParams"}, {0x00260000, StartConversion, "StartConversion"}, {0x00270000, StopConversion, "StopConversion"}, {0x00280000, IsBusyConversion, "IsBusyConversion"}, - {0x002901C0, SetConversionParams, "SetConversionParams"}, + {0x002901C0, SetPackageParameter, "SetPackageParameter"}, {0x002A0000, PingProcess, "PingProcess"}, {0x002B0000, DriverInitialize, "DriverInitialize"}, {0x002C0000, DriverFinalize, "DriverFinalize"}, - {0x002D0000, nullptr, "GetPackageParameter"}, + {0x002D0000, GetPackageParameter, "GetPackageParameter"}, }; //////////////////////////////////////////////////////////////////////////////////////////////////// diff --git a/src/core/hle/service/y2r_u.h b/src/core/hle/service/y2r_u.h index 3965a5545..95fa2fdb7 100644 --- a/src/core/hle/service/y2r_u.h +++ b/src/core/hle/service/y2r_u.h @@ -97,6 +97,7 @@ struct ConversionConfiguration { u16 input_line_width; u16 input_lines; CoefficientSet coefficients; + u8 padding; u16 alpha; /// Input parameters for the Y (luma) plane @@ -109,6 +110,25 @@ struct ConversionConfiguration { ResultCode SetStandardCoefficient(StandardCoefficient standard_coefficient); }; +struct DitheringWeightParams { + u16 w0_xEven_yEven; + u16 w0_xOdd_yEven; + u16 w0_xEven_yOdd; + u16 w0_xOdd_yOdd; + u16 w1_xEven_yEven; + u16 w1_xOdd_yEven; + u16 w1_xEven_yOdd; + u16 w1_xOdd_yOdd; + u16 w2_xEven_yEven; + u16 w2_xOdd_yEven; + u16 w2_xEven_yOdd; + u16 w2_xOdd_yOdd; + u16 w3_xEven_yEven; + u16 w3_xOdd_yEven; + u16 w3_xEven_yOdd; + u16 w3_xOdd_yOdd; +}; + class Interface : public Service::Interface { public: Interface(); From 15b44fb38093b05413acc00ee36c396e5f649764 Mon Sep 17 00:00:00 2001 From: tfarley Date: Wed, 2 Mar 2016 01:06:38 -0500 Subject: [PATCH 070/104] Update to ext-boost with interval_map --- externals/boost | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/externals/boost b/externals/boost index d81b92699..2dcb9d979 160000 --- a/externals/boost +++ b/externals/boost @@ -1 +1 @@ -Subproject commit d81b9269900ae183d0dc98403eea4c971590a807 +Subproject commit 2dcb9d979665b6aabb1635c617973e02914e60ec From e46d086189908ce9b9d7d68e3e4453396e48c7cc Mon Sep 17 00:00:00 2001 From: tfarley Date: Sat, 16 Apr 2016 18:51:49 -0400 Subject: [PATCH 071/104] Config: Add scaled resolution option --- src/citra/config.cpp | 1 + src/citra/default_ini.h | 4 ++++ src/citra_qt/config.cpp | 2 ++ src/citra_qt/configure_general.cpp | 2 ++ src/citra_qt/configure_general.ui | 7 +++++++ src/core/settings.cpp | 2 +- src/core/settings.h | 1 + src/video_core/video_core.cpp | 1 + src/video_core/video_core.h | 1 + 9 files changed, 20 insertions(+), 1 deletion(-) diff --git a/src/citra/config.cpp b/src/citra/config.cpp index 6b6617352..9e2ecd307 100644 --- a/src/citra/config.cpp +++ b/src/citra/config.cpp @@ -65,6 +65,7 @@ void Config::ReadValues() { // Renderer Settings::values.use_hw_renderer = sdl2_config->GetBoolean("Renderer", "use_hw_renderer", false); Settings::values.use_shader_jit = sdl2_config->GetBoolean("Renderer", "use_shader_jit", true); + Settings::values.use_scaled_resolution = sdl2_config->GetBoolean("Renderer", "use_scaled_resolution", false); Settings::values.bg_red = (float)sdl2_config->GetReal("Renderer", "bg_red", 1.0); Settings::values.bg_green = (float)sdl2_config->GetReal("Renderer", "bg_green", 1.0); diff --git a/src/citra/default_ini.h b/src/citra/default_ini.h index c9b490a00..1f1aa716b 100644 --- a/src/citra/default_ini.h +++ b/src/citra/default_ini.h @@ -46,6 +46,10 @@ use_hw_renderer = # 0 : Interpreter (slow), 1 (default): JIT (fast) use_shader_jit = +# Whether to use native 3DS screen resolution or to scale rendering resolution to the displayed screen size. +# 0 (default): Native, 1: Scaled +use_scaled_resolution = + # The clear color for the renderer. What shows up on the sides of the bottom screen. # Must be in range of 0.0-1.0. Defaults to 1.0 for all. bg_red = diff --git a/src/citra_qt/config.cpp b/src/citra_qt/config.cpp index e363be38a..7dc61fe40 100644 --- a/src/citra_qt/config.cpp +++ b/src/citra_qt/config.cpp @@ -45,6 +45,7 @@ void Config::ReadValues() { qt_config->beginGroup("Renderer"); Settings::values.use_hw_renderer = qt_config->value("use_hw_renderer", false).toBool(); Settings::values.use_shader_jit = qt_config->value("use_shader_jit", true).toBool(); + Settings::values.use_scaled_resolution = qt_config->value("use_scaled_resolution", false).toBool(); Settings::values.bg_red = qt_config->value("bg_red", 1.0).toFloat(); Settings::values.bg_green = qt_config->value("bg_green", 1.0).toFloat(); @@ -129,6 +130,7 @@ void Config::SaveValues() { qt_config->beginGroup("Renderer"); qt_config->setValue("use_hw_renderer", Settings::values.use_hw_renderer); qt_config->setValue("use_shader_jit", Settings::values.use_shader_jit); + qt_config->setValue("use_scaled_resolution", Settings::values.use_scaled_resolution); // Cast to double because Qt's written float values are not human-readable qt_config->setValue("bg_red", (double)Settings::values.bg_red); diff --git a/src/citra_qt/configure_general.cpp b/src/citra_qt/configure_general.cpp index a27d0d26c..62648e665 100644 --- a/src/citra_qt/configure_general.cpp +++ b/src/citra_qt/configure_general.cpp @@ -25,6 +25,7 @@ void ConfigureGeneral::setConfiguration() { ui->region_combobox->setCurrentIndex(Settings::values.region_value); ui->toogle_hw_renderer->setChecked(Settings::values.use_hw_renderer); ui->toogle_shader_jit->setChecked(Settings::values.use_shader_jit); + ui->toogle_scaled_resolution->setChecked(Settings::values.use_scaled_resolution); } void ConfigureGeneral::applyConfiguration() { @@ -33,5 +34,6 @@ void ConfigureGeneral::applyConfiguration() { Settings::values.region_value = ui->region_combobox->currentIndex(); Settings::values.use_hw_renderer = ui->toogle_hw_renderer->isChecked(); Settings::values.use_shader_jit = ui->toogle_shader_jit->isChecked(); + Settings::values.use_scaled_resolution = ui->toogle_scaled_resolution->isChecked(); Settings::Apply(); } diff --git a/src/citra_qt/configure_general.ui b/src/citra_qt/configure_general.ui index 47184c5c6..5eb309793 100644 --- a/src/citra_qt/configure_general.ui +++ b/src/citra_qt/configure_general.ui @@ -128,6 +128,13 @@ + + + + Enable scaled resolution + + + diff --git a/src/core/settings.cpp b/src/core/settings.cpp index 1aa26fbd2..eaf5c8461 100644 --- a/src/core/settings.cpp +++ b/src/core/settings.cpp @@ -19,7 +19,7 @@ void Apply() { VideoCore::g_hw_renderer_enabled = values.use_hw_renderer; VideoCore::g_shader_jit_enabled = values.use_shader_jit; - + VideoCore::g_scaled_resolution_enabled = values.use_scaled_resolution; } } // namespace diff --git a/src/core/settings.h b/src/core/settings.h index 4933a516d..d620d8461 100644 --- a/src/core/settings.h +++ b/src/core/settings.h @@ -55,6 +55,7 @@ struct Values { // Renderer bool use_hw_renderer; bool use_shader_jit; + bool use_scaled_resolution; float bg_red; float bg_green; diff --git a/src/video_core/video_core.cpp b/src/video_core/video_core.cpp index 256899c89..855286173 100644 --- a/src/video_core/video_core.cpp +++ b/src/video_core/video_core.cpp @@ -25,6 +25,7 @@ std::unique_ptr g_renderer; ///< Renderer plugin std::atomic g_hw_renderer_enabled; std::atomic g_shader_jit_enabled; +std::atomic g_scaled_resolution_enabled; /// Initialize the video core bool Init(EmuWindow* emu_window) { diff --git a/src/video_core/video_core.h b/src/video_core/video_core.h index bca67fb8c..30267489e 100644 --- a/src/video_core/video_core.h +++ b/src/video_core/video_core.h @@ -36,6 +36,7 @@ extern EmuWindow* g_emu_window; ///< Emu window // TODO: Wrap these in a user settings struct along with any other graphics settings (often set from qt ui) extern std::atomic g_hw_renderer_enabled; extern std::atomic g_shader_jit_enabled; +extern std::atomic g_scaled_resolution_enabled; /// Start the video core void Start(); From 22f3a7e94ce0e325a8c3dfeb0814c4b82a42649d Mon Sep 17 00:00:00 2001 From: tfarley Date: Sat, 16 Apr 2016 18:57:57 -0400 Subject: [PATCH 072/104] HWRasterizer: Texture forwarding --- src/core/hle/service/fs/archive.cpp | 1 + src/core/hle/service/gsp_gpu.cpp | 31 +- src/core/hle/service/y2r_u.cpp | 10 +- src/core/hw/gpu.cpp | 351 ++++---- src/core/hw/gpu.h | 4 +- src/core/memory.cpp | 140 +++ src/core/memory.h | 16 + src/video_core/debug_utils/debug_utils.cpp | 4 +- src/video_core/pica.h | 2 +- src/video_core/rasterizer_interface.h | 31 +- src/video_core/renderer_base.cpp | 2 - .../renderer_opengl/gl_rasterizer.cpp | 851 +++++++----------- .../renderer_opengl/gl_rasterizer.h | 76 +- .../renderer_opengl/gl_rasterizer_cache.cpp | 719 ++++++++++++++- .../renderer_opengl/gl_rasterizer_cache.h | 215 ++++- src/video_core/renderer_opengl/gl_state.cpp | 63 +- src/video_core/renderer_opengl/gl_state.h | 25 +- .../renderer_opengl/renderer_opengl.cpp | 128 +-- .../renderer_opengl/renderer_opengl.h | 44 +- src/video_core/swrasterizer.h | 6 +- 20 files changed, 1749 insertions(+), 970 deletions(-) diff --git a/src/core/hle/service/fs/archive.cpp b/src/core/hle/service/fs/archive.cpp index e9588cb72..cc51ede0c 100644 --- a/src/core/hle/service/fs/archive.cpp +++ b/src/core/hle/service/fs/archive.cpp @@ -114,6 +114,7 @@ ResultVal File::SyncRequest() { return read.Code(); } cmd_buff[2] = static_cast(*read); + Memory::RasterizerFlushAndInvalidateRegion(Memory::VirtualToPhysicalAddress(address), length); break; } diff --git a/src/core/hle/service/gsp_gpu.cpp b/src/core/hle/service/gsp_gpu.cpp index 0c655395e..211fcf599 100644 --- a/src/core/hle/service/gsp_gpu.cpp +++ b/src/core/hle/service/gsp_gpu.cpp @@ -4,6 +4,7 @@ #include "common/bit_field.h" #include "common/microprofile.h" +#include "common/profiler.h" #include "core/memory.h" #include "core/hle/kernel/event.h" @@ -15,8 +16,6 @@ #include "video_core/gpu_debugger.h" #include "video_core/debug_utils/debug_utils.h" -#include "video_core/renderer_base.h" -#include "video_core/video_core.h" #include "gsp_gpu.h" @@ -291,8 +290,6 @@ static void FlushDataCache(Service::Interface* self) { u32 size = cmd_buff[2]; u32 process = cmd_buff[4]; - VideoCore::g_renderer->Rasterizer()->InvalidateRegion(Memory::VirtualToPhysicalAddress(address), size); - // TODO(purpasmart96): Verify return header on HW cmd_buff[1] = RESULT_SUCCESS.raw; // No error @@ -408,6 +405,8 @@ void SignalInterrupt(InterruptId interrupt_id) { g_interrupt_event->Signal(); } +MICROPROFILE_DEFINE(GPU_GSP_DMA, "GPU", "GSP DMA", MP_RGB(100, 0, 255)); + /// Executes the next GSP command static void ExecuteCommand(const Command& command, u32 thread_id) { // Utility function to convert register ID to address @@ -419,18 +418,21 @@ static void ExecuteCommand(const Command& command, u32 thread_id) { // GX request DMA - typically used for copying memory from GSP heap to VRAM case CommandId::REQUEST_DMA: - VideoCore::g_renderer->Rasterizer()->FlushRegion(Memory::VirtualToPhysicalAddress(command.dma_request.source_address), - command.dma_request.size); + { + MICROPROFILE_SCOPE(GPU_GSP_DMA); + + // TODO: Consider attempting rasterizer-accelerated surface blit if that usage is ever possible/likely + Memory::RasterizerFlushRegion(Memory::VirtualToPhysicalAddress(command.dma_request.source_address), + command.dma_request.size); + Memory::RasterizerFlushAndInvalidateRegion(Memory::VirtualToPhysicalAddress(command.dma_request.dest_address), + command.dma_request.size); memcpy(Memory::GetPointer(command.dma_request.dest_address), Memory::GetPointer(command.dma_request.source_address), command.dma_request.size); SignalInterrupt(InterruptId::DMA); - - VideoCore::g_renderer->Rasterizer()->InvalidateRegion(Memory::VirtualToPhysicalAddress(command.dma_request.dest_address), - command.dma_request.size); break; - + } // TODO: This will need some rework in the future. (why?) case CommandId::SUBMIT_GPU_CMDLIST: { @@ -517,13 +519,8 @@ static void ExecuteCommand(const Command& command, u32 thread_id) { case CommandId::CACHE_FLUSH: { - for (auto& region : command.cache_flush.regions) { - if (region.size == 0) - break; - - VideoCore::g_renderer->Rasterizer()->InvalidateRegion( - Memory::VirtualToPhysicalAddress(region.address), region.size); - } + // NOTE: Rasterizer flushing handled elsewhere in CPU read/write and other GPU handlers + // Use command.cache_flush.regions to implement this handler break; } diff --git a/src/core/hle/service/y2r_u.cpp b/src/core/hle/service/y2r_u.cpp index 22f373adf..1672ad775 100644 --- a/src/core/hle/service/y2r_u.cpp +++ b/src/core/hle/service/y2r_u.cpp @@ -12,9 +12,6 @@ #include "core/hle/service/y2r_u.h" #include "core/hw/y2r.h" -#include "video_core/renderer_base.h" -#include "video_core/video_core.h" - //////////////////////////////////////////////////////////////////////////////////////////////////// // Namespace Y2R_U @@ -262,13 +259,12 @@ static void SetAlpha(Service::Interface* self) { static void StartConversion(Service::Interface* self) { u32* cmd_buff = Kernel::GetCommandBuffer(); - HW::Y2R::PerformConversion(conversion); - // dst_image_size would seem to be perfect for this, but it doesn't include the gap :( u32 total_output_size = conversion.input_lines * (conversion.dst.transfer_unit + conversion.dst.gap); - VideoCore::g_renderer->Rasterizer()->InvalidateRegion( - Memory::VirtualToPhysicalAddress(conversion.dst.address), total_output_size); + Memory::RasterizerFlushAndInvalidateRegion(Memory::VirtualToPhysicalAddress(conversion.dst.address), total_output_size); + + HW::Y2R::PerformConversion(conversion); LOG_DEBUG(Service_Y2R, "called"); completion_event->Signal(); diff --git a/src/core/hw/gpu.cpp b/src/core/hw/gpu.cpp index 7e2f9cdfa..2fe856293 100644 --- a/src/core/hw/gpu.cpp +++ b/src/core/hw/gpu.cpp @@ -115,21 +115,39 @@ inline void Write(u32 addr, const T data) { u8* start = Memory::GetPhysicalPointer(config.GetStartAddress()); u8* end = Memory::GetPhysicalPointer(config.GetEndAddress()); - if (config.fill_24bit) { - // fill with 24-bit values - for (u8* ptr = start; ptr < end; ptr += 3) { - ptr[0] = config.value_24bit_r; - ptr[1] = config.value_24bit_g; - ptr[2] = config.value_24bit_b; + // TODO: Consider always accelerating and returning vector of + // regions that the accelerated fill did not cover to + // reduce/eliminate the fill that the cpu has to do. + // This would also mean that the flush below is not needed. + // Fill should first flush all surfaces that touch but are + // not completely within the fill range. + // Then fill all completely covered surfaces, and return the + // regions that were between surfaces or within the touching + // ones for cpu to manually fill here. + if (!VideoCore::g_renderer->Rasterizer()->AccelerateFill(config)) { + Memory::RasterizerFlushAndInvalidateRegion(config.GetStartAddress(), config.GetEndAddress() - config.GetStartAddress()); + + if (config.fill_24bit) { + // fill with 24-bit values + for (u8* ptr = start; ptr < end; ptr += 3) { + ptr[0] = config.value_24bit_r; + ptr[1] = config.value_24bit_g; + ptr[2] = config.value_24bit_b; + } + } else if (config.fill_32bit) { + // fill with 32-bit values + if (end > start) { + u32 value = config.value_32bit; + size_t len = (end - start) / sizeof(u32); + for (size_t i = 0; i < len; ++i) + memcpy(&start[i * sizeof(u32)], &value, sizeof(u32)); + } + } else { + // fill with 16-bit values + u16 value_16bit = config.value_16bit.Value(); + for (u8* ptr = start; ptr < end; ptr += sizeof(u16)) + memcpy(ptr, &value_16bit, sizeof(u16)); } - } else if (config.fill_32bit) { - // fill with 32-bit values - for (u32* ptr = (u32*)start; ptr < (u32*)end; ++ptr) - *ptr = config.value_32bit; - } else { - // fill with 16-bit values - for (u16* ptr = (u16*)start; ptr < (u16*)end; ++ptr) - *ptr = config.value_16bit; } LOG_TRACE(HW_GPU, "MemoryFill from 0x%08x to 0x%08x", config.GetStartAddress(), config.GetEndAddress()); @@ -139,8 +157,6 @@ inline void Write(u32 addr, const T data) { } else { GSP_GPU::SignalInterrupt(GSP_GPU::InterruptId::PSC1); } - - VideoCore::g_renderer->Rasterizer()->InvalidateRegion(config.GetStartAddress(), config.GetEndAddress() - config.GetStartAddress()); } // Reset "trigger" flag and set the "finish" flag @@ -161,184 +177,185 @@ inline void Write(u32 addr, const T data) { if (Pica::g_debug_context) Pica::g_debug_context->OnEvent(Pica::DebugContext::Event::IncomingDisplayTransfer, nullptr); - u8* src_pointer = Memory::GetPhysicalPointer(config.GetPhysicalInputAddress()); - u8* dst_pointer = Memory::GetPhysicalPointer(config.GetPhysicalOutputAddress()); + if (!VideoCore::g_renderer->Rasterizer()->AccelerateDisplayTransfer(config)) { + u8* src_pointer = Memory::GetPhysicalPointer(config.GetPhysicalInputAddress()); + u8* dst_pointer = Memory::GetPhysicalPointer(config.GetPhysicalOutputAddress()); - if (config.is_texture_copy) { - u32 input_width = config.texture_copy.input_width * 16; - u32 input_gap = config.texture_copy.input_gap * 16; - u32 output_width = config.texture_copy.output_width * 16; - u32 output_gap = config.texture_copy.output_gap * 16; + if (config.is_texture_copy) { + u32 input_width = config.texture_copy.input_width * 16; + u32 input_gap = config.texture_copy.input_gap * 16; + u32 output_width = config.texture_copy.output_width * 16; + u32 output_gap = config.texture_copy.output_gap * 16; - size_t contiguous_input_size = config.texture_copy.size / input_width * (input_width + input_gap); - VideoCore::g_renderer->Rasterizer()->FlushRegion(config.GetPhysicalInputAddress(), contiguous_input_size); + size_t contiguous_input_size = config.texture_copy.size / input_width * (input_width + input_gap); + Memory::RasterizerFlushRegion(config.GetPhysicalInputAddress(), contiguous_input_size); - u32 remaining_size = config.texture_copy.size; - u32 remaining_input = input_width; - u32 remaining_output = output_width; - while (remaining_size > 0) { - u32 copy_size = std::min({ remaining_input, remaining_output, remaining_size }); + size_t contiguous_output_size = config.texture_copy.size / output_width * (output_width + output_gap); + Memory::RasterizerFlushAndInvalidateRegion(config.GetPhysicalOutputAddress(), contiguous_output_size); - std::memcpy(dst_pointer, src_pointer, copy_size); - src_pointer += copy_size; - dst_pointer += copy_size; + u32 remaining_size = config.texture_copy.size; + u32 remaining_input = input_width; + u32 remaining_output = output_width; + while (remaining_size > 0) { + u32 copy_size = std::min({ remaining_input, remaining_output, remaining_size }); - remaining_input -= copy_size; - remaining_output -= copy_size; - remaining_size -= copy_size; + std::memcpy(dst_pointer, src_pointer, copy_size); + src_pointer += copy_size; + dst_pointer += copy_size; - if (remaining_input == 0) { - remaining_input = input_width; - src_pointer += input_gap; - } - if (remaining_output == 0) { - remaining_output = output_width; - dst_pointer += output_gap; - } - } + remaining_input -= copy_size; + remaining_output -= copy_size; + remaining_size -= copy_size; - LOG_TRACE(HW_GPU, "TextureCopy: 0x%X bytes from 0x%08X(%u+%u)-> 0x%08X(%u+%u), flags 0x%08X", - config.texture_copy.size, - config.GetPhysicalInputAddress(), input_width, input_gap, - config.GetPhysicalOutputAddress(), output_width, output_gap, - config.flags); - - size_t contiguous_output_size = config.texture_copy.size / output_width * (output_width + output_gap); - VideoCore::g_renderer->Rasterizer()->InvalidateRegion(config.GetPhysicalOutputAddress(), contiguous_output_size); - - GSP_GPU::SignalInterrupt(GSP_GPU::InterruptId::PPF); - break; - } - - if (config.scaling > config.ScaleXY) { - LOG_CRITICAL(HW_GPU, "Unimplemented display transfer scaling mode %u", config.scaling.Value()); - UNIMPLEMENTED(); - break; - } - - if (config.input_linear && config.scaling != config.NoScale) { - LOG_CRITICAL(HW_GPU, "Scaling is only implemented on tiled input"); - UNIMPLEMENTED(); - break; - } - - bool horizontal_scale = config.scaling != config.NoScale; - bool vertical_scale = config.scaling == config.ScaleXY; - - u32 output_width = config.output_width >> horizontal_scale; - u32 output_height = config.output_height >> vertical_scale; - - u32 input_size = config.input_width * config.input_height * GPU::Regs::BytesPerPixel(config.input_format); - u32 output_size = output_width * output_height * GPU::Regs::BytesPerPixel(config.output_format); - - VideoCore::g_renderer->Rasterizer()->FlushRegion(config.GetPhysicalInputAddress(), input_size); - - for (u32 y = 0; y < output_height; ++y) { - for (u32 x = 0; x < output_width; ++x) { - Math::Vec4 src_color; - - // Calculate the [x,y] position of the input image - // based on the current output position and the scale - u32 input_x = x << horizontal_scale; - u32 input_y = y << vertical_scale; - - if (config.flip_vertically) { - // Flip the y value of the output data, - // we do this after calculating the [x,y] position of the input image - // to account for the scaling options. - y = output_height - y - 1; - } - - u32 dst_bytes_per_pixel = GPU::Regs::BytesPerPixel(config.output_format); - u32 src_bytes_per_pixel = GPU::Regs::BytesPerPixel(config.input_format); - u32 src_offset; - u32 dst_offset; - - if (config.input_linear) { - if (!config.dont_swizzle) { - // Interpret the input as linear and the output as tiled - u32 coarse_y = y & ~7; - u32 stride = output_width * dst_bytes_per_pixel; - - src_offset = (input_x + input_y * config.input_width) * src_bytes_per_pixel; - dst_offset = VideoCore::GetMortonOffset(x, y, dst_bytes_per_pixel) + coarse_y * stride; - } else { - // Both input and output are linear - src_offset = (input_x + input_y * config.input_width) * src_bytes_per_pixel; - dst_offset = (x + y * output_width) * dst_bytes_per_pixel; + if (remaining_input == 0) { + remaining_input = input_width; + src_pointer += input_gap; } - } else { - if (!config.dont_swizzle) { - // Interpret the input as tiled and the output as linear - u32 coarse_y = input_y & ~7; - u32 stride = config.input_width * src_bytes_per_pixel; - - src_offset = VideoCore::GetMortonOffset(input_x, input_y, src_bytes_per_pixel) + coarse_y * stride; - dst_offset = (x + y * output_width) * dst_bytes_per_pixel; - } else { - // Both input and output are tiled - u32 out_coarse_y = y & ~7; - u32 out_stride = output_width * dst_bytes_per_pixel; - - u32 in_coarse_y = input_y & ~7; - u32 in_stride = config.input_width * src_bytes_per_pixel; - - src_offset = VideoCore::GetMortonOffset(input_x, input_y, src_bytes_per_pixel) + in_coarse_y * in_stride; - dst_offset = VideoCore::GetMortonOffset(x, y, dst_bytes_per_pixel) + out_coarse_y * out_stride; + if (remaining_output == 0) { + remaining_output = output_width; + dst_pointer += output_gap; } } - const u8* src_pixel = src_pointer + src_offset; - src_color = DecodePixel(config.input_format, src_pixel); - if (config.scaling == config.ScaleX) { - Math::Vec4 pixel = DecodePixel(config.input_format, src_pixel + src_bytes_per_pixel); - src_color = ((src_color + pixel) / 2).Cast(); - } else if (config.scaling == config.ScaleXY) { - Math::Vec4 pixel1 = DecodePixel(config.input_format, src_pixel + 1 * src_bytes_per_pixel); - Math::Vec4 pixel2 = DecodePixel(config.input_format, src_pixel + 2 * src_bytes_per_pixel); - Math::Vec4 pixel3 = DecodePixel(config.input_format, src_pixel + 3 * src_bytes_per_pixel); - src_color = (((src_color + pixel1) + (pixel2 + pixel3)) / 4).Cast(); - } + LOG_TRACE(HW_GPU, "TextureCopy: 0x%X bytes from 0x%08X(%u+%u)-> 0x%08X(%u+%u), flags 0x%08X", + config.texture_copy.size, + config.GetPhysicalInputAddress(), input_width, input_gap, + config.GetPhysicalOutputAddress(), output_width, output_gap, + config.flags); - u8* dst_pixel = dst_pointer + dst_offset; - switch (config.output_format) { - case Regs::PixelFormat::RGBA8: - Color::EncodeRGBA8(src_color, dst_pixel); - break; + GSP_GPU::SignalInterrupt(GSP_GPU::InterruptId::PPF); + break; + } - case Regs::PixelFormat::RGB8: - Color::EncodeRGB8(src_color, dst_pixel); - break; + if (config.scaling > config.ScaleXY) { + LOG_CRITICAL(HW_GPU, "Unimplemented display transfer scaling mode %u", config.scaling.Value()); + UNIMPLEMENTED(); + break; + } - case Regs::PixelFormat::RGB565: - Color::EncodeRGB565(src_color, dst_pixel); - break; + if (config.input_linear && config.scaling != config.NoScale) { + LOG_CRITICAL(HW_GPU, "Scaling is only implemented on tiled input"); + UNIMPLEMENTED(); + break; + } - case Regs::PixelFormat::RGB5A1: - Color::EncodeRGB5A1(src_color, dst_pixel); - break; + int horizontal_scale = config.scaling != config.NoScale ? 1 : 0; + int vertical_scale = config.scaling == config.ScaleXY ? 1 : 0; - case Regs::PixelFormat::RGBA4: - Color::EncodeRGBA4(src_color, dst_pixel); - break; + u32 output_width = config.output_width >> horizontal_scale; + u32 output_height = config.output_height >> vertical_scale; - default: - LOG_ERROR(HW_GPU, "Unknown destination framebuffer format %x", config.output_format.Value()); - break; + u32 input_size = config.input_width * config.input_height * GPU::Regs::BytesPerPixel(config.input_format); + u32 output_size = output_width * output_height * GPU::Regs::BytesPerPixel(config.output_format); + + Memory::RasterizerFlushRegion(config.GetPhysicalInputAddress(), input_size); + Memory::RasterizerFlushAndInvalidateRegion(config.GetPhysicalOutputAddress(), output_size); + + for (u32 y = 0; y < output_height; ++y) { + for (u32 x = 0; x < output_width; ++x) { + Math::Vec4 src_color; + + // Calculate the [x,y] position of the input image + // based on the current output position and the scale + u32 input_x = x << horizontal_scale; + u32 input_y = y << vertical_scale; + + if (config.flip_vertically) { + // Flip the y value of the output data, + // we do this after calculating the [x,y] position of the input image + // to account for the scaling options. + y = output_height - y - 1; + } + + u32 dst_bytes_per_pixel = GPU::Regs::BytesPerPixel(config.output_format); + u32 src_bytes_per_pixel = GPU::Regs::BytesPerPixel(config.input_format); + u32 src_offset; + u32 dst_offset; + + if (config.input_linear) { + if (!config.dont_swizzle) { + // Interpret the input as linear and the output as tiled + u32 coarse_y = y & ~7; + u32 stride = output_width * dst_bytes_per_pixel; + + src_offset = (input_x + input_y * config.input_width) * src_bytes_per_pixel; + dst_offset = VideoCore::GetMortonOffset(x, y, dst_bytes_per_pixel) + coarse_y * stride; + } else { + // Both input and output are linear + src_offset = (input_x + input_y * config.input_width) * src_bytes_per_pixel; + dst_offset = (x + y * output_width) * dst_bytes_per_pixel; + } + } else { + if (!config.dont_swizzle) { + // Interpret the input as tiled and the output as linear + u32 coarse_y = input_y & ~7; + u32 stride = config.input_width * src_bytes_per_pixel; + + src_offset = VideoCore::GetMortonOffset(input_x, input_y, src_bytes_per_pixel) + coarse_y * stride; + dst_offset = (x + y * output_width) * dst_bytes_per_pixel; + } else { + // Both input and output are tiled + u32 out_coarse_y = y & ~7; + u32 out_stride = output_width * dst_bytes_per_pixel; + + u32 in_coarse_y = input_y & ~7; + u32 in_stride = config.input_width * src_bytes_per_pixel; + + src_offset = VideoCore::GetMortonOffset(input_x, input_y, src_bytes_per_pixel) + in_coarse_y * in_stride; + dst_offset = VideoCore::GetMortonOffset(x, y, dst_bytes_per_pixel) + out_coarse_y * out_stride; + } + } + + const u8* src_pixel = src_pointer + src_offset; + src_color = DecodePixel(config.input_format, src_pixel); + if (config.scaling == config.ScaleX) { + Math::Vec4 pixel = DecodePixel(config.input_format, src_pixel + src_bytes_per_pixel); + src_color = ((src_color + pixel) / 2).Cast(); + } else if (config.scaling == config.ScaleXY) { + Math::Vec4 pixel1 = DecodePixel(config.input_format, src_pixel + 1 * src_bytes_per_pixel); + Math::Vec4 pixel2 = DecodePixel(config.input_format, src_pixel + 2 * src_bytes_per_pixel); + Math::Vec4 pixel3 = DecodePixel(config.input_format, src_pixel + 3 * src_bytes_per_pixel); + src_color = (((src_color + pixel1) + (pixel2 + pixel3)) / 4).Cast(); + } + + u8* dst_pixel = dst_pointer + dst_offset; + switch (config.output_format) { + case Regs::PixelFormat::RGBA8: + Color::EncodeRGBA8(src_color, dst_pixel); + break; + + case Regs::PixelFormat::RGB8: + Color::EncodeRGB8(src_color, dst_pixel); + break; + + case Regs::PixelFormat::RGB565: + Color::EncodeRGB565(src_color, dst_pixel); + break; + + case Regs::PixelFormat::RGB5A1: + Color::EncodeRGB5A1(src_color, dst_pixel); + break; + + case Regs::PixelFormat::RGBA4: + Color::EncodeRGBA4(src_color, dst_pixel); + break; + + default: + LOG_ERROR(HW_GPU, "Unknown destination framebuffer format %x", config.output_format.Value()); + break; + } } } - } - LOG_TRACE(HW_GPU, "DisplayTriggerTransfer: 0x%08x bytes from 0x%08x(%ux%u)-> 0x%08x(%ux%u), dst format %x, flags 0x%08X", + LOG_TRACE(HW_GPU, "DisplayTriggerTransfer: 0x%08x bytes from 0x%08x(%ux%u)-> 0x%08x(%ux%u), dst format %x, flags 0x%08X", config.output_height * output_width * GPU::Regs::BytesPerPixel(config.output_format), config.GetPhysicalInputAddress(), config.input_width.Value(), config.input_height.Value(), config.GetPhysicalOutputAddress(), output_width, output_height, config.output_format.Value(), config.flags); + } g_regs.display_transfer_config.trigger = 0; GSP_GPU::SignalInterrupt(GSP_GPU::InterruptId::PPF); - - VideoCore::g_renderer->Rasterizer()->InvalidateRegion(config.GetPhysicalOutputAddress(), output_size); } break; } diff --git a/src/core/hw/gpu.h b/src/core/hw/gpu.h index a00adbf53..da4c345b4 100644 --- a/src/core/hw/gpu.h +++ b/src/core/hw/gpu.h @@ -78,7 +78,7 @@ struct Regs { INSERT_PADDING_WORDS(0x4); - struct { + struct MemoryFillConfig { u32 address_start; u32 address_end; @@ -165,7 +165,7 @@ struct Regs { INSERT_PADDING_WORDS(0x169); - struct { + struct DisplayTransferConfig { u32 input_address; u32 output_address; diff --git a/src/core/memory.cpp b/src/core/memory.cpp index 7de5bd15d..ee9b69f81 100644 --- a/src/core/memory.cpp +++ b/src/core/memory.cpp @@ -15,6 +15,9 @@ #include "core/memory_setup.h" #include "core/mmio.h" +#include "video_core/renderer_base.h" +#include "video_core/video_core.h" + namespace Memory { enum class PageType { @@ -22,8 +25,12 @@ enum class PageType { Unmapped, /// Page is mapped to regular memory. This is the only type you can get pointers to. Memory, + /// Page is mapped to regular memory, but also needs to check for rasterizer cache flushing and invalidation + RasterizerCachedMemory, /// Page is mapped to a I/O region. Writing and reading to this page is handled by functions. Special, + /// Page is mapped to a I/O region, but also needs to check for rasterizer cache flushing and invalidation + RasterizerCachedSpecial, }; struct SpecialRegion { @@ -57,6 +64,12 @@ struct PageTable { * the corresponding entry in `pointers` MUST be set to null. */ std::array attributes; + + /** + * Indicates the number of externally cached resources touching a page that should be + * flushed before the memory is accessed + */ + std::array cached_res_count; }; /// Singular page table used for the singleton process @@ -72,8 +85,15 @@ static void MapPages(u32 base, u32 size, u8* memory, PageType type) { while (base != end) { ASSERT_MSG(base < PageTable::NUM_ENTRIES, "out of range mapping at %08X", base); + // Since pages are unmapped on shutdown after video core is shutdown, the renderer may be null here + if (current_page_table->attributes[base] == PageType::RasterizerCachedMemory || + current_page_table->attributes[base] == PageType::RasterizerCachedSpecial) { + RasterizerFlushAndInvalidateRegion(VirtualToPhysicalAddress(base << PAGE_BITS), PAGE_SIZE); + } + current_page_table->attributes[base] = type; current_page_table->pointers[base] = memory; + current_page_table->cached_res_count[base] = 0; base += 1; if (memory != nullptr) @@ -84,6 +104,7 @@ static void MapPages(u32 base, u32 size, u8* memory, PageType type) { void InitMemoryMap() { main_page_table.pointers.fill(nullptr); main_page_table.attributes.fill(PageType::Unmapped); + main_page_table.cached_res_count.fill(0); } void MapMemoryRegion(VAddr base, u32 size, u8* target) { @@ -106,6 +127,28 @@ void UnmapRegion(VAddr base, u32 size) { MapPages(base / PAGE_SIZE, size / PAGE_SIZE, nullptr, PageType::Unmapped); } +/** + * Gets a pointer to the exact memory at the virtual address (i.e. not page aligned) + * using a VMA from the current process + */ +static u8* GetPointerFromVMA(VAddr vaddr) { + u8* direct_pointer = nullptr; + + auto& vma = Kernel::g_current_process->vm_manager.FindVMA(vaddr)->second; + switch (vma.type) { + case Kernel::VMAType::AllocatedMemoryBlock: + direct_pointer = vma.backing_block->data() + vma.offset; + break; + case Kernel::VMAType::BackingMemory: + direct_pointer = vma.backing_memory; + break; + default: + UNREACHABLE(); + } + + return direct_pointer + (vaddr - vma.base); +} + /** * This function should only be called for virtual addreses with attribute `PageType::Special`. */ @@ -126,6 +169,7 @@ template T Read(const VAddr vaddr) { const u8* page_pointer = current_page_table->pointers[vaddr >> PAGE_BITS]; if (page_pointer) { + // NOTE: Avoid adding any extra logic to this fast-path block T value; std::memcpy(&value, &page_pointer[vaddr & PAGE_MASK], sizeof(T)); return value; @@ -139,8 +183,22 @@ T Read(const VAddr vaddr) { case PageType::Memory: ASSERT_MSG(false, "Mapped memory page without a pointer @ %08X", vaddr); break; + case PageType::RasterizerCachedMemory: + { + RasterizerFlushRegion(VirtualToPhysicalAddress(vaddr), sizeof(T)); + + T value; + std::memcpy(&value, GetPointerFromVMA(vaddr), sizeof(T)); + return value; + } case PageType::Special: return ReadMMIO(GetMMIOHandler(vaddr), vaddr); + case PageType::RasterizerCachedSpecial: + { + RasterizerFlushRegion(VirtualToPhysicalAddress(vaddr), sizeof(T)); + + return ReadMMIO(GetMMIOHandler(vaddr), vaddr); + } default: UNREACHABLE(); } @@ -153,6 +211,7 @@ template void Write(const VAddr vaddr, const T data) { u8* page_pointer = current_page_table->pointers[vaddr >> PAGE_BITS]; if (page_pointer) { + // NOTE: Avoid adding any extra logic to this fast-path block std::memcpy(&page_pointer[vaddr & PAGE_MASK], &data, sizeof(T)); return; } @@ -165,9 +224,23 @@ void Write(const VAddr vaddr, const T data) { case PageType::Memory: ASSERT_MSG(false, "Mapped memory page without a pointer @ %08X", vaddr); break; + case PageType::RasterizerCachedMemory: + { + RasterizerFlushAndInvalidateRegion(VirtualToPhysicalAddress(vaddr), sizeof(T)); + + std::memcpy(GetPointerFromVMA(vaddr), &data, sizeof(T)); + break; + } case PageType::Special: WriteMMIO(GetMMIOHandler(vaddr), vaddr, data); break; + case PageType::RasterizerCachedSpecial: + { + RasterizerFlushAndInvalidateRegion(VirtualToPhysicalAddress(vaddr), sizeof(T)); + + WriteMMIO(GetMMIOHandler(vaddr), vaddr, data); + break; + } default: UNREACHABLE(); } @@ -179,6 +252,10 @@ u8* GetPointer(const VAddr vaddr) { return page_pointer + (vaddr & PAGE_MASK); } + if (current_page_table->attributes[vaddr >> PAGE_BITS] == PageType::RasterizerCachedMemory) { + return GetPointerFromVMA(vaddr); + } + LOG_ERROR(HW_Memory, "unknown GetPointer @ 0x%08x", vaddr); return nullptr; } @@ -187,6 +264,69 @@ u8* GetPhysicalPointer(PAddr address) { return GetPointer(PhysicalToVirtualAddress(address)); } +void RasterizerMarkRegionCached(PAddr start, u32 size, int count_delta) { + if (start == 0) { + return; + } + + u32 num_pages = ((start + size - 1) >> PAGE_BITS) - (start >> PAGE_BITS) + 1; + PAddr paddr = start; + + for (unsigned i = 0; i < num_pages; ++i) { + VAddr vaddr = PhysicalToVirtualAddress(paddr); + u8& res_count = current_page_table->cached_res_count[vaddr >> PAGE_BITS]; + ASSERT_MSG(count_delta <= UINT8_MAX - res_count, "Rasterizer resource cache counter overflow!"); + ASSERT_MSG(count_delta >= -res_count, "Rasterizer resource cache counter underflow!"); + + // Switch page type to cached if now cached + if (res_count == 0) { + PageType& page_type = current_page_table->attributes[vaddr >> PAGE_BITS]; + switch (page_type) { + case PageType::Memory: + page_type = PageType::RasterizerCachedMemory; + current_page_table->pointers[vaddr >> PAGE_BITS] = nullptr; + break; + case PageType::Special: + page_type = PageType::RasterizerCachedSpecial; + break; + default: + UNREACHABLE(); + } + } + + res_count += count_delta; + + // Switch page type to uncached if now uncached + if (res_count == 0) { + PageType& page_type = current_page_table->attributes[vaddr >> PAGE_BITS]; + switch (page_type) { + case PageType::RasterizerCachedMemory: + page_type = PageType::Memory; + current_page_table->pointers[vaddr >> PAGE_BITS] = GetPointerFromVMA(vaddr & ~PAGE_MASK); + break; + case PageType::RasterizerCachedSpecial: + page_type = PageType::Special; + break; + default: + UNREACHABLE(); + } + } + paddr += PAGE_SIZE; + } +} + +void RasterizerFlushRegion(PAddr start, u32 size) { + if (VideoCore::g_renderer != nullptr) { + VideoCore::g_renderer->Rasterizer()->FlushRegion(start, size); + } +} + +void RasterizerFlushAndInvalidateRegion(PAddr start, u32 size) { + if (VideoCore::g_renderer != nullptr) { + VideoCore::g_renderer->Rasterizer()->FlushAndInvalidateRegion(start, size); + } +} + u8 Read8(const VAddr addr) { return Read(addr); } diff --git a/src/core/memory.h b/src/core/memory.h index 5af72b7a7..9caa3c3f5 100644 --- a/src/core/memory.h +++ b/src/core/memory.h @@ -148,4 +148,20 @@ VAddr PhysicalToVirtualAddress(PAddr addr); */ u8* GetPhysicalPointer(PAddr address); +/** + * Adds the supplied value to the rasterizer resource cache counter of each + * page touching the region. + */ +void RasterizerMarkRegionCached(PAddr start, u32 size, int count_delta); + +/** + * Flushes any externally cached rasterizer resources touching the given region. + */ +void RasterizerFlushRegion(PAddr start, u32 size); + +/** + * Flushes and invalidates any externally cached rasterizer resources touching the given region. + */ +void RasterizerFlushAndInvalidateRegion(PAddr start, u32 size); + } diff --git a/src/video_core/debug_utils/debug_utils.cpp b/src/video_core/debug_utils/debug_utils.cpp index c3a9c9598..1f058c4e2 100644 --- a/src/video_core/debug_utils/debug_utils.cpp +++ b/src/video_core/debug_utils/debug_utils.cpp @@ -47,8 +47,8 @@ void DebugContext::OnEvent(Event event, void* data) { { std::unique_lock lock(breakpoint_mutex); - // Commit the hardware renderer's framebuffer so it will show on debug widgets - VideoCore::g_renderer->Rasterizer()->FlushFramebuffer(); + // Commit the rasterizer's caches so framebuffers, render targets, etc. will show on debug widgets + VideoCore::g_renderer->Rasterizer()->FlushAll(); // TODO: Should stop the CPU thread here once we multithread emulation. diff --git a/src/video_core/pica.h b/src/video_core/pica.h index 4552ff81c..1810eca98 100644 --- a/src/video_core/pica.h +++ b/src/video_core/pica.h @@ -577,7 +577,7 @@ struct Regs { } } - struct { + struct FramebufferConfig { INSERT_PADDING_WORDS(0x3); union { diff --git a/src/video_core/rasterizer_interface.h b/src/video_core/rasterizer_interface.h index 008c5827b..bf7101665 100644 --- a/src/video_core/rasterizer_interface.h +++ b/src/video_core/rasterizer_interface.h @@ -6,6 +6,10 @@ #include "common/common_types.h" +#include "core/hw/gpu.h" + +struct ScreenInfo; + namespace Pica { namespace Shader { struct OutputVertex; @@ -18,12 +22,6 @@ class RasterizerInterface { public: virtual ~RasterizerInterface() {} - /// Initialize API-specific GPU objects - virtual void InitObjects() = 0; - - /// Reset the rasterizer, such as flushing all caches and updating all state - virtual void Reset() = 0; - /// Queues the primitive formed by the given vertices for rendering virtual void AddTriangle(const Pica::Shader::OutputVertex& v0, const Pica::Shader::OutputVertex& v1, @@ -32,17 +30,26 @@ public: /// Draw the current batch of triangles virtual void DrawTriangles() = 0; - /// Commit the rasterizer's framebuffer contents immediately to the current 3DS memory framebuffer - virtual void FlushFramebuffer() = 0; - /// Notify rasterizer that the specified PICA register has been changed virtual void NotifyPicaRegisterChanged(u32 id) = 0; - /// Notify rasterizer that any caches of the specified region should be flushed to 3DS memory. + /// Notify rasterizer that all caches should be flushed to 3DS memory + virtual void FlushAll() = 0; + + /// Notify rasterizer that any caches of the specified region should be flushed to 3DS memory virtual void FlushRegion(PAddr addr, u32 size) = 0; - /// Notify rasterizer that any caches of the specified region should be discraded and reloaded from 3DS memory. - virtual void InvalidateRegion(PAddr addr, u32 size) = 0; + /// Notify rasterizer that any caches of the specified region should be flushed to 3DS memory and invalidated + virtual void FlushAndInvalidateRegion(PAddr addr, u32 size) = 0; + + /// Attempt to use a faster method to perform a display transfer + virtual bool AccelerateDisplayTransfer(const GPU::Regs::DisplayTransferConfig& config) { return false; } + + /// Attempt to use a faster method to fill a region + virtual bool AccelerateFill(const GPU::Regs::MemoryFillConfig& config) { return false; } + + /// Attempt to use a faster method to display the framebuffer to screen + virtual bool AccelerateDisplay(const GPU::Regs::FramebufferConfig& config, PAddr framebuffer_addr, u32 pixel_stride, ScreenInfo& screen_info) { return false; } }; } diff --git a/src/video_core/renderer_base.cpp b/src/video_core/renderer_base.cpp index 101f84eb9..ccd497de0 100644 --- a/src/video_core/renderer_base.cpp +++ b/src/video_core/renderer_base.cpp @@ -21,7 +21,5 @@ void RendererBase::RefreshRasterizerSetting() { } else { rasterizer = std::make_unique(); } - rasterizer->InitObjects(); - rasterizer->Reset(); } } diff --git a/src/video_core/renderer_opengl/gl_rasterizer.cpp b/src/video_core/renderer_opengl/gl_rasterizer.cpp index 6ca9f45e2..da4121c35 100644 --- a/src/video_core/renderer_opengl/gl_rasterizer.cpp +++ b/src/video_core/renderer_opengl/gl_rasterizer.cpp @@ -36,10 +36,7 @@ static bool IsPassThroughTevStage(const Pica::Regs::TevStageConfig& stage) { stage.GetAlphaMultiplier() == 1); } -RasterizerOpenGL::RasterizerOpenGL() : cached_fb_color_addr(0), cached_fb_depth_addr(0) { } -RasterizerOpenGL::~RasterizerOpenGL() { } - -void RasterizerOpenGL::InitObjects() { +RasterizerOpenGL::RasterizerOpenGL() : shader_dirty(true) { // Create sampler objects for (size_t i = 0; i < texture_samplers.size(); ++i) { texture_samplers[i].Create(); @@ -61,6 +58,10 @@ void RasterizerOpenGL::InitObjects() { uniform_block_data.dirty = true; + for (unsigned index = 0; index < lighting_luts.size(); index++) { + uniform_block_data.lut_dirty[index] = true; + } + // Set vertex attributes glVertexAttribPointer(GLShader::ATTRIBUTE_POSITION, 4, GL_FLOAT, GL_FALSE, sizeof(HardwareVertex), (GLvoid*)offsetof(HardwareVertex, position)); glEnableVertexAttribArray(GLShader::ATTRIBUTE_POSITION); @@ -81,70 +82,24 @@ void RasterizerOpenGL::InitObjects() { glVertexAttribPointer(GLShader::ATTRIBUTE_VIEW, 3, GL_FLOAT, GL_FALSE, sizeof(HardwareVertex), (GLvoid*)offsetof(HardwareVertex, view)); glEnableVertexAttribArray(GLShader::ATTRIBUTE_VIEW); - SetShader(); - - // Create textures for OGL framebuffer that will be rendered to, initially 1x1 to succeed in framebuffer creation - fb_color_texture.texture.Create(); - ReconfigureColorTexture(fb_color_texture, Pica::Regs::ColorFormat::RGBA8, 1, 1); - - state.texture_units[0].texture_2d = fb_color_texture.texture.handle; - state.Apply(); - - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, 0); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); - - state.texture_units[0].texture_2d = 0; - state.Apply(); - - fb_depth_texture.texture.Create(); - ReconfigureDepthTexture(fb_depth_texture, Pica::Regs::DepthFormat::D16, 1, 1); - - state.texture_units[0].texture_2d = fb_depth_texture.texture.handle; - state.Apply(); - - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, 0); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_FUNC, GL_LEQUAL); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE, GL_NONE); - - state.texture_units[0].texture_2d = 0; - state.Apply(); - - // Configure OpenGL framebuffer + // Create render framebuffer framebuffer.Create(); - state.draw.framebuffer = framebuffer.handle; + // Allocate and bind lighting lut textures + for (size_t i = 0; i < lighting_luts.size(); ++i) { + lighting_luts[i].Create(); + state.lighting_luts[i].texture_1d = lighting_luts[i].handle; + } state.Apply(); - glActiveTexture(GL_TEXTURE0); - glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, fb_color_texture.texture.handle, 0); - glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, fb_depth_texture.texture.handle, 0); - - for (size_t i = 0; i < lighting_lut.size(); ++i) { - lighting_lut[i].Create(); - state.lighting_lut[i].texture_1d = lighting_lut[i].handle; - + for (size_t i = 0; i < lighting_luts.size(); ++i) { glActiveTexture(GL_TEXTURE3 + i); - glBindTexture(GL_TEXTURE_1D, state.lighting_lut[i].texture_1d); - glTexImage1D(GL_TEXTURE_1D, 0, GL_RGBA32F, 256, 0, GL_RGBA, GL_FLOAT, nullptr); glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); } - state.Apply(); - GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER); - ASSERT_MSG(status == GL_FRAMEBUFFER_COMPLETE, - "OpenGL rasterizer framebuffer setup failed, status %X", status); -} - -void RasterizerOpenGL::Reset() { + // Sync fixed function OpenGL state SyncCullMode(); SyncDepthModifiers(); SyncBlendEnabled(); @@ -156,10 +111,10 @@ void RasterizerOpenGL::Reset() { SyncColorWriteMask(); SyncStencilWriteMask(); SyncDepthWriteMask(); +} - SetShader(); +RasterizerOpenGL::~RasterizerOpenGL() { - res_cache.InvalidateAll(); } /** @@ -196,47 +151,98 @@ void RasterizerOpenGL::DrawTriangles() { if (vertex_batch.empty()) return; - SyncFramebuffer(); - SyncDrawState(); + const auto& regs = Pica::g_state.regs; - if (state.draw.shader_dirty) { - SetShader(); - state.draw.shader_dirty = false; + // Sync and bind the framebuffer surfaces + CachedSurface* color_surface; + CachedSurface* depth_surface; + MathUtil::Rectangle rect; + std::tie(color_surface, depth_surface, rect) = res_cache.GetFramebufferSurfaces(regs.framebuffer); + + state.draw.draw_framebuffer = framebuffer.handle; + state.Apply(); + + glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, color_surface != nullptr ? color_surface->texture.handle : 0, 0); + glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, depth_surface != nullptr ? depth_surface->texture.handle : 0, 0); + bool has_stencil = regs.framebuffer.depth_format == Pica::Regs::DepthFormat::D24S8; + glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_TEXTURE_2D, (has_stencil && depth_surface != nullptr) ? depth_surface->texture.handle : 0, 0); + + if (OpenGLState::CheckFBStatus(GL_DRAW_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) { + return; } - for (unsigned index = 0; index < lighting_lut.size(); index++) { + // Sync the viewport + // These registers hold half-width and half-height, so must be multiplied by 2 + GLsizei viewport_width = (GLsizei)Pica::float24::FromRaw(regs.viewport_size_x).ToFloat32() * 2; + GLsizei viewport_height = (GLsizei)Pica::float24::FromRaw(regs.viewport_size_y).ToFloat32() * 2; + + glViewport((GLint)(rect.left + regs.viewport_corner.x * color_surface->res_scale_width), + (GLint)(rect.bottom + regs.viewport_corner.y * color_surface->res_scale_height), + (GLsizei)(viewport_width * color_surface->res_scale_width), (GLsizei)(viewport_height * color_surface->res_scale_height)); + + // Sync and bind the texture surfaces + const auto pica_textures = regs.GetTextures(); + for (unsigned texture_index = 0; texture_index < pica_textures.size(); ++texture_index) { + const auto& texture = pica_textures[texture_index]; + + if (texture.enabled) { + texture_samplers[texture_index].SyncWithConfig(texture.config); + CachedSurface* surface = res_cache.GetTextureSurface(texture); + if (surface != nullptr) { + state.texture_units[texture_index].texture_2d = surface->texture.handle; + } else { + // Can occur when texture addr is null or its memory is unmapped/invalid + state.texture_units[texture_index].texture_2d = 0; + } + } else { + state.texture_units[texture_index].texture_2d = 0; + } + } + + // Sync and bind the shader + if (shader_dirty) { + SetShader(); + shader_dirty = false; + } + + // Sync the lighting luts + for (unsigned index = 0; index < lighting_luts.size(); index++) { if (uniform_block_data.lut_dirty[index]) { SyncLightingLUT(index); uniform_block_data.lut_dirty[index] = false; } } + // Sync the uniform data if (uniform_block_data.dirty) { glBufferData(GL_UNIFORM_BUFFER, sizeof(UniformData), &uniform_block_data.data, GL_STATIC_DRAW); uniform_block_data.dirty = false; } + state.Apply(); + + // Draw the vertex batch glBufferData(GL_ARRAY_BUFFER, vertex_batch.size() * sizeof(HardwareVertex), vertex_batch.data(), GL_STREAM_DRAW); glDrawArrays(GL_TRIANGLES, 0, (GLsizei)vertex_batch.size()); + // Mark framebuffer surfaces as dirty + // TODO: Restrict invalidation area to the viewport + if (color_surface != nullptr) { + color_surface->dirty = true; + res_cache.FlushRegion(color_surface->addr, color_surface->size, color_surface, true); + } + if (depth_surface != nullptr) { + depth_surface->dirty = true; + res_cache.FlushRegion(depth_surface->addr, depth_surface->size, depth_surface, true); + } + vertex_batch.clear(); - // Flush the resource cache at the current depth and color framebuffer addresses for render-to-texture - const auto& regs = Pica::g_state.regs; - - u32 cached_fb_color_size = Pica::Regs::BytesPerColorPixel(fb_color_texture.format) - * fb_color_texture.width * fb_color_texture.height; - - u32 cached_fb_depth_size = Pica::Regs::BytesPerDepthPixel(fb_depth_texture.format) - * fb_depth_texture.width * fb_depth_texture.height; - - res_cache.InvalidateInRange(cached_fb_color_addr, cached_fb_color_size, true); - res_cache.InvalidateInRange(cached_fb_depth_addr, cached_fb_depth_size, true); -} - -void RasterizerOpenGL::FlushFramebuffer() { - CommitColorBuffer(); - CommitDepthBuffer(); + // Unbind textures for potential future use as framebuffer attachments + for (unsigned texture_index = 0; texture_index < pica_textures.size(); ++texture_index) { + state.texture_units[texture_index].texture_2d = 0; + } + state.Apply(); } void RasterizerOpenGL::NotifyPicaRegisterChanged(u32 id) { @@ -268,7 +274,7 @@ void RasterizerOpenGL::NotifyPicaRegisterChanged(u32 id) { // Alpha test case PICA_REG_INDEX(output_merger.alpha_test): SyncAlphaTest(); - state.draw.shader_dirty = true; + shader_dirty = true; break; // Sync GL stencil test + stencil write mask @@ -334,7 +340,7 @@ void RasterizerOpenGL::NotifyPicaRegisterChanged(u32 id) { case PICA_REG_INDEX(tev_stage5.color_op): case PICA_REG_INDEX(tev_stage5.color_scale): case PICA_REG_INDEX(tev_combiner_buffer_input): - state.draw.shader_dirty = true; + shader_dirty = true; break; case PICA_REG_INDEX(tev_stage0.const_r): SyncTevConstColor(0, regs.tev_stage0); @@ -521,41 +527,257 @@ void RasterizerOpenGL::NotifyPicaRegisterChanged(u32 id) { } } -void RasterizerOpenGL::FlushRegion(PAddr addr, u32 size) { - const auto& regs = Pica::g_state.regs; - - u32 cached_fb_color_size = Pica::Regs::BytesPerColorPixel(fb_color_texture.format) - * fb_color_texture.width * fb_color_texture.height; - - u32 cached_fb_depth_size = Pica::Regs::BytesPerDepthPixel(fb_depth_texture.format) - * fb_depth_texture.width * fb_depth_texture.height; - - // If source memory region overlaps 3DS framebuffers, commit them before the copy happens - if (MathUtil::IntervalsIntersect(addr, size, cached_fb_color_addr, cached_fb_color_size)) - CommitColorBuffer(); - - if (MathUtil::IntervalsIntersect(addr, size, cached_fb_depth_addr, cached_fb_depth_size)) - CommitDepthBuffer(); +void RasterizerOpenGL::FlushAll() { + res_cache.FlushAll(); } -void RasterizerOpenGL::InvalidateRegion(PAddr addr, u32 size) { - const auto& regs = Pica::g_state.regs; +void RasterizerOpenGL::FlushRegion(PAddr addr, u32 size) { + res_cache.FlushRegion(addr, size, nullptr, false); +} - u32 cached_fb_color_size = Pica::Regs::BytesPerColorPixel(fb_color_texture.format) - * fb_color_texture.width * fb_color_texture.height; +void RasterizerOpenGL::FlushAndInvalidateRegion(PAddr addr, u32 size) { + res_cache.FlushRegion(addr, size, nullptr, true); +} - u32 cached_fb_depth_size = Pica::Regs::BytesPerDepthPixel(fb_depth_texture.format) - * fb_depth_texture.width * fb_depth_texture.height; +bool RasterizerOpenGL::AccelerateDisplayTransfer(const GPU::Regs::DisplayTransferConfig& config) { + using PixelFormat = CachedSurface::PixelFormat; + using SurfaceType = CachedSurface::SurfaceType; - // If modified memory region overlaps 3DS framebuffers, reload their contents into OpenGL - if (MathUtil::IntervalsIntersect(addr, size, cached_fb_color_addr, cached_fb_color_size)) - ReloadColorBuffer(); + if (config.is_texture_copy) { + // TODO(tfarley): Try to hardware accelerate this + return false; + } - if (MathUtil::IntervalsIntersect(addr, size, cached_fb_depth_addr, cached_fb_depth_size)) - ReloadDepthBuffer(); + CachedSurface src_params; + src_params.addr = config.GetPhysicalInputAddress(); + src_params.width = config.output_width; + src_params.height = config.output_height; + src_params.is_tiled = !config.input_linear; + src_params.pixel_format = CachedSurface::PixelFormatFromGPUPixelFormat(config.input_format); - // Notify cache of flush in case the region touches a cached resource - res_cache.InvalidateInRange(addr, size); + CachedSurface dst_params; + dst_params.addr = config.GetPhysicalOutputAddress(); + dst_params.width = config.scaling != config.NoScale ? config.output_width / 2 : config.output_width.Value(); + dst_params.height = config.scaling == config.ScaleXY ? config.output_height / 2 : config.output_height.Value(); + dst_params.is_tiled = config.input_linear != config.dont_swizzle; + dst_params.pixel_format = CachedSurface::PixelFormatFromGPUPixelFormat(config.output_format); + + MathUtil::Rectangle src_rect; + CachedSurface* src_surface = res_cache.GetSurfaceRect(src_params, false, true, src_rect); + + if (src_surface == nullptr) { + return false; + } + + // Require destination surface to have same resolution scale as source to preserve scaling + dst_params.res_scale_width = src_surface->res_scale_width; + dst_params.res_scale_height = src_surface->res_scale_height; + + MathUtil::Rectangle dst_rect; + CachedSurface* dst_surface = res_cache.GetSurfaceRect(dst_params, true, false, dst_rect); + + if (dst_surface == nullptr) { + return false; + } + + // Don't accelerate if the src and dst surfaces are the same + if (src_surface == dst_surface) { + return false; + } + + if (config.flip_vertically) { + std::swap(dst_rect.top, dst_rect.bottom); + } + + if (!res_cache.TryBlitSurfaces(src_surface, src_rect, dst_surface, dst_rect)) { + return false; + } + + u32 dst_size = dst_params.width * dst_params.height * CachedSurface::GetFormatBpp(dst_params.pixel_format) / 8; + dst_surface->dirty = true; + res_cache.FlushRegion(config.GetPhysicalOutputAddress(), dst_size, dst_surface, true); + return true; +} + +bool RasterizerOpenGL::AccelerateFill(const GPU::Regs::MemoryFillConfig& config) { + using PixelFormat = CachedSurface::PixelFormat; + using SurfaceType = CachedSurface::SurfaceType; + + CachedSurface* dst_surface = res_cache.TryGetFillSurface(config); + + if (dst_surface == nullptr) { + return false; + } + + OpenGLState cur_state = OpenGLState::GetCurState(); + + SurfaceType dst_type = CachedSurface::GetFormatType(dst_surface->pixel_format); + + GLuint old_fb = cur_state.draw.draw_framebuffer; + cur_state.draw.draw_framebuffer = framebuffer.handle; + // TODO: When scissor test is implemented, need to disable scissor test in cur_state here so Clear call isn't affected + cur_state.Apply(); + + if (dst_type == SurfaceType::Color || dst_type == SurfaceType::Texture) { + glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, dst_surface->texture.handle, 0); + glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_TEXTURE_2D, 0, 0); + + if (OpenGLState::CheckFBStatus(GL_DRAW_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) { + return false; + } + + GLfloat color_values[4] = {0.0f, 0.0f, 0.0f, 0.0f}; + + // TODO: Handle additional pixel format and fill value size combinations to accelerate more cases + // For instance, checking if fill value's bytes/bits repeat to allow filling I8/A8/I4/A4/... + // Currently only handles formats that are multiples of the fill value size + + if (config.fill_24bit) { + switch (dst_surface->pixel_format) { + case PixelFormat::RGB8: + color_values[0] = config.value_24bit_r / 255.0f; + color_values[1] = config.value_24bit_g / 255.0f; + color_values[2] = config.value_24bit_b / 255.0f; + break; + default: + return false; + } + } else if (config.fill_32bit) { + u32 value = config.value_32bit; + + switch (dst_surface->pixel_format) { + case PixelFormat::RGBA8: + color_values[0] = (value >> 24) / 255.0f; + color_values[1] = ((value >> 16) & 0xFF) / 255.0f; + color_values[2] = ((value >> 8) & 0xFF) / 255.0f; + color_values[3] = (value & 0xFF) / 255.0f; + break; + default: + return false; + } + } else { + u16 value_16bit = config.value_16bit.Value(); + Math::Vec4 color; + + switch (dst_surface->pixel_format) { + case PixelFormat::RGBA8: + color_values[0] = (value_16bit >> 8) / 255.0f; + color_values[1] = (value_16bit & 0xFF) / 255.0f; + color_values[2] = color_values[0]; + color_values[3] = color_values[1]; + break; + case PixelFormat::RGB5A1: + color = Color::DecodeRGB5A1((const u8*)&value_16bit); + color_values[0] = color[0] / 31.0f; + color_values[1] = color[1] / 31.0f; + color_values[2] = color[2] / 31.0f; + color_values[3] = color[3]; + break; + case PixelFormat::RGB565: + color = Color::DecodeRGB565((const u8*)&value_16bit); + color_values[0] = color[0] / 31.0f; + color_values[1] = color[1] / 63.0f; + color_values[2] = color[2] / 31.0f; + break; + case PixelFormat::RGBA4: + color = Color::DecodeRGBA4((const u8*)&value_16bit); + color_values[0] = color[0] / 15.0f; + color_values[1] = color[1] / 15.0f; + color_values[2] = color[2] / 15.0f; + color_values[3] = color[3] / 15.0f; + break; + case PixelFormat::IA8: + case PixelFormat::RG8: + color_values[0] = (value_16bit >> 8) / 255.0f; + color_values[1] = (value_16bit & 0xFF) / 255.0f; + break; + default: + return false; + } + } + + cur_state.color_mask.red_enabled = true; + cur_state.color_mask.green_enabled = true; + cur_state.color_mask.blue_enabled = true; + cur_state.color_mask.alpha_enabled = true; + cur_state.Apply(); + glClearBufferfv(GL_COLOR, 0, color_values); + } else if (dst_type == SurfaceType::Depth) { + glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, 0, 0); + glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, dst_surface->texture.handle, 0); + glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_TEXTURE_2D, 0, 0); + + if (OpenGLState::CheckFBStatus(GL_DRAW_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) { + return false; + } + + GLfloat value_float; + if (dst_surface->pixel_format == CachedSurface::PixelFormat::D16) { + value_float = config.value_32bit / 65535.0f; // 2^16 - 1 + } else if (dst_surface->pixel_format == CachedSurface::PixelFormat::D24) { + value_float = config.value_32bit / 16777215.0f; // 2^24 - 1 + } + + cur_state.depth.write_mask = true; + cur_state.Apply(); + glClearBufferfv(GL_DEPTH, 0, &value_float); + } else if (dst_type == SurfaceType::DepthStencil) { + glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, 0, 0); + glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_TEXTURE_2D, dst_surface->texture.handle, 0); + + if (OpenGLState::CheckFBStatus(GL_DRAW_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) { + return false; + } + + GLfloat value_float = (config.value_32bit & 0xFFFFFF) / 16777215.0f; // 2^24 - 1 + GLint value_int = (config.value_32bit >> 24); + + cur_state.depth.write_mask = true; + cur_state.stencil.write_mask = true; + cur_state.Apply(); + glClearBufferfi(GL_DEPTH_STENCIL, 0, value_float, value_int); + } + + cur_state.draw.draw_framebuffer = old_fb; + // TODO: Return scissor test to previous value when scissor test is implemented + cur_state.Apply(); + + dst_surface->dirty = true; + res_cache.FlushRegion(dst_surface->addr, dst_surface->size, dst_surface, true); + return true; +} + +bool RasterizerOpenGL::AccelerateDisplay(const GPU::Regs::FramebufferConfig& config, PAddr framebuffer_addr, u32 pixel_stride, ScreenInfo& screen_info) { + if (framebuffer_addr == 0) { + return false; + } + + CachedSurface src_params; + src_params.addr = framebuffer_addr; + src_params.width = config.width; + src_params.height = config.height; + src_params.stride = pixel_stride; + src_params.is_tiled = false; + src_params.pixel_format = CachedSurface::PixelFormatFromGPUPixelFormat(config.color_format); + + MathUtil::Rectangle src_rect; + CachedSurface* src_surface = res_cache.GetSurfaceRect(src_params, false, true, src_rect); + + if (src_surface == nullptr) { + return false; + } + + u32 scaled_width = src_surface->GetScaledWidth(); + u32 scaled_height = src_surface->GetScaledHeight(); + + screen_info.display_texcoords = MathUtil::Rectangle((float)src_rect.top / (float)scaled_height, + (float)src_rect.left / (float)scaled_width, + (float)src_rect.bottom / (float)scaled_height, + (float)src_rect.right / (float)scaled_width); + + screen_info.display_texture = src_surface->texture.handle; + + return true; } void RasterizerOpenGL::SamplerInfo::Create() { @@ -597,108 +819,6 @@ void RasterizerOpenGL::SamplerInfo::SyncWithConfig(const Pica::Regs::TextureConf } } -void RasterizerOpenGL::ReconfigureColorTexture(TextureInfo& texture, Pica::Regs::ColorFormat format, u32 width, u32 height) { - GLint internal_format; - - texture.format = format; - texture.width = width; - texture.height = height; - - switch (format) { - case Pica::Regs::ColorFormat::RGBA8: - internal_format = GL_RGBA; - texture.gl_format = GL_RGBA; - texture.gl_type = GL_UNSIGNED_INT_8_8_8_8; - break; - - case Pica::Regs::ColorFormat::RGB8: - // This pixel format uses BGR since GL_UNSIGNED_BYTE specifies byte-order, unlike every - // specific OpenGL type used in this function using native-endian (that is, little-endian - // mostly everywhere) for words or half-words. - // TODO: check how those behave on big-endian processors. - internal_format = GL_RGB; - texture.gl_format = GL_BGR; - texture.gl_type = GL_UNSIGNED_BYTE; - break; - - case Pica::Regs::ColorFormat::RGB5A1: - internal_format = GL_RGBA; - texture.gl_format = GL_RGBA; - texture.gl_type = GL_UNSIGNED_SHORT_5_5_5_1; - break; - - case Pica::Regs::ColorFormat::RGB565: - internal_format = GL_RGB; - texture.gl_format = GL_RGB; - texture.gl_type = GL_UNSIGNED_SHORT_5_6_5; - break; - - case Pica::Regs::ColorFormat::RGBA4: - internal_format = GL_RGBA; - texture.gl_format = GL_RGBA; - texture.gl_type = GL_UNSIGNED_SHORT_4_4_4_4; - break; - - default: - LOG_CRITICAL(Render_OpenGL, "Unknown framebuffer texture color format %x", format); - UNIMPLEMENTED(); - break; - } - - state.texture_units[0].texture_2d = texture.texture.handle; - state.Apply(); - - glActiveTexture(GL_TEXTURE0); - glTexImage2D(GL_TEXTURE_2D, 0, internal_format, texture.width, texture.height, 0, - texture.gl_format, texture.gl_type, nullptr); - - state.texture_units[0].texture_2d = 0; - state.Apply(); -} - -void RasterizerOpenGL::ReconfigureDepthTexture(DepthTextureInfo& texture, Pica::Regs::DepthFormat format, u32 width, u32 height) { - GLint internal_format; - - texture.format = format; - texture.width = width; - texture.height = height; - - switch (format) { - case Pica::Regs::DepthFormat::D16: - internal_format = GL_DEPTH_COMPONENT16; - texture.gl_format = GL_DEPTH_COMPONENT; - texture.gl_type = GL_UNSIGNED_SHORT; - break; - - case Pica::Regs::DepthFormat::D24: - internal_format = GL_DEPTH_COMPONENT24; - texture.gl_format = GL_DEPTH_COMPONENT; - texture.gl_type = GL_UNSIGNED_INT; - break; - - case Pica::Regs::DepthFormat::D24S8: - internal_format = GL_DEPTH24_STENCIL8; - texture.gl_format = GL_DEPTH_STENCIL; - texture.gl_type = GL_UNSIGNED_INT_24_8; - break; - - default: - LOG_CRITICAL(Render_OpenGL, "Unknown framebuffer texture depth format %x", format); - UNIMPLEMENTED(); - break; - } - - state.texture_units[0].texture_2d = texture.texture.handle; - state.Apply(); - - glActiveTexture(GL_TEXTURE0); - glTexImage2D(GL_TEXTURE_2D, 0, internal_format, texture.width, texture.height, 0, - texture.gl_format, texture.gl_type, nullptr); - - state.texture_units[0].texture_2d = 0; - state.Apply(); -} - void RasterizerOpenGL::SetShader() { PicaShaderConfig config = PicaShaderConfig::CurrentConfig(); std::unique_ptr shader = std::make_unique(); @@ -761,83 +881,6 @@ void RasterizerOpenGL::SetShader() { } } -void RasterizerOpenGL::SyncFramebuffer() { - const auto& regs = Pica::g_state.regs; - - PAddr new_fb_color_addr = regs.framebuffer.GetColorBufferPhysicalAddress(); - Pica::Regs::ColorFormat new_fb_color_format = regs.framebuffer.color_format; - - PAddr new_fb_depth_addr = regs.framebuffer.GetDepthBufferPhysicalAddress(); - Pica::Regs::DepthFormat new_fb_depth_format = regs.framebuffer.depth_format; - - bool fb_size_changed = fb_color_texture.width != static_cast(regs.framebuffer.GetWidth()) || - fb_color_texture.height != static_cast(regs.framebuffer.GetHeight()); - - bool color_fb_prop_changed = fb_color_texture.format != new_fb_color_format || - fb_size_changed; - - bool depth_fb_prop_changed = fb_depth_texture.format != new_fb_depth_format || - fb_size_changed; - - bool color_fb_modified = cached_fb_color_addr != new_fb_color_addr || - color_fb_prop_changed; - - bool depth_fb_modified = cached_fb_depth_addr != new_fb_depth_addr || - depth_fb_prop_changed; - - // Commit if framebuffer modified in any way - if (color_fb_modified) - CommitColorBuffer(); - - if (depth_fb_modified) - CommitDepthBuffer(); - - // Reconfigure framebuffer textures if any property has changed - if (color_fb_prop_changed) { - ReconfigureColorTexture(fb_color_texture, new_fb_color_format, - regs.framebuffer.GetWidth(), regs.framebuffer.GetHeight()); - } - - if (depth_fb_prop_changed) { - ReconfigureDepthTexture(fb_depth_texture, new_fb_depth_format, - regs.framebuffer.GetWidth(), regs.framebuffer.GetHeight()); - - // Only attach depth buffer as stencil if it supports stencil - switch (new_fb_depth_format) { - case Pica::Regs::DepthFormat::D16: - case Pica::Regs::DepthFormat::D24: - glFramebufferTexture2D(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_TEXTURE_2D, 0, 0); - break; - - case Pica::Regs::DepthFormat::D24S8: - glFramebufferTexture2D(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_TEXTURE_2D, fb_depth_texture.texture.handle, 0); - break; - - default: - LOG_CRITICAL(Render_OpenGL, "Unknown framebuffer depth format %x", new_fb_depth_format); - UNIMPLEMENTED(); - break; - } - } - - // Load buffer data again if fb modified in any way - if (color_fb_modified) { - cached_fb_color_addr = new_fb_color_addr; - - ReloadColorBuffer(); - } - - if (depth_fb_modified) { - cached_fb_depth_addr = new_fb_depth_addr; - - ReloadDepthBuffer(); - } - - GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER); - ASSERT_MSG(status == GL_FRAMEBUFFER_COMPLETE, - "OpenGL rasterizer framebuffer setup failed, status %X", status); -} - void RasterizerOpenGL::SyncCullMode() { const auto& regs = Pica::g_state.regs; @@ -1034,229 +1077,3 @@ void RasterizerOpenGL::SyncLightPosition(int light_index) { uniform_block_data.dirty = true; } } - -void RasterizerOpenGL::SyncDrawState() { - const auto& regs = Pica::g_state.regs; - - // Sync the viewport - GLsizei viewport_width = (GLsizei)Pica::float24::FromRaw(regs.viewport_size_x).ToFloat32() * 2; - GLsizei viewport_height = (GLsizei)Pica::float24::FromRaw(regs.viewport_size_y).ToFloat32() * 2; - - // OpenGL uses different y coordinates, so negate corner offset and flip origin - // TODO: Ensure viewport_corner.x should not be negated or origin flipped - // TODO: Use floating-point viewports for accuracy if supported - glViewport((GLsizei)regs.viewport_corner.x, - (GLsizei)regs.viewport_corner.y, - viewport_width, viewport_height); - - // Sync bound texture(s), upload if not cached - const auto pica_textures = regs.GetTextures(); - for (unsigned texture_index = 0; texture_index < pica_textures.size(); ++texture_index) { - const auto& texture = pica_textures[texture_index]; - - if (texture.enabled) { - texture_samplers[texture_index].SyncWithConfig(texture.config); - res_cache.LoadAndBindTexture(state, texture_index, texture); - } else { - state.texture_units[texture_index].texture_2d = 0; - } - } - - state.draw.uniform_buffer = uniform_buffer.handle; - state.Apply(); -} - -MICROPROFILE_DEFINE(OpenGL_FramebufferReload, "OpenGL", "FB Reload", MP_RGB(70, 70, 200)); - -void RasterizerOpenGL::ReloadColorBuffer() { - u8* color_buffer = Memory::GetPhysicalPointer(cached_fb_color_addr); - - if (color_buffer == nullptr) - return; - - MICROPROFILE_SCOPE(OpenGL_FramebufferReload); - - u32 bytes_per_pixel = Pica::Regs::BytesPerColorPixel(fb_color_texture.format); - - std::unique_ptr temp_fb_color_buffer(new u8[fb_color_texture.width * fb_color_texture.height * bytes_per_pixel]); - - // Directly copy pixels. Internal OpenGL color formats are consistent so no conversion is necessary. - for (int y = 0; y < fb_color_texture.height; ++y) { - for (int x = 0; x < fb_color_texture.width; ++x) { - const u32 coarse_y = y & ~7; - u32 dst_offset = VideoCore::GetMortonOffset(x, y, bytes_per_pixel) + coarse_y * fb_color_texture.width * bytes_per_pixel; - u32 gl_pixel_index = (x + (fb_color_texture.height - 1 - y) * fb_color_texture.width) * bytes_per_pixel; - - u8* pixel = color_buffer + dst_offset; - memcpy(&temp_fb_color_buffer[gl_pixel_index], pixel, bytes_per_pixel); - } - } - - state.texture_units[0].texture_2d = fb_color_texture.texture.handle; - state.Apply(); - - glActiveTexture(GL_TEXTURE0); - glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, fb_color_texture.width, fb_color_texture.height, - fb_color_texture.gl_format, fb_color_texture.gl_type, temp_fb_color_buffer.get()); - - state.texture_units[0].texture_2d = 0; - state.Apply(); -} - -void RasterizerOpenGL::ReloadDepthBuffer() { - if (cached_fb_depth_addr == 0) - return; - - // TODO: Appears to work, but double-check endianness of depth values and order of depth-stencil - u8* depth_buffer = Memory::GetPhysicalPointer(cached_fb_depth_addr); - - if (depth_buffer == nullptr) - return; - - MICROPROFILE_SCOPE(OpenGL_FramebufferReload); - - u32 bytes_per_pixel = Pica::Regs::BytesPerDepthPixel(fb_depth_texture.format); - - // OpenGL needs 4 bpp alignment for D24 - u32 gl_bpp = bytes_per_pixel == 3 ? 4 : bytes_per_pixel; - - std::unique_ptr temp_fb_depth_buffer(new u8[fb_depth_texture.width * fb_depth_texture.height * gl_bpp]); - - u8* temp_fb_depth_data = bytes_per_pixel == 3 ? (temp_fb_depth_buffer.get() + 1) : temp_fb_depth_buffer.get(); - - if (fb_depth_texture.format == Pica::Regs::DepthFormat::D24S8) { - for (int y = 0; y < fb_depth_texture.height; ++y) { - for (int x = 0; x < fb_depth_texture.width; ++x) { - const u32 coarse_y = y & ~7; - u32 dst_offset = VideoCore::GetMortonOffset(x, y, bytes_per_pixel) + coarse_y * fb_depth_texture.width * bytes_per_pixel; - u32 gl_pixel_index = (x + (fb_depth_texture.height - 1 - y) * fb_depth_texture.width); - - u8* pixel = depth_buffer + dst_offset; - u32 depth_stencil = *(u32*)pixel; - ((u32*)temp_fb_depth_data)[gl_pixel_index] = (depth_stencil << 8) | (depth_stencil >> 24); - } - } - } else { - for (int y = 0; y < fb_depth_texture.height; ++y) { - for (int x = 0; x < fb_depth_texture.width; ++x) { - const u32 coarse_y = y & ~7; - u32 dst_offset = VideoCore::GetMortonOffset(x, y, bytes_per_pixel) + coarse_y * fb_depth_texture.width * bytes_per_pixel; - u32 gl_pixel_index = (x + (fb_depth_texture.height - 1 - y) * fb_depth_texture.width) * gl_bpp; - - u8* pixel = depth_buffer + dst_offset; - memcpy(&temp_fb_depth_data[gl_pixel_index], pixel, bytes_per_pixel); - } - } - } - - state.texture_units[0].texture_2d = fb_depth_texture.texture.handle; - state.Apply(); - - glActiveTexture(GL_TEXTURE0); - if (fb_depth_texture.format == Pica::Regs::DepthFormat::D24S8) { - // TODO(Subv): There is a bug with Intel Windows drivers that makes glTexSubImage2D not change the stencil buffer. - // The bug has been reported to Intel (https://communities.intel.com/message/324464) - glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH24_STENCIL8, fb_depth_texture.width, fb_depth_texture.height, 0, - GL_DEPTH_STENCIL, GL_UNSIGNED_INT_24_8, temp_fb_depth_buffer.get()); - } else { - glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, fb_depth_texture.width, fb_depth_texture.height, - fb_depth_texture.gl_format, fb_depth_texture.gl_type, temp_fb_depth_buffer.get()); - } - - state.texture_units[0].texture_2d = 0; - state.Apply(); -} - -Common::Profiling::TimingCategory buffer_commit_category("Framebuffer Commit"); -MICROPROFILE_DEFINE(OpenGL_FramebufferCommit, "OpenGL", "FB Commit", MP_RGB(70, 70, 200)); - -void RasterizerOpenGL::CommitColorBuffer() { - if (cached_fb_color_addr != 0) { - u8* color_buffer = Memory::GetPhysicalPointer(cached_fb_color_addr); - - if (color_buffer != nullptr) { - Common::Profiling::ScopeTimer timer(buffer_commit_category); - MICROPROFILE_SCOPE(OpenGL_FramebufferCommit); - - u32 bytes_per_pixel = Pica::Regs::BytesPerColorPixel(fb_color_texture.format); - - std::unique_ptr temp_gl_color_buffer(new u8[fb_color_texture.width * fb_color_texture.height * bytes_per_pixel]); - - state.texture_units[0].texture_2d = fb_color_texture.texture.handle; - state.Apply(); - - glActiveTexture(GL_TEXTURE0); - glGetTexImage(GL_TEXTURE_2D, 0, fb_color_texture.gl_format, fb_color_texture.gl_type, temp_gl_color_buffer.get()); - - state.texture_units[0].texture_2d = 0; - state.Apply(); - - // Directly copy pixels. Internal OpenGL color formats are consistent so no conversion is necessary. - for (int y = 0; y < fb_color_texture.height; ++y) { - for (int x = 0; x < fb_color_texture.width; ++x) { - const u32 coarse_y = y & ~7; - u32 dst_offset = VideoCore::GetMortonOffset(x, y, bytes_per_pixel) + coarse_y * fb_color_texture.width * bytes_per_pixel; - u32 gl_pixel_index = x * bytes_per_pixel + (fb_color_texture.height - 1 - y) * fb_color_texture.width * bytes_per_pixel; - - u8* pixel = color_buffer + dst_offset; - memcpy(pixel, &temp_gl_color_buffer[gl_pixel_index], bytes_per_pixel); - } - } - } - } -} - -void RasterizerOpenGL::CommitDepthBuffer() { - if (cached_fb_depth_addr != 0) { - // TODO: Output seems correct visually, but doesn't quite match sw renderer output. One of them is wrong. - u8* depth_buffer = Memory::GetPhysicalPointer(cached_fb_depth_addr); - - if (depth_buffer != nullptr) { - Common::Profiling::ScopeTimer timer(buffer_commit_category); - MICROPROFILE_SCOPE(OpenGL_FramebufferCommit); - - u32 bytes_per_pixel = Pica::Regs::BytesPerDepthPixel(fb_depth_texture.format); - - // OpenGL needs 4 bpp alignment for D24 - u32 gl_bpp = bytes_per_pixel == 3 ? 4 : bytes_per_pixel; - - std::unique_ptr temp_gl_depth_buffer(new u8[fb_depth_texture.width * fb_depth_texture.height * gl_bpp]); - - state.texture_units[0].texture_2d = fb_depth_texture.texture.handle; - state.Apply(); - - glActiveTexture(GL_TEXTURE0); - glGetTexImage(GL_TEXTURE_2D, 0, fb_depth_texture.gl_format, fb_depth_texture.gl_type, temp_gl_depth_buffer.get()); - - state.texture_units[0].texture_2d = 0; - state.Apply(); - - u8* temp_gl_depth_data = bytes_per_pixel == 3 ? (temp_gl_depth_buffer.get() + 1) : temp_gl_depth_buffer.get(); - - if (fb_depth_texture.format == Pica::Regs::DepthFormat::D24S8) { - for (int y = 0; y < fb_depth_texture.height; ++y) { - for (int x = 0; x < fb_depth_texture.width; ++x) { - const u32 coarse_y = y & ~7; - u32 dst_offset = VideoCore::GetMortonOffset(x, y, bytes_per_pixel) + coarse_y * fb_depth_texture.width * bytes_per_pixel; - u32 gl_pixel_index = (x + (fb_depth_texture.height - 1 - y) * fb_depth_texture.width); - - u8* pixel = depth_buffer + dst_offset; - u32 depth_stencil = ((u32*)temp_gl_depth_data)[gl_pixel_index]; - *(u32*)pixel = (depth_stencil >> 8) | (depth_stencil << 24); - } - } - } else { - for (int y = 0; y < fb_depth_texture.height; ++y) { - for (int x = 0; x < fb_depth_texture.width; ++x) { - const u32 coarse_y = y & ~7; - u32 dst_offset = VideoCore::GetMortonOffset(x, y, bytes_per_pixel) + coarse_y * fb_depth_texture.width * bytes_per_pixel; - u32 gl_pixel_index = (x + (fb_depth_texture.height - 1 - y) * fb_depth_texture.width) * gl_bpp; - - u8* pixel = depth_buffer + dst_offset; - memcpy(pixel, &temp_gl_depth_data[gl_pixel_index], bytes_per_pixel); - } - } - } - } - } -} diff --git a/src/video_core/renderer_opengl/gl_rasterizer.h b/src/video_core/renderer_opengl/gl_rasterizer.h index 390349a0c..5aa638985 100644 --- a/src/video_core/renderer_opengl/gl_rasterizer.h +++ b/src/video_core/renderer_opengl/gl_rasterizer.h @@ -19,6 +19,7 @@ #include "video_core/renderer_opengl/gl_rasterizer_cache.h" #include "video_core/renderer_opengl/gl_state.h" #include "video_core/renderer_opengl/pica_to_gl.h" +#include "video_core/renderer_opengl/renderer_opengl.h" #include "video_core/shader/shader_interpreter.h" /** @@ -191,16 +192,17 @@ public: RasterizerOpenGL(); ~RasterizerOpenGL() override; - void InitObjects() override; - void Reset() override; void AddTriangle(const Pica::Shader::OutputVertex& v0, const Pica::Shader::OutputVertex& v1, const Pica::Shader::OutputVertex& v2) override; void DrawTriangles() override; - void FlushFramebuffer() override; void NotifyPicaRegisterChanged(u32 id) override; + void FlushAll() override; void FlushRegion(PAddr addr, u32 size) override; - void InvalidateRegion(PAddr addr, u32 size) override; + void FlushAndInvalidateRegion(PAddr addr, u32 size) override; + bool AccelerateDisplayTransfer(const GPU::Regs::DisplayTransferConfig& config) override; + bool AccelerateFill(const GPU::Regs::MemoryFillConfig& config) override; + bool AccelerateDisplay(const GPU::Regs::FramebufferConfig& config, PAddr framebuffer_addr, u32 pixel_stride, ScreenInfo& screen_info) override; /// OpenGL shader generated for a given Pica register state struct PicaShader { @@ -210,26 +212,6 @@ public: private: - /// Structure used for storing information about color textures - struct TextureInfo { - OGLTexture texture; - GLsizei width; - GLsizei height; - Pica::Regs::ColorFormat format; - GLenum gl_format; - GLenum gl_type; - }; - - /// Structure used for storing information about depth textures - struct DepthTextureInfo { - OGLTexture texture; - GLsizei width; - GLsizei height; - Pica::Regs::DepthFormat format; - GLenum gl_format; - GLenum gl_type; - }; - struct SamplerInfo { using TextureConfig = Pica::Regs::TextureConfig; @@ -311,18 +293,9 @@ private: static_assert(sizeof(UniformData) == 0x310, "The size of the UniformData structure has changed, update the structure in the shader"); static_assert(sizeof(UniformData) < 16384, "UniformData structure must be less than 16kb as per the OpenGL spec"); - /// Reconfigure the OpenGL color texture to use the given format and dimensions - void ReconfigureColorTexture(TextureInfo& texture, Pica::Regs::ColorFormat format, u32 width, u32 height); - - /// Reconfigure the OpenGL depth texture to use the given format and dimensions - void ReconfigureDepthTexture(DepthTextureInfo& texture, Pica::Regs::DepthFormat format, u32 width, u32 height); - /// Sets the OpenGL shader in accordance with the current PICA register state void SetShader(); - /// Syncs the state and contents of the OpenGL framebuffer to match the current PICA framebuffer - void SyncFramebuffer(); - /// Syncs the cull mode to match the PICA register void SyncCullMode(); @@ -386,45 +359,15 @@ private: /// Syncs the specified light's specular 1 color to match the PICA register void SyncLightSpecular1(int light_index); - /// Syncs the remaining OpenGL drawing state to match the current PICA state - void SyncDrawState(); - - /// Copies the 3DS color framebuffer into the OpenGL color framebuffer texture - void ReloadColorBuffer(); - - /// Copies the 3DS depth framebuffer into the OpenGL depth framebuffer texture - void ReloadDepthBuffer(); - - /** - * Save the current OpenGL color framebuffer to the current PICA framebuffer in 3DS memory - * Loads the OpenGL framebuffer textures into temporary buffers - * Then copies into the 3DS framebuffer using proper Morton order - */ - void CommitColorBuffer(); - - /** - * Save the current OpenGL depth framebuffer to the current PICA framebuffer in 3DS memory - * Loads the OpenGL framebuffer textures into temporary buffers - * Then copies into the 3DS framebuffer using proper Morton order - */ - void CommitDepthBuffer(); + OpenGLState state; RasterizerCacheOpenGL res_cache; std::vector vertex_batch; - OpenGLState state; - - PAddr cached_fb_color_addr; - PAddr cached_fb_depth_addr; - - // Hardware rasterizer - std::array texture_samplers; - TextureInfo fb_color_texture; - DepthTextureInfo fb_depth_texture; - std::unordered_map> shader_cache; const PicaShader* current_shader = nullptr; + bool shader_dirty; struct { UniformData data; @@ -432,11 +375,12 @@ private: bool dirty; } uniform_block_data; + std::array texture_samplers; OGLVertexArray vertex_array; OGLBuffer vertex_buffer; OGLBuffer uniform_buffer; OGLFramebuffer framebuffer; - std::array lighting_lut; + std::array lighting_luts; std::array, 6> lighting_lut_data; }; diff --git a/src/video_core/renderer_opengl/gl_rasterizer_cache.cpp b/src/video_core/renderer_opengl/gl_rasterizer_cache.cpp index 1323c12e4..55c2fb283 100644 --- a/src/video_core/renderer_opengl/gl_rasterizer_cache.cpp +++ b/src/video_core/renderer_opengl/gl_rasterizer_cache.cpp @@ -2,8 +2,9 @@ // Licensed under GPLv2 or any later version // Refer to the license.txt file included. -#include +#include +#include "common/emu_window.h" #include "common/hash.h" #include "common/math_util.h" #include "common/microprofile.h" @@ -12,71 +13,693 @@ #include "core/memory.h" #include "video_core/debug_utils/debug_utils.h" +#include "video_core/pica_state.h" #include "video_core/renderer_opengl/gl_rasterizer_cache.h" #include "video_core/renderer_opengl/pica_to_gl.h" +#include "video_core/utils.h" +#include "video_core/video_core.h" + +struct FormatTuple { + GLint internal_format; + GLenum format; + GLenum type; +}; + +static const std::array fb_format_tuples = {{ + { GL_RGBA8, GL_RGBA, GL_UNSIGNED_INT_8_8_8_8 }, // RGBA8 + { GL_RGB8, GL_BGR, GL_UNSIGNED_BYTE }, // RGB8 + { GL_RGB5_A1, GL_RGBA, GL_UNSIGNED_SHORT_5_5_5_1 }, // RGB5A1 + { GL_RGB565, GL_RGB, GL_UNSIGNED_SHORT_5_6_5 }, // RGB565 + { GL_RGBA4, GL_RGBA, GL_UNSIGNED_SHORT_4_4_4_4 }, // RGBA4 +}}; + +static const std::array depth_format_tuples = {{ + { GL_DEPTH_COMPONENT16, GL_DEPTH_COMPONENT, GL_UNSIGNED_SHORT }, // D16 + {}, + { GL_DEPTH_COMPONENT24, GL_DEPTH_COMPONENT, GL_UNSIGNED_INT }, // D24 + { GL_DEPTH24_STENCIL8, GL_DEPTH_STENCIL, GL_UNSIGNED_INT_24_8 }, // D24S8 +}}; + +RasterizerCacheOpenGL::RasterizerCacheOpenGL() { + transfer_framebuffers[0].Create(); + transfer_framebuffers[1].Create(); +} RasterizerCacheOpenGL::~RasterizerCacheOpenGL() { - InvalidateAll(); + FlushAll(); } -MICROPROFILE_DEFINE(OpenGL_TextureUpload, "OpenGL", "Texture Upload", MP_RGB(128, 64, 192)); +static void MortonCopyPixels(CachedSurface::PixelFormat pixel_format, u32 width, u32 height, u32 bytes_per_pixel, u32 gl_bytes_per_pixel, u8* morton_data, u8* gl_data, bool morton_to_gl) { + using PixelFormat = CachedSurface::PixelFormat; -void RasterizerCacheOpenGL::LoadAndBindTexture(OpenGLState &state, unsigned texture_unit, const Pica::DebugUtils::TextureInfo& info) { - const auto cached_texture = texture_cache.find(info.physical_address); + u8* data_ptrs[2]; + u32 depth_stencil_shifts[2] = {24, 8}; - if (cached_texture != texture_cache.end()) { - state.texture_units[texture_unit].texture_2d = cached_texture->second->texture.handle; - state.Apply(); - } else { - MICROPROFILE_SCOPE(OpenGL_TextureUpload); + if (morton_to_gl) { + std::swap(depth_stencil_shifts[0], depth_stencil_shifts[1]); + } - std::unique_ptr new_texture = std::make_unique(); + if (pixel_format == PixelFormat::D24S8) { + for (unsigned y = 0; y < height; ++y) { + for (unsigned x = 0; x < width; ++x) { + const u32 coarse_y = y & ~7; + u32 morton_offset = VideoCore::GetMortonOffset(x, y, bytes_per_pixel) + coarse_y * width * bytes_per_pixel; + u32 gl_pixel_index = (x + (height - 1 - y) * width) * gl_bytes_per_pixel; - new_texture->texture.Create(); - state.texture_units[texture_unit].texture_2d = new_texture->texture.handle; - state.Apply(); - glActiveTexture(GL_TEXTURE0 + texture_unit); + data_ptrs[morton_to_gl] = morton_data + morton_offset; + data_ptrs[!morton_to_gl] = &gl_data[gl_pixel_index]; - u8* texture_src_data = Memory::GetPhysicalPointer(info.physical_address); + // Swap depth and stencil value ordering since 3DS does not match OpenGL + u32 depth_stencil; + memcpy(&depth_stencil, data_ptrs[1], sizeof(u32)); + depth_stencil = (depth_stencil << depth_stencil_shifts[0]) | (depth_stencil >> depth_stencil_shifts[1]); - new_texture->width = info.width; - new_texture->height = info.height; - new_texture->size = info.stride * info.height; - new_texture->addr = info.physical_address; - new_texture->hash = Common::ComputeHash64(texture_src_data, new_texture->size); - - std::unique_ptr[]> temp_texture_buffer_rgba(new Math::Vec4[info.width * info.height]); - - for (int y = 0; y < info.height; ++y) { - for (int x = 0; x < info.width; ++x) { - temp_texture_buffer_rgba[x + info.width * y] = Pica::DebugUtils::LookupTexture(texture_src_data, x, info.height - 1 - y, info); + memcpy(data_ptrs[0], &depth_stencil, sizeof(u32)); } } + } else { + for (unsigned y = 0; y < height; ++y) { + for (unsigned x = 0; x < width; ++x) { + const u32 coarse_y = y & ~7; + u32 morton_offset = VideoCore::GetMortonOffset(x, y, bytes_per_pixel) + coarse_y * width * bytes_per_pixel; + u32 gl_pixel_index = (x + (height - 1 - y) * width) * gl_bytes_per_pixel; - glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, info.width, info.height, 0, GL_RGBA, GL_UNSIGNED_BYTE, temp_texture_buffer_rgba.get()); + data_ptrs[morton_to_gl] = morton_data + morton_offset; + data_ptrs[!morton_to_gl] = &gl_data[gl_pixel_index]; - texture_cache.emplace(info.physical_address, std::move(new_texture)); - } -} - -void RasterizerCacheOpenGL::InvalidateInRange(PAddr addr, u32 size, bool ignore_hash) { - // TODO: Optimize by also inserting upper bound (addr + size) of each texture into the same map and also narrow using lower_bound - auto cache_upper_bound = texture_cache.upper_bound(addr + size); - - for (auto it = texture_cache.begin(); it != cache_upper_bound;) { - const auto& info = *it->second; - - // Flush the texture only if the memory region intersects and a change is detected - if (MathUtil::IntervalsIntersect(addr, size, info.addr, info.size) && - (ignore_hash || info.hash != Common::ComputeHash64(Memory::GetPhysicalPointer(info.addr), info.size))) { - - it = texture_cache.erase(it); - } else { - ++it; + memcpy(data_ptrs[0], data_ptrs[1], bytes_per_pixel); + } } } } -void RasterizerCacheOpenGL::InvalidateAll() { - texture_cache.clear(); +bool RasterizerCacheOpenGL::BlitTextures(GLuint src_tex, GLuint dst_tex, CachedSurface::SurfaceType type, const MathUtil::Rectangle& src_rect, const MathUtil::Rectangle& dst_rect) { + using SurfaceType = CachedSurface::SurfaceType; + + OpenGLState cur_state = OpenGLState::GetCurState(); + + // Make sure textures aren't bound to texture units, since going to bind them to framebuffer components + OpenGLState::ResetTexture(src_tex); + OpenGLState::ResetTexture(dst_tex); + + // Keep track of previous framebuffer bindings + GLuint old_fbs[2] = { cur_state.draw.read_framebuffer, cur_state.draw.draw_framebuffer }; + cur_state.draw.read_framebuffer = transfer_framebuffers[0].handle; + cur_state.draw.draw_framebuffer = transfer_framebuffers[1].handle; + cur_state.Apply(); + + u32 buffers = 0; + + if (type == SurfaceType::Color || type == SurfaceType::Texture) { + glFramebufferTexture2D(GL_READ_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, src_tex, 0); + glFramebufferTexture2D(GL_READ_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_TEXTURE_2D, 0, 0); + + glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, dst_tex, 0); + glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_TEXTURE_2D, 0, 0); + + buffers = GL_COLOR_BUFFER_BIT; + } else if (type == SurfaceType::Depth) { + glFramebufferTexture2D(GL_READ_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, 0, 0); + glFramebufferTexture2D(GL_READ_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, src_tex, 0); + glFramebufferTexture2D(GL_READ_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_TEXTURE_2D, 0, 0); + + glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, 0, 0); + glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, dst_tex, 0); + glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_TEXTURE_2D, 0, 0); + + buffers = GL_DEPTH_BUFFER_BIT; + } else if (type == SurfaceType::DepthStencil) { + glFramebufferTexture2D(GL_READ_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, 0, 0); + glFramebufferTexture2D(GL_READ_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_TEXTURE_2D, src_tex, 0); + + glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, 0, 0); + glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_TEXTURE_2D, dst_tex, 0); + + buffers = GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT; + } + + if (OpenGLState::CheckFBStatus(GL_READ_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) { + return false; + } + + if (OpenGLState::CheckFBStatus(GL_DRAW_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) { + return false; + } + + glBlitFramebuffer(src_rect.left, src_rect.top, src_rect.right, src_rect.bottom, + dst_rect.left, dst_rect.top, dst_rect.right, dst_rect.bottom, + buffers, buffers == GL_COLOR_BUFFER_BIT ? GL_LINEAR : GL_NEAREST); + + // Restore previous framebuffer bindings + cur_state.draw.read_framebuffer = old_fbs[0]; + cur_state.draw.draw_framebuffer = old_fbs[1]; + cur_state.Apply(); + + return true; +} + +bool RasterizerCacheOpenGL::TryBlitSurfaces(CachedSurface* src_surface, const MathUtil::Rectangle& src_rect, CachedSurface* dst_surface, const MathUtil::Rectangle& dst_rect) { + using SurfaceType = CachedSurface::SurfaceType; + + if (!CachedSurface::CheckFormatsBlittable(src_surface->pixel_format, dst_surface->pixel_format)) { + return false; + } + + return BlitTextures(src_surface->texture.handle, dst_surface->texture.handle, CachedSurface::GetFormatType(src_surface->pixel_format), src_rect, dst_rect); +} + +static void AllocateSurfaceTexture(GLuint texture, CachedSurface::PixelFormat pixel_format, u32 width, u32 height) { + // Allocate an uninitialized texture of appropriate size and format for the surface + using SurfaceType = CachedSurface::SurfaceType; + + OpenGLState cur_state = OpenGLState::GetCurState(); + + // Keep track of previous texture bindings + GLuint old_tex = cur_state.texture_units[0].texture_2d; + cur_state.texture_units[0].texture_2d = texture; + cur_state.Apply(); + glActiveTexture(GL_TEXTURE0); + + SurfaceType type = CachedSurface::GetFormatType(pixel_format); + + FormatTuple tuple; + if (type == SurfaceType::Color) { + ASSERT((size_t)pixel_format < fb_format_tuples.size()); + tuple = fb_format_tuples[(unsigned int)pixel_format]; + } else if (type == SurfaceType::Depth || type == SurfaceType::DepthStencil) { + size_t tuple_idx = (size_t)pixel_format - 14; + ASSERT(tuple_idx < depth_format_tuples.size()); + tuple = depth_format_tuples[tuple_idx]; + } else { + tuple = { GL_RGBA8, GL_RGBA, GL_UNSIGNED_BYTE }; + } + + glTexImage2D(GL_TEXTURE_2D, 0, tuple.internal_format, width, height, 0, + tuple.format, tuple.type, nullptr); + + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, 0); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); + + // Restore previous texture bindings + cur_state.texture_units[0].texture_2d = old_tex; + cur_state.Apply(); +} + +MICROPROFILE_DEFINE(OpenGL_SurfaceUpload, "OpenGL", "Surface Upload", MP_RGB(128, 64, 192)); +CachedSurface* RasterizerCacheOpenGL::GetSurface(const CachedSurface& params, bool match_res_scale, bool load_if_create) { + using PixelFormat = CachedSurface::PixelFormat; + using SurfaceType = CachedSurface::SurfaceType; + + if (params.addr == 0) { + return nullptr; + } + + u32 params_size = params.width * params.height * CachedSurface::GetFormatBpp(params.pixel_format) / 8; + + // Check for an exact match in existing surfaces + CachedSurface* best_exact_surface = nullptr; + float exact_surface_goodness = -1.f; + + auto surface_interval = boost::icl::interval::right_open(params.addr, params.addr + params_size); + auto range = surface_cache.equal_range(surface_interval); + for (auto it = range.first; it != range.second; ++it) { + for (auto it2 = it->second.begin(); it2 != it->second.end(); ++it2) { + CachedSurface* surface = it2->get(); + + // Check if the request matches the surface exactly + if (params.addr == surface->addr && + params.width == surface->width && params.height == surface->height && + params.pixel_format == surface->pixel_format) + { + // Make sure optional param-matching criteria are fulfilled + bool tiling_match = (params.is_tiled == surface->is_tiled); + bool res_scale_match = (params.res_scale_width == surface->res_scale_width && params.res_scale_height == surface->res_scale_height); + if (!match_res_scale || res_scale_match) { + // Prioritize same-tiling and highest resolution surfaces + float match_goodness = (float)tiling_match + surface->res_scale_width * surface->res_scale_height; + if (match_goodness > exact_surface_goodness || surface->dirty) { + exact_surface_goodness = match_goodness; + best_exact_surface = surface; + } + } + } + } + } + + // Return the best exact surface if found + if (best_exact_surface != nullptr) { + return best_exact_surface; + } + + // No matching surfaces found, so create a new one + u8* texture_src_data = Memory::GetPhysicalPointer(params.addr); + if (texture_src_data == nullptr) { + return nullptr; + } + + MICROPROFILE_SCOPE(OpenGL_SurfaceUpload); + + std::shared_ptr new_surface = std::make_shared(); + + new_surface->addr = params.addr; + new_surface->size = params_size; + + new_surface->texture.Create(); + new_surface->width = params.width; + new_surface->height = params.height; + new_surface->stride = params.stride; + new_surface->res_scale_width = params.res_scale_width; + new_surface->res_scale_height = params.res_scale_height; + + new_surface->is_tiled = params.is_tiled; + new_surface->pixel_format = params.pixel_format; + new_surface->dirty = false; + + if (!load_if_create) { + // Don't load any data; just allocate the surface's texture + AllocateSurfaceTexture(new_surface->texture.handle, new_surface->pixel_format, new_surface->GetScaledWidth(), new_surface->GetScaledHeight()); + } else { + // TODO: Consider attempting subrect match in existing surfaces and direct blit here instead of memory upload below if that's a common scenario in some game + + Memory::RasterizerFlushRegion(params.addr, params_size); + + // Load data from memory to the new surface + OpenGLState cur_state = OpenGLState::GetCurState(); + + GLuint old_tex = cur_state.texture_units[0].texture_2d; + cur_state.texture_units[0].texture_2d = new_surface->texture.handle; + cur_state.Apply(); + glActiveTexture(GL_TEXTURE0); + + glPixelStorei(GL_UNPACK_ROW_LENGTH, (GLint)new_surface->stride); + if (!new_surface->is_tiled) { + // TODO: Ensure this will always be a color format, not a depth or other format + ASSERT((size_t)new_surface->pixel_format < fb_format_tuples.size()); + const FormatTuple& tuple = fb_format_tuples[(unsigned int)params.pixel_format]; + + glTexImage2D(GL_TEXTURE_2D, 0, tuple.internal_format, params.width, params.height, 0, + tuple.format, tuple.type, texture_src_data); + } else { + SurfaceType type = CachedSurface::GetFormatType(new_surface->pixel_format); + if (type != SurfaceType::Depth && type != SurfaceType::DepthStencil) { + FormatTuple tuple; + if ((size_t)params.pixel_format < fb_format_tuples.size()) { + tuple = fb_format_tuples[(unsigned int)params.pixel_format]; + } else { + // Texture + tuple = { GL_RGBA8, GL_RGBA, GL_UNSIGNED_BYTE }; + } + + std::vector> tex_buffer(params.width * params.height); + + Pica::DebugUtils::TextureInfo tex_info; + tex_info.width = params.width; + tex_info.height = params.height; + tex_info.stride = params.width * CachedSurface::GetFormatBpp(params.pixel_format) / 8; + tex_info.format = (Pica::Regs::TextureFormat)params.pixel_format; + tex_info.physical_address = params.addr; + + for (unsigned y = 0; y < params.height; ++y) { + for (unsigned x = 0; x < params.width; ++x) { + tex_buffer[x + params.width * y] = Pica::DebugUtils::LookupTexture(texture_src_data, x, params.height - 1 - y, tex_info); + } + } + + glTexImage2D(GL_TEXTURE_2D, 0, tuple.internal_format, params.width, params.height, 0, GL_RGBA, GL_UNSIGNED_BYTE, tex_buffer.data()); + } else { + // Depth/Stencil formats need special treatment since they aren't sampleable using LookupTexture and can't use RGBA format + size_t tuple_idx = (size_t)params.pixel_format - 14; + ASSERT(tuple_idx < depth_format_tuples.size()); + const FormatTuple& tuple = depth_format_tuples[tuple_idx]; + + u32 bytes_per_pixel = CachedSurface::GetFormatBpp(params.pixel_format) / 8; + + // OpenGL needs 4 bpp alignment for D24 since using GL_UNSIGNED_INT as type + bool use_4bpp = (params.pixel_format == PixelFormat::D24); + + u32 gl_bytes_per_pixel = use_4bpp ? 4 : bytes_per_pixel; + + std::vector temp_fb_depth_buffer(params.width * params.height * gl_bytes_per_pixel); + + u8* temp_fb_depth_buffer_ptr = use_4bpp ? temp_fb_depth_buffer.data() + 1 : temp_fb_depth_buffer.data(); + + MortonCopyPixels(params.pixel_format, params.width, params.height, bytes_per_pixel, gl_bytes_per_pixel, texture_src_data, temp_fb_depth_buffer_ptr, true); + + glTexImage2D(GL_TEXTURE_2D, 0, tuple.internal_format, params.width, params.height, 0, + tuple.format, tuple.type, temp_fb_depth_buffer.data()); + } + } + glPixelStorei(GL_UNPACK_ROW_LENGTH, 0); + + // If not 1x scale, blit 1x texture to a new scaled texture and replace texture in surface + if (new_surface->res_scale_width != 1.f || new_surface->res_scale_height != 1.f) { + OGLTexture scaled_texture; + scaled_texture.Create(); + + AllocateSurfaceTexture(scaled_texture.handle, new_surface->pixel_format, new_surface->GetScaledWidth(), new_surface->GetScaledHeight()); + BlitTextures(new_surface->texture.handle, scaled_texture.handle, CachedSurface::GetFormatType(new_surface->pixel_format), + MathUtil::Rectangle(0, 0, new_surface->width, new_surface->height), + MathUtil::Rectangle(0, 0, new_surface->GetScaledWidth(), new_surface->GetScaledHeight())); + + new_surface->texture.Release(); + new_surface->texture.handle = scaled_texture.handle; + scaled_texture.handle = 0; + cur_state.texture_units[0].texture_2d = new_surface->texture.handle; + cur_state.Apply(); + } + + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, 0); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); + + cur_state.texture_units[0].texture_2d = old_tex; + cur_state.Apply(); + } + + Memory::RasterizerMarkRegionCached(new_surface->addr, new_surface->size, 1); + surface_cache.add(std::make_pair(boost::icl::interval::right_open(new_surface->addr, new_surface->addr + new_surface->size), std::set>({ new_surface }))); + return new_surface.get(); +} + +CachedSurface* RasterizerCacheOpenGL::GetSurfaceRect(const CachedSurface& params, bool match_res_scale, bool load_if_create, MathUtil::Rectangle& out_rect) { + if (params.addr == 0) { + return nullptr; + } + + u32 total_pixels = params.width * params.height; + u32 params_size = total_pixels * CachedSurface::GetFormatBpp(params.pixel_format) / 8; + + // Attempt to find encompassing surfaces + CachedSurface* best_subrect_surface = nullptr; + float subrect_surface_goodness = -1.f; + + auto surface_interval = boost::icl::interval::right_open(params.addr, params.addr + params_size); + auto cache_upper_bound = surface_cache.upper_bound(surface_interval); + for (auto it = surface_cache.lower_bound(surface_interval); it != cache_upper_bound; ++it) { + for (auto it2 = it->second.begin(); it2 != it->second.end(); ++it2) { + CachedSurface* surface = it2->get(); + + // Check if the request is contained in the surface + if (params.addr >= surface->addr && + params.addr + params_size - 1 <= surface->addr + surface->size - 1 && + params.pixel_format == surface->pixel_format) + { + // Make sure optional param-matching criteria are fulfilled + bool tiling_match = (params.is_tiled == surface->is_tiled); + bool res_scale_match = (params.res_scale_width == surface->res_scale_width && params.res_scale_height == surface->res_scale_height); + if (!match_res_scale || res_scale_match) { + // Prioritize same-tiling and highest resolution surfaces + float match_goodness = (float)tiling_match + surface->res_scale_width * surface->res_scale_height; + if (match_goodness > subrect_surface_goodness || surface->dirty) { + subrect_surface_goodness = match_goodness; + best_subrect_surface = surface; + } + } + } + } + } + + // Return the best subrect surface if found + if (best_subrect_surface != nullptr) { + unsigned int bytes_per_pixel = (CachedSurface::GetFormatBpp(best_subrect_surface->pixel_format) / 8); + + int x0, y0; + + if (!params.is_tiled) { + u32 begin_pixel_index = (params.addr - best_subrect_surface->addr) / bytes_per_pixel; + x0 = begin_pixel_index % best_subrect_surface->width; + y0 = begin_pixel_index / best_subrect_surface->width; + + out_rect = MathUtil::Rectangle(x0, y0, x0 + params.width, y0 + params.height); + } else { + u32 bytes_per_tile = 8 * 8 * bytes_per_pixel; + u32 tiles_per_row = best_subrect_surface->width / 8; + + u32 begin_tile_index = (params.addr - best_subrect_surface->addr) / bytes_per_tile; + x0 = begin_tile_index % tiles_per_row * 8; + y0 = begin_tile_index / tiles_per_row * 8; + + // Tiled surfaces are flipped vertically in the rasterizer vs. 3DS memory. + out_rect = MathUtil::Rectangle(x0, best_subrect_surface->height - y0, x0 + params.width, best_subrect_surface->height - (y0 + params.height)); + } + + out_rect.left = (int)(out_rect.left * best_subrect_surface->res_scale_width); + out_rect.right = (int)(out_rect.right * best_subrect_surface->res_scale_width); + out_rect.top = (int)(out_rect.top * best_subrect_surface->res_scale_height); + out_rect.bottom = (int)(out_rect.bottom * best_subrect_surface->res_scale_height); + + return best_subrect_surface; + } + + // No subrect found - create and return a new surface + if (!params.is_tiled) { + out_rect = MathUtil::Rectangle(0, 0, (int)(params.width * params.res_scale_width), (int)(params.height * params.res_scale_height)); + } else { + out_rect = MathUtil::Rectangle(0, (int)(params.height * params.res_scale_height), (int)(params.width * params.res_scale_width), 0); + } + + return GetSurface(params, match_res_scale, load_if_create); +} + +CachedSurface* RasterizerCacheOpenGL::GetTextureSurface(const Pica::Regs::FullTextureConfig& config) { + Pica::DebugUtils::TextureInfo info = Pica::DebugUtils::TextureInfo::FromPicaRegister(config.config, config.format); + + CachedSurface params; + params.addr = info.physical_address; + params.width = info.width; + params.height = info.height; + params.is_tiled = true; + params.pixel_format = CachedSurface::PixelFormatFromTextureFormat(info.format); + return GetSurface(params, false, true); +} + +std::tuple> RasterizerCacheOpenGL::GetFramebufferSurfaces(const Pica::Regs::FramebufferConfig& config) { + const auto& regs = Pica::g_state.regs; + + // Make sur that framebuffers don't overlap if both color and depth are being used + u32 fb_area = config.GetWidth() * config.GetHeight(); + bool framebuffers_overlap = config.GetColorBufferPhysicalAddress() != 0 && + config.GetDepthBufferPhysicalAddress() != 0 && + MathUtil::IntervalsIntersect(config.GetColorBufferPhysicalAddress(), fb_area * GPU::Regs::BytesPerPixel(GPU::Regs::PixelFormat(config.color_format.Value())), + config.GetDepthBufferPhysicalAddress(), fb_area * Pica::Regs::BytesPerDepthPixel(config.depth_format)); + bool using_color_fb = config.GetColorBufferPhysicalAddress() != 0; + bool using_depth_fb = config.GetDepthBufferPhysicalAddress() != 0 && (regs.output_merger.depth_test_enable || regs.output_merger.depth_write_enable || !framebuffers_overlap); + + if (framebuffers_overlap && using_color_fb && using_depth_fb) { + LOG_CRITICAL(Render_OpenGL, "Color and depth framebuffer memory regions overlap; overlapping framebuffers not supported!"); + using_depth_fb = false; + } + + // get color and depth surfaces + CachedSurface color_params; + CachedSurface depth_params; + color_params.width = depth_params.width = config.GetWidth(); + color_params.height = depth_params.height = config.GetHeight(); + color_params.is_tiled = depth_params.is_tiled = true; + if (VideoCore::g_scaled_resolution_enabled) { + auto layout = VideoCore::g_emu_window->GetFramebufferLayout(); + + // Assume same scaling factor for top and bottom screens + color_params.res_scale_width = depth_params.res_scale_width = (float)layout.top_screen.GetWidth() / VideoCore::kScreenTopWidth; + color_params.res_scale_height = depth_params.res_scale_height = (float)layout.top_screen.GetHeight() / VideoCore::kScreenTopHeight; + } + + color_params.addr = config.GetColorBufferPhysicalAddress(); + color_params.pixel_format = CachedSurface::PixelFormatFromColorFormat(config.color_format); + + depth_params.addr = config.GetDepthBufferPhysicalAddress(); + depth_params.pixel_format = CachedSurface::PixelFormatFromDepthFormat(config.depth_format); + + MathUtil::Rectangle color_rect; + CachedSurface* color_surface = using_color_fb ? GetSurfaceRect(color_params, true, true, color_rect) : nullptr; + + MathUtil::Rectangle depth_rect; + CachedSurface* depth_surface = using_depth_fb ? GetSurfaceRect(depth_params, true, true, depth_rect) : nullptr; + + // Sanity check to make sure found surfaces aren't the same + if (using_depth_fb && using_color_fb && color_surface == depth_surface) { + LOG_CRITICAL(Render_OpenGL, "Color and depth framebuffer surfaces overlap; overlapping surfaces not supported!"); + using_depth_fb = false; + depth_surface = nullptr; + } + + MathUtil::Rectangle rect; + + if (color_surface != nullptr && depth_surface != nullptr && (depth_rect.left != color_rect.left || depth_rect.top != color_rect.top)) { + // Can't specify separate color and depth viewport offsets in OpenGL, so re-zero both if they don't match + if (color_rect.left != 0 || color_rect.top != 0) { + color_surface = GetSurface(color_params, true, true); + } + + if (depth_rect.left != 0 || depth_rect.top != 0) { + depth_surface = GetSurface(depth_params, true, true); + } + + if (!color_surface->is_tiled) { + rect = MathUtil::Rectangle(0, 0, (int)(color_params.width * color_params.res_scale_width), (int)(color_params.height * color_params.res_scale_height)); + } else { + rect = MathUtil::Rectangle(0, (int)(color_params.height * color_params.res_scale_height), (int)(color_params.width * color_params.res_scale_width), 0); + } + } else if (color_surface != nullptr) { + rect = color_rect; + } else if (depth_surface != nullptr) { + rect = depth_rect; + } else { + rect = MathUtil::Rectangle(0, 0, 0, 0); + } + + return std::make_tuple(color_surface, depth_surface, rect); +} + +CachedSurface* RasterizerCacheOpenGL::TryGetFillSurface(const GPU::Regs::MemoryFillConfig& config) { + auto surface_interval = boost::icl::interval::right_open(config.GetStartAddress(), config.GetEndAddress()); + auto range = surface_cache.equal_range(surface_interval); + for (auto it = range.first; it != range.second; ++it) { + for (auto it2 = it->second.begin(); it2 != it->second.end(); ++it2) { + int bits_per_value = 0; + if (config.fill_24bit) { + bits_per_value = 24; + } else if (config.fill_32bit) { + bits_per_value = 32; + } else { + bits_per_value = 16; + } + + CachedSurface* surface = it2->get(); + + if (surface->addr == config.GetStartAddress() && + CachedSurface::GetFormatBpp(surface->pixel_format) == bits_per_value && + (surface->width * surface->height * CachedSurface::GetFormatBpp(surface->pixel_format) / 8) == (config.GetEndAddress() - config.GetStartAddress())) + { + return surface; + } + } + } + + return nullptr; +} + +MICROPROFILE_DEFINE(OpenGL_SurfaceDownload, "OpenGL", "Surface Download", MP_RGB(128, 192, 64)); +void RasterizerCacheOpenGL::FlushSurface(CachedSurface* surface) { + using PixelFormat = CachedSurface::PixelFormat; + using SurfaceType = CachedSurface::SurfaceType; + + if (!surface->dirty) { + return; + } + + MICROPROFILE_SCOPE(OpenGL_SurfaceDownload); + + u8* dst_buffer = Memory::GetPhysicalPointer(surface->addr); + if (dst_buffer == nullptr) { + return; + } + + OpenGLState cur_state = OpenGLState::GetCurState(); + GLuint old_tex = cur_state.texture_units[0].texture_2d; + + OGLTexture unscaled_tex; + GLuint texture_to_flush = surface->texture.handle; + + // If not 1x scale, blit scaled texture to a new 1x texture and use that to flush + if (surface->res_scale_width != 1.f || surface->res_scale_height != 1.f) { + unscaled_tex.Create(); + + AllocateSurfaceTexture(unscaled_tex.handle, surface->pixel_format, surface->width, surface->height); + BlitTextures(surface->texture.handle, unscaled_tex.handle, CachedSurface::GetFormatType(surface->pixel_format), + MathUtil::Rectangle(0, 0, surface->GetScaledWidth(), surface->GetScaledHeight()), + MathUtil::Rectangle(0, 0, surface->width, surface->height)); + + texture_to_flush = unscaled_tex.handle; + } + + cur_state.texture_units[0].texture_2d = texture_to_flush; + cur_state.Apply(); + glActiveTexture(GL_TEXTURE0); + + glPixelStorei(GL_PACK_ROW_LENGTH, (GLint)surface->stride); + if (!surface->is_tiled) { + // TODO: Ensure this will always be a color format, not a depth or other format + ASSERT((size_t)surface->pixel_format < fb_format_tuples.size()); + const FormatTuple& tuple = fb_format_tuples[(unsigned int)surface->pixel_format]; + + glGetTexImage(GL_TEXTURE_2D, 0, tuple.format, tuple.type, dst_buffer); + } else { + SurfaceType type = CachedSurface::GetFormatType(surface->pixel_format); + if (type != SurfaceType::Depth && type != SurfaceType::DepthStencil) { + ASSERT((size_t)surface->pixel_format < fb_format_tuples.size()); + const FormatTuple& tuple = fb_format_tuples[(unsigned int)surface->pixel_format]; + + u32 bytes_per_pixel = CachedSurface::GetFormatBpp(surface->pixel_format) / 8; + + std::vector temp_gl_buffer(surface->width * surface->height * bytes_per_pixel); + + glGetTexImage(GL_TEXTURE_2D, 0, tuple.format, tuple.type, temp_gl_buffer.data()); + + // Directly copy pixels. Internal OpenGL color formats are consistent so no conversion is necessary. + MortonCopyPixels(surface->pixel_format, surface->width, surface->height, bytes_per_pixel, bytes_per_pixel, dst_buffer, temp_gl_buffer.data(), false); + } else { + // Depth/Stencil formats need special treatment since they aren't sampleable using LookupTexture and can't use RGBA format + size_t tuple_idx = (size_t)surface->pixel_format - 14; + ASSERT(tuple_idx < depth_format_tuples.size()); + const FormatTuple& tuple = depth_format_tuples[tuple_idx]; + + u32 bytes_per_pixel = CachedSurface::GetFormatBpp(surface->pixel_format) / 8; + + // OpenGL needs 4 bpp alignment for D24 since using GL_UNSIGNED_INT as type + bool use_4bpp = (surface->pixel_format == PixelFormat::D24); + + u32 gl_bytes_per_pixel = use_4bpp ? 4 : bytes_per_pixel; + + std::vector temp_gl_buffer(surface->width * surface->height * gl_bytes_per_pixel); + + glGetTexImage(GL_TEXTURE_2D, 0, tuple.format, tuple.type, temp_gl_buffer.data()); + + u8* temp_gl_buffer_ptr = use_4bpp ? temp_gl_buffer.data() + 1 : temp_gl_buffer.data(); + + MortonCopyPixels(surface->pixel_format, surface->width, surface->height, bytes_per_pixel, gl_bytes_per_pixel, dst_buffer, temp_gl_buffer_ptr, false); + } + } + glPixelStorei(GL_PACK_ROW_LENGTH, 0); + + surface->dirty = false; + + cur_state.texture_units[0].texture_2d = old_tex; + cur_state.Apply(); +} + +void RasterizerCacheOpenGL::FlushRegion(PAddr addr, u32 size, const CachedSurface* skip_surface, bool invalidate) { + if (size == 0) { + return; + } + + // Gather up unique surfaces that touch the region + std::unordered_set> touching_surfaces; + + auto surface_interval = boost::icl::interval::right_open(addr, addr + size); + auto cache_upper_bound = surface_cache.upper_bound(surface_interval); + for (auto it = surface_cache.lower_bound(surface_interval); it != cache_upper_bound; ++it) { + std::copy_if(it->second.begin(), it->second.end(), std::inserter(touching_surfaces, touching_surfaces.end()), + [skip_surface](std::shared_ptr surface) { return (surface.get() != skip_surface); }); + } + + // Flush and invalidate surfaces + for (auto surface : touching_surfaces) { + FlushSurface(surface.get()); + if (invalidate) { + Memory::RasterizerMarkRegionCached(surface->addr, surface->size, -1); + surface_cache.subtract(std::make_pair(boost::icl::interval::right_open(surface->addr, surface->addr + surface->size), std::set>({ surface }))); + } + } +} + +void RasterizerCacheOpenGL::FlushAll() { + for (auto& surfaces : surface_cache) { + for (auto& surface : surfaces.second) { + FlushSurface(surface.get()); + } + } } diff --git a/src/video_core/renderer_opengl/gl_rasterizer_cache.h b/src/video_core/renderer_opengl/gl_rasterizer_cache.h index b69651427..893d51138 100644 --- a/src/video_core/renderer_opengl/gl_rasterizer_cache.h +++ b/src/video_core/renderer_opengl/gl_rasterizer_cache.h @@ -6,38 +6,211 @@ #include #include +#include + +#include + +#include "common/math_util.h" + +#include "core/hw/gpu.h" #include "video_core/pica.h" #include "video_core/debug_utils/debug_utils.h" #include "video_core/renderer_opengl/gl_resource_manager.h" #include "video_core/renderer_opengl/gl_state.h" -class RasterizerCacheOpenGL : NonCopyable { -public: - ~RasterizerCacheOpenGL(); +struct CachedSurface; - /// Loads a texture from 3DS memory to OpenGL and caches it (if not already cached) - void LoadAndBindTexture(OpenGLState &state, unsigned texture_unit, const Pica::DebugUtils::TextureInfo& info); +using SurfaceCache = boost::icl::interval_map>>; - void LoadAndBindTexture(OpenGLState &state, unsigned texture_unit, const Pica::Regs::FullTextureConfig& config) { - LoadAndBindTexture(state, texture_unit, Pica::DebugUtils::TextureInfo::FromPicaRegister(config.config, config.format)); - } +struct CachedSurface { + enum class PixelFormat { + // First 5 formats are shared between textures and color buffers + RGBA8 = 0, + RGB8 = 1, + RGB5A1 = 2, + RGB565 = 3, + RGBA4 = 4, - /// Invalidate any cached resource intersecting the specified region. - void InvalidateInRange(PAddr addr, u32 size, bool ignore_hash = false); + // Texture-only formats + IA8 = 5, + RG8 = 6, + I8 = 7, + A8 = 8, + IA4 = 9, + I4 = 10, + A4 = 11, + ETC1 = 12, + ETC1A4 = 13, - /// Invalidate all cached OpenGL resources tracked by this cache manager - void InvalidateAll(); + // Depth buffer-only formats + D16 = 14, + // gap + D24 = 16, + D24S8 = 17, -private: - struct CachedTexture { - OGLTexture texture; - GLuint width; - GLuint height; - u32 size; - u64 hash; - PAddr addr; + Invalid = 255, }; - std::map> texture_cache; + enum class SurfaceType { + Color = 0, + Texture = 1, + Depth = 2, + DepthStencil = 3, + Invalid = 4, + }; + + static unsigned int GetFormatBpp(CachedSurface::PixelFormat format) { + static const std::array bpp_table = { + 32, // RGBA8 + 24, // RGB8 + 16, // RGB5A1 + 16, // RGB565 + 16, // RGBA4 + 16, // IA8 + 16, // RG8 + 8, // I8 + 8, // A8 + 8, // IA4 + 4, // I4 + 4, // A4 + 4, // ETC1 + 8, // ETC1A4 + 16, // D16 + 0, + 24, // D24 + 32, // D24S8 + }; + + ASSERT((unsigned int)format < ARRAY_SIZE(bpp_table)); + return bpp_table[(unsigned int)format]; + } + + static PixelFormat PixelFormatFromTextureFormat(Pica::Regs::TextureFormat format) { + return ((unsigned int)format < 14) ? (PixelFormat)format : PixelFormat::Invalid; + } + + static PixelFormat PixelFormatFromColorFormat(Pica::Regs::ColorFormat format) { + return ((unsigned int)format < 5) ? (PixelFormat)format : PixelFormat::Invalid; + } + + static PixelFormat PixelFormatFromDepthFormat(Pica::Regs::DepthFormat format) { + return ((unsigned int)format < 4) ? (PixelFormat)((unsigned int)format + 14) : PixelFormat::Invalid; + } + + static PixelFormat PixelFormatFromGPUPixelFormat(GPU::Regs::PixelFormat format) { + switch (format) { + // RGB565 and RGB5A1 are switched in PixelFormat compared to ColorFormat + case GPU::Regs::PixelFormat::RGB565: + return PixelFormat::RGB565; + case GPU::Regs::PixelFormat::RGB5A1: + return PixelFormat::RGB5A1; + default: + return ((unsigned int)format < 5) ? (PixelFormat)format : PixelFormat::Invalid; + } + } + + static bool CheckFormatsBlittable(PixelFormat pixel_format_a, PixelFormat pixel_format_b) { + SurfaceType a_type = GetFormatType(pixel_format_a); + SurfaceType b_type = GetFormatType(pixel_format_b); + + if ((a_type == SurfaceType::Color || a_type == SurfaceType::Texture) && (b_type == SurfaceType::Color || b_type == SurfaceType::Texture)) { + return true; + } + + if (a_type == SurfaceType::Depth && b_type == SurfaceType::Depth) { + return true; + } + + if (a_type == SurfaceType::DepthStencil && b_type == SurfaceType::DepthStencil) { + return true; + } + + return false; + } + + static SurfaceType GetFormatType(PixelFormat pixel_format) { + if ((unsigned int)pixel_format < 5) { + return SurfaceType::Color; + } + + if ((unsigned int)pixel_format < 14) { + return SurfaceType::Texture; + } + + if (pixel_format == PixelFormat::D16 || pixel_format == PixelFormat::D24) { + return SurfaceType::Depth; + } + + if (pixel_format == PixelFormat::D24S8) { + return SurfaceType::DepthStencil; + } + + return SurfaceType::Invalid; + } + + u32 GetScaledWidth() const { + return (u32)(width * res_scale_width); + } + + u32 GetScaledHeight() const { + return (u32)(height * res_scale_height); + } + + PAddr addr; + u32 size; + + PAddr min_valid; + PAddr max_valid; + + OGLTexture texture; + u32 width; + u32 height; + u32 stride = 0; + float res_scale_width = 1.f; + float res_scale_height = 1.f; + + bool is_tiled; + PixelFormat pixel_format; + bool dirty; +}; + +class RasterizerCacheOpenGL : NonCopyable { +public: + RasterizerCacheOpenGL(); + ~RasterizerCacheOpenGL(); + + /// Blits one texture to another + bool BlitTextures(GLuint src_tex, GLuint dst_tex, CachedSurface::SurfaceType type, const MathUtil::Rectangle& src_rect, const MathUtil::Rectangle& dst_rect); + + /// Attempt to blit one surface's texture to another + bool TryBlitSurfaces(CachedSurface* src_surface, const MathUtil::Rectangle& src_rect, CachedSurface* dst_surface, const MathUtil::Rectangle& dst_rect); + + /// Loads a texture from 3DS memory to OpenGL and caches it (if not already cached) + CachedSurface* GetSurface(const CachedSurface& params, bool match_res_scale, bool load_if_create); + + /// Attempt to find a subrect (resolution scaled) of a surface, otherwise loads a texture from 3DS memory to OpenGL and caches it (if not already cached) + CachedSurface* GetSurfaceRect(const CachedSurface& params, bool match_res_scale, bool load_if_create, MathUtil::Rectangle& out_rect); + + /// Gets a surface based on the texture configuration + CachedSurface* GetTextureSurface(const Pica::Regs::FullTextureConfig& config); + + /// Gets the color and depth surfaces and rect (resolution scaled) based on the framebuffer configuration + std::tuple> GetFramebufferSurfaces(const Pica::Regs::FramebufferConfig& config); + + /// Attempt to get a surface that exactly matches the fill region and format + CachedSurface* TryGetFillSurface(const GPU::Regs::MemoryFillConfig& config); + + /// Write the surface back to memory + void FlushSurface(CachedSurface* surface); + + /// Write any cached resources overlapping the region back to memory (if dirty) and optionally invalidate them in the cache + void FlushRegion(PAddr addr, u32 size, const CachedSurface* skip_surface, bool invalidate); + + /// Flush all cached resources tracked by this cache manager + void FlushAll(); + +private: + SurfaceCache surface_cache; + OGLFramebuffer transfer_framebuffers[2]; }; diff --git a/src/video_core/renderer_opengl/gl_state.cpp b/src/video_core/renderer_opengl/gl_state.cpp index 08e4d0b54..f04bdd8c5 100644 --- a/src/video_core/renderer_opengl/gl_state.cpp +++ b/src/video_core/renderer_opengl/gl_state.cpp @@ -3,6 +3,7 @@ // Refer to the license.txt file included. #include "video_core/pica.h" +#include "video_core/renderer_opengl/gl_resource_manager.h" #include "video_core/renderer_opengl/gl_state.h" OpenGLState OpenGLState::cur_state; @@ -48,17 +49,19 @@ OpenGLState::OpenGLState() { texture_unit.sampler = 0; } - for (auto& lut : lighting_lut) { + for (auto& lut : lighting_luts) { lut.texture_1d = 0; } - draw.framebuffer = 0; + draw.read_framebuffer = 0; + draw.draw_framebuffer = 0; draw.vertex_array = 0; draw.vertex_buffer = 0; + draw.uniform_buffer = 0; draw.shader_program = 0; } -void OpenGLState::Apply() { +void OpenGLState::Apply() const { // Culling if (cull.enabled != cur_state.cull.enabled) { if (cull.enabled) { @@ -175,16 +178,19 @@ void OpenGLState::Apply() { } // Lighting LUTs - for (unsigned i = 0; i < ARRAY_SIZE(lighting_lut); ++i) { - if (lighting_lut[i].texture_1d != cur_state.lighting_lut[i].texture_1d) { + for (unsigned i = 0; i < ARRAY_SIZE(lighting_luts); ++i) { + if (lighting_luts[i].texture_1d != cur_state.lighting_luts[i].texture_1d) { glActiveTexture(GL_TEXTURE3 + i); - glBindTexture(GL_TEXTURE_1D, lighting_lut[i].texture_1d); + glBindTexture(GL_TEXTURE_1D, lighting_luts[i].texture_1d); } } // Framebuffer - if (draw.framebuffer != cur_state.draw.framebuffer) { - glBindFramebuffer(GL_FRAMEBUFFER, draw.framebuffer); + if (draw.read_framebuffer != cur_state.draw.read_framebuffer) { + glBindFramebuffer(GL_READ_FRAMEBUFFER, draw.read_framebuffer); + } + if (draw.draw_framebuffer != cur_state.draw.draw_framebuffer) { + glBindFramebuffer(GL_DRAW_FRAMEBUFFER, draw.draw_framebuffer); } // Vertex array @@ -210,45 +216,58 @@ void OpenGLState::Apply() { cur_state = *this; } -void OpenGLState::ResetTexture(GLuint id) { +GLenum OpenGLState::CheckFBStatus(GLenum target) { + GLenum fb_status = glCheckFramebufferStatus(target); + if (fb_status != GL_FRAMEBUFFER_COMPLETE) { + const char* fb_description = (target == GL_READ_FRAMEBUFFER ? "READ" : (target == GL_DRAW_FRAMEBUFFER ? "DRAW" : "UNK")); + LOG_CRITICAL(Render_OpenGL, "OpenGL %s framebuffer check failed, status %X", fb_description, fb_status); + } + + return fb_status; +} + +void OpenGLState::ResetTexture(GLuint handle) { for (auto& unit : cur_state.texture_units) { - if (unit.texture_2d == id) { + if (unit.texture_2d == handle) { unit.texture_2d = 0; } } } -void OpenGLState::ResetSampler(GLuint id) { +void OpenGLState::ResetSampler(GLuint handle) { for (auto& unit : cur_state.texture_units) { - if (unit.sampler == id) { + if (unit.sampler == handle) { unit.sampler = 0; } } } -void OpenGLState::ResetProgram(GLuint id) { - if (cur_state.draw.shader_program == id) { +void OpenGLState::ResetProgram(GLuint handle) { + if (cur_state.draw.shader_program == handle) { cur_state.draw.shader_program = 0; } } -void OpenGLState::ResetBuffer(GLuint id) { - if (cur_state.draw.vertex_buffer == id) { +void OpenGLState::ResetBuffer(GLuint handle) { + if (cur_state.draw.vertex_buffer == handle) { cur_state.draw.vertex_buffer = 0; } - if (cur_state.draw.uniform_buffer == id) { + if (cur_state.draw.uniform_buffer == handle) { cur_state.draw.uniform_buffer = 0; } } -void OpenGLState::ResetVertexArray(GLuint id) { - if (cur_state.draw.vertex_array == id) { +void OpenGLState::ResetVertexArray(GLuint handle) { + if (cur_state.draw.vertex_array == handle) { cur_state.draw.vertex_array = 0; } } -void OpenGLState::ResetFramebuffer(GLuint id) { - if (cur_state.draw.framebuffer == id) { - cur_state.draw.framebuffer = 0; +void OpenGLState::ResetFramebuffer(GLuint handle) { + if (cur_state.draw.read_framebuffer == handle) { + cur_state.draw.read_framebuffer = 0; + } + if (cur_state.draw.draw_framebuffer == handle) { + cur_state.draw.draw_framebuffer = 0; } } diff --git a/src/video_core/renderer_opengl/gl_state.h b/src/video_core/renderer_opengl/gl_state.h index e848058d7..0f72e9004 100644 --- a/src/video_core/renderer_opengl/gl_state.h +++ b/src/video_core/renderer_opengl/gl_state.h @@ -5,6 +5,7 @@ #pragma once #include +#include class OpenGLState { public: @@ -63,15 +64,15 @@ public: struct { GLuint texture_1d; // GL_TEXTURE_BINDING_1D - } lighting_lut[6]; + } lighting_luts[6]; struct { - GLuint framebuffer; // GL_DRAW_FRAMEBUFFER_BINDING + GLuint read_framebuffer; // GL_READ_FRAMEBUFFER_BINDING + GLuint draw_framebuffer; // GL_DRAW_FRAMEBUFFER_BINDING GLuint vertex_array; // GL_VERTEX_ARRAY_BINDING GLuint vertex_buffer; // GL_ARRAY_BUFFER_BINDING GLuint uniform_buffer; // GL_UNIFORM_BUFFER_BINDING GLuint shader_program; // GL_CURRENT_PROGRAM - bool shader_dirty; } draw; OpenGLState(); @@ -82,14 +83,18 @@ public: } /// Apply this state as the current OpenGL state - void Apply(); + void Apply() const; - static void ResetTexture(GLuint id); - static void ResetSampler(GLuint id); - static void ResetProgram(GLuint id); - static void ResetBuffer(GLuint id); - static void ResetVertexArray(GLuint id); - static void ResetFramebuffer(GLuint id); + /// Check the status of the current OpenGL read or draw framebuffer configuration + static GLenum CheckFBStatus(GLenum target); + + /// Resets and unbinds any references to the given resource in the current OpenGL state + static void ResetTexture(GLuint handle); + static void ResetSampler(GLuint handle); + static void ResetProgram(GLuint handle); + static void ResetBuffer(GLuint handle); + static void ResetVertexArray(GLuint handle); + static void ResetFramebuffer(GLuint handle); private: static OpenGLState cur_state; diff --git a/src/video_core/renderer_opengl/renderer_opengl.cpp b/src/video_core/renderer_opengl/renderer_opengl.cpp index 11c4d0daf..8f907593f 100644 --- a/src/video_core/renderer_opengl/renderer_opengl.cpp +++ b/src/video_core/renderer_opengl/renderer_opengl.cpp @@ -107,7 +107,7 @@ void RendererOpenGL::SwapBuffers() { OpenGLState prev_state = OpenGLState::GetCurState(); state.Apply(); - for(int i : {0, 1}) { + for (int i : {0, 1}) { const auto& framebuffer = GPU::g_regs.framebuffer_config[i]; // Main LCD (0): 0x1ED02204, Sub LCD (1): 0x1ED02A04 @@ -117,25 +117,25 @@ void RendererOpenGL::SwapBuffers() { LCD::Read(color_fill.raw, lcd_color_addr); if (color_fill.is_enabled) { - LoadColorToActiveGLTexture(color_fill.color_r, color_fill.color_g, color_fill.color_b, textures[i]); + LoadColorToActiveGLTexture(color_fill.color_r, color_fill.color_g, color_fill.color_b, screen_infos[i].texture); // Resize the texture in case the framebuffer size has changed - textures[i].width = 1; - textures[i].height = 1; + screen_infos[i].texture.width = 1; + screen_infos[i].texture.height = 1; } else { - if (textures[i].width != (GLsizei)framebuffer.width || - textures[i].height != (GLsizei)framebuffer.height || - textures[i].format != framebuffer.color_format) { + if (screen_infos[i].texture.width != (GLsizei)framebuffer.width || + screen_infos[i].texture.height != (GLsizei)framebuffer.height || + screen_infos[i].texture.format != framebuffer.color_format) { // Reallocate texture if the framebuffer size has changed. // This is expected to not happen very often and hence should not be a // performance problem. - ConfigureFramebufferTexture(textures[i], framebuffer); + ConfigureFramebufferTexture(screen_infos[i].texture, framebuffer); } - LoadFBToActiveGLTexture(framebuffer, textures[i]); + LoadFBToScreenInfo(framebuffer, screen_infos[i]); // Resize the texture in case the framebuffer size has changed - textures[i].width = framebuffer.width; - textures[i].height = framebuffer.height; + screen_infos[i].texture.width = framebuffer.width; + screen_infos[i].texture.height = framebuffer.height; } } @@ -166,8 +166,8 @@ void RendererOpenGL::SwapBuffers() { /** * Loads framebuffer from emulated memory into the active OpenGL texture. */ -void RendererOpenGL::LoadFBToActiveGLTexture(const GPU::Regs::FramebufferConfig& framebuffer, - const TextureInfo& texture) { +void RendererOpenGL::LoadFBToScreenInfo(const GPU::Regs::FramebufferConfig& framebuffer, + ScreenInfo& screen_info) { const PAddr framebuffer_addr = framebuffer.active_fb == 0 ? framebuffer.address_left1 : framebuffer.address_left2; @@ -177,8 +177,6 @@ void RendererOpenGL::LoadFBToActiveGLTexture(const GPU::Regs::FramebufferConfig& framebuffer_addr, (int)framebuffer.width, (int)framebuffer.height, (int)framebuffer.format); - const u8* framebuffer_data = Memory::GetPhysicalPointer(framebuffer_addr); - int bpp = GPU::Regs::BytesPerPixel(framebuffer.color_format); size_t pixel_stride = framebuffer.stride / bpp; @@ -189,24 +187,34 @@ void RendererOpenGL::LoadFBToActiveGLTexture(const GPU::Regs::FramebufferConfig& // only allows rows to have a memory alignement of 4. ASSERT(pixel_stride % 4 == 0); - state.texture_units[0].texture_2d = texture.handle; - state.Apply(); + if (!Rasterizer()->AccelerateDisplay(framebuffer, framebuffer_addr, pixel_stride, screen_info)) { + // Reset the screen info's display texture to its own permanent texture + screen_info.display_texture = screen_info.texture.resource.handle; + screen_info.display_texcoords = MathUtil::Rectangle(0.f, 0.f, 1.f, 1.f); - glActiveTexture(GL_TEXTURE0); - glPixelStorei(GL_UNPACK_ROW_LENGTH, (GLint)pixel_stride); + Memory::RasterizerFlushRegion(framebuffer_addr, framebuffer.stride * framebuffer.height); - // Update existing texture - // TODO: Test what happens on hardware when you change the framebuffer dimensions so that they - // differ from the LCD resolution. - // TODO: Applications could theoretically crash Citra here by specifying too large - // framebuffer sizes. We should make sure that this cannot happen. - glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, framebuffer.width, framebuffer.height, - texture.gl_format, texture.gl_type, framebuffer_data); + const u8* framebuffer_data = Memory::GetPhysicalPointer(framebuffer_addr); - glPixelStorei(GL_UNPACK_ROW_LENGTH, 0); + state.texture_units[0].texture_2d = screen_info.texture.resource.handle; + state.Apply(); - state.texture_units[0].texture_2d = 0; - state.Apply(); + glActiveTexture(GL_TEXTURE0); + glPixelStorei(GL_UNPACK_ROW_LENGTH, (GLint)pixel_stride); + + // Update existing texture + // TODO: Test what happens on hardware when you change the framebuffer dimensions so that they + // differ from the LCD resolution. + // TODO: Applications could theoretically crash Citra here by specifying too large + // framebuffer sizes. We should make sure that this cannot happen. + glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, framebuffer.width, framebuffer.height, + screen_info.texture.gl_format, screen_info.texture.gl_type, framebuffer_data); + + glPixelStorei(GL_UNPACK_ROW_LENGTH, 0); + + state.texture_units[0].texture_2d = 0; + state.Apply(); + } } /** @@ -216,7 +224,7 @@ void RendererOpenGL::LoadFBToActiveGLTexture(const GPU::Regs::FramebufferConfig& */ void RendererOpenGL::LoadColorToActiveGLTexture(u8 color_r, u8 color_g, u8 color_b, const TextureInfo& texture) { - state.texture_units[0].texture_2d = texture.handle; + state.texture_units[0].texture_2d = texture.resource.handle; state.Apply(); glActiveTexture(GL_TEXTURE0); @@ -224,6 +232,9 @@ void RendererOpenGL::LoadColorToActiveGLTexture(u8 color_r, u8 color_g, u8 color // Update existing texture glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 1, 1, 0, GL_RGB, GL_UNSIGNED_BYTE, framebuffer_data); + + state.texture_units[0].texture_2d = 0; + state.Apply(); } /** @@ -233,20 +244,22 @@ void RendererOpenGL::InitOpenGLObjects() { glClearColor(Settings::values.bg_red, Settings::values.bg_green, Settings::values.bg_blue, 0.0f); // Link shaders and get variable locations - program_id = GLShader::LoadProgram(vertex_shader, fragment_shader); - uniform_modelview_matrix = glGetUniformLocation(program_id, "modelview_matrix"); - uniform_color_texture = glGetUniformLocation(program_id, "color_texture"); - attrib_position = glGetAttribLocation(program_id, "vert_position"); - attrib_tex_coord = glGetAttribLocation(program_id, "vert_tex_coord"); + shader.Create(vertex_shader, fragment_shader); + state.draw.shader_program = shader.handle; + state.Apply(); + uniform_modelview_matrix = glGetUniformLocation(shader.handle, "modelview_matrix"); + uniform_color_texture = glGetUniformLocation(shader.handle, "color_texture"); + attrib_position = glGetAttribLocation(shader.handle, "vert_position"); + attrib_tex_coord = glGetAttribLocation(shader.handle, "vert_tex_coord"); // Generate VBO handle for drawing - glGenBuffers(1, &vertex_buffer_handle); + vertex_buffer.Create(); // Generate VAO - glGenVertexArrays(1, &vertex_array_handle); + vertex_array.Create(); - state.draw.vertex_array = vertex_array_handle; - state.draw.vertex_buffer = vertex_buffer_handle; + state.draw.vertex_array = vertex_array.handle; + state.draw.vertex_buffer = vertex_buffer.handle; state.draw.uniform_buffer = 0; state.Apply(); @@ -258,13 +271,13 @@ void RendererOpenGL::InitOpenGLObjects() { glEnableVertexAttribArray(attrib_tex_coord); // Allocate textures for each screen - for (auto& texture : textures) { - glGenTextures(1, &texture.handle); + for (auto& screen_info : screen_infos) { + screen_info.texture.resource.Create(); // Allocation of storage is deferred until the first frame, when we // know the framebuffer size. - state.texture_units[0].texture_2d = texture.handle; + state.texture_units[0].texture_2d = screen_info.texture.resource.handle; state.Apply(); glActiveTexture(GL_TEXTURE0); @@ -273,6 +286,8 @@ void RendererOpenGL::InitOpenGLObjects() { glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); + + screen_info.display_texture = screen_info.texture.resource.handle; } state.texture_units[0].texture_2d = 0; @@ -327,30 +342,38 @@ void RendererOpenGL::ConfigureFramebufferTexture(TextureInfo& texture, UNIMPLEMENTED(); } - state.texture_units[0].texture_2d = texture.handle; + state.texture_units[0].texture_2d = texture.resource.handle; state.Apply(); glActiveTexture(GL_TEXTURE0); glTexImage2D(GL_TEXTURE_2D, 0, internal_format, texture.width, texture.height, 0, texture.gl_format, texture.gl_type, nullptr); + + state.texture_units[0].texture_2d = 0; + state.Apply(); } /** * Draws a single texture to the emulator window, rotating the texture to correct for the 3DS's LCD rotation. */ -void RendererOpenGL::DrawSingleScreenRotated(const TextureInfo& texture, float x, float y, float w, float h) { +void RendererOpenGL::DrawSingleScreenRotated(const ScreenInfo& screen_info, float x, float y, float w, float h) { + auto& texcoords = screen_info.display_texcoords; + std::array vertices = {{ - ScreenRectVertex(x, y, 1.f, 0.f), - ScreenRectVertex(x+w, y, 1.f, 1.f), - ScreenRectVertex(x, y+h, 0.f, 0.f), - ScreenRectVertex(x+w, y+h, 0.f, 1.f), + ScreenRectVertex(x, y, texcoords.bottom, texcoords.left), + ScreenRectVertex(x+w, y, texcoords.bottom, texcoords.right), + ScreenRectVertex(x, y+h, texcoords.top, texcoords.left), + ScreenRectVertex(x+w, y+h, texcoords.top, texcoords.right), }}; - state.texture_units[0].texture_2d = texture.handle; + state.texture_units[0].texture_2d = screen_info.display_texture; state.Apply(); glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(vertices), vertices.data()); glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); + + state.texture_units[0].texture_2d = 0; + state.Apply(); } /** @@ -362,9 +385,6 @@ void RendererOpenGL::DrawScreens() { glViewport(0, 0, layout.width, layout.height); glClear(GL_COLOR_BUFFER_BIT); - state.draw.shader_program = program_id; - state.Apply(); - // Set projection matrix std::array ortho_matrix = MakeOrthographicMatrix((float)layout.width, (float)layout.height); @@ -374,9 +394,9 @@ void RendererOpenGL::DrawScreens() { glActiveTexture(GL_TEXTURE0); glUniform1i(uniform_color_texture, 0); - DrawSingleScreenRotated(textures[0], (float)layout.top_screen.left, (float)layout.top_screen.top, + DrawSingleScreenRotated(screen_infos[0], (float)layout.top_screen.left, (float)layout.top_screen.top, (float)layout.top_screen.GetWidth(), (float)layout.top_screen.GetHeight()); - DrawSingleScreenRotated(textures[1], (float)layout.bottom_screen.left,(float)layout.bottom_screen.top, + DrawSingleScreenRotated(screen_infos[1], (float)layout.bottom_screen.left,(float)layout.bottom_screen.top, (float)layout.bottom_screen.GetWidth(), (float)layout.bottom_screen.GetHeight()); m_current_frame++; diff --git a/src/video_core/renderer_opengl/renderer_opengl.h b/src/video_core/renderer_opengl/renderer_opengl.h index fe4d142a5..5ca5255ac 100644 --- a/src/video_core/renderer_opengl/renderer_opengl.h +++ b/src/video_core/renderer_opengl/renderer_opengl.h @@ -11,10 +11,28 @@ #include "core/hw/gpu.h" #include "video_core/renderer_base.h" +#include "video_core/renderer_opengl/gl_resource_manager.h" #include "video_core/renderer_opengl/gl_state.h" class EmuWindow; +/// Structure used for storing information about the textures for each 3DS screen +struct TextureInfo { + OGLTexture resource; + GLsizei width; + GLsizei height; + GPU::Regs::PixelFormat format; + GLenum gl_format; + GLenum gl_type; +}; + +/// Structure used for storing information about the display target for each 3DS screen +struct ScreenInfo { + GLuint display_texture; + MathUtil::Rectangle display_texcoords; + TextureInfo texture; +}; + class RendererOpenGL : public RendererBase { public: @@ -37,26 +55,16 @@ public: void ShutDown() override; private: - /// Structure used for storing information about the textures for each 3DS screen - struct TextureInfo { - GLuint handle; - GLsizei width; - GLsizei height; - GPU::Regs::PixelFormat format; - GLenum gl_format; - GLenum gl_type; - }; - void InitOpenGLObjects(); void ConfigureFramebufferTexture(TextureInfo& texture, const GPU::Regs::FramebufferConfig& framebuffer); void DrawScreens(); - void DrawSingleScreenRotated(const TextureInfo& texture, float x, float y, float w, float h); + void DrawSingleScreenRotated(const ScreenInfo& screen_info, float x, float y, float w, float h); void UpdateFramerate(); - // Loads framebuffer from emulated memory into the active OpenGL texture. - void LoadFBToActiveGLTexture(const GPU::Regs::FramebufferConfig& framebuffer, - const TextureInfo& texture); + // Loads framebuffer from emulated memory into the display information structure + void LoadFBToScreenInfo(const GPU::Regs::FramebufferConfig& framebuffer, + ScreenInfo& screen_info); // Fills active OpenGL texture with the given RGB color. void LoadColorToActiveGLTexture(u8 color_r, u8 color_g, u8 color_b, const TextureInfo& texture); @@ -69,10 +77,10 @@ private: OpenGLState state; // OpenGL object IDs - GLuint vertex_array_handle; - GLuint vertex_buffer_handle; - GLuint program_id; - std::array textures; ///< Textures for top and bottom screens respectively + OGLVertexArray vertex_array; + OGLBuffer vertex_buffer; + OGLShader shader; + std::array screen_infos; ///< Display information for top and bottom screens respectively // Shader uniform location indices GLuint uniform_modelview_matrix; GLuint uniform_color_texture; diff --git a/src/video_core/swrasterizer.h b/src/video_core/swrasterizer.h index 9a9a76d7a..090f899bc 100644 --- a/src/video_core/swrasterizer.h +++ b/src/video_core/swrasterizer.h @@ -11,16 +11,14 @@ namespace VideoCore { class SWRasterizer : public RasterizerInterface { - void InitObjects() override {} - void Reset() override {} void AddTriangle(const Pica::Shader::OutputVertex& v0, const Pica::Shader::OutputVertex& v1, const Pica::Shader::OutputVertex& v2) override; void DrawTriangles() override {} - void FlushFramebuffer() override {} void NotifyPicaRegisterChanged(u32 id) override {} + void FlushAll() override {} void FlushRegion(PAddr addr, u32 size) override {} - void InvalidateRegion(PAddr addr, u32 size) override {} + void FlushAndInvalidateRegion(PAddr addr, u32 size) override {} }; } From 3268cab26b49468bbab7c09e6eb8f36ed4a91158 Mon Sep 17 00:00:00 2001 From: tfarley Date: Fri, 22 Apr 2016 10:48:00 -0400 Subject: [PATCH 073/104] HWRasterizer: sync specular uniform for new shaders --- src/video_core/renderer_opengl/gl_rasterizer.cpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/video_core/renderer_opengl/gl_rasterizer.cpp b/src/video_core/renderer_opengl/gl_rasterizer.cpp index da4121c35..30187d4cf 100644 --- a/src/video_core/renderer_opengl/gl_rasterizer.cpp +++ b/src/video_core/renderer_opengl/gl_rasterizer.cpp @@ -874,6 +874,8 @@ void RasterizerOpenGL::SetShader() { SyncGlobalAmbient(); for (int light_index = 0; light_index < 8; light_index++) { + SyncLightSpecular0(light_index); + SyncLightSpecular1(light_index); SyncLightDiffuse(light_index); SyncLightAmbient(light_index); SyncLightPosition(light_index); From 562f36a1442f112fa4bedfce12f7a0e8470369cf Mon Sep 17 00:00:00 2001 From: tfarley Date: Fri, 22 Apr 2016 10:52:02 -0400 Subject: [PATCH 074/104] HWRasterizer: reorder declarations to match defs --- src/video_core/renderer_opengl/gl_rasterizer.h | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/src/video_core/renderer_opengl/gl_rasterizer.h b/src/video_core/renderer_opengl/gl_rasterizer.h index 5aa638985..8d6177e88 100644 --- a/src/video_core/renderer_opengl/gl_rasterizer.h +++ b/src/video_core/renderer_opengl/gl_rasterizer.h @@ -332,18 +332,24 @@ private: /// Syncs the depth test states to match the PICA register void SyncDepthTest(); - /// Syncs the TEV constant color to match the PICA register - void SyncTevConstColor(int tev_index, const Pica::Regs::TevStageConfig& tev_stage); - /// Syncs the TEV combiner color buffer to match the PICA register void SyncCombinerColor(); + /// Syncs the TEV constant color to match the PICA register + void SyncTevConstColor(int tev_index, const Pica::Regs::TevStageConfig& tev_stage); + /// Syncs the lighting global ambient color to match the PICA register void SyncGlobalAmbient(); /// Syncs the lighting lookup tables void SyncLightingLUT(unsigned index); + /// Syncs the specified light's specular 0 color to match the PICA register + void SyncLightSpecular0(int light_index); + + /// Syncs the specified light's specular 1 color to match the PICA register + void SyncLightSpecular1(int light_index); + /// Syncs the specified light's diffuse color to match the PICA register void SyncLightDiffuse(int light_index); @@ -353,12 +359,6 @@ private: /// Syncs the specified light's position to match the PICA register void SyncLightPosition(int light_index); - /// Syncs the specified light's specular 0 color to match the PICA register - void SyncLightSpecular0(int light_index); - - /// Syncs the specified light's specular 1 color to match the PICA register - void SyncLightSpecular1(int light_index); - OpenGLState state; RasterizerCacheOpenGL res_cache; From d051bd303225838e0e50a3e3ddc22337c1fc0f0c Mon Sep 17 00:00:00 2001 From: Sam Spilsbury Date: Sun, 27 Mar 2016 11:59:50 +0800 Subject: [PATCH 075/104] CMakeLists: Use CMAKE_THREAD_LIBS_INIT --- CMakeLists.txt | 6 ++++-- src/citra/CMakeLists.txt | 2 +- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 3a0a161e7..ddde19760 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -65,8 +65,8 @@ endif() message(STATUS "Target architecture: ${ARCHITECTURE}") if (NOT MSVC) - set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++1y -Wno-attributes -pthread") - set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -pthread") + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++1y -Wno-attributes") + set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS}") if (ARCHITECTURE_x86_64) set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -msse4.1") @@ -135,6 +135,8 @@ list(APPEND CMAKE_MODULE_PATH "${CMAKE_SOURCE_DIR}/externals/cmake-modules") find_package(OpenGL REQUIRED) include_directories(${OPENGL_INCLUDE_DIR}) +find_package(Threads REQUIRED) + if (ENABLE_SDL2) if (CITRA_USE_BUNDLED_SDL2) # Detect toolchain and platform diff --git a/src/citra/CMakeLists.txt b/src/citra/CMakeLists.txt index fa615deb9..351752c1c 100644 --- a/src/citra/CMakeLists.txt +++ b/src/citra/CMakeLists.txt @@ -21,7 +21,7 @@ target_link_libraries(citra ${SDL2_LIBRARY} ${OPENGL_gl_LIBRARY} inih glad) if (MSVC) target_link_libraries(citra getopt) endif() -target_link_libraries(citra ${PLATFORM_LIBRARIES}) +target_link_libraries(citra ${PLATFORM_LIBRARIES} ${CMAKE_THREAD_LIBS_INIT}) if(${CMAKE_SYSTEM_NAME} MATCHES "Linux|FreeBSD|OpenBSD|NetBSD") install(TARGETS citra RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}/bin") From aacc3a4a59a9a66c3768c8cbba0ab4c03a4e5920 Mon Sep 17 00:00:00 2001 From: Sam Spilsbury Date: Sun, 27 Mar 2016 12:01:29 +0800 Subject: [PATCH 076/104] microprofile: Use std::abs Using the global-namespace C function will cause the wrong overload to get picked --- externals/microprofile/microprofileui.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/externals/microprofile/microprofileui.h b/externals/microprofile/microprofileui.h index eac1119a4..cc12739cb 100644 --- a/externals/microprofile/microprofileui.h +++ b/externals/microprofile/microprofileui.h @@ -879,7 +879,7 @@ void MicroProfileDrawDetailedBars(uint32_t nWidth, uint32_t nHeight, int nBaseY, static int64_t nRefCpu = 0, nRefGpu = 0; if(MicroProfileGetGpuTickReference(&nTickReferenceCpu, &nTickReferenceGpu)) { - if(0 == nRefCpu || abs(nRefCpu-nBaseTicksCpu) > abs(nTickReferenceCpu-nBaseTicksCpu)) + if(0 == nRefCpu || std::abs(nRefCpu-nBaseTicksCpu) > std::abs(nTickReferenceCpu-nBaseTicksCpu)) { nRefCpu = nTickReferenceCpu; nRefGpu = nTickReferenceGpu; From fdd7e9e86aba614b20d1773112c43c094f668803 Mon Sep 17 00:00:00 2001 From: Sam Spilsbury Date: Sun, 27 Mar 2016 12:01:57 +0800 Subject: [PATCH 077/104] microprofileui: Use correct printf specifier --- externals/microprofile/microprofileui.h | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/externals/microprofile/microprofileui.h b/externals/microprofile/microprofileui.h index cc12739cb..45bec8af6 100644 --- a/externals/microprofile/microprofileui.h +++ b/externals/microprofile/microprofileui.h @@ -1230,7 +1230,12 @@ void MicroProfileDrawDetailedBars(uint32_t nWidth, uint32_t nHeight, int nBaseY, char ThreadName[MicroProfileThreadLog::THREAD_MAX_LEN + 16]; const char* cLocal = MicroProfileIsLocalThread(nThreadId) ? "*": " "; +#if defined(WIN32) + // nThreadId is 32-bit on Windows int nStrLen = snprintf(ThreadName, sizeof(ThreadName)-1, "%04x: %s%s", nThreadId, cLocal, i < nNumThreadsBase ? &S.Pool[i]->ThreadName[0] : MICROPROFILE_THREAD_NAME_FROM_ID(nThreadId) ); +#else + int nStrLen = snprintf(ThreadName, sizeof(ThreadName)-1, "%04llx: %s%s", nThreadId, cLocal, i < nNumThreadsBase ? &S.Pool[i]->ThreadName[0] : MICROPROFILE_THREAD_NAME_FROM_ID(nThreadId) ); +#endif uint32_t nThreadColor = -1; if(nThreadId == nContextSwitchHoverThreadAfter || nThreadId == nContextSwitchHoverThreadBefore) nThreadColor = UI.nHoverColorShared|0x906060; From 2850a223592edad677e2fcd31a5f53b057c4ecc8 Mon Sep 17 00:00:00 2001 From: Sam Spilsbury Date: Sun, 27 Mar 2016 12:02:22 +0800 Subject: [PATCH 078/104] debugger: Warn if we reach an unreachable format --- src/citra_qt/debugger/graphics_framebuffer.cpp | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/src/citra_qt/debugger/graphics_framebuffer.cpp b/src/citra_qt/debugger/graphics_framebuffer.cpp index c30e75933..68cff78b2 100644 --- a/src/citra_qt/debugger/graphics_framebuffer.cpp +++ b/src/citra_qt/debugger/graphics_framebuffer.cpp @@ -346,5 +346,11 @@ u32 GraphicsFramebufferWidget::BytesPerPixel(GraphicsFramebufferWidget::Format f case Format::RGBA4: case Format::D16: return 2; + default: + UNREACHABLE_MSG("GraphicsFramebufferWidget::BytesPerPixel: this " + "should not be reached as this function should " + "be given a format which is in " + "GraphicsFramebufferWidget::Format. Instead got %i", + static_cast(format)); } } From 41ec40e9aa2e8445ac73f90f9784c4130b977dae Mon Sep 17 00:00:00 2001 From: Sam Spilsbury Date: Sun, 27 Mar 2016 12:03:19 +0800 Subject: [PATCH 079/104] gdbstub: Don't check if unsigned int is > 0 --- src/core/gdbstub/gdbstub.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/core/gdbstub/gdbstub.cpp b/src/core/gdbstub/gdbstub.cpp index c1a7ec5bf..ae0c116ef 100644 --- a/src/core/gdbstub/gdbstub.cpp +++ b/src/core/gdbstub/gdbstub.cpp @@ -529,7 +529,7 @@ static void ReadRegister() { id |= HexCharToValue(command_buffer[2]); } - if (id >= R0_REGISTER && id <= R15_REGISTER) { + if (id <= R15_REGISTER) { IntToGdbHex(reply, Core::g_app_core->GetReg(id)); } else if (id == CPSR_REGISTER) { IntToGdbHex(reply, Core::g_app_core->GetCPSR()); @@ -584,7 +584,7 @@ static void WriteRegister() { id |= HexCharToValue(command_buffer[2]); } - if (id >= R0_REGISTER && id <= R15_REGISTER) { + if (id <= R15_REGISTER) { Core::g_app_core->SetReg(id, GdbHexToInt(buffer_ptr)); } else if (id == CPSR_REGISTER) { Core::g_app_core->SetCPSR(GdbHexToInt(buffer_ptr)); From 040b7386a92fcadc5c4b08643299567de876c4d6 Mon Sep 17 00:00:00 2001 From: Sam Spilsbury Date: Sun, 27 Mar 2016 12:03:44 +0800 Subject: [PATCH 080/104] fs: Fix what appears to be a typo (filename_size / file_size) --- src/core/hle/service/fs/fs_user.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/core/hle/service/fs/fs_user.cpp b/src/core/hle/service/fs/fs_user.cpp index 3ec7ceb30..7df7da5a4 100644 --- a/src/core/hle/service/fs/fs_user.cpp +++ b/src/core/hle/service/fs/fs_user.cpp @@ -250,7 +250,7 @@ static void CreateFile(Service::Interface* self) { FileSys::Path file_path(filename_type, filename_size, filename_ptr); - LOG_DEBUG(Service_FS, "type=%d size=%llu data=%s", filename_type, filename_size, file_path.DebugStr().c_str()); + LOG_DEBUG(Service_FS, "type=%d size=%llu data=%s", filename_type, file_size, file_path.DebugStr().c_str()); cmd_buff[1] = CreateFileInArchive(archive_handle, file_path, file_size).raw; } From 60f2587eaca6d9e3d73f5361b37b67dcd4a2a72d Mon Sep 17 00:00:00 2001 From: Sam Spilsbury Date: Sun, 27 Mar 2016 12:04:01 +0800 Subject: [PATCH 081/104] ncch: Use correct format specifier (for long long uint) --- src/core/loader/ncch.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/core/loader/ncch.cpp b/src/core/loader/ncch.cpp index a4b47ef8c..066e91a9e 100644 --- a/src/core/loader/ncch.cpp +++ b/src/core/loader/ncch.cpp @@ -255,7 +255,7 @@ ResultStatus AppLoader_NCCH::Load() { resource_limit_category = exheader_header.arm11_system_local_caps.resource_limit_category; LOG_INFO(Loader, "Name: %s" , exheader_header.codeset_info.name); - LOG_INFO(Loader, "Program ID: %016X" , ncch_header.program_id); + LOG_INFO(Loader, "Program ID: %016llX" , ncch_header.program_id); LOG_DEBUG(Loader, "Code compressed: %s" , is_compressed ? "yes" : "no"); LOG_DEBUG(Loader, "Entry point: 0x%08X", entry_point); LOG_DEBUG(Loader, "Code size: 0x%08X", code_size); From 39d4994c15c46aeef0b3643e6db8b1f735674a7a Mon Sep 17 00:00:00 2001 From: Sam Spilsbury Date: Sun, 27 Mar 2016 12:04:16 +0800 Subject: [PATCH 082/104] pica: Handle default lighting case --- src/video_core/pica.h | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/src/video_core/pica.h b/src/video_core/pica.h index 1810eca98..cf130d7f8 100644 --- a/src/video_core/pica.h +++ b/src/video_core/pica.h @@ -747,8 +747,13 @@ struct Regs { case LightingSampler::ReflectGreen: case LightingSampler::ReflectBlue: return (config == LightingConfig::Config4) || (config == LightingConfig::Config5) || (config == LightingConfig::Config7); + default: + UNREACHABLE_MSG("Regs::IsLightingSamplerSupported: Reached " + "unreachable section, sampler should be one " + "of Distribution0, Distribution1, Fresnel, " + "ReflectRed, ReflectGreen or ReflectBlue, instead " + "got %i", static_cast(config)); } - return false; } struct { From 205e8f9f9ece7ee335a1987aa4a1b72f7409abd5 Mon Sep 17 00:00:00 2001 From: Sam Spilsbury Date: Mon, 11 Apr 2016 07:22:41 +0800 Subject: [PATCH 083/104] assert: Add _MSG variations for UNREACHABLE and UNIMPLEMENTED --- src/common/assert.h | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/common/assert.h b/src/common/assert.h index 6849778b7..d7f19f5eb 100644 --- a/src/common/assert.h +++ b/src/common/assert.h @@ -39,6 +39,7 @@ static void assert_noinline_call(const Fn& fn) { }); } while (0) #define UNREACHABLE() ASSERT_MSG(false, "Unreachable code!") +#define UNREACHABLE_MSG(_a_, ...) ASSERT_MSG(false, _a_, __VA_ARGS__) #ifdef _DEBUG #define DEBUG_ASSERT(_a_) ASSERT(_a_) @@ -49,3 +50,4 @@ static void assert_noinline_call(const Fn& fn) { #endif #define UNIMPLEMENTED() DEBUG_ASSERT_MSG(false, "Unimplemented code!") +#define UNIMPLEMENTED_MSG(_a_, ...) ASSERT_MSG(false, _a_, __VA_ARGS__) \ No newline at end of file From 9572652ddce1ff51f48829d787ebe33272c6aff6 Mon Sep 17 00:00:00 2001 From: LittleWhite Date: Sat, 23 Apr 2016 15:45:35 +0200 Subject: [PATCH 084/104] Protect use of std::is_trivially_copyable to compile with GCC 4.9 --- src/common/file_util.h | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/common/file_util.h b/src/common/file_util.h index b54a9fb72..3aac4fa46 100644 --- a/src/common/file_util.h +++ b/src/common/file_util.h @@ -192,7 +192,9 @@ public: size_t ReadArray(T* data, size_t length) { static_assert(std::is_standard_layout(), "Given array does not consist of standard layout objects"); +#if (__GNUC__ >= 5) || defined(__clang__) || defined(_MSC_VER) static_assert(std::is_trivially_copyable(), "Given array does not consist of trivially copyable objects"); +#endif if (!IsOpen()) { m_good = false; @@ -210,7 +212,9 @@ public: size_t WriteArray(const T* data, size_t length) { static_assert(std::is_standard_layout(), "Given array does not consist of standard layout objects"); +#if (__GNUC__ >= 5) || defined(__clang__) || defined(_MSC_VER) static_assert(std::is_trivially_copyable(), "Given array does not consist of trivially copyable objects"); +#endif if (!IsOpen()) { m_good = false; From 913f7ee524f9691ae2dc22625b5af9be3dcfe49e Mon Sep 17 00:00:00 2001 From: MerryMage Date: Sun, 24 Apr 2016 09:01:53 +0100 Subject: [PATCH 085/104] DSP_DSP: Remove unused variable --- src/core/hle/service/dsp_dsp.cpp | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/core/hle/service/dsp_dsp.cpp b/src/core/hle/service/dsp_dsp.cpp index 08e437125..751cb3d61 100644 --- a/src/core/hle/service/dsp_dsp.cpp +++ b/src/core/hle/service/dsp_dsp.cpp @@ -17,7 +17,6 @@ namespace DSP_DSP { -static u32 read_pipe_count; static Kernel::SharedPtr semaphore_event; struct PairHash { @@ -458,7 +457,6 @@ const Interface::FunctionInfo FunctionTable[] = { Interface::Interface() { semaphore_event = Kernel::Event::Create(Kernel::ResetType::OneShot, "DSP_DSP::semaphore_event"); - read_pipe_count = 0; Register(FunctionTable); } From 01a1555b5d6d6b560c3168b76e5235175e7d081b Mon Sep 17 00:00:00 2001 From: Henrik Rydgard Date: Sun, 24 Apr 2016 14:19:49 +0200 Subject: [PATCH 086/104] Replace std::map with std::array for graphics event breakpoints, and allow the compiler to inline. Saves 1%+ in vertex heavy situations. --- src/citra_qt/debugger/graphics_breakpoints.cpp | 4 ++-- src/video_core/debug_utils/debug_utils.cpp | 5 +---- src/video_core/debug_utils/debug_utils.h | 16 +++++++++++++--- 3 files changed, 16 insertions(+), 9 deletions(-) diff --git a/src/citra_qt/debugger/graphics_breakpoints.cpp b/src/citra_qt/debugger/graphics_breakpoints.cpp index 819ec7707..c8510128a 100644 --- a/src/citra_qt/debugger/graphics_breakpoints.cpp +++ b/src/citra_qt/debugger/graphics_breakpoints.cpp @@ -75,7 +75,7 @@ QVariant BreakPointModel::data(const QModelIndex& index, int role) const case Role_IsEnabled: { auto context = context_weak.lock(); - return context && context->breakpoints[event].enabled; + return context && context->breakpoints[(int)event].enabled; } default: @@ -110,7 +110,7 @@ bool BreakPointModel::setData(const QModelIndex& index, const QVariant& value, i if (!context) return false; - context->breakpoints[event].enabled = value == Qt::Checked; + context->breakpoints[(int)event].enabled = value == Qt::Checked; QModelIndex changed_index = createIndex(index.row(), 0); emit dataChanged(changed_index, changed_index); return true; diff --git a/src/video_core/debug_utils/debug_utils.cpp b/src/video_core/debug_utils/debug_utils.cpp index 1f058c4e2..178a566f7 100644 --- a/src/video_core/debug_utils/debug_utils.cpp +++ b/src/video_core/debug_utils/debug_utils.cpp @@ -40,10 +40,7 @@ using nihstro::DVLPHeader; namespace Pica { -void DebugContext::OnEvent(Event event, void* data) { - if (!breakpoints[event].enabled) - return; - +void DebugContext::DoOnEvent(Event event, void* data) { { std::unique_lock lock(breakpoint_mutex); diff --git a/src/video_core/debug_utils/debug_utils.h b/src/video_core/debug_utils/debug_utils.h index 7df941619..56f9bd958 100644 --- a/src/video_core/debug_utils/debug_utils.h +++ b/src/video_core/debug_utils/debug_utils.h @@ -114,7 +114,15 @@ public: * @param event Event which has happened * @param data Optional data pointer (pass nullptr if unused). Needs to remain valid until Resume() is called. */ - void OnEvent(Event event, void* data); + void OnEvent(Event event, void* data) { + // This check is left in the header to allow the compiler to inline it. + if (!breakpoints[(int)event].enabled) + return; + // For the rest of event handling, call a separate function. + DoOnEvent(event, data); + } + + void DoOnEvent(Event event, void *data); /** * Resume from the current breakpoint. @@ -126,12 +134,14 @@ public: * Delete all set breakpoints and resume emulation. */ void ClearBreakpoints() { - breakpoints.clear(); + for (auto &bp : breakpoints) { + bp.enabled = false; + } Resume(); } // TODO: Evaluate if access to these members should be hidden behind a public interface. - std::map breakpoints; + std::array breakpoints; Event active_breakpoint; bool at_breakpoint = false; From df81fa11fc8972a5775a57ccde1e0ef8d7fbfe64 Mon Sep 17 00:00:00 2001 From: Sam Spilsbury Date: Sun, 24 Apr 2016 23:39:25 +0800 Subject: [PATCH 087/104] CMakeLists: Use imported version of Threads::Threads This requires bumping up to a minimum of CMake 3.1. The benefit of using the imported target is that you can switch to the -pthread compiler flag on request, which may be necessary for some systems if available. --- CMakeLists.txt | 8 +++++--- src/citra/CMakeLists.txt | 2 +- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index ddde19760..019321ad8 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,6 +1,6 @@ -# CMake 2.8.11 required for Qt5 settings to be applied automatically on -# dependent libraries. -cmake_minimum_required(VERSION 2.8.11) +# CMake 3.1 required for Qt5 settings to be applied automatically on +# dependent libraries and IMPORTED targets. +cmake_minimum_required(VERSION 3.1) function(download_bundled_external remote_path lib_name prefix_var) set(prefix "${CMAKE_BINARY_DIR}/externals/${lib_name}") @@ -135,6 +135,8 @@ list(APPEND CMAKE_MODULE_PATH "${CMAKE_SOURCE_DIR}/externals/cmake-modules") find_package(OpenGL REQUIRED) include_directories(${OPENGL_INCLUDE_DIR}) +# Prefer the -pthread flag on Linux. +set (THREADS_PREFER_PTHREAD_FLAG ON) find_package(Threads REQUIRED) if (ENABLE_SDL2) diff --git a/src/citra/CMakeLists.txt b/src/citra/CMakeLists.txt index 351752c1c..43fa06b4e 100644 --- a/src/citra/CMakeLists.txt +++ b/src/citra/CMakeLists.txt @@ -21,7 +21,7 @@ target_link_libraries(citra ${SDL2_LIBRARY} ${OPENGL_gl_LIBRARY} inih glad) if (MSVC) target_link_libraries(citra getopt) endif() -target_link_libraries(citra ${PLATFORM_LIBRARIES} ${CMAKE_THREAD_LIBS_INIT}) +target_link_libraries(citra ${PLATFORM_LIBRARIES} Threads::Threads) if(${CMAKE_SYSTEM_NAME} MATCHES "Linux|FreeBSD|OpenBSD|NetBSD") install(TARGETS citra RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}/bin") From ef6873980eb3854d351c319514fca4116165283c Mon Sep 17 00:00:00 2001 From: Sam Spilsbury Date: Sun, 24 Apr 2016 23:40:14 +0800 Subject: [PATCH 088/104] assert: Allow UNREACHABLE_MSG to have just one argument --- src/common/assert.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/common/assert.h b/src/common/assert.h index d7f19f5eb..cd9b819a9 100644 --- a/src/common/assert.h +++ b/src/common/assert.h @@ -39,7 +39,7 @@ static void assert_noinline_call(const Fn& fn) { }); } while (0) #define UNREACHABLE() ASSERT_MSG(false, "Unreachable code!") -#define UNREACHABLE_MSG(_a_, ...) ASSERT_MSG(false, _a_, __VA_ARGS__) +#define UNREACHABLE_MSG(...) ASSERT_MSG(false, __VA_ARGS__) #ifdef _DEBUG #define DEBUG_ASSERT(_a_) ASSERT(_a_) From e16541e47c657923ad5dedd64560afd0902cdda2 Mon Sep 17 00:00:00 2001 From: Sam Spilsbury Date: Sun, 24 Apr 2016 23:40:41 +0800 Subject: [PATCH 089/104] am: title_id is long long uint --- src/core/hle/service/am/am.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/core/hle/service/am/am.cpp b/src/core/hle/service/am/am.cpp index 9591522e5..3f71e7f2b 100644 --- a/src/core/hle/service/am/am.cpp +++ b/src/core/hle/service/am/am.cpp @@ -43,7 +43,7 @@ void FindContentInfos(Service::Interface* self) { am_content_count[media_type] = cmd_buff[4]; cmd_buff[1] = RESULT_SUCCESS.raw; - LOG_WARNING(Service_AM, "(STUBBED) media_type=%u, title_id=0x%016lx, content_cound=%u, content_ids_pointer=0x%08x, content_info_pointer=0x%08x", + LOG_WARNING(Service_AM, "(STUBBED) media_type=%u, title_id=0x%016llx, content_cound=%u, content_ids_pointer=0x%08x, content_info_pointer=0x%08x", media_type, title_id, am_content_count[media_type], content_ids_pointer, content_info_pointer); } From bbffa6ad6945f2ea91a61dc7ab45c0fd814fcf82 Mon Sep 17 00:00:00 2001 From: Sam Spilsbury Date: Sun, 24 Apr 2016 23:40:52 +0800 Subject: [PATCH 090/104] shader: Format string must be provided inline and not as a variable --- src/video_core/shader/shader_jit_x64.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/video_core/shader/shader_jit_x64.cpp b/src/video_core/shader/shader_jit_x64.cpp index b47d3beda..d5a6a349c 100644 --- a/src/video_core/shader/shader_jit_x64.cpp +++ b/src/video_core/shader/shader_jit_x64.cpp @@ -148,7 +148,7 @@ static Instruction GetVertexShaderInstruction(size_t offset) { } static void LogCritical(const char* msg) { - LOG_CRITICAL(HW_GPU, msg); + LOG_CRITICAL(HW_GPU, "%s", msg); } void JitShader::Compile_Assert(bool condition, const char* msg) { From c6709d97bce27f248b78374a531a3ee01275c65d Mon Sep 17 00:00:00 2001 From: Sam Spilsbury Date: Sun, 24 Apr 2016 23:41:25 +0800 Subject: [PATCH 091/104] shader: Handle non-CALL opcodes with a break --- src/video_core/shader/shader_jit_x64.cpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/video_core/shader/shader_jit_x64.cpp b/src/video_core/shader/shader_jit_x64.cpp index d5a6a349c..9ee4065bf 100644 --- a/src/video_core/shader/shader_jit_x64.cpp +++ b/src/video_core/shader/shader_jit_x64.cpp @@ -795,6 +795,8 @@ void JitShader::FindReturnOffsets() { case OpCode::Id::CALLU: return_offsets.push_back(instr.flow_control.dest_offset + instr.flow_control.num_instructions); break; + default: + break; } } From 656a4424332824c144ef5b91482ee2a8d89fc0fb Mon Sep 17 00:00:00 2001 From: Sam Spilsbury Date: Sun, 24 Apr 2016 23:41:44 +0800 Subject: [PATCH 092/104] shader: Shader size is long uint, not uint. --- src/video_core/shader/shader_jit_x64.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/video_core/shader/shader_jit_x64.cpp b/src/video_core/shader/shader_jit_x64.cpp index 9ee4065bf..b7747fa42 100644 --- a/src/video_core/shader/shader_jit_x64.cpp +++ b/src/video_core/shader/shader_jit_x64.cpp @@ -856,7 +856,7 @@ void JitShader::Compile() { uintptr_t size = reinterpret_cast(GetCodePtr()) - reinterpret_cast(program); ASSERT_MSG(size <= MAX_SHADER_SIZE, "Compiled a shader that exceeds the allocated size!"); - LOG_DEBUG(HW_GPU, "Compiled shader size=%d", size); + LOG_DEBUG(HW_GPU, "Compiled shader size=%lu", size); } JitShader::JitShader() { From 599dc2bbb5e7325b9baa8d55ef17915dd283173d Mon Sep 17 00:00:00 2001 From: Sam Spilsbury Date: Mon, 25 Apr 2016 09:40:12 +0800 Subject: [PATCH 093/104] travis: Install cmake 3.1 --- .travis-deps.sh | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/.travis-deps.sh b/.travis-deps.sh index c7bb7e785..4a79feb70 100755 --- a/.travis-deps.sh +++ b/.travis-deps.sh @@ -9,7 +9,7 @@ if [ "$TRAVIS_OS_NAME" = "linux" -o -z "$TRAVIS_OS_NAME" ]; then export CXX=g++-5 mkdir -p $HOME/.local - curl -L http://www.cmake.org/files/v2.8/cmake-2.8.11-Linux-i386.tar.gz \ + curl -L http://www.cmake.org/files/v3.1/cmake-3.1.0-Linux-i386.tar.gz \ | tar -xz -C $HOME/.local --strip-components=1 ( @@ -20,6 +20,7 @@ if [ "$TRAVIS_OS_NAME" = "linux" -o -z "$TRAVIS_OS_NAME" ]; then ) elif [ "$TRAVIS_OS_NAME" = "osx" ]; then brew update > /dev/null # silence the very verbose output - brew install qt5 sdl2 dylibbundler + brew unlink cmake + brew install cmake31 qt5 sdl2 dylibbundler gem install xcpretty fi From 555907ce8dc842ef0859537a0c25443a5e9527bb Mon Sep 17 00:00:00 2001 From: MerryMage Date: Sun, 24 Apr 2016 09:12:15 +0100 Subject: [PATCH 094/104] DSP/Pipe: There are 8 pipes --- src/audio_core/hle/pipe.cpp | 28 +++++++++++++++++----------- src/audio_core/hle/pipe.h | 4 ++-- 2 files changed, 19 insertions(+), 13 deletions(-) diff --git a/src/audio_core/hle/pipe.cpp b/src/audio_core/hle/pipe.cpp index 9381883b4..7ec97dfda 100644 --- a/src/audio_core/hle/pipe.cpp +++ b/src/audio_core/hle/pipe.cpp @@ -17,7 +17,7 @@ namespace HLE { static DspState dsp_state = DspState::Off; -static std::array, static_cast(DspPipe::DspPipe_MAX)> pipe_data; +static std::array, NUM_DSP_PIPE> pipe_data; void ResetPipes() { for (auto& data : pipe_data) { @@ -27,16 +27,18 @@ void ResetPipes() { } std::vector PipeRead(DspPipe pipe_number, u32 length) { - if (pipe_number >= DspPipe::DspPipe_MAX) { - LOG_ERROR(Audio_DSP, "pipe_number = %u invalid", pipe_number); + const size_t pipe_index = static_cast(pipe_number); + + if (pipe_index >= NUM_DSP_PIPE) { + LOG_ERROR(Audio_DSP, "pipe_number = %zu invalid", pipe_index); return {}; } - std::vector& data = pipe_data[static_cast(pipe_number)]; + std::vector& data = pipe_data[pipe_index]; if (length > data.size()) { - LOG_WARNING(Audio_DSP, "pipe_number = %u is out of data, application requested read of %u but %zu remain", - pipe_number, length, data.size()); + LOG_WARNING(Audio_DSP, "pipe_number = %zu is out of data, application requested read of %u but %zu remain", + pipe_index, length, data.size()); length = data.size(); } @@ -49,16 +51,20 @@ std::vector PipeRead(DspPipe pipe_number, u32 length) { } size_t GetPipeReadableSize(DspPipe pipe_number) { - if (pipe_number >= DspPipe::DspPipe_MAX) { - LOG_ERROR(Audio_DSP, "pipe_number = %u invalid", pipe_number); + const size_t pipe_index = static_cast(pipe_number); + + if (pipe_index >= NUM_DSP_PIPE) { + LOG_ERROR(Audio_DSP, "pipe_number = %zu invalid", pipe_index); return 0; } - return pipe_data[static_cast(pipe_number)].size(); + return pipe_data[pipe_index].size(); } static void WriteU16(DspPipe pipe_number, u16 value) { - std::vector& data = pipe_data[static_cast(pipe_number)]; + const size_t pipe_index = static_cast(pipe_number); + + std::vector& data = pipe_data.at(pipe_index); // Little endian data.emplace_back(value & 0xFF); data.emplace_back(value >> 8); @@ -145,7 +151,7 @@ void PipeWrite(DspPipe pipe_number, const std::vector& buffer) { return; } default: - LOG_CRITICAL(Audio_DSP, "pipe_number = %u unimplemented", pipe_number); + LOG_CRITICAL(Audio_DSP, "pipe_number = %zu unimplemented", static_cast(pipe_number)); UNIMPLEMENTED(); return; } diff --git a/src/audio_core/hle/pipe.h b/src/audio_core/hle/pipe.h index 382d35e87..64d97f8ba 100644 --- a/src/audio_core/hle/pipe.h +++ b/src/audio_core/hle/pipe.h @@ -19,9 +19,9 @@ enum class DspPipe { Debug = 0, Dma = 1, Audio = 2, - Binary = 3, - DspPipe_MAX + Binary = 3 }; +constexpr size_t NUM_DSP_PIPE = 8; /** * Read a DSP pipe. From 591ffad670d742d85bdf2e975415a7bbdd82a14f Mon Sep 17 00:00:00 2001 From: Emmanuel Gil Peyrot Date: Tue, 26 Apr 2016 21:01:11 +0100 Subject: [PATCH 095/104] Qt Frontend: Add Threads::Threads import in CMakeLists.txt. This had been forgotten in df81fa11fc8972a5775a57ccde1e0ef8d7fbfe64. Fixes #1711. --- src/citra_qt/CMakeLists.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/citra_qt/CMakeLists.txt b/src/citra_qt/CMakeLists.txt index 6660d9879..cc9e0c624 100644 --- a/src/citra_qt/CMakeLists.txt +++ b/src/citra_qt/CMakeLists.txt @@ -92,7 +92,7 @@ else() endif() target_link_libraries(citra-qt core video_core audio_core common qhexedit) target_link_libraries(citra-qt ${OPENGL_gl_LIBRARY} ${CITRA_QT_LIBS}) -target_link_libraries(citra-qt ${PLATFORM_LIBRARIES}) +target_link_libraries(citra-qt ${PLATFORM_LIBRARIES} Threads::Threads) if(${CMAKE_SYSTEM_NAME} MATCHES "Linux|FreeBSD|OpenBSD|NetBSD") install(TARGETS citra-qt RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}/bin") From 12f72a65973716799e1ecd3885cdbc27603e631c Mon Sep 17 00:00:00 2001 From: bunnei Date: Tue, 26 Apr 2016 19:49:19 -0400 Subject: [PATCH 096/104] y2r_u: Cleanup some formatting. --- src/core/hle/service/y2r_u.cpp | 141 +++++++++++++++++++++------------ 1 file changed, 89 insertions(+), 52 deletions(-) diff --git a/src/core/hle/service/y2r_u.cpp b/src/core/hle/service/y2r_u.cpp index 76ec154dd..d16578f87 100644 --- a/src/core/hle/service/y2r_u.cpp +++ b/src/core/hle/service/y2r_u.cpp @@ -88,10 +88,11 @@ static void SetInputFormat(Service::Interface* self) { u32* cmd_buff = Kernel::GetCommandBuffer(); conversion.input_format = static_cast(cmd_buff[1]); - LOG_DEBUG(Service_Y2R, "called input_format=%hhu", conversion.input_format); cmd_buff[0] = IPC::MakeHeader(0x1, 1, 0); cmd_buff[1] = RESULT_SUCCESS.raw; + + LOG_DEBUG(Service_Y2R, "called input_format=%hhu", conversion.input_format); } static void GetInputFormat(Service::Interface* self) { @@ -100,6 +101,7 @@ static void GetInputFormat(Service::Interface* self) { cmd_buff[0] = IPC::MakeHeader(0x2, 2, 0); cmd_buff[1] = RESULT_SUCCESS.raw; cmd_buff[2] = static_cast(conversion.input_format); + LOG_DEBUG(Service_Y2R, "called input_format=%hhu", conversion.input_format); } @@ -107,10 +109,11 @@ static void SetOutputFormat(Service::Interface* self) { u32* cmd_buff = Kernel::GetCommandBuffer(); conversion.output_format = static_cast(cmd_buff[1]); - LOG_DEBUG(Service_Y2R, "called output_format=%hhu", conversion.output_format); cmd_buff[0] = IPC::MakeHeader(0x3, 1, 0); cmd_buff[1] = RESULT_SUCCESS.raw; + + LOG_DEBUG(Service_Y2R, "called output_format=%hhu", conversion.output_format); } static void GetOutputFormat(Service::Interface* self) { @@ -119,6 +122,7 @@ static void GetOutputFormat(Service::Interface* self) { cmd_buff[0] = IPC::MakeHeader(0x4, 2, 0); cmd_buff[1] = RESULT_SUCCESS.raw; cmd_buff[2] = static_cast(conversion.output_format); + LOG_DEBUG(Service_Y2R, "called output_format=%hhu", conversion.output_format); } @@ -126,10 +130,11 @@ static void SetRotation(Service::Interface* self) { u32* cmd_buff = Kernel::GetCommandBuffer(); conversion.rotation = static_cast(cmd_buff[1]); - LOG_DEBUG(Service_Y2R, "called rotation=%hhu", conversion.rotation); cmd_buff[0] = IPC::MakeHeader(0x5, 1, 0); cmd_buff[1] = RESULT_SUCCESS.raw; + + LOG_DEBUG(Service_Y2R, "called rotation=%hhu", conversion.rotation); } static void GetRotation(Service::Interface* self) { @@ -138,6 +143,7 @@ static void GetRotation(Service::Interface* self) { cmd_buff[0] = IPC::MakeHeader(0x6, 2, 0); cmd_buff[1] = RESULT_SUCCESS.raw; cmd_buff[2] = static_cast(conversion.rotation); + LOG_DEBUG(Service_Y2R, "called rotation=%hhu", conversion.rotation); } @@ -145,10 +151,11 @@ static void SetBlockAlignment(Service::Interface* self) { u32* cmd_buff = Kernel::GetCommandBuffer(); conversion.block_alignment = static_cast(cmd_buff[1]); - LOG_DEBUG(Service_Y2R, "called block_alignment=%hhu", conversion.block_alignment); cmd_buff[0] = IPC::MakeHeader(0x7, 1, 0); cmd_buff[1] = RESULT_SUCCESS.raw; + + LOG_DEBUG(Service_Y2R, "called block_alignment=%hhu", conversion.block_alignment); } static void GetBlockAlignment(Service::Interface* self) { @@ -157,6 +164,7 @@ static void GetBlockAlignment(Service::Interface* self) { cmd_buff[0] = IPC::MakeHeader(0x8, 2, 0); cmd_buff[1] = RESULT_SUCCESS.raw; cmd_buff[2] = static_cast(conversion.block_alignment); + LOG_DEBUG(Service_Y2R, "called block_alignment=%hhu", conversion.block_alignment); } @@ -173,6 +181,7 @@ static void SetSpacialDithering(Service::Interface* self) { cmd_buff[0] = IPC::MakeHeader(0x9, 1, 0); cmd_buff[1] = RESULT_SUCCESS.raw; + LOG_WARNING(Service_Y2R, "(STUBBED) called"); } @@ -188,6 +197,7 @@ static void GetSpacialDithering(Service::Interface* self) { cmd_buff[0] = IPC::MakeHeader(0xA, 2, 0); cmd_buff[1] = RESULT_SUCCESS.raw; cmd_buff[2] = spacial_dithering_enabled; + LOG_WARNING(Service_Y2R, "(STUBBED) called"); } @@ -204,6 +214,7 @@ static void SetTemporalDithering(Service::Interface* self) { cmd_buff[0] = IPC::MakeHeader(0xB, 1, 0); cmd_buff[1] = RESULT_SUCCESS.raw; + LOG_WARNING(Service_Y2R, "(STUBBED) called"); } @@ -219,6 +230,7 @@ static void GetTemporalDithering(Service::Interface* self) { cmd_buff[0] = IPC::MakeHeader(0xC, 2, 0); cmd_buff[1] = RESULT_SUCCESS.raw; cmd_buff[2] = temporal_dithering_enabled; + LOG_WARNING(Service_Y2R, "(STUBBED) called"); } @@ -235,6 +247,7 @@ static void SetTransferEndInterrupt(Service::Interface* self) { cmd_buff[0] = IPC::MakeHeader(0xD, 1, 0); cmd_buff[1] = RESULT_SUCCESS.raw; + LOG_WARNING(Service_Y2R, "(STUBBED) called"); } @@ -250,6 +263,7 @@ static void GetTransferEndInterrupt(Service::Interface* self) { cmd_buff[0] = IPC::MakeHeader(0xE, 2, 0); cmd_buff[1] = RESULT_SUCCESS.raw; cmd_buff[2] = transfer_end_interrupt_enabled; + LOG_WARNING(Service_Y2R, "(STUBBED) called"); } @@ -265,6 +279,7 @@ static void GetTransferEndEvent(Service::Interface* self) { cmd_buff[0] = IPC::MakeHeader(0xF, 2, 0); cmd_buff[1] = RESULT_SUCCESS.raw; cmd_buff[3] = Kernel::g_handle_table.Create(completion_event).MoveFrom(); + LOG_DEBUG(Service_Y2R, "called"); } @@ -275,13 +290,12 @@ static void SetSendingY(Service::Interface* self) { conversion.src_Y.image_size = cmd_buff[2]; conversion.src_Y.transfer_unit = cmd_buff[3]; conversion.src_Y.gap = cmd_buff[4]; - u32 src_process_handle = cmd_buff[6]; - LOG_DEBUG(Service_Y2R, "called image_size=0x%08X, transfer_unit=%hu, transfer_stride=%hu, " - "src_process_handle=0x%08X", conversion.src_Y.image_size, - conversion.src_Y.transfer_unit, conversion.src_Y.gap, src_process_handle); cmd_buff[0] = IPC::MakeHeader(0x10, 1, 0); cmd_buff[1] = RESULT_SUCCESS.raw; + + LOG_DEBUG(Service_Y2R, "called image_size=0x%08X, transfer_unit=%hu, transfer_stride=%hu, src_process_handle=0x%08X", + conversion.src_Y.image_size, conversion.src_Y.transfer_unit, conversion.src_Y.gap, cmd_buff[6]); } static void SetSendingU(Service::Interface* self) { @@ -291,13 +305,12 @@ static void SetSendingU(Service::Interface* self) { conversion.src_U.image_size = cmd_buff[2]; conversion.src_U.transfer_unit = cmd_buff[3]; conversion.src_U.gap = cmd_buff[4]; - u32 src_process_handle = cmd_buff[6]; - LOG_DEBUG(Service_Y2R, "called image_size=0x%08X, transfer_unit=%hu, transfer_stride=%hu, " - "src_process_handle=0x%08X", conversion.src_U.image_size, - conversion.src_U.transfer_unit, conversion.src_U.gap, src_process_handle); cmd_buff[0] = IPC::MakeHeader(0x11, 1, 0); cmd_buff[1] = RESULT_SUCCESS.raw; + + LOG_DEBUG(Service_Y2R, "called image_size=0x%08X, transfer_unit=%hu, transfer_stride=%hu, src_process_handle=0x%08X", + conversion.src_U.image_size, conversion.src_U.transfer_unit, conversion.src_U.gap, cmd_buff[6]); } static void SetSendingV(Service::Interface* self) { @@ -307,13 +320,12 @@ static void SetSendingV(Service::Interface* self) { conversion.src_V.image_size = cmd_buff[2]; conversion.src_V.transfer_unit = cmd_buff[3]; conversion.src_V.gap = cmd_buff[4]; - u32 src_process_handle = cmd_buff[6]; - LOG_DEBUG(Service_Y2R, "called image_size=0x%08X, transfer_unit=%hu, transfer_stride=%hu, " - "src_process_handle=0x%08X", conversion.src_V.image_size, - conversion.src_V.transfer_unit, conversion.src_V.gap, src_process_handle); cmd_buff[0] = IPC::MakeHeader(0x12, 1, 0); cmd_buff[1] = RESULT_SUCCESS.raw; + + LOG_DEBUG(Service_Y2R, "called image_size=0x%08X, transfer_unit=%hu, transfer_stride=%hu, src_process_handle=0x%08X", + conversion.src_V.image_size, conversion.src_V.transfer_unit, conversion.src_V.gap, cmd_buff[6]); } static void SetSendingYUYV(Service::Interface* self) { @@ -323,13 +335,12 @@ static void SetSendingYUYV(Service::Interface* self) { conversion.src_YUYV.image_size = cmd_buff[2]; conversion.src_YUYV.transfer_unit = cmd_buff[3]; conversion.src_YUYV.gap = cmd_buff[4]; - u32 src_process_handle = cmd_buff[6]; - LOG_DEBUG(Service_Y2R, "called image_size=0x%08X, transfer_unit=%hu, transfer_stride=%hu, " - "src_process_handle=0x%08X", conversion.src_YUYV.image_size, - conversion.src_YUYV.transfer_unit, conversion.src_YUYV.gap, src_process_handle); cmd_buff[0] = IPC::MakeHeader(0x13, 1, 0); cmd_buff[1] = RESULT_SUCCESS.raw; + + LOG_DEBUG(Service_Y2R, "called image_size=0x%08X, transfer_unit=%hu, transfer_stride=%hu, src_process_handle=0x%08X", + conversion.src_YUYV.image_size, conversion.src_YUYV.transfer_unit, conversion.src_YUYV.gap, cmd_buff[6]); } /** @@ -344,6 +355,7 @@ static void IsFinishedSendingYuv(Service::Interface* self) { cmd_buff[0] = IPC::MakeHeader(0x14, 2, 0); cmd_buff[1] = RESULT_SUCCESS.raw; cmd_buff[2] = 1; + LOG_WARNING(Service_Y2R, "(STUBBED) called"); } @@ -359,6 +371,7 @@ static void IsFinishedSendingY(Service::Interface* self) { cmd_buff[0] = IPC::MakeHeader(0x15, 2, 0); cmd_buff[1] = RESULT_SUCCESS.raw; cmd_buff[2] = 1; + LOG_WARNING(Service_Y2R, "(STUBBED) called"); } @@ -374,6 +387,7 @@ static void IsFinishedSendingU(Service::Interface* self) { cmd_buff[0] = IPC::MakeHeader(0x16, 2, 0); cmd_buff[1] = RESULT_SUCCESS.raw; cmd_buff[2] = 1; + LOG_WARNING(Service_Y2R, "(STUBBED) called"); } @@ -389,6 +403,7 @@ static void IsFinishedSendingV(Service::Interface* self) { cmd_buff[0] = IPC::MakeHeader(0x17, 2, 0); cmd_buff[1] = RESULT_SUCCESS.raw; cmd_buff[2] = 1; + LOG_WARNING(Service_Y2R, "(STUBBED) called"); } @@ -399,14 +414,12 @@ static void SetReceiving(Service::Interface* self) { conversion.dst.image_size = cmd_buff[2]; conversion.dst.transfer_unit = cmd_buff[3]; conversion.dst.gap = cmd_buff[4]; - u32 dst_process_handle = cmd_buff[6]; - LOG_DEBUG(Service_Y2R, "called image_size=0x%08X, transfer_unit=%hu, transfer_stride=%hu, " - "dst_process_handle=0x%08X", conversion.dst.image_size, - conversion.dst.transfer_unit, conversion.dst.gap, - dst_process_handle); cmd_buff[0] = IPC::MakeHeader(0x18, 1, 0); cmd_buff[1] = RESULT_SUCCESS.raw; + + LOG_DEBUG(Service_Y2R, "called image_size=0x%08X, transfer_unit=%hu, transfer_stride=%hu, dst_process_handle=0x%08X", + conversion.dst.image_size, conversion.dst.transfer_unit, conversion.dst.gap, cmd_buff[6]); } /** @@ -421,15 +434,17 @@ static void IsFinishedReceiving(Service::Interface* self) { cmd_buff[0] = IPC::MakeHeader(0x19, 2, 0); cmd_buff[1] = RESULT_SUCCESS.raw; cmd_buff[2] = 1; + LOG_WARNING(Service_Y2R, "(STUBBED) called"); } static void SetInputLineWidth(Service::Interface* self) { u32* cmd_buff = Kernel::GetCommandBuffer(); - LOG_DEBUG(Service_Y2R, "called input_line_width=%u", cmd_buff[1]); cmd_buff[0] = IPC::MakeHeader(0x1A, 1, 0); cmd_buff[1] = conversion.SetInputLineWidth(cmd_buff[1]).raw; + + LOG_DEBUG(Service_Y2R, "called input_line_width=%u", cmd_buff[1]); } static void GetInputLineWidth(Service::Interface* self) { @@ -438,15 +453,17 @@ static void GetInputLineWidth(Service::Interface* self) { cmd_buff[0] = IPC::MakeHeader(0x1B, 2, 0); cmd_buff[1] = RESULT_SUCCESS.raw; cmd_buff[2] = conversion.input_line_width; + LOG_DEBUG(Service_Y2R, "called input_line_width=%u", conversion.input_line_width); } static void SetInputLines(Service::Interface* self) { u32* cmd_buff = Kernel::GetCommandBuffer(); - LOG_DEBUG(Service_Y2R, "called input_lines=%u", cmd_buff[1]); cmd_buff[0] = IPC::MakeHeader(0x1C, 1, 0); cmd_buff[1] = conversion.SetInputLines(cmd_buff[1]).raw; + + LOG_DEBUG(Service_Y2R, "called input_lines=%u", cmd_buff[1]); } static void GetInputLines(Service::Interface* self) { @@ -455,6 +472,7 @@ static void GetInputLines(Service::Interface* self) { cmd_buff[0] = IPC::MakeHeader(0x1D, 2, 0); cmd_buff[1] = RESULT_SUCCESS.raw; cmd_buff[2] = static_cast(conversion.input_lines); + LOG_DEBUG(Service_Y2R, "called input_lines=%u", conversion.input_lines); } @@ -463,12 +481,13 @@ static void SetCoefficient(Service::Interface* self) { const u16* coefficients = reinterpret_cast(&cmd_buff[1]); std::memcpy(conversion.coefficients.data(), coefficients, sizeof(CoefficientSet)); - LOG_DEBUG(Service_Y2R, "called coefficients=[%hX, %hX, %hX, %hX, %hX, %hX, %hX, %hX]", - coefficients[0], coefficients[1], coefficients[2], coefficients[3], - coefficients[4], coefficients[5], coefficients[6], coefficients[7]); cmd_buff[0] = IPC::MakeHeader(0x1E, 1, 0); cmd_buff[1] = RESULT_SUCCESS.raw; + + LOG_DEBUG(Service_Y2R, "called coefficients=[%hX, %hX, %hX, %hX, %hX, %hX, %hX, %hX]", + coefficients[0], coefficients[1], coefficients[2], coefficients[3], + coefficients[4], coefficients[5], coefficients[6], coefficients[7]); } static void GetCoefficient(Service::Interface* self) { @@ -477,6 +496,8 @@ static void GetCoefficient(Service::Interface* self) { cmd_buff[0] = IPC::MakeHeader(0x1F, 5, 0); cmd_buff[1] = RESULT_SUCCESS.raw; std::memcpy(&cmd_buff[2], conversion.coefficients.data(), sizeof(CoefficientSet)); + + LOG_DEBUG(Service_Y2R, "called"); } static void SetStandardCoefficient(Service::Interface* self) { @@ -486,6 +507,7 @@ static void SetStandardCoefficient(Service::Interface* self) { cmd_buff[0] = IPC::MakeHeader(0x20, 1, 0); cmd_buff[1] = conversion.SetStandardCoefficient((StandardCoefficient)index).raw; + LOG_DEBUG(Service_Y2R, "called standard_coefficient=%u", index); } @@ -495,15 +517,15 @@ static void GetStandardCoefficient(Service::Interface* self) { u32 index = cmd_buff[1]; if (index < ARRAY_SIZE(standard_coefficients)) { - std::memcpy(&cmd_buff[2], &standard_coefficients[index], sizeof(CoefficientSet)); - cmd_buff[0] = IPC::MakeHeader(0x21, 5, 0); cmd_buff[1] = RESULT_SUCCESS.raw; + std::memcpy(&cmd_buff[2], &standard_coefficients[index], sizeof(CoefficientSet)); + LOG_DEBUG(Service_Y2R, "called standard_coefficient=%u ", index); - } - else { + } else { cmd_buff[0] = IPC::MakeHeader(0x21, 1, 0); - cmd_buff[1] = -1; + cmd_buff[1] = -1; // TODO(bunnei): Identify the correct error code for this + LOG_ERROR(Service_Y2R, "called standard_coefficient=%u The argument is invalid!", index); } } @@ -512,10 +534,11 @@ static void SetAlpha(Service::Interface* self) { u32* cmd_buff = Kernel::GetCommandBuffer(); conversion.alpha = cmd_buff[1]; - LOG_DEBUG(Service_Y2R, "called alpha=%hu", conversion.alpha); cmd_buff[0] = IPC::MakeHeader(0x22, 1, 0); cmd_buff[1] = RESULT_SUCCESS.raw; + + LOG_DEBUG(Service_Y2R, "called alpha=%hu", conversion.alpha); } static void GetAlpha(Service::Interface* self) { @@ -524,6 +547,7 @@ static void GetAlpha(Service::Interface* self) { cmd_buff[0] = IPC::MakeHeader(0x23, 2, 0); cmd_buff[1] = RESULT_SUCCESS.raw; cmd_buff[2] = conversion.alpha; + LOG_DEBUG(Service_Y2R, "called alpha=%hu", conversion.alpha); } @@ -533,6 +557,7 @@ static void SetDitheringWeightParams(Service::Interface* self) { cmd_buff[0] = IPC::MakeHeader(0x24, 1, 0); cmd_buff[1] = RESULT_SUCCESS.raw; + LOG_DEBUG(Service_Y2R, "called"); } @@ -542,6 +567,7 @@ static void GetDitheringWeightParams(Service::Interface* self) { cmd_buff[0] = IPC::MakeHeader(0x25, 9, 0); cmd_buff[1] = RESULT_SUCCESS.raw; std::memcpy(&cmd_buff[2], &dithering_weight_params, sizeof(DitheringWeightParams)); + LOG_DEBUG(Service_Y2R, "called"); } @@ -549,17 +575,17 @@ static void StartConversion(Service::Interface* self) { u32* cmd_buff = Kernel::GetCommandBuffer(); // dst_image_size would seem to be perfect for this, but it doesn't include the gap :( - u32 total_output_size = conversion.input_lines * - (conversion.dst.transfer_unit + conversion.dst.gap); + u32 total_output_size = conversion.input_lines * (conversion.dst.transfer_unit + conversion.dst.gap); Memory::RasterizerFlushAndInvalidateRegion(Memory::VirtualToPhysicalAddress(conversion.dst.address), total_output_size); HW::Y2R::PerformConversion(conversion); - LOG_DEBUG(Service_Y2R, "called"); completion_event->Signal(); cmd_buff[0] = IPC::MakeHeader(0x26, 1, 0); cmd_buff[1] = RESULT_SUCCESS.raw; + + LOG_DEBUG(Service_Y2R, "called"); } static void StopConversion(Service::Interface* self) { @@ -567,6 +593,7 @@ static void StopConversion(Service::Interface* self) { cmd_buff[0] = IPC::MakeHeader(0x27, 1, 0); cmd_buff[1] = RESULT_SUCCESS.raw; + LOG_DEBUG(Service_Y2R, "called"); } @@ -582,6 +609,7 @@ static void IsBusyConversion(Service::Interface* self) { cmd_buff[0] = IPC::MakeHeader(0x28, 2, 0); cmd_buff[1] = RESULT_SUCCESS.raw; cmd_buff[2] = 0; // StartConversion always finishes immediately + LOG_DEBUG(Service_Y2R, "called"); } @@ -592,32 +620,38 @@ static void SetPackageParameter(Service::Interface* self) { u32* cmd_buff = Kernel::GetCommandBuffer(); auto params = reinterpret_cast(&cmd_buff[1]); - LOG_DEBUG(Service_Y2R, - "called input_format=%hhu output_format=%hhu rotation=%hhu block_alignment=%hhu " - "input_line_width=%hu input_lines=%hu standard_coefficient=%hhu " - "reserved=%hhu alpha=%hX", - params->input_format, params->output_format, params->rotation, params->block_alignment, - params->input_line_width, params->input_lines, params->standard_coefficient, - params->padding, params->alpha); - - ResultCode result = RESULT_SUCCESS; conversion.input_format = params->input_format; conversion.output_format = params->output_format; conversion.rotation = params->rotation; conversion.block_alignment = params->block_alignment; - result = conversion.SetInputLineWidth(params->input_line_width); - if (result.IsError()) goto cleanup; + + ResultCode result = conversion.SetInputLineWidth(params->input_line_width); + + if (result.IsError()) + goto cleanup; + result = conversion.SetInputLines(params->input_lines); - if (result.IsError()) goto cleanup; + + if (result.IsError()) + goto cleanup; + result = conversion.SetStandardCoefficient(params->standard_coefficient); - if (result.IsError()) goto cleanup; + + if (result.IsError()) + goto cleanup; + conversion.padding = params->padding; conversion.alpha = params->alpha; cleanup: cmd_buff[0] = IPC::MakeHeader(0x29, 1, 0); cmd_buff[1] = result.raw; + + LOG_DEBUG(Service_Y2R, "called input_format=%hhu output_format=%hhu rotation=%hhu block_alignment=%hhu " + "input_line_width=%hu input_lines=%hu standard_coefficient=%hhu reserved=%hhu alpha=%hX", + params->input_format, params->output_format, params->rotation, params->block_alignment, + params->input_line_width, params->input_lines, params->standard_coefficient, params->padding, params->alpha); } static void PingProcess(Service::Interface* self) { @@ -626,6 +660,7 @@ static void PingProcess(Service::Interface* self) { cmd_buff[0] = IPC::MakeHeader(0x2A, 2, 0); cmd_buff[1] = RESULT_SUCCESS.raw; cmd_buff[2] = 0; + LOG_WARNING(Service_Y2R, "(STUBBED) called"); } @@ -651,6 +686,7 @@ static void DriverInitialize(Service::Interface* self) { cmd_buff[0] = IPC::MakeHeader(0x2B, 1, 0); cmd_buff[1] = RESULT_SUCCESS.raw; + LOG_DEBUG(Service_Y2R, "called"); } @@ -659,6 +695,7 @@ static void DriverFinalize(Service::Interface* self) { cmd_buff[0] = IPC::MakeHeader(0x2C, 1, 0); cmd_buff[1] = RESULT_SUCCESS.raw; + LOG_DEBUG(Service_Y2R, "called"); } From ff6db69c6052f674265c453932a3dc7637c46412 Mon Sep 17 00:00:00 2001 From: MerryMage Date: Sun, 24 Apr 2016 10:21:10 +0100 Subject: [PATCH 097/104] DSP_DSP: Updated interrupt implementation --- src/audio_core/audio_core.cpp | 7 +- src/audio_core/hle/pipe.cpp | 4 + src/core/hle/service/dsp_dsp.cpp | 129 +++++++++++++++++++++++-------- src/core/hle/service/dsp_dsp.h | 19 ++--- 4 files changed, 113 insertions(+), 46 deletions(-) diff --git a/src/audio_core/audio_core.cpp b/src/audio_core/audio_core.cpp index 894f46990..0685eaf85 100644 --- a/src/audio_core/audio_core.cpp +++ b/src/audio_core/audio_core.cpp @@ -4,6 +4,7 @@ #include "audio_core/audio_core.h" #include "audio_core/hle/dsp.h" +#include "audio_core/hle/pipe.h" #include "core/core_timing.h" #include "core/hle/kernel/vm_manager.h" @@ -17,10 +18,8 @@ static constexpr u64 audio_frame_ticks = 1310252ull; ///< Units: ARM11 cycles static void AudioTickCallback(u64 /*userdata*/, int cycles_late) { if (DSP::HLE::Tick()) { - // HACK: We're not signaling the interrups when they should be, but just firing them all off together. - // It should be only (interrupt_id = 2, channel_id = 2) that's signalled here. - // TODO(merry): Understand when the other interrupts are fired. - DSP_DSP::SignalAllInterrupts(); + // TODO(merry): Signal all the other interrupts as appropriate. + DSP_DSP::SignalPipeInterrupt(DSP::HLE::DspPipe::Audio); } // Reschedule recurrent event diff --git a/src/audio_core/hle/pipe.cpp b/src/audio_core/hle/pipe.cpp index 7ec97dfda..03280780f 100644 --- a/src/audio_core/hle/pipe.cpp +++ b/src/audio_core/hle/pipe.cpp @@ -12,6 +12,8 @@ #include "common/common_types.h" #include "common/logging/log.h" +#include "core/hle/service/dsp_dsp.h" + namespace DSP { namespace HLE { @@ -97,6 +99,8 @@ static void AudioPipeWriteStructAddresses() { for (u16 addr : struct_addresses) { WriteU16(DspPipe::Audio, addr); } + // Signal that we have data on this pipe. + DSP_DSP::SignalPipeInterrupt(DspPipe::Audio); } void PipeWrite(DspPipe pipe_number, const std::vector& buffer) { diff --git a/src/core/hle/service/dsp_dsp.cpp b/src/core/hle/service/dsp_dsp.cpp index 751cb3d61..e9ef50f86 100644 --- a/src/core/hle/service/dsp_dsp.cpp +++ b/src/core/hle/service/dsp_dsp.cpp @@ -2,6 +2,7 @@ // Licensed under GPLv2 or any later version // Refer to the license.txt file included. +#include #include #include "audio_core/hle/pipe.h" @@ -12,6 +13,8 @@ #include "core/hle/kernel/event.h" #include "core/hle/service/dsp_dsp.h" +using DspPipe = DSP::HLE::DspPipe; + //////////////////////////////////////////////////////////////////////////////////////////////////// // Namespace DSP_DSP @@ -19,29 +22,71 @@ namespace DSP_DSP { static Kernel::SharedPtr semaphore_event; -struct PairHash { - template - std::size_t operator()(const std::pair &x) const { - // TODO(yuriks): Replace with better hash combining function. - return std::hash()(x.first) ^ std::hash()(x.second); +/// There are three types of interrupts +enum class InterruptType { + Zero, One, Pipe +}; +constexpr size_t NUM_INTERRUPT_TYPE = 3; + +class InterruptEvents final { +public: + void Signal(InterruptType type, DspPipe pipe) { + Kernel::SharedPtr& event = Get(type, pipe); + if (event) { + event->Signal(); + } } + + Kernel::SharedPtr& Get(InterruptType type, DspPipe dsp_pipe) { + switch (type) { + case InterruptType::Zero: + return zero; + case InterruptType::One: + return one; + case InterruptType::Pipe: { + const size_t pipe_index = static_cast(dsp_pipe); + ASSERT(pipe_index < DSP::HLE::NUM_DSP_PIPE); + return pipe[pipe_index]; + } + } + + UNREACHABLE_MSG("Invalid interrupt type = %zu", static_cast(type)); + } + + bool HasTooManyEventsRegistered() const { + // Actual service implementation only has 6 'slots' for interrupts. + constexpr size_t max_number_of_interrupt_events = 6; + + size_t number = std::count_if(pipe.begin(), pipe.end(), [](const auto& evt) { + return evt != nullptr; + }); + + if (zero != nullptr) + number++; + if (one != nullptr) + number++; + + return number >= max_number_of_interrupt_events; + } + +private: + /// Currently unknown purpose + Kernel::SharedPtr zero = nullptr; + /// Currently unknown purpose + Kernel::SharedPtr one = nullptr; + /// Each DSP pipe has an associated interrupt + std::array, DSP::HLE::NUM_DSP_PIPE> pipe = {{}}; }; -/// Map of (audio interrupt number, channel number) to Kernel::Events. See: RegisterInterruptEvents -static std::unordered_map, Kernel::SharedPtr, PairHash> interrupt_events; +static InterruptEvents interrupt_events; // DSP Interrupts: -// Interrupt #2 occurs every frame tick. Userland programs normally have a thread that's waiting -// for an interrupt event. Immediately after this interrupt event, userland normally updates the -// state in the next region and increments the relevant frame counter by two. -void SignalAllInterrupts() { - // HACK: The other interrupts have currently unknown purpose, we trigger them each tick in any case. - for (auto& interrupt_event : interrupt_events) - interrupt_event.second->Signal(); -} - -void SignalInterrupt(u32 interrupt, u32 channel) { - interrupt_events[std::make_pair(interrupt, channel)]->Signal(); +// The audio-pipe interrupt occurs every frame tick. Userland programs normally have a thread +// that's waiting for an interrupt event. Immediately after this interrupt event, userland +// normally updates the state in the next region and increments the relevant frame counter by +// two. +void SignalPipeInterrupt(DspPipe pipe) { + interrupt_events.Signal(InterruptType::Pipe, pipe); } /** @@ -147,8 +192,8 @@ static void FlushDataCache(Service::Interface* self) { /** * DSP_DSP::RegisterInterruptEvents service function * Inputs: - * 1 : Interrupt Number - * 2 : Channel Number + * 1 : Interrupt Type + * 2 : Pipe Number * 4 : Interrupt event handle * Outputs: * 1 : Result of function, 0 on success, otherwise error code @@ -156,23 +201,40 @@ static void FlushDataCache(Service::Interface* self) { static void RegisterInterruptEvents(Service::Interface* self) { u32* cmd_buff = Kernel::GetCommandBuffer(); - u32 interrupt = cmd_buff[1]; - u32 channel = cmd_buff[2]; + u32 type_index = cmd_buff[1]; + u32 pipe_index = cmd_buff[2]; u32 event_handle = cmd_buff[4]; + ASSERT_MSG(type_index < NUM_INTERRUPT_TYPE && pipe_index < DSP::HLE::NUM_DSP_PIPE, + "Invalid type or pipe: type = %u, pipe = %u", type_index, pipe_index); + + InterruptType type = static_cast(cmd_buff[1]); + DspPipe pipe = static_cast(cmd_buff[2]); + + cmd_buff[0] = IPC::MakeHeader(0x15, 1, 0); + if (event_handle) { auto evt = Kernel::g_handle_table.Get(cmd_buff[4]); - if (evt) { - interrupt_events[std::make_pair(interrupt, channel)] = evt; - cmd_buff[1] = RESULT_SUCCESS.raw; - LOG_INFO(Service_DSP, "Registered interrupt=%u, channel=%u, event_handle=0x%08X", interrupt, channel, event_handle); - } else { - LOG_CRITICAL(Service_DSP, "Invalid event handle! interrupt=%u, channel=%u, event_handle=0x%08X", interrupt, channel, event_handle); - ASSERT(false); // This should really be handled at a IPC translation layer. + + if (!evt) { + LOG_INFO(Service_DSP, "Invalid event handle! type=%u, pipe=%u, event_handle=0x%08X", type_index, pipe_index, event_handle); + ASSERT(false); // TODO: This should really be handled at an IPC translation layer. } + + if (interrupt_events.HasTooManyEventsRegistered()) { + LOG_INFO(Service_DSP, "Ran out of space to register interrupts (Attempted to register type=%u, pipe=%u, event_handle=0x%08X)", + type_index, pipe_index, event_handle); + cmd_buff[1] = ResultCode(ErrorDescription::InvalidResultValue, ErrorModule::DSP, ErrorSummary::OutOfResource, ErrorLevel::Status).raw; + return; + } + + interrupt_events.Get(type, pipe) = evt; + LOG_INFO(Service_DSP, "Registered type=%u, pipe=%u, event_handle=0x%08X", type_index, pipe_index, event_handle); + cmd_buff[1] = RESULT_SUCCESS.raw; } else { - interrupt_events.erase(std::make_pair(interrupt, channel)); - LOG_INFO(Service_DSP, "Unregistered interrupt=%u, channel=%u, event_handle=0x%08X", interrupt, channel, event_handle); + interrupt_events.Get(type, pipe) = nullptr; + LOG_INFO(Service_DSP, "Unregistered interrupt=%u, channel=%u, event_handle=0x%08X", type_index, pipe_index, event_handle); + cmd_buff[1] = RESULT_SUCCESS.raw; } } @@ -194,7 +256,7 @@ static void SetSemaphore(Service::Interface* self) { /** * DSP_DSP::WriteProcessPipe service function * Inputs: - * 1 : Channel + * 1 : Pipe Number * 2 : Size * 3 : (size << 14) | 0x402 * 4 : Buffer @@ -457,13 +519,14 @@ const Interface::FunctionInfo FunctionTable[] = { Interface::Interface() { semaphore_event = Kernel::Event::Create(Kernel::ResetType::OneShot, "DSP_DSP::semaphore_event"); + interrupt_events = {}; Register(FunctionTable); } Interface::~Interface() { semaphore_event = nullptr; - interrupt_events.clear(); + interrupt_events = {}; } } // namespace diff --git a/src/core/hle/service/dsp_dsp.h b/src/core/hle/service/dsp_dsp.h index 32b89e9bb..22f6687cc 100644 --- a/src/core/hle/service/dsp_dsp.h +++ b/src/core/hle/service/dsp_dsp.h @@ -8,6 +8,12 @@ #include "core/hle/service/service.h" +namespace DSP { +namespace HLE { +enum class DspPipe; +} +} + //////////////////////////////////////////////////////////////////////////////////////////////////// // Namespace DSP_DSP @@ -23,15 +29,10 @@ public: } }; -/// Signal all audio related interrupts. -void SignalAllInterrupts(); - /** - * Signal a specific audio related interrupt based on interrupt id and channel id. - * @param interrupt_id The interrupt id - * @param channel_id The channel id - * The significance of various values of interrupt_id and channel_id is not yet known. + * Signal a specific DSP related interrupt of type == InterruptType::Pipe, pipe == pipe. + * @param pipe The DSP pipe for which to signal an interrupt for. */ -void SignalInterrupt(u32 interrupt_id, u32 channel_id); +void SignalPipeInterrupt(DSP::HLE::DspPipe pipe); -} // namespace +} // namespace DSP_DSP From 2929b67c5f76a6bb7bc99e612fc582c5de28353f Mon Sep 17 00:00:00 2001 From: MerryMage Date: Sun, 24 Apr 2016 11:39:59 +0100 Subject: [PATCH 098/104] DSP_DSP: Add return IPC headers --- src/core/hle/result.h | 1 + src/core/hle/service/dsp_dsp.cpp | 30 ++++++++++++++++++++++++++---- 2 files changed, 27 insertions(+), 4 deletions(-) diff --git a/src/core/hle/result.h b/src/core/hle/result.h index 2d22652d9..53931a106 100644 --- a/src/core/hle/result.h +++ b/src/core/hle/result.h @@ -18,6 +18,7 @@ /// Detailed description of the error. This listing is likely incomplete. enum class ErrorDescription : u32 { Success = 0, + OS_InvalidBufferDescriptor = 48, WrongAddress = 53, FS_NotFound = 120, FS_AlreadyExists = 190, diff --git a/src/core/hle/service/dsp_dsp.cpp b/src/core/hle/service/dsp_dsp.cpp index e9ef50f86..58ded7eb5 100644 --- a/src/core/hle/service/dsp_dsp.cpp +++ b/src/core/hle/service/dsp_dsp.cpp @@ -102,7 +102,10 @@ static void ConvertProcessAddressFromDspDram(Service::Interface* self) { u32 addr = cmd_buff[1]; + cmd_buff[0] = IPC::MakeHeader(0xC, 2, 0); cmd_buff[1] = RESULT_SUCCESS.raw; // No error + + // TODO(merry): There is a per-region offset missing in this calculation (that seems to be always zero). cmd_buff[2] = (addr << 1) + (Memory::DSP_RAM_VADDR + 0x40000); LOG_DEBUG(Service_DSP, "addr=0x%08X", addr); @@ -157,7 +160,9 @@ static void LoadComponent(Service::Interface* self) { static void GetSemaphoreEventHandle(Service::Interface* self) { u32* cmd_buff = Kernel::GetCommandBuffer(); + cmd_buff[0] = IPC::MakeHeader(0x16, 1, 2); cmd_buff[1] = RESULT_SUCCESS.raw; // No error + // cmd_buff[2] not set cmd_buff[3] = Kernel::g_handle_table.Create(semaphore_event).MoveFrom(); // Event handle LOG_WARNING(Service_DSP, "(STUBBED) called"); @@ -182,8 +187,7 @@ static void FlushDataCache(Service::Interface* self) { u32 size = cmd_buff[2]; u32 process = cmd_buff[4]; - // TODO(purpasmart96): Verify return header on HW - + cmd_buff[0] = IPC::MakeHeader(0x13, 1, 0); cmd_buff[1] = RESULT_SUCCESS.raw; // No error LOG_TRACE(Service_DSP, "called address=0x%08X, size=0x%X, process=0x%08X", address, size, process); @@ -248,6 +252,7 @@ static void RegisterInterruptEvents(Service::Interface* self) { static void SetSemaphore(Service::Interface* self) { u32* cmd_buff = Kernel::GetCommandBuffer(); + cmd_buff[0] = IPC::MakeHeader(0x7, 1, 0); cmd_buff[1] = RESULT_SUCCESS.raw; // No error LOG_WARNING(Service_DSP, "(STUBBED) called"); @@ -271,17 +276,23 @@ static void WriteProcessPipe(Service::Interface* self) { u32 size = cmd_buff[2]; u32 buffer = cmd_buff[4]; - ASSERT_MSG(IPC::StaticBufferDesc(size, 1) == cmd_buff[3], "IPC static buffer descriptor failed validation (0x%X). pipe=%u, size=0x%X, buffer=0x%08X", cmd_buff[3], pipe, size, buffer); + if (IPC::StaticBufferDesc(size, 1) != cmd_buff[3]) { + LOG_ERROR(Service_DSP, "IPC static buffer descriptor failed validation (0x%X). pipe=%u, size=0x%X, buffer=0x%08X", cmd_buff[3], pipe, size, buffer); + cmd_buff[0] = IPC::MakeHeader(0, 1, 0); + cmd_buff[1] = ResultCode(ErrorDescription::OS_InvalidBufferDescriptor, ErrorModule::OS, ErrorSummary::WrongArgument, ErrorLevel::Permanent).raw; + return; + } + ASSERT_MSG(Memory::GetPointer(buffer) != nullptr, "Invalid Buffer: pipe=%u, size=0x%X, buffer=0x%08X", pipe, size, buffer); std::vector message(size); - for (size_t i = 0; i < size; i++) { message[i] = Memory::Read8(buffer + i); } DSP::HLE::PipeWrite(pipe, message); + cmd_buff[0] = IPC::MakeHeader(0xD, 1, 0); cmd_buff[1] = RESULT_SUCCESS.raw; // No error LOG_DEBUG(Service_DSP, "pipe=%u, size=0x%X, buffer=0x%08X", pipe, size, buffer); @@ -311,6 +322,7 @@ static void ReadPipeIfPossible(Service::Interface* self) { ASSERT_MSG(Memory::GetPointer(addr) != nullptr, "Invalid addr: pipe=0x%08X, unknown=0x%08X, size=0x%X, buffer=0x%08X", pipe, unknown, size, addr); + cmd_buff[0] = IPC::MakeHeader(0x10, 1, 2); cmd_buff[1] = RESULT_SUCCESS.raw; // No error if (DSP::HLE::GetPipeReadableSize(pipe) >= size) { std::vector response = DSP::HLE::PipeRead(pipe, size); @@ -321,6 +333,8 @@ static void ReadPipeIfPossible(Service::Interface* self) { } else { cmd_buff[2] = 0; // Return no data } + cmd_buff[3] = IPC::StaticBufferDesc(size, 0); + cmd_buff[4] = addr; LOG_DEBUG(Service_DSP, "pipe=0x%08X, unknown=0x%08X, size=0x%X, buffer=0x%08X, return cmd_buff[2]=0x%08X", pipe, unknown, size, addr, cmd_buff[2]); } @@ -351,8 +365,11 @@ static void ReadPipe(Service::Interface* self) { Memory::WriteBlock(addr, response.data(), response.size()); + cmd_buff[0] = IPC::MakeHeader(0xE, 2, 2); cmd_buff[1] = RESULT_SUCCESS.raw; // No error cmd_buff[2] = static_cast(response.size()); + cmd_buff[3] = IPC::StaticBufferDesc(size, 0); + cmd_buff[4] = addr; } else { // No more data is in pipe. Hardware hangs in this case; this should never happen. UNREACHABLE(); @@ -376,6 +393,7 @@ static void GetPipeReadableSize(Service::Interface* self) { DSP::HLE::DspPipe pipe = static_cast(cmd_buff[1]); u32 unknown = cmd_buff[2]; + cmd_buff[0] = IPC::MakeHeader(0xF, 2, 0); cmd_buff[1] = RESULT_SUCCESS.raw; // No error cmd_buff[2] = DSP::HLE::GetPipeReadableSize(pipe); @@ -394,6 +412,7 @@ static void SetSemaphoreMask(Service::Interface* self) { u32 mask = cmd_buff[1]; + cmd_buff[0] = IPC::MakeHeader(0x17, 1, 0); cmd_buff[1] = RESULT_SUCCESS.raw; // No error LOG_WARNING(Service_DSP, "(STUBBED) called mask=0x%08X", mask); @@ -411,6 +430,7 @@ static void SetSemaphoreMask(Service::Interface* self) { static void GetHeadphoneStatus(Service::Interface* self) { u32* cmd_buff = Kernel::GetCommandBuffer(); + cmd_buff[0] = IPC::MakeHeader(0x1F, 2, 0); cmd_buff[1] = RESULT_SUCCESS.raw; // No error cmd_buff[2] = 0; // Not using headphones? @@ -437,6 +457,7 @@ static void RecvData(Service::Interface* self) { // Application reads this after requesting DSP shutdown, to verify the DSP has indeed shutdown or slept. + cmd_buff[0] = IPC::MakeHeader(0x1, 2, 0); cmd_buff[1] = RESULT_SUCCESS.raw; switch (DSP::HLE::GetDspState()) { case DSP::HLE::DspState::On: @@ -472,6 +493,7 @@ static void RecvDataIsReady(Service::Interface* self) { ASSERT_MSG(register_number == 0, "Unknown register_number %u", register_number); + cmd_buff[0] = IPC::MakeHeader(0x2, 2, 0); cmd_buff[1] = RESULT_SUCCESS.raw; cmd_buff[2] = 1; // Ready to read From a47f149e0769127b137ec98dcd732aff6464c333 Mon Sep 17 00:00:00 2001 From: MerryMage Date: Sun, 24 Apr 2016 13:36:44 +0100 Subject: [PATCH 099/104] AudioCore: Hack to prevent regressions: Trigger Binary pipe interrupt every audio frame --- src/audio_core/audio_core.cpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/audio_core/audio_core.cpp b/src/audio_core/audio_core.cpp index 0685eaf85..b512b0f9b 100644 --- a/src/audio_core/audio_core.cpp +++ b/src/audio_core/audio_core.cpp @@ -20,6 +20,8 @@ static void AudioTickCallback(u64 /*userdata*/, int cycles_late) { if (DSP::HLE::Tick()) { // TODO(merry): Signal all the other interrupts as appropriate. DSP_DSP::SignalPipeInterrupt(DSP::HLE::DspPipe::Audio); + // HACK(merry): Added to prevent regressions. Will remove soon. + DSP_DSP::SignalPipeInterrupt(DSP::HLE::DspPipe::Binary); } // Reschedule recurrent event From c379b22117f61bcbeda8f8edb3035d080a4dc223 Mon Sep 17 00:00:00 2001 From: MerryMage Date: Tue, 26 Apr 2016 19:28:53 +0100 Subject: [PATCH 100/104] DSP_DSP: Fix log format strings and arguments --- src/core/hle/service/dsp_dsp.cpp | 32 ++++++++++++++++++++------------ 1 file changed, 20 insertions(+), 12 deletions(-) diff --git a/src/core/hle/service/dsp_dsp.cpp b/src/core/hle/service/dsp_dsp.cpp index 58ded7eb5..995bee3f9 100644 --- a/src/core/hle/service/dsp_dsp.cpp +++ b/src/core/hle/service/dsp_dsp.cpp @@ -272,18 +272,20 @@ static void SetSemaphore(Service::Interface* self) { static void WriteProcessPipe(Service::Interface* self) { u32* cmd_buff = Kernel::GetCommandBuffer(); - DSP::HLE::DspPipe pipe = static_cast(cmd_buff[1]); + u32 pipe_index = cmd_buff[1]; u32 size = cmd_buff[2]; u32 buffer = cmd_buff[4]; + DSP::HLE::DspPipe pipe = static_cast(pipe_index); + if (IPC::StaticBufferDesc(size, 1) != cmd_buff[3]) { - LOG_ERROR(Service_DSP, "IPC static buffer descriptor failed validation (0x%X). pipe=%u, size=0x%X, buffer=0x%08X", cmd_buff[3], pipe, size, buffer); + LOG_ERROR(Service_DSP, "IPC static buffer descriptor failed validation (0x%X). pipe=%u, size=0x%X, buffer=0x%08X", cmd_buff[3], pipe_index, size, buffer); cmd_buff[0] = IPC::MakeHeader(0, 1, 0); cmd_buff[1] = ResultCode(ErrorDescription::OS_InvalidBufferDescriptor, ErrorModule::OS, ErrorSummary::WrongArgument, ErrorLevel::Permanent).raw; return; } - ASSERT_MSG(Memory::GetPointer(buffer) != nullptr, "Invalid Buffer: pipe=%u, size=0x%X, buffer=0x%08X", pipe, size, buffer); + ASSERT_MSG(Memory::GetPointer(buffer) != nullptr, "Invalid Buffer: pipe=%u, size=0x%X, buffer=0x%08X", pipe_index, size, buffer); std::vector message(size); for (size_t i = 0; i < size; i++) { @@ -295,7 +297,7 @@ static void WriteProcessPipe(Service::Interface* self) { cmd_buff[0] = IPC::MakeHeader(0xD, 1, 0); cmd_buff[1] = RESULT_SUCCESS.raw; // No error - LOG_DEBUG(Service_DSP, "pipe=%u, size=0x%X, buffer=0x%08X", pipe, size, buffer); + LOG_DEBUG(Service_DSP, "pipe=%u, size=0x%X, buffer=0x%08X", pipe_index, size, buffer); } /** @@ -315,12 +317,14 @@ static void WriteProcessPipe(Service::Interface* self) { static void ReadPipeIfPossible(Service::Interface* self) { u32* cmd_buff = Kernel::GetCommandBuffer(); - DSP::HLE::DspPipe pipe = static_cast(cmd_buff[1]); + u32 pipe_index = cmd_buff[1]; u32 unknown = cmd_buff[2]; u32 size = cmd_buff[3] & 0xFFFF; // Lower 16 bits are size VAddr addr = cmd_buff[0x41]; - ASSERT_MSG(Memory::GetPointer(addr) != nullptr, "Invalid addr: pipe=0x%08X, unknown=0x%08X, size=0x%X, buffer=0x%08X", pipe, unknown, size, addr); + DSP::HLE::DspPipe pipe = static_cast(pipe_index); + + ASSERT_MSG(Memory::GetPointer(addr) != nullptr, "Invalid addr: pipe=%u, unknown=0x%08X, size=0x%X, buffer=0x%08X", pipe_index, unknown, size, addr); cmd_buff[0] = IPC::MakeHeader(0x10, 1, 2); cmd_buff[1] = RESULT_SUCCESS.raw; // No error @@ -336,7 +340,7 @@ static void ReadPipeIfPossible(Service::Interface* self) { cmd_buff[3] = IPC::StaticBufferDesc(size, 0); cmd_buff[4] = addr; - LOG_DEBUG(Service_DSP, "pipe=0x%08X, unknown=0x%08X, size=0x%X, buffer=0x%08X, return cmd_buff[2]=0x%08X", pipe, unknown, size, addr, cmd_buff[2]); + LOG_DEBUG(Service_DSP, "pipe=%u, unknown=0x%08X, size=0x%X, buffer=0x%08X, return cmd_buff[2]=0x%08X", pipe_index, unknown, size, addr, cmd_buff[2]); } /** @@ -353,12 +357,14 @@ static void ReadPipeIfPossible(Service::Interface* self) { static void ReadPipe(Service::Interface* self) { u32* cmd_buff = Kernel::GetCommandBuffer(); - DSP::HLE::DspPipe pipe = static_cast(cmd_buff[1]); + u32 pipe_index = cmd_buff[1]; u32 unknown = cmd_buff[2]; u32 size = cmd_buff[3] & 0xFFFF; // Lower 16 bits are size VAddr addr = cmd_buff[0x41]; - ASSERT_MSG(Memory::GetPointer(addr) != nullptr, "Invalid addr: pipe=0x%08X, unknown=0x%08X, size=0x%X, buffer=0x%08X", pipe, unknown, size, addr); + DSP::HLE::DspPipe pipe = static_cast(pipe_index); + + ASSERT_MSG(Memory::GetPointer(addr) != nullptr, "Invalid addr: pipe=%u, unknown=0x%08X, size=0x%X, buffer=0x%08X", pipe_index, unknown, size, addr); if (DSP::HLE::GetPipeReadableSize(pipe) >= size) { std::vector response = DSP::HLE::PipeRead(pipe, size); @@ -375,7 +381,7 @@ static void ReadPipe(Service::Interface* self) { UNREACHABLE(); } - LOG_DEBUG(Service_DSP, "pipe=0x%08X, unknown=0x%08X, size=0x%X, buffer=0x%08X, return cmd_buff[2]=0x%08X", pipe, unknown, size, addr, cmd_buff[2]); + LOG_DEBUG(Service_DSP, "pipe=%u, unknown=0x%08X, size=0x%X, buffer=0x%08X, return cmd_buff[2]=0x%08X", pipe_index, unknown, size, addr, cmd_buff[2]); } /** @@ -390,14 +396,16 @@ static void ReadPipe(Service::Interface* self) { static void GetPipeReadableSize(Service::Interface* self) { u32* cmd_buff = Kernel::GetCommandBuffer(); - DSP::HLE::DspPipe pipe = static_cast(cmd_buff[1]); + u32 pipe_index = cmd_buff[1]; u32 unknown = cmd_buff[2]; + DSP::HLE::DspPipe pipe = static_cast(pipe_index); + cmd_buff[0] = IPC::MakeHeader(0xF, 2, 0); cmd_buff[1] = RESULT_SUCCESS.raw; // No error cmd_buff[2] = DSP::HLE::GetPipeReadableSize(pipe); - LOG_DEBUG(Service_DSP, "pipe=0x%08X, unknown=0x%08X, return cmd_buff[2]=0x%08X", pipe, unknown, cmd_buff[2]); + LOG_DEBUG(Service_DSP, "pipe=%u, unknown=0x%08X, return cmd_buff[2]=0x%08X", pipe_index, unknown, cmd_buff[2]); } /** From dda9ffe7901b354d45ab48844801a16b806da9a2 Mon Sep 17 00:00:00 2001 From: MerryMage Date: Sun, 24 Apr 2016 13:20:13 +0100 Subject: [PATCH 101/104] AudioCore: Move samples_per_frame and num_sources into hle/common.h --- src/audio_core/audio_core.h | 2 -- src/audio_core/hle/common.h | 9 +++++---- src/audio_core/hle/dsp.h | 12 ++++++------ 3 files changed, 11 insertions(+), 12 deletions(-) diff --git a/src/audio_core/audio_core.h b/src/audio_core/audio_core.h index 64c330914..b349895ea 100644 --- a/src/audio_core/audio_core.h +++ b/src/audio_core/audio_core.h @@ -10,8 +10,6 @@ class VMManager; namespace AudioCore { -constexpr int num_sources = 24; -constexpr int samples_per_frame = 160; ///< Samples per audio frame at native sample rate constexpr int native_sample_rate = 32728; ///< 32kHz /// Initialise Audio Core diff --git a/src/audio_core/hle/common.h b/src/audio_core/hle/common.h index 37d441eb2..7910f42ae 100644 --- a/src/audio_core/hle/common.h +++ b/src/audio_core/hle/common.h @@ -7,18 +7,19 @@ #include #include -#include "audio_core/audio_core.h" - #include "common/common_types.h" namespace DSP { namespace HLE { +constexpr int num_sources = 24; +constexpr int samples_per_frame = 160; ///< Samples per audio frame at native sample rate + /// The final output to the speakers is stereo. Preprocessing output in Source is also stereo. -using StereoFrame16 = std::array, AudioCore::samples_per_frame>; +using StereoFrame16 = std::array, samples_per_frame>; /// The DSP is quadraphonic internally. -using QuadFrame32 = std::array, AudioCore::samples_per_frame>; +using QuadFrame32 = std::array, samples_per_frame>; /** * This performs the filter operation defined by FilterT::ProcessSample on the frame in-place. diff --git a/src/audio_core/hle/dsp.h b/src/audio_core/hle/dsp.h index c15ef0b7a..c76350bdd 100644 --- a/src/audio_core/hle/dsp.h +++ b/src/audio_core/hle/dsp.h @@ -7,7 +7,7 @@ #include #include -#include "audio_core/audio_core.h" +#include "audio_core/hle/common.h" #include "common/bit_field.h" #include "common/common_funcs.h" @@ -305,7 +305,7 @@ struct SourceConfiguration { u16_le buffer_id; }; - Configuration config[AudioCore::num_sources]; + Configuration config[num_sources]; }; ASSERT_DSP_STRUCT(SourceConfiguration::Configuration, 192); ASSERT_DSP_STRUCT(SourceConfiguration::Configuration::Buffer, 20); @@ -320,7 +320,7 @@ struct SourceStatus { INSERT_PADDING_DSPWORDS(1); }; - Status status[AudioCore::num_sources]; + Status status[num_sources]; }; ASSERT_DSP_STRUCT(SourceStatus::Status, 12); @@ -413,7 +413,7 @@ ASSERT_DSP_STRUCT(DspConfiguration::ReverbEffect, 52); struct AdpcmCoefficients { /// Coefficients are signed fixed point with 11 fractional bits. /// Each source has 16 coefficients associated with it. - s16_le coeff[AudioCore::num_sources][16]; + s16_le coeff[num_sources][16]; }; ASSERT_DSP_STRUCT(AdpcmCoefficients, 768); @@ -427,7 +427,7 @@ ASSERT_DSP_STRUCT(DspStatus, 32); /// Final mixed output in PCM16 stereo format, what you hear out of the speakers. /// When the application writes to this region it has no effect. struct FinalMixSamples { - s16_le pcm16[2 * AudioCore::samples_per_frame]; + s16_le pcm16[2 * samples_per_frame]; }; ASSERT_DSP_STRUCT(FinalMixSamples, 640); @@ -437,7 +437,7 @@ ASSERT_DSP_STRUCT(FinalMixSamples, 640); /// Values that exceed s16 range will be clipped by the DSP after further processing. struct IntermediateMixSamples { struct Samples { - s32_le pcm32[4][AudioCore::samples_per_frame]; ///< Little-endian as opposed to DSP middle-endian. + s32_le pcm32[4][samples_per_frame]; ///< Little-endian as opposed to DSP middle-endian. }; Samples mix1; From 27ce3b3f51998b7bd8f25d7cb1c9cc1321ad6f31 Mon Sep 17 00:00:00 2001 From: MerryMage Date: Sun, 24 Apr 2016 14:18:30 +0100 Subject: [PATCH 102/104] Externals: Add soundtouch --- .gitmodules | 3 +++ CMakeLists.txt | 3 +++ externals/soundtouch | 1 + src/audio_core/CMakeLists.txt | 5 ++++- 4 files changed, 11 insertions(+), 1 deletion(-) create mode 160000 externals/soundtouch diff --git a/.gitmodules b/.gitmodules index 598e4c64d..059512902 100644 --- a/.gitmodules +++ b/.gitmodules @@ -7,3 +7,6 @@ [submodule "nihstro"] path = externals/nihstro url = https://github.com/neobrain/nihstro.git +[submodule "soundtouch"] + path = externals/soundtouch + url = https://github.com/citra-emu/soundtouch.git diff --git a/CMakeLists.txt b/CMakeLists.txt index 019321ad8..d628ecc50 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -249,6 +249,9 @@ if(ENABLE_QT) include_directories(externals/qhexedit) add_subdirectory(externals/qhexedit) endif() + +add_subdirectory(externals/soundtouch) + add_subdirectory(src) # Install freedesktop.org metadata files, following those specifications: diff --git a/externals/soundtouch b/externals/soundtouch new file mode 160000 index 000000000..5274ec4de --- /dev/null +++ b/externals/soundtouch @@ -0,0 +1 @@ +Subproject commit 5274ec4dec498bd88ccbcd28862a0f78a3b95eff diff --git a/src/audio_core/CMakeLists.txt b/src/audio_core/CMakeLists.txt index 869da5e83..c08ce69e0 100644 --- a/src/audio_core/CMakeLists.txt +++ b/src/audio_core/CMakeLists.txt @@ -16,6 +16,9 @@ set(HEADERS sink.h ) +include_directories(../../externals/soundtouch/include) + create_directory_groups(${SRCS} ${HEADERS}) -add_library(audio_core STATIC ${SRCS} ${HEADERS}) \ No newline at end of file +add_library(audio_core STATIC ${SRCS} ${HEADERS}) +target_link_libraries(audio_core SoundTouch) From 90501f20e6b91fcd2beaccf0b1a0174b189da09c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Henrik=20Rydg=C3=A5rd?= Date: Fri, 29 Apr 2016 02:17:31 +0200 Subject: [PATCH 103/104] Make Citra build with MICROPROFILE_ENABLED set to 0 (#1709) * Make Citra build with MICROPROFILE_ENABLED set to 0 * Buildfix with microprofile kept on * moc did not like a dialog to conditionally exist. * Cleanup * Fix end of line --- src/citra_qt/bootmanager.cpp | 2 ++ src/citra_qt/debugger/profiler.cpp | 13 +++++++++++++ src/citra_qt/debugger/profiler.h | 3 +++ src/citra_qt/main.cpp | 9 ++++++++- src/common/microprofile.h | 4 ++++ 5 files changed, 30 insertions(+), 1 deletion(-) diff --git a/src/citra_qt/bootmanager.cpp b/src/citra_qt/bootmanager.cpp index 8e60b9cad..01b81c11c 100644 --- a/src/citra_qt/bootmanager.cpp +++ b/src/citra_qt/bootmanager.cpp @@ -71,7 +71,9 @@ void EmuThread::run() { // Shutdown the core emulation System::Shutdown(); +#if MICROPROFILE_ENABLED MicroProfileOnThreadExit(); +#endif render_window->moveContext(); } diff --git a/src/citra_qt/debugger/profiler.cpp b/src/citra_qt/debugger/profiler.cpp index 4f6ba0e1f..e90973b8e 100644 --- a/src/citra_qt/debugger/profiler.cpp +++ b/src/citra_qt/debugger/profiler.cpp @@ -14,8 +14,10 @@ // Include the implementation of the UI in this file. This isn't in microprofile.cpp because the // non-Qt frontends don't need it (and don't implement the UI drawing hooks either). +#if MICROPROFILE_ENABLED #define MICROPROFILEUI_IMPL 1 #include "common/microprofileui.h" +#endif using namespace Common::Profiling; @@ -148,6 +150,8 @@ void ProfilerWidget::setProfilingInfoUpdateEnabled(bool enable) } } +#if MICROPROFILE_ENABLED + class MicroProfileWidget : public QWidget { public: MicroProfileWidget(QWidget* parent = nullptr); @@ -171,6 +175,8 @@ private: QTimer update_timer; }; +#endif + MicroProfileDialog::MicroProfileDialog(QWidget* parent) : QWidget(parent, Qt::Dialog) { @@ -180,6 +186,8 @@ MicroProfileDialog::MicroProfileDialog(QWidget* parent) // Remove the "?" button from the titlebar and enable the maximize button setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint | Qt::WindowMaximizeButtonHint); +#if MICROPROFILE_ENABLED + MicroProfileWidget* widget = new MicroProfileWidget(this); QLayout* layout = new QVBoxLayout(this); @@ -191,6 +199,7 @@ MicroProfileDialog::MicroProfileDialog(QWidget* parent) setFocusProxy(widget); widget->setFocusPolicy(Qt::StrongFocus); widget->setFocus(); +#endif } QAction* MicroProfileDialog::toggleViewAction() { @@ -218,6 +227,9 @@ void MicroProfileDialog::hideEvent(QHideEvent* ev) { QWidget::hideEvent(ev); } + +#if MICROPROFILE_ENABLED + /// There's no way to pass a user pointer to MicroProfile, so this variable is used to make the /// QPainter available inside the drawing callbacks. static QPainter* mp_painter = nullptr; @@ -337,3 +349,4 @@ void MicroProfileDrawLine2D(u32 vertices_length, float* vertices, u32 hex_color) mp_painter->drawPolyline(point_buf.data(), vertices_length); point_buf.clear(); } +#endif diff --git a/src/citra_qt/debugger/profiler.h b/src/citra_qt/debugger/profiler.h index 036054740..3b38ed8ec 100644 --- a/src/citra_qt/debugger/profiler.h +++ b/src/citra_qt/debugger/profiler.h @@ -7,8 +7,10 @@ #include #include #include + #include "ui_profiler.h" +#include "common/microprofile.h" #include "common/profiler_reporting.h" class ProfilerModel : public QAbstractItemModel @@ -49,6 +51,7 @@ private: QTimer update_timer; }; + class MicroProfileDialog : public QWidget { Q_OBJECT diff --git a/src/citra_qt/main.cpp b/src/citra_qt/main.cpp index 2ca1e51f6..f1ab29755 100644 --- a/src/citra_qt/main.cpp +++ b/src/citra_qt/main.cpp @@ -69,8 +69,10 @@ GMainWindow::GMainWindow() : config(new Config()), emu_thread(nullptr) addDockWidget(Qt::BottomDockWidgetArea, profilerWidget); profilerWidget->hide(); +#if MICROPROFILE_ENABLED microProfileDialog = new MicroProfileDialog(this); microProfileDialog->hide(); +#endif disasmWidget = new DisassemblerWidget(this, emu_thread.get()); addDockWidget(Qt::BottomDockWidgetArea, disasmWidget); @@ -110,7 +112,9 @@ GMainWindow::GMainWindow() : config(new Config()), emu_thread(nullptr) QMenu* debug_menu = ui.menu_View->addMenu(tr("Debugging")); debug_menu->addAction(profilerWidget->toggleViewAction()); +#if MICROPROFILE_ENABLED debug_menu->addAction(microProfileDialog->toggleViewAction()); +#endif debug_menu->addAction(disasmWidget->toggleViewAction()); debug_menu->addAction(registersWidget->toggleViewAction()); debug_menu->addAction(callstackWidget->toggleViewAction()); @@ -136,8 +140,10 @@ GMainWindow::GMainWindow() : config(new Config()), emu_thread(nullptr) restoreGeometry(UISettings::values.geometry); restoreState(UISettings::values.state); render_window->restoreGeometry(UISettings::values.renderwindow_geometry); +#if MICROPROFILE_ENABLED microProfileDialog->restoreGeometry(UISettings::values.microprofile_geometry); microProfileDialog->setVisible(UISettings::values.microprofile_visible); +#endif game_list->LoadInterfaceLayout(); @@ -511,9 +517,10 @@ void GMainWindow::closeEvent(QCloseEvent* event) { UISettings::values.geometry = saveGeometry(); UISettings::values.state = saveState(); UISettings::values.renderwindow_geometry = render_window->saveGeometry(); +#if MICROPROFILE_ENABLED UISettings::values.microprofile_geometry = microProfileDialog->saveGeometry(); UISettings::values.microprofile_visible = microProfileDialog->isVisible(); - +#endif UISettings::values.single_window_mode = ui.action_Single_Window_Mode->isChecked(); UISettings::values.display_titlebar = ui.actionDisplay_widget_title_bars->isChecked(); UISettings::values.first_start = false; diff --git a/src/common/microprofile.h b/src/common/microprofile.h index d3b6cb97c..ef312c6e1 100644 --- a/src/common/microprofile.h +++ b/src/common/microprofile.h @@ -4,6 +4,10 @@ #pragma once +// Uncomment this to disable microprofile. This will get you cleaner profiles when using +// external sampling profilers like "Very Sleepy", and will improve performance somewhat. +// #define MICROPROFILE_ENABLED 0 + // Customized Citra settings. // This file wraps the MicroProfile header so that these are consistent everywhere. #define MICROPROFILE_WEBSERVER 0 From e3a8292495cf0fb4297be27c696649dc44e011f0 Mon Sep 17 00:00:00 2001 From: Yuri Kunde Schlesner Date: Fri, 29 Apr 2016 00:07:10 -0700 Subject: [PATCH 104/104] Common: Remove section measurement from profiler (#1731) This has been entirely superseded by MicroProfile. The rest of the code can go when a simpler frametime/FPS meter is added to the GUI. --- src/citra_qt/debugger/profiler.cpp | 26 +-- src/common/CMakeLists.txt | 1 - src/common/microprofileui.h | 3 + src/common/profiler.cpp | 82 ---------- src/common/profiler.h | 152 ------------------ src/common/profiler_reporting.h | 27 +--- .../arm/dyncom/arm_dyncom_interpreter.cpp | 7 - src/core/hle/service/gsp_gpu.cpp | 1 - src/core/hle/svc.cpp | 4 - src/video_core/command_processor.cpp | 4 - src/video_core/rasterizer.cpp | 3 - .../renderer_opengl/gl_rasterizer.cpp | 1 - src/video_core/shader/shader.cpp | 3 - 13 files changed, 8 insertions(+), 306 deletions(-) delete mode 100644 src/common/profiler.h diff --git a/src/citra_qt/debugger/profiler.cpp b/src/citra_qt/debugger/profiler.cpp index e90973b8e..7bb010f77 100644 --- a/src/citra_qt/debugger/profiler.cpp +++ b/src/citra_qt/debugger/profiler.cpp @@ -9,6 +9,7 @@ #include "citra_qt/debugger/profiler.h" #include "citra_qt/util/util.h" +#include "common/common_types.h" #include "common/microprofile.h" #include "common/profiler_reporting.h" @@ -36,21 +37,9 @@ static QVariant GetDataForColumn(int col, const AggregatedDuration& duration) } } -static const TimingCategoryInfo* GetCategoryInfo(int id) -{ - const auto& categories = GetProfilingManager().GetTimingCategoriesInfo(); - if ((size_t)id >= categories.size()) { - return nullptr; - } else { - return &categories[id]; - } -} - ProfilerModel::ProfilerModel(QObject* parent) : QAbstractItemModel(parent) { updateProfilingInfo(); - const auto& categories = GetProfilingManager().GetTimingCategoriesInfo(); - results.time_per_category.resize(categories.size()); } QVariant ProfilerModel::headerData(int section, Qt::Orientation orientation, int role) const @@ -87,7 +76,7 @@ int ProfilerModel::rowCount(const QModelIndex& parent) const if (parent.isValid()) { return 0; } else { - return static_cast(results.time_per_category.size() + 2); + return 2; } } @@ -106,17 +95,6 @@ QVariant ProfilerModel::data(const QModelIndex& index, int role) const } else { return GetDataForColumn(index.column(), results.interframe_time); } - } else { - if (index.column() == 0) { - const TimingCategoryInfo* info = GetCategoryInfo(index.row() - 2); - return info != nullptr ? QString(info->name) : QVariant(); - } else { - if (index.row() - 2 < (int)results.time_per_category.size()) { - return GetDataForColumn(index.column(), results.time_per_category[index.row() - 2]); - } else { - return QVariant(); - } - } } } diff --git a/src/common/CMakeLists.txt b/src/common/CMakeLists.txt index c839ce173..aa6eee2a3 100644 --- a/src/common/CMakeLists.txt +++ b/src/common/CMakeLists.txt @@ -47,7 +47,6 @@ set(HEADERS microprofile.h microprofileui.h platform.h - profiler.h profiler_reporting.h scm_rev.h scope_exit.h diff --git a/src/common/microprofileui.h b/src/common/microprofileui.h index 97c369bd9..41abe6b75 100644 --- a/src/common/microprofileui.h +++ b/src/common/microprofileui.h @@ -13,4 +13,7 @@ #define MICROPROFILE_HELP_ALT "Right-Click" #define MICROPROFILE_HELP_MOD "Ctrl" +// This isn't included by microprofileui.h :( +#include // For std::abs + #include diff --git a/src/common/profiler.cpp b/src/common/profiler.cpp index 7792edd2f..49eb3f40c 100644 --- a/src/common/profiler.cpp +++ b/src/common/profiler.cpp @@ -7,71 +7,16 @@ #include #include "common/assert.h" -#include "common/profiler.h" #include "common/profiler_reporting.h" #include "common/synchronized_wrapper.h" -#if defined(_MSC_VER) && _MSC_VER <= 1800 // MSVC 2013. - #define WIN32_LEAN_AND_MEAN - #include // For QueryPerformanceCounter/Frequency -#endif - namespace Common { namespace Profiling { -#if ENABLE_PROFILING -thread_local Timer* Timer::current_timer = nullptr; -#endif - -#if defined(_MSC_VER) && _MSC_VER <= 1800 // MSVC 2013 -QPCClock::time_point QPCClock::now() { - static LARGE_INTEGER freq; - // Use this dummy local static to ensure this gets initialized once. - static BOOL dummy = QueryPerformanceFrequency(&freq); - - LARGE_INTEGER ticks; - QueryPerformanceCounter(&ticks); - - // This is prone to overflow when multiplying, which is why I'm using micro instead of nano. The - // correct way to approach this would be to just return ticks as a time_point and then subtract - // and do this conversion when creating a duration from two time_points, however, as far as I - // could tell the C++ requirements for these types are incompatible with this approach. - return time_point(duration(ticks.QuadPart * std::micro::den / freq.QuadPart)); -} -#endif - -TimingCategory::TimingCategory(const char* name, TimingCategory* parent) - : accumulated_duration(0) { - - ProfilingManager& manager = GetProfilingManager(); - category_id = manager.RegisterTimingCategory(this, name); - if (parent != nullptr) - manager.SetTimingCategoryParent(category_id, parent->category_id); -} - ProfilingManager::ProfilingManager() : last_frame_end(Clock::now()), this_frame_start(Clock::now()) { } -unsigned int ProfilingManager::RegisterTimingCategory(TimingCategory* category, const char* name) { - TimingCategoryInfo info; - info.category = category; - info.name = name; - info.parent = TimingCategoryInfo::NO_PARENT; - - unsigned int id = (unsigned int)timing_categories.size(); - timing_categories.push_back(std::move(info)); - - return id; -} - -void ProfilingManager::SetTimingCategoryParent(unsigned int category, unsigned int parent) { - ASSERT(category < timing_categories.size()); - ASSERT(parent < timing_categories.size()); - - timing_categories[category].parent = parent; -} - void ProfilingManager::BeginFrame() { this_frame_start = Clock::now(); } @@ -82,11 +27,6 @@ void ProfilingManager::FinishFrame() { results.interframe_time = now - last_frame_end; results.frame_time = now - this_frame_start; - results.time_per_category.resize(timing_categories.size()); - for (size_t i = 0; i < timing_categories.size(); ++i) { - results.time_per_category[i] = timing_categories[i].category->GetAccumulatedTime(); - } - last_frame_end = now; } @@ -100,26 +40,9 @@ void TimingResultsAggregator::Clear() { window_size = cursor = 0; } -void TimingResultsAggregator::SetNumberOfCategories(size_t n) { - size_t old_size = times_per_category.size(); - if (n == old_size) - return; - - times_per_category.resize(n); - - for (size_t i = old_size; i < n; ++i) { - times_per_category[i].resize(max_window_size, Duration::zero()); - } -} - void TimingResultsAggregator::AddFrame(const ProfilingFrameResult& frame_result) { - SetNumberOfCategories(frame_result.time_per_category.size()); - interframe_times[cursor] = frame_result.interframe_time; frame_times[cursor] = frame_result.frame_time; - for (size_t i = 0; i < frame_result.time_per_category.size(); ++i) { - times_per_category[i][cursor] = frame_result.time_per_category[i]; - } ++cursor; if (cursor == max_window_size) @@ -162,11 +85,6 @@ AggregatedFrameResult TimingResultsAggregator::GetAggregatedResults() const { result.fps = 0.0f; } - result.time_per_category.resize(times_per_category.size()); - for (size_t i = 0; i < times_per_category.size(); ++i) { - result.time_per_category[i] = AggregateField(times_per_category[i], window_size); - } - return result; } diff --git a/src/common/profiler.h b/src/common/profiler.h deleted file mode 100644 index 3e967b4bc..000000000 --- a/src/common/profiler.h +++ /dev/null @@ -1,152 +0,0 @@ -// Copyright 2015 Citra Emulator Project -// Licensed under GPLv2 or any later version -// Refer to the license.txt file included. - -#pragma once - -#include -#include - -#include "common/assert.h" -#include "common/thread.h" - -namespace Common { -namespace Profiling { - -// If this is defined to 0, it turns all Timers into no-ops. -#ifndef ENABLE_PROFILING -#define ENABLE_PROFILING 1 -#endif - -#if defined(_MSC_VER) && _MSC_VER <= 1800 // MSVC 2013 -// MSVC up to 2013 doesn't use QueryPerformanceCounter for high_resolution_clock, so it has bad -// precision. We manually implement a clock based on QPC to get good results. - -struct QPCClock { - using duration = std::chrono::microseconds; - using time_point = std::chrono::time_point; - using rep = duration::rep; - using period = duration::period; - static const bool is_steady = false; - - static time_point now(); -}; - -using Clock = QPCClock; -#else -using Clock = std::chrono::high_resolution_clock; -#endif - -using Duration = Clock::duration; - -/** - * Represents a timing category that measured time can be accounted towards. Should be declared as a - * global variable and passed to Timers. - */ -class TimingCategory final { -public: - TimingCategory(const char* name, TimingCategory* parent = nullptr); - - unsigned int GetCategoryId() const { - return category_id; - } - - /// Adds some time to this category. Can safely be called from multiple threads at the same time. - void AddTime(Duration amount) { - std::atomic_fetch_add_explicit( - &accumulated_duration, amount.count(), - std::memory_order_relaxed); - } - - /** - * Atomically retrieves the accumulated measured time for this category and resets the counter - * to zero. Can be safely called concurrently with AddTime. - */ - Duration GetAccumulatedTime() { - return Duration(std::atomic_exchange_explicit( - &accumulated_duration, (Duration::rep)0, - std::memory_order_relaxed)); - } - -private: - unsigned int category_id; - std::atomic accumulated_duration; -}; - -/** - * Measures time elapsed between a call to Start and a call to Stop and attributes it to the given - * TimingCategory. Start/Stop can be called multiple times on the same timer, but each call must be - * appropriately paired. - * - * When a Timer is started, it automatically pauses a previously running timer on the same thread, - * which is resumed when it is stopped. As such, no special action needs to be taken to avoid - * double-accounting of time on two categories. - */ -class Timer { -public: - Timer(TimingCategory& category) : category(category) { - } - - void Start() { -#if ENABLE_PROFILING - ASSERT(!running); - previous_timer = current_timer; - current_timer = this; - if (previous_timer != nullptr) - previous_timer->StopTiming(); - - StartTiming(); -#endif - } - - void Stop() { -#if ENABLE_PROFILING - ASSERT(running); - StopTiming(); - - if (previous_timer != nullptr) - previous_timer->StartTiming(); - current_timer = previous_timer; -#endif - } - -private: -#if ENABLE_PROFILING - void StartTiming() { - start = Clock::now(); - running = true; - } - - void StopTiming() { - auto duration = Clock::now() - start; - running = false; - category.AddTime(std::chrono::duration_cast(duration)); - } - - Clock::time_point start; - bool running = false; - - Timer* previous_timer; - static thread_local Timer* current_timer; -#endif - - TimingCategory& category; -}; - -/** - * A Timer that automatically starts timing when created and stops at the end of the scope. Should - * be used in the majority of cases. - */ -class ScopeTimer : public Timer { -public: - ScopeTimer(TimingCategory& category) : Timer(category) { - Start(); - } - - ~ScopeTimer() { - Stop(); - } -}; - -} // namespace Profiling -} // namespace Common diff --git a/src/common/profiler_reporting.h b/src/common/profiler_reporting.h index df98e05b7..fa1ac883f 100644 --- a/src/common/profiler_reporting.h +++ b/src/common/profiler_reporting.h @@ -4,22 +4,17 @@ #pragma once +#include #include #include -#include "common/profiler.h" #include "common/synchronized_wrapper.h" namespace Common { namespace Profiling { -struct TimingCategoryInfo { - static const unsigned int NO_PARENT = -1; - - TimingCategory* category; - const char* name; - unsigned int parent; -}; +using Clock = std::chrono::high_resolution_clock; +using Duration = Clock::duration; struct ProfilingFrameResult { /// Time since the last delivered frame @@ -27,22 +22,12 @@ struct ProfilingFrameResult { /// Time spent processing a frame, excluding VSync Duration frame_time; - - /// Total amount of time spent inside each category in this frame. Indexed by the category id - std::vector time_per_category; }; class ProfilingManager final { public: ProfilingManager(); - unsigned int RegisterTimingCategory(TimingCategory* category, const char* name); - void SetTimingCategoryParent(unsigned int category, unsigned int parent); - - const std::vector& GetTimingCategoriesInfo() const { - return timing_categories; - } - /// This should be called after swapping screen buffers. void BeginFrame(); /// This should be called before swapping screen buffers. @@ -54,7 +39,6 @@ public: } private: - std::vector timing_categories; Clock::time_point last_frame_end; Clock::time_point this_frame_start; @@ -73,9 +57,6 @@ struct AggregatedFrameResult { AggregatedDuration frame_time; float fps; - - /// Total amount of time spent inside each category in this frame. Indexed by the category id - std::vector time_per_category; }; class TimingResultsAggregator final { @@ -83,7 +64,6 @@ public: TimingResultsAggregator(size_t window_size); void Clear(); - void SetNumberOfCategories(size_t n); void AddFrame(const ProfilingFrameResult& frame_result); @@ -95,7 +75,6 @@ public: std::vector interframe_times; std::vector frame_times; - std::vector> times_per_category; }; ProfilingManager& GetProfilingManager(); diff --git a/src/core/arm/dyncom/arm_dyncom_interpreter.cpp b/src/core/arm/dyncom/arm_dyncom_interpreter.cpp index 647784208..8d4b26815 100644 --- a/src/core/arm/dyncom/arm_dyncom_interpreter.cpp +++ b/src/core/arm/dyncom/arm_dyncom_interpreter.cpp @@ -10,7 +10,6 @@ #include "common/common_types.h" #include "common/logging/log.h" #include "common/microprofile.h" -#include "common/profiler.h" #include "core/memory.h" #include "core/hle/svc.h" @@ -25,9 +24,6 @@ #include "core/gdbstub/gdbstub.h" -Common::Profiling::TimingCategory profile_execute("DynCom::Execute"); -Common::Profiling::TimingCategory profile_decode("DynCom::Decode"); - enum { COND = (1 << 0), NON_BRANCH = (1 << 1), @@ -3496,7 +3492,6 @@ static unsigned int InterpreterTranslateInstruction(const ARMul_State* cpu, cons } static int InterpreterTranslateBlock(ARMul_State* cpu, int& bb_start, u32 addr) { - Common::Profiling::ScopeTimer timer_decode(profile_decode); MICROPROFILE_SCOPE(DynCom_Decode); // Decode instruction, get index @@ -3530,7 +3525,6 @@ static int InterpreterTranslateBlock(ARMul_State* cpu, int& bb_start, u32 addr) } static int InterpreterTranslateSingle(ARMul_State* cpu, int& bb_start, u32 addr) { - Common::Profiling::ScopeTimer timer_decode(profile_decode); MICROPROFILE_SCOPE(DynCom_Decode); ARM_INST_PTR inst_base = nullptr; @@ -3565,7 +3559,6 @@ static int clz(unsigned int x) { MICROPROFILE_DEFINE(DynCom_Execute, "DynCom", "Execute", MP_RGB(255, 0, 0)); unsigned InterpreterMainLoop(ARMul_State* cpu) { - Common::Profiling::ScopeTimer timer_execute(profile_execute); MICROPROFILE_SCOPE(DynCom_Execute); GDBStub::BreakpointAddress breakpoint_data; diff --git a/src/core/hle/service/gsp_gpu.cpp b/src/core/hle/service/gsp_gpu.cpp index 211fcf599..233592d7f 100644 --- a/src/core/hle/service/gsp_gpu.cpp +++ b/src/core/hle/service/gsp_gpu.cpp @@ -4,7 +4,6 @@ #include "common/bit_field.h" #include "common/microprofile.h" -#include "common/profiler.h" #include "core/memory.h" #include "core/hle/kernel/event.h" diff --git a/src/core/hle/svc.cpp b/src/core/hle/svc.cpp index ae54afb1c..a9a1a3244 100644 --- a/src/core/hle/svc.cpp +++ b/src/core/hle/svc.cpp @@ -6,7 +6,6 @@ #include "common/logging/log.h" #include "common/microprofile.h" -#include "common/profiler.h" #include "common/string_util.h" #include "common/symbols.h" @@ -1031,8 +1030,6 @@ static const FunctionDef SVC_Table[] = { {0x7D, HLE::Wrap, "QueryProcessMemory"}, }; -Common::Profiling::TimingCategory profiler_svc("SVC Calls"); - static const FunctionDef* GetSVCInfo(u32 func_num) { if (func_num >= ARRAY_SIZE(SVC_Table)) { LOG_ERROR(Kernel_SVC, "unknown svc=0x%02X", func_num); @@ -1044,7 +1041,6 @@ static const FunctionDef* GetSVCInfo(u32 func_num) { MICROPROFILE_DEFINE(Kernel_SVC, "Kernel", "SVC", MP_RGB(70, 200, 70)); void CallSVC(u32 immediate) { - Common::Profiling::ScopeTimer timer_svc(profiler_svc); MICROPROFILE_SCOPE(Kernel_SVC); const FunctionDef* info = GetSVCInfo(immediate); diff --git a/src/video_core/command_processor.cpp b/src/video_core/command_processor.cpp index 3abe79c09..97ba8214e 100644 --- a/src/video_core/command_processor.cpp +++ b/src/video_core/command_processor.cpp @@ -7,7 +7,6 @@ #include "common/alignment.h" #include "common/microprofile.h" -#include "common/profiler.h" #include "core/settings.h" #include "core/hle/service/gsp_gpu.h" @@ -35,8 +34,6 @@ static int default_attr_counter = 0; static u32 default_attr_write_buffer[3]; -Common::Profiling::TimingCategory category_drawing("Drawing"); - // Expand a 4-bit mask to 4-byte mask, e.g. 0b0101 -> 0x00FF00FF static const u32 expand_bits_to_bytes[] = { 0x00000000, 0x000000ff, 0x0000ff00, 0x0000ffff, @@ -186,7 +183,6 @@ static void WritePicaReg(u32 id, u32 value, u32 mask) { case PICA_REG_INDEX(trigger_draw): case PICA_REG_INDEX(trigger_draw_indexed): { - Common::Profiling::ScopeTimer scope_timer(category_drawing); MICROPROFILE_SCOPE(GPU_Drawing); #if PICA_LOG_TEV diff --git a/src/video_core/rasterizer.cpp b/src/video_core/rasterizer.cpp index 0434ad05a..9cf77b1f2 100644 --- a/src/video_core/rasterizer.cpp +++ b/src/video_core/rasterizer.cpp @@ -9,7 +9,6 @@ #include "common/common_types.h" #include "common/math_util.h" #include "common/microprofile.h" -#include "common/profiler.h" #include "core/memory.h" #include "core/hw/gpu.h" @@ -287,7 +286,6 @@ static int SignedArea (const Math::Vec2& vtx1, return Math::Cross(vec1, vec2).z; }; -static Common::Profiling::TimingCategory rasterization_category("Rasterization"); MICROPROFILE_DEFINE(GPU_Rasterization, "GPU", "Rasterization", MP_RGB(50, 50, 240)); /** @@ -300,7 +298,6 @@ static void ProcessTriangleInternal(const Shader::OutputVertex& v0, bool reversed = false) { const auto& regs = g_state.regs; - Common::Profiling::ScopeTimer timer(rasterization_category); MICROPROFILE_SCOPE(GPU_Rasterization); // vertex positions in rasterizer coordinates diff --git a/src/video_core/renderer_opengl/gl_rasterizer.cpp b/src/video_core/renderer_opengl/gl_rasterizer.cpp index 30187d4cf..a8c775c80 100644 --- a/src/video_core/renderer_opengl/gl_rasterizer.cpp +++ b/src/video_core/renderer_opengl/gl_rasterizer.cpp @@ -11,7 +11,6 @@ #include "common/file_util.h" #include "common/math_util.h" #include "common/microprofile.h" -#include "common/profiler.h" #include "core/memory.h" #include "core/settings.h" diff --git a/src/video_core/shader/shader.cpp b/src/video_core/shader/shader.cpp index 75301accd..043e99190 100644 --- a/src/video_core/shader/shader.cpp +++ b/src/video_core/shader/shader.cpp @@ -9,7 +9,6 @@ #include "common/hash.h" #include "common/microprofile.h" -#include "common/profiler.h" #include "video_core/debug_utils/debug_utils.h" #include "video_core/pica.h" @@ -57,13 +56,11 @@ void Shutdown() { #endif // ARCHITECTURE_x86_64 } -static Common::Profiling::TimingCategory shader_category("Vertex Shader"); MICROPROFILE_DEFINE(GPU_VertexShader, "GPU", "Vertex Shader", MP_RGB(50, 50, 240)); OutputVertex Run(UnitState& state, const InputVertex& input, int num_attributes) { auto& config = g_state.regs.vs; - Common::Profiling::ScopeTimer timer(shader_category); MICROPROFILE_SCOPE(GPU_VertexShader); state.program_counter = config.main_offset;