diff options
Diffstat (limited to 'src')
22 files changed, 1159 insertions, 499 deletions
diff --git a/src/citra/default_ini.h b/src/citra/default_ini.h index 084372df4..d8a8fe44f 100644 --- a/src/citra/default_ini.h +++ b/src/citra/default_ini.h @@ -19,7 +19,13 @@ const char* sdl2_config_file = R"(  #      - "joystick": the index of the joystick to bind  #      - "button"(optional): the index of the button to bind  #      - "hat"(optional): the index of the hat to bind as direction buttons +#      - "axis"(optional): the index of the axis to bind  #      - "direction"(only used for hat): the direction name of the hat to bind. Can be "up", "down", "left" or "right" +#      - "threshould"(only used for axis): a float value in (-1.0, 1.0) which the button is +#          triggered if the axis value crosses +#      - "direction"(only used for axis): "+" means the button is triggered when the axis value +#          is greater than the threshold; "-" means the button is triggered when the axis value +#          is smaller than the threshold  button_a=  button_b=  button_x= diff --git a/src/citra_qt/configuration/config.cpp b/src/citra_qt/configuration/config.cpp index 0b9b73f9e..2b99447ec 100644 --- a/src/citra_qt/configuration/config.cpp +++ b/src/citra_qt/configuration/config.cpp @@ -177,6 +177,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.show_filter_bar = qt_config->value("showFilterBar", true).toBool();      UISettings::values.show_status_bar = qt_config->value("showStatusBar", true).toBool();      UISettings::values.confirm_before_closing = qt_config->value("confirmClose", true).toBool();      UISettings::values.first_start = qt_config->value("firstStart", true).toBool(); @@ -295,6 +296,7 @@ void Config::SaveValues() {      qt_config->setValue("singleWindowMode", UISettings::values.single_window_mode);      qt_config->setValue("displayTitleBars", UISettings::values.display_titlebar); +    qt_config->setValue("showFilterBar", UISettings::values.show_filter_bar);      qt_config->setValue("showStatusBar", UISettings::values.show_status_bar);      qt_config->setValue("confirmClose", UISettings::values.confirm_before_closing);      qt_config->setValue("firstStart", UISettings::values.first_start); diff --git a/src/citra_qt/game_list.cpp b/src/citra_qt/game_list.cpp index a9ec9e830..d6e26ed47 100644 --- a/src/citra_qt/game_list.cpp +++ b/src/citra_qt/game_list.cpp @@ -4,9 +4,9 @@  #include <QFileInfo>  #include <QHeaderView> +#include <QKeyEvent>  #include <QMenu>  #include <QThreadPool> -#include <QVBoxLayout>  #include "common/common_paths.h"  #include "common/logging/log.h"  #include "common/string_util.h" @@ -15,10 +15,189 @@  #include "game_list_p.h"  #include "ui_settings.h" -GameList::GameList(QWidget* parent) : QWidget{parent} { -    QVBoxLayout* layout = new QVBoxLayout; +GameList::SearchField::KeyReleaseEater::KeyReleaseEater(GameList* gamelist) { +    this->gamelist = gamelist; +    edit_filter_text_old = ""; +} + +// EventFilter in order to process systemkeys while editing the searchfield +bool GameList::SearchField::KeyReleaseEater::eventFilter(QObject* obj, QEvent* event) { +    // If it isn't a KeyRelease event then continue with standard event processing +    if (event->type() != QEvent::KeyRelease) +        return QObject::eventFilter(obj, event); + +    QKeyEvent* keyEvent = static_cast<QKeyEvent*>(event); +    int rowCount = gamelist->tree_view->model()->rowCount(); +    QString edit_filter_text = gamelist->search_field->edit_filter->text().toLower(); + +    // If the searchfield's text hasn't changed special function keys get checked +    // If no function key changes the searchfield's text the filter doesn't need to get reloaded +    if (edit_filter_text == edit_filter_text_old) { +        switch (keyEvent->key()) { +        // Escape: Resets the searchfield +        case Qt::Key_Escape: { +            if (edit_filter_text_old.isEmpty()) { +                return QObject::eventFilter(obj, event); +            } else { +                gamelist->search_field->edit_filter->clear(); +                edit_filter_text = ""; +            } +            break; +        } +        // Return and Enter +        // If the enter key gets pressed first checks how many and which entry is visable +        // If there is only one result launch this game +        case Qt::Key_Return: +        case Qt::Key_Enter: { +            QStandardItemModel* item_model = new QStandardItemModel(gamelist->tree_view); +            QModelIndex root_index = item_model->invisibleRootItem()->index(); +            QStandardItem* child_file; +            QString file_path; +            int resultCount = 0; +            for (int i = 0; i < rowCount; ++i) { +                if (!gamelist->tree_view->isRowHidden(i, root_index)) { +                    ++resultCount; +                    child_file = gamelist->item_model->item(i, 0); +                    file_path = child_file->data(GameListItemPath::FullPathRole).toString(); +                } +            } +            if (resultCount == 1) { +                // To avoid loading error dialog loops while confirming them using enter +                // Also users usually want to run a diffrent game after closing one +                gamelist->search_field->edit_filter->setText(""); +                edit_filter_text = ""; +                emit gamelist->GameChosen(file_path); +            } else { +                return QObject::eventFilter(obj, event); +            } +            break; +        } +        default: +            return QObject::eventFilter(obj, event); +        } +    } +    edit_filter_text_old = edit_filter_text; +    return QObject::eventFilter(obj, event); +} + +void GameList::SearchField::setFilterResult(int visable, int total) { +    QString result_of_text = tr("of"); +    QString result_text; +    if (total == 1) { +        result_text = tr("result"); +    } else { +        result_text = tr("results"); +    } +    label_filter_result->setText( +        QString("%1 %2 %3 %4").arg(visable).arg(result_of_text).arg(total).arg(result_text)); +} + +void GameList::SearchField::clear() { +    edit_filter->setText(""); +} +void GameList::SearchField::setFocus() { +    if (edit_filter->isVisible()) { +        edit_filter->setFocus(); +    } +} + +GameList::SearchField::SearchField(GameList* parent) : QWidget{parent} { +    KeyReleaseEater* keyReleaseEater = new KeyReleaseEater(parent); +    layout_filter = new QHBoxLayout; +    layout_filter->setMargin(8); +    label_filter = new QLabel; +    label_filter->setText(tr("Filter:")); +    edit_filter = new QLineEdit; +    edit_filter->setText(""); +    edit_filter->setPlaceholderText(tr("Enter pattern to filter")); +    edit_filter->installEventFilter(keyReleaseEater); +    edit_filter->setClearButtonEnabled(true); +    connect(edit_filter, SIGNAL(textChanged(const QString&)), parent, +            SLOT(onTextChanged(const QString&))); +    label_filter_result = new QLabel; +    button_filter_close = new QToolButton(this); +    button_filter_close->setText("X"); +    button_filter_close->setCursor(Qt::ArrowCursor); +    button_filter_close->setStyleSheet("QToolButton{ border: none; padding: 0px; color: " +                                       "#000000; font-weight: bold; background: #F0F0F0; }" +                                       "QToolButton:hover{ border: none; padding: 0px; color: " +                                       "#EEEEEE; font-weight: bold; background: #E81123}"); +    connect(button_filter_close, SIGNAL(clicked()), parent, SLOT(onFilterCloseClicked())); +    layout_filter->setSpacing(10); +    layout_filter->addWidget(label_filter); +    layout_filter->addWidget(edit_filter); +    layout_filter->addWidget(label_filter_result); +    layout_filter->addWidget(button_filter_close); +    setLayout(layout_filter); +} + +/** +* Checks if all words separated by spaces are contained in another string +* This offers a word order insensitive search function +* +* @param String that gets checked if it contains all words of the userinput string +* @param String containing all words getting checked +* @return true if the haystack contains all words of userinput +*/ +bool GameList::containsAllWords(QString haystack, QString userinput) { +    QStringList userinput_split = userinput.split(" ", QString::SplitBehavior::SkipEmptyParts); +    return std::all_of(userinput_split.begin(), userinput_split.end(), +                       [haystack](QString s) { return haystack.contains(s); }); +} + +// Event in order to filter the gamelist after editing the searchfield +void GameList::onTextChanged(const QString& newText) { +    int rowCount = tree_view->model()->rowCount(); +    QString edit_filter_text = newText.toLower(); + +    QModelIndex root_index = item_model->invisibleRootItem()->index(); + +    // If the searchfield is empty every item is visible +    // Otherwise the filter gets applied +    if (edit_filter_text.isEmpty()) { +        for (int i = 0; i < rowCount; ++i) { +            tree_view->setRowHidden(i, root_index, false); +        } +        search_field->setFilterResult(rowCount, rowCount); +    } else { +        QStandardItem* child_file; +        QString file_path, file_name, file_title, file_programmid; +        int result_count = 0; +        for (int i = 0; i < rowCount; ++i) { +            child_file = item_model->item(i, 0); +            file_path = child_file->data(GameListItemPath::FullPathRole).toString().toLower(); +            file_name = file_path.mid(file_path.lastIndexOf("/") + 1); +            file_title = child_file->data(GameListItemPath::TitleRole).toString().toLower(); +            file_programmid = +                child_file->data(GameListItemPath::ProgramIdRole).toString().toLower(); + +            // Only items which filename in combination with its title contains all words +            // that are in the searchfiel will be visible in the gamelist +            // The search is case insensitive because of toLower() +            // I decided not to use Qt::CaseInsensitive in containsAllWords to prevent +            // multiple conversions of edit_filter_text for each game in the gamelist +            if (containsAllWords(file_name.append(" ").append(file_title), edit_filter_text) || +                (file_programmid.count() == 16 && edit_filter_text.contains(file_programmid))) { +                tree_view->setRowHidden(i, root_index, false); +                ++result_count; +            } else { +                tree_view->setRowHidden(i, root_index, true); +            } +            search_field->setFilterResult(result_count, rowCount); +        } +    } +} + +void GameList::onFilterCloseClicked() { +    main_window->filterBarSetChecked(false); +} + +GameList::GameList(GMainWindow* parent) : QWidget{parent} { +    this->main_window = parent; +    layout = new QVBoxLayout;      tree_view = new QTreeView; +    search_field = new SearchField(this);      item_model = new QStandardItemModel(tree_view);      tree_view->setModel(item_model); @@ -46,7 +225,9 @@ GameList::GameList(QWidget* parent) : QWidget{parent} {      qRegisterMetaType<QList<QStandardItem*>>("QList<QStandardItem*>");      layout->setContentsMargins(0, 0, 0, 0); +    layout->setSpacing(0);      layout->addWidget(tree_view); +    layout->addWidget(search_field);      setLayout(layout);  } @@ -54,6 +235,18 @@ GameList::~GameList() {      emit ShouldCancelWorker();  } +void GameList::setFilterFocus() { +    search_field->setFocus(); +} + +void GameList::setFilterVisible(bool visablility) { +    search_field->setVisible(visablility); +} + +void GameList::clearFilter() { +    search_field->clear(); +} +  void GameList::AddEntry(const QList<QStandardItem*>& entry_items) {      item_model->invisibleRootItem()->appendRow(entry_items);  } @@ -69,11 +262,16 @@ void GameList::ValidateEntry(const QModelIndex& item) {      std::string std_file_path(file_path.toStdString());      if (!FileUtil::Exists(std_file_path) || FileUtil::IsDirectory(std_file_path))          return; +    // Users usually want to run a diffrent game after closing one +    search_field->clear();      emit GameChosen(file_path);  }  void GameList::DonePopulating() {      tree_view->setEnabled(true); +    int rowCount = tree_view->model()->rowCount(); +    search_field->setFilterResult(rowCount, rowCount); +    search_field->setFocus();  }  void GameList::PopupContextMenu(const QPoint& menu_location) { @@ -151,25 +349,26 @@ static bool HasSupportedFileExtension(const std::string& file_name) {  void GameList::RefreshGameDirectory() {      if (!UISettings::values.gamedir.isEmpty() && current_worker != nullptr) {          LOG_INFO(Frontend, "Change detected in the games directory. Reloading game list."); +        search_field->clear();          PopulateAsync(UISettings::values.gamedir, UISettings::values.gamedir_deepscan);      }  }  /** - * Adds the game list folder to the QFileSystemWatcher to check for updates. - * - * The file watcher will fire off an update to the game list when a change is detected in the game - * list folder. - * - * Notice: This method is run on the UI thread because QFileSystemWatcher is not thread safe and - * this function is fast enough to not stall the UI thread. If performance is an issue, it should - * be moved to another thread and properly locked to prevent concurrency issues. - * - * @param dir folder to check for changes in - * @param recursion 0 if recursion is disabled. Any positive number passed to this will add each - *        directory recursively to the watcher and will update the file list if any of the folders - *        change. The number determines how deep the recursion should traverse. - */ +* Adds the game list folder to the QFileSystemWatcher to check for updates. +* +* The file watcher will fire off an update to the game list when a change is detected in the game +* list folder. +* +* Notice: This method is run on the UI thread because QFileSystemWatcher is not thread safe and +* this function is fast enough to not stall the UI thread. If performance is an issue, it should +* be moved to another thread and properly locked to prevent concurrency issues. +* +* @param dir folder to check for changes in +* @param recursion 0 if recursion is disabled. Any positive number passed to this will add each +*        directory recursively to the watcher and will update the file list if any of the folders +*        change. The number determines how deep the recursion should traverse. +*/  void GameList::UpdateWatcherList(const std::string& dir, unsigned int recursion) {      const auto callback = [this, recursion](unsigned* num_entries_out, const std::string& directory,                                              const std::string& virtual_name) -> bool { diff --git a/src/citra_qt/game_list.h b/src/citra_qt/game_list.h index b141fa3a5..3c06cddc8 100644 --- a/src/citra_qt/game_list.h +++ b/src/citra_qt/game_list.h @@ -5,13 +5,19 @@  #pragma once  #include <QFileSystemWatcher> +#include <QHBoxLayout> +#include <QLabel> +#include <QLineEdit>  #include <QModelIndex>  #include <QSettings>  #include <QStandardItem>  #include <QStandardItemModel>  #include <QString> +#include <QToolButton>  #include <QTreeView> +#include <QVBoxLayout>  #include <QWidget> +#include "main.h"  class GameListWorker; @@ -26,9 +32,40 @@ public:          COLUMN_COUNT, // Number of columns      }; -    explicit GameList(QWidget* parent = nullptr); +    class SearchField : public QWidget { +    public: +        void setFilterResult(int visable, int total); +        void clear(); +        void setFocus(); +        explicit SearchField(GameList* parent = nullptr); + +    private: +        class KeyReleaseEater : public QObject { +        public: +            explicit KeyReleaseEater(GameList* gamelist); + +        private: +            GameList* gamelist = nullptr; +            QString edit_filter_text_old; + +        protected: +            bool eventFilter(QObject* obj, QEvent* event); +        }; +        QHBoxLayout* layout_filter = nullptr; +        QTreeView* tree_view = nullptr; +        QLabel* label_filter = nullptr; +        QLineEdit* edit_filter = nullptr; +        QLabel* label_filter_result = nullptr; +        QToolButton* button_filter_close = nullptr; +    }; + +    explicit GameList(GMainWindow* parent = nullptr);      ~GameList() override; +    void clearFilter(); +    void setFilterFocus(); +    void setFilterVisible(bool visablility); +      void PopulateAsync(const QString& dir_path, bool deep_scan);      void SaveInterfaceLayout(); @@ -41,6 +78,10 @@ signals:      void ShouldCancelWorker();      void OpenSaveFolderRequested(u64 program_id); +private slots: +    void onTextChanged(const QString& newText); +    void onFilterCloseClicked(); +  private:      void AddEntry(const QList<QStandardItem*>& entry_items);      void ValidateEntry(const QModelIndex& item); @@ -49,7 +90,11 @@ private:      void PopupContextMenu(const QPoint& menu_location);      void UpdateWatcherList(const std::string& path, unsigned int recursion);      void RefreshGameDirectory(); +    bool containsAllWords(QString haystack, QString userinput); +    SearchField* search_field; +    GMainWindow* main_window = nullptr; +    QVBoxLayout* layout = nullptr;      QTreeView* tree_view = nullptr;      QStandardItemModel* item_model = nullptr;      GameListWorker* current_worker = nullptr; diff --git a/src/citra_qt/main.cpp b/src/citra_qt/main.cpp index 73b4dd34f..ea66cc425 100644 --- a/src/citra_qt/main.cpp +++ b/src/citra_qt/main.cpp @@ -93,7 +93,7 @@ void GMainWindow::InitializeWidgets() {      render_window = new GRenderWindow(this, emu_thread.get());      render_window->hide(); -    game_list = new GameList(); +    game_list = new GameList(this);      ui.horizontalLayout->addWidget(game_list);      // Create status bar @@ -115,6 +115,7 @@ void GMainWindow::InitializeWidgets() {          statusBar()->addPermanentWidget(label);      }      statusBar()->setVisible(true); +    setStyleSheet("QStatusBar::item{border: none;}");  }  void GMainWindow::InitializeDebugWidgets() { @@ -246,6 +247,9 @@ void GMainWindow::RestoreUIState() {      ui.action_Display_Dock_Widget_Headers->setChecked(UISettings::values.display_titlebar);      OnDisplayTitleBars(ui.action_Display_Dock_Widget_Headers->isChecked()); +    ui.action_Show_Filter_Bar->setChecked(UISettings::values.show_filter_bar); +    game_list->setFilterVisible(ui.action_Show_Filter_Bar->isChecked()); +      ui.action_Show_Status_Bar->setChecked(UISettings::values.show_status_bar);      statusBar()->setVisible(ui.action_Show_Status_Bar->isChecked());  } @@ -282,6 +286,8 @@ void GMainWindow::ConnectMenuEvents() {              &GMainWindow::ToggleWindowMode);      connect(ui.action_Display_Dock_Widget_Headers, &QAction::triggered, this,              &GMainWindow::OnDisplayTitleBars); +    ui.action_Show_Filter_Bar->setShortcut(tr("CTRL+F")); +    connect(ui.action_Show_Filter_Bar, &QAction::triggered, this, &GMainWindow::OnToggleFilterBar);      connect(ui.action_Show_Status_Bar, &QAction::triggered, statusBar(), &QStatusBar::setVisible);  } @@ -443,6 +449,7 @@ void GMainWindow::ShutdownGame() {      ui.action_Stop->setEnabled(false);      render_window->hide();      game_list->show(); +    game_list->setFilterFocus();      // Disable status bar updates      status_bar_update_timer.stop(); @@ -616,6 +623,15 @@ void GMainWindow::OnConfigure() {      }  } +void GMainWindow::OnToggleFilterBar() { +    game_list->setFilterVisible(ui.action_Show_Filter_Bar->isChecked()); +    if (ui.action_Show_Filter_Bar->isChecked()) { +        game_list->setFilterFocus(); +    } else { +        game_list->clearFilter(); +    } +} +  void GMainWindow::OnSwapScreens() {      Settings::values.swap_screen = !Settings::values.swap_screen;      Settings::Apply(); @@ -670,6 +686,7 @@ void GMainWindow::closeEvent(QCloseEvent* event) {  #endif      UISettings::values.single_window_mode = ui.action_Single_Window_Mode->isChecked();      UISettings::values.display_titlebar = ui.action_Display_Dock_Widget_Headers->isChecked(); +    UISettings::values.show_filter_bar = ui.action_Show_Filter_Bar->isChecked();      UISettings::values.show_status_bar = ui.action_Show_Status_Bar->isChecked();      UISettings::values.first_start = false; @@ -719,6 +736,11 @@ bool GMainWindow::ConfirmChangeGame() {      return answer != QMessageBox::No;  } +void GMainWindow::filterBarSetChecked(bool state) { +    ui.action_Show_Filter_Bar->setChecked(state); +    emit(OnToggleFilterBar()); +} +  #ifdef main  #undef main  #endif diff --git a/src/citra_qt/main.h b/src/citra_qt/main.h index ec841eaa5..2f398eb7b 100644 --- a/src/citra_qt/main.h +++ b/src/citra_qt/main.h @@ -7,6 +7,7 @@  #include <memory>  #include <QMainWindow> +#include <QTimer>  #include "ui_main.h"  class CallstackWidget; @@ -41,6 +42,7 @@ class GMainWindow : public QMainWindow {      };  public: +    void filterBarSetChecked(bool state);      GMainWindow();      ~GMainWindow(); @@ -122,6 +124,7 @@ private slots:      void OnMenuRecentFile();      void OnSwapScreens();      void OnConfigure(); +    void OnToggleFilterBar();      void OnDisplayTitleBars(bool);      void ToggleWindowMode();      void OnCreateGraphicsSurfaceViewer(); diff --git a/src/citra_qt/main.ui b/src/citra_qt/main.ui index 47dbb6ef7..f64b878f0 100644 --- a/src/citra_qt/main.ui +++ b/src/citra_qt/main.ui @@ -88,6 +88,7 @@      </widget>      <addaction name="action_Single_Window_Mode"/>      <addaction name="action_Display_Dock_Widget_Headers"/> +    <addaction name="action_Show_Filter_Bar"/>      <addaction name="action_Show_Status_Bar"/>      <addaction name="menu_View_Debugging"/>     </widget> @@ -167,6 +168,14 @@      <string>Display Dock Widget Headers</string>     </property>    </action> +  <action name="action_Show_Filter_Bar"> +   <property name="checkable"> +    <bool>true</bool> +   </property> +   <property name="text"> +    <string>Show Filter Bar</string> +   </property> +  </action>    <action name="action_Show_Status_Bar">     <property name="checkable">      <bool>true</bool> diff --git a/src/citra_qt/ui_settings.h b/src/citra_qt/ui_settings.h index 6408ece2b..bc37f81c5 100644 --- a/src/citra_qt/ui_settings.h +++ b/src/citra_qt/ui_settings.h @@ -27,6 +27,7 @@ struct Values {      bool single_window_mode;      bool display_titlebar; +    bool show_filter_bar;      bool show_status_bar;      bool confirm_before_closing; diff --git a/src/core/hle/service/dsp_dsp.cpp b/src/core/hle/service/dsp_dsp.cpp index fe8a6c2d6..39711ea97 100644 --- a/src/core/hle/service/dsp_dsp.cpp +++ b/src/core/hle/service/dsp_dsp.cpp @@ -303,6 +303,24 @@ static void WriteProcessPipe(Service::Interface* self) {          message[i] = Memory::Read8(buffer + i);      } +    // This behaviour was confirmed by RE. +    // The likely reason for this is that games tend to pass in garbage at these bytes +    // because they read random bytes off the stack. +    switch (pipe) { +    case DSP::HLE::DspPipe::Audio: +        ASSERT(message.size() >= 4); +        message[2] = 0; +        message[3] = 0; +        break; +    case DSP::HLE::DspPipe::Binary: +        ASSERT(message.size() >= 8); +        message[4] = 1; +        message[5] = 0; +        message[6] = 0; +        message[7] = 0; +        break; +    } +      DSP::HLE::PipeWrite(pipe, message);      cmd_buff[0] = IPC::MakeHeader(0xD, 1, 0); diff --git a/src/core/hle/service/ldr_ro/ldr_ro.cpp b/src/core/hle/service/ldr_ro/ldr_ro.cpp index 7af76676b..d1e6d869f 100644 --- a/src/core/hle/service/ldr_ro/ldr_ro.cpp +++ b/src/core/hle/service/ldr_ro/ldr_ro.cpp @@ -40,9 +40,6 @@ static const ResultCode ERROR_INVALID_MEMORY_STATE = // 0xD8A12C08  static const ResultCode ERROR_NOT_LOADED = // 0xD8A12C0D      ResultCode(static_cast<ErrorDescription>(13), ErrorModule::RO, ErrorSummary::InvalidState,                 ErrorLevel::Permanent); -static const ResultCode ERROR_INVALID_DESCRIPTOR = // 0xD9001830 -    ResultCode(ErrorDescription::OS_InvalidBufferDescriptor, ErrorModule::OS, -               ErrorSummary::WrongArgument, ErrorLevel::Permanent);  static MemorySynchronizer memory_synchronizer; @@ -71,66 +68,61 @@ static bool VerifyBufferState(VAddr buffer_ptr, u32 size) {   *      1 : Result of function, 0 on success, otherwise error code   */  static void Initialize(Interface* self) { -    u32* cmd_buff = Kernel::GetCommandBuffer(); -    VAddr crs_buffer_ptr = cmd_buff[1]; -    u32 crs_size = cmd_buff[2]; -    VAddr crs_address = cmd_buff[3]; -    u32 descriptor = cmd_buff[4]; -    u32 process = cmd_buff[5]; - -    LOG_DEBUG(Service_LDR, "called, crs_buffer_ptr=0x%08X, crs_address=0x%08X, crs_size=0x%X, " -                           "descriptor=0x%08X, process=0x%08X", -              crs_buffer_ptr, crs_address, crs_size, descriptor, process); - -    if (descriptor != 0) { -        LOG_ERROR(Service_LDR, "IPC handle descriptor failed validation (0x%X)", descriptor); -        cmd_buff[0] = IPC::MakeHeader(0, 1, 0); -        cmd_buff[1] = ERROR_INVALID_DESCRIPTOR.raw; -        return; -    } +    IPC::RequestParser rp(Kernel::GetCommandBuffer(), 0x01, 3, 2); +    VAddr crs_buffer_ptr = rp.Pop<u32>(); +    u32 crs_size = rp.Pop<u32>(); +    VAddr crs_address = rp.Pop<u32>(); +    // TODO (wwylele): RO service checks the descriptor here and return error 0xD9001830 for +    // incorrect descriptor. This error return should be probably built in IPC::RequestParser. +    // All other service functions below have the same issue. +    Kernel::Handle process = rp.PopHandle(); + +    LOG_DEBUG(Service_LDR, +              "called, crs_buffer_ptr=0x%08X, crs_address=0x%08X, crs_size=0x%X, process=0x%08X", +              crs_buffer_ptr, crs_address, crs_size, process); -    cmd_buff[0] = IPC::MakeHeader(1, 1, 0); +    IPC::RequestBuilder rb = rp.MakeBuilder(1, 0);      if (loaded_crs != 0) {          LOG_ERROR(Service_LDR, "Already initialized"); -        cmd_buff[1] = ERROR_ALREADY_INITIALIZED.raw; +        rb.Push(ERROR_ALREADY_INITIALIZED);          return;      }      if (crs_size < CRO_HEADER_SIZE) {          LOG_ERROR(Service_LDR, "CRS is too small"); -        cmd_buff[1] = ERROR_BUFFER_TOO_SMALL.raw; +        rb.Push(ERROR_BUFFER_TOO_SMALL);          return;      }      if (crs_buffer_ptr & Memory::PAGE_MASK) {          LOG_ERROR(Service_LDR, "CRS original address is not aligned"); -        cmd_buff[1] = ERROR_MISALIGNED_ADDRESS.raw; +        rb.Push(ERROR_MISALIGNED_ADDRESS);          return;      }      if (crs_address & Memory::PAGE_MASK) {          LOG_ERROR(Service_LDR, "CRS mapping address is not aligned"); -        cmd_buff[1] = ERROR_MISALIGNED_ADDRESS.raw; +        rb.Push(ERROR_MISALIGNED_ADDRESS);          return;      }      if (crs_size & Memory::PAGE_MASK) {          LOG_ERROR(Service_LDR, "CRS size is not aligned"); -        cmd_buff[1] = ERROR_MISALIGNED_SIZE.raw; +        rb.Push(ERROR_MISALIGNED_SIZE);          return;      }      if (!VerifyBufferState(crs_buffer_ptr, crs_size)) {          LOG_ERROR(Service_LDR, "CRS original buffer is in invalid state"); -        cmd_buff[1] = ERROR_INVALID_MEMORY_STATE.raw; +        rb.Push(ERROR_INVALID_MEMORY_STATE);          return;      }      if (crs_address < Memory::PROCESS_IMAGE_VADDR ||          crs_address + crs_size > Memory::PROCESS_IMAGE_VADDR_END) {          LOG_ERROR(Service_LDR, "CRS mapping address is not in the process image region"); -        cmd_buff[1] = ERROR_ILLEGAL_ADDRESS.raw; +        rb.Push(ERROR_ILLEGAL_ADDRESS);          return;      } @@ -145,7 +137,7 @@ static void Initialize(Interface* self) {                       .Code();          if (result.IsError()) {              LOG_ERROR(Service_LDR, "Error mapping memory block %08X", result.raw); -            cmd_buff[1] = result.raw; +            rb.Push(result);              return;          } @@ -153,7 +145,7 @@ static void Initialize(Interface* self) {                                                                        Kernel::VMAPermission::Read);          if (result.IsError()) {              LOG_ERROR(Service_LDR, "Error reprotecting memory block %08X", result.raw); -            cmd_buff[1] = result.raw; +            rb.Push(result);              return;          } @@ -172,7 +164,7 @@ static void Initialize(Interface* self) {      result = crs.Rebase(0, crs_size, 0, 0, 0, 0, true);      if (result.IsError()) {          LOG_ERROR(Service_LDR, "Error rebasing CRS 0x%08X", result.raw); -        cmd_buff[1] = result.raw; +        rb.Push(result);          return;      } @@ -180,7 +172,7 @@ static void Initialize(Interface* self) {      loaded_crs = crs_address; -    cmd_buff[1] = RESULT_SUCCESS.raw; +    rb.Push(RESULT_SUCCESS);  }  /** @@ -196,25 +188,17 @@ static void Initialize(Interface* self) {   *      1 : Result of function, 0 on success, otherwise error code   */  static void LoadCRR(Interface* self) { -    u32* cmd_buff = Kernel::GetCommandBuffer(); -    u32 crr_buffer_ptr = cmd_buff[1]; -    u32 crr_size = cmd_buff[2]; -    u32 descriptor = cmd_buff[3]; -    u32 process = cmd_buff[4]; - -    if (descriptor != 0) { -        LOG_ERROR(Service_LDR, "IPC handle descriptor failed validation (0x%X)", descriptor); -        cmd_buff[0] = IPC::MakeHeader(0, 1, 0); -        cmd_buff[1] = ERROR_INVALID_DESCRIPTOR.raw; -        return; -    } +    IPC::RequestParser rp(Kernel::GetCommandBuffer(), 0x02, 2, 2); +    VAddr crr_buffer_ptr = rp.Pop<u32>(); +    u32 crr_size = rp.Pop<u32>(); +    Kernel::Handle process = rp.PopHandle(); -    cmd_buff[0] = IPC::MakeHeader(2, 1, 0); -    cmd_buff[1] = RESULT_SUCCESS.raw; // No error +    IPC::RequestBuilder rb = rp.MakeBuilder(1, 0); +    rb.Push(RESULT_SUCCESS); -    LOG_WARNING(Service_LDR, "(STUBBED) called, crr_buffer_ptr=0x%08X, crr_size=0x%08X, " -                             "descriptor=0x%08X, process=0x%08X", -                crr_buffer_ptr, crr_size, descriptor, process); +    LOG_WARNING(Service_LDR, +                "(STUBBED) called, crr_buffer_ptr=0x%08X, crr_size=0x%08X, process=0x%08X", +                crr_buffer_ptr, crr_size, process);  }  /** @@ -229,24 +213,15 @@ static void LoadCRR(Interface* self) {   *      1 : Result of function, 0 on success, otherwise error code   */  static void UnloadCRR(Interface* self) { -    u32* cmd_buff = Kernel::GetCommandBuffer(); -    u32 crr_buffer_ptr = cmd_buff[1]; -    u32 descriptor = cmd_buff[2]; -    u32 process = cmd_buff[3]; - -    if (descriptor != 0) { -        LOG_ERROR(Service_LDR, "IPC handle descriptor failed validation (0x%X)", descriptor); -        cmd_buff[0] = IPC::MakeHeader(0, 1, 0); -        cmd_buff[1] = ERROR_INVALID_DESCRIPTOR.raw; -        return; -    } +    IPC::RequestParser rp(Kernel::GetCommandBuffer(), 0x03, 1, 2); +    u32 crr_buffer_ptr = rp.Pop<u32>(); +    Kernel::Handle process = rp.PopHandle(); -    cmd_buff[0] = IPC::MakeHeader(3, 1, 0); -    cmd_buff[1] = RESULT_SUCCESS.raw; // No error +    IPC::RequestBuilder rb = rp.MakeBuilder(1, 0); +    rb.Push(RESULT_SUCCESS); -    LOG_WARNING(Service_LDR, -                "(STUBBED) called, crr_buffer_ptr=0x%08X, descriptor=0x%08X, process=0x%08X", -                crr_buffer_ptr, descriptor, process); +    LOG_WARNING(Service_LDR, "(STUBBED) called, crr_buffer_ptr=0x%08X, process=0x%08X", +                crr_buffer_ptr, process);  }  /** @@ -276,87 +251,85 @@ static void UnloadCRR(Interface* self) {   *      There is a dispatcher template below.   */  static void LoadCRO(Interface* self, bool link_on_load_bug_fix) { -    u32* cmd_buff = Kernel::GetCommandBuffer(); -    VAddr cro_buffer_ptr = cmd_buff[1]; -    VAddr cro_address = cmd_buff[2]; -    u32 cro_size = cmd_buff[3]; -    VAddr data_segment_address = cmd_buff[4]; -    u32 zero = cmd_buff[5]; -    u32 data_segment_size = cmd_buff[6]; -    u32 bss_segment_address = cmd_buff[7]; -    u32 bss_segment_size = cmd_buff[8]; -    bool auto_link = (cmd_buff[9] & 0xFF) != 0; -    u32 fix_level = cmd_buff[10]; -    VAddr crr_address = cmd_buff[11]; -    u32 descriptor = cmd_buff[12]; -    u32 process = cmd_buff[13]; - -    LOG_DEBUG(Service_LDR, -              "called (%s), cro_buffer_ptr=0x%08X, cro_address=0x%08X, cro_size=0x%X, " -              "data_segment_address=0x%08X, zero=%d, data_segment_size=0x%X, " -              "bss_segment_address=0x%08X, bss_segment_size=0x%X, " -              "auto_link=%s, fix_level=%d, crr_address=0x%08X, descriptor=0x%08X, process=0x%08X", +    IPC::RequestParser rp(Kernel::GetCommandBuffer(), link_on_load_bug_fix ? 0x09 : 0x04, 11, 2); +    VAddr cro_buffer_ptr = rp.Pop<u32>(); +    VAddr cro_address = rp.Pop<u32>(); +    u32 cro_size = rp.Pop<u32>(); +    VAddr data_segment_address = rp.Pop<u32>(); +    u32 zero = rp.Pop<u32>(); +    u32 data_segment_size = rp.Pop<u32>(); +    u32 bss_segment_address = rp.Pop<u32>(); +    u32 bss_segment_size = rp.Pop<u32>(); +    bool auto_link = rp.Pop<bool>(); +    u32 fix_level = rp.Pop<u32>(); +    VAddr crr_address = rp.Pop<u32>(); +    Kernel::Handle process = rp.PopHandle(); + +    LOG_DEBUG(Service_LDR, "called (%s), cro_buffer_ptr=0x%08X, cro_address=0x%08X, cro_size=0x%X, " +                           "data_segment_address=0x%08X, zero=%d, data_segment_size=0x%X, " +                           "bss_segment_address=0x%08X, bss_segment_size=0x%X, auto_link=%s, " +                           "fix_level=%d, crr_address=0x%08X, process=0x%08X",                link_on_load_bug_fix ? "new" : "old", cro_buffer_ptr, cro_address, cro_size,                data_segment_address, zero, data_segment_size, bss_segment_address, bss_segment_size, -              auto_link ? "true" : "false", fix_level, crr_address, descriptor, process); - -    if (descriptor != 0) { -        LOG_ERROR(Service_LDR, "IPC handle descriptor failed validation (0x%X)", descriptor); -        cmd_buff[0] = IPC::MakeHeader(0, 1, 0); -        cmd_buff[1] = ERROR_INVALID_DESCRIPTOR.raw; -        return; -    } +              auto_link ? "true" : "false", fix_level, crr_address, process); -    cmd_buff[0] = IPC::MakeHeader(link_on_load_bug_fix ? 9 : 4, 2, 0); +    IPC::RequestBuilder rb = rp.MakeBuilder(2, 0);      if (loaded_crs == 0) {          LOG_ERROR(Service_LDR, "Not initialized"); -        cmd_buff[1] = ERROR_NOT_INITIALIZED.raw; +        rb.Push(ERROR_NOT_INITIALIZED); +        rb.Push<u32>(0);          return;      }      if (cro_size < CRO_HEADER_SIZE) {          LOG_ERROR(Service_LDR, "CRO too small"); -        cmd_buff[1] = ERROR_BUFFER_TOO_SMALL.raw; +        rb.Push(ERROR_BUFFER_TOO_SMALL); +        rb.Push<u32>(0);          return;      }      if (cro_buffer_ptr & Memory::PAGE_MASK) {          LOG_ERROR(Service_LDR, "CRO original address is not aligned"); -        cmd_buff[1] = ERROR_MISALIGNED_ADDRESS.raw; +        rb.Push(ERROR_MISALIGNED_ADDRESS); +        rb.Push<u32>(0);          return;      }      if (cro_address & Memory::PAGE_MASK) {          LOG_ERROR(Service_LDR, "CRO mapping address is not aligned"); -        cmd_buff[1] = ERROR_MISALIGNED_ADDRESS.raw; +        rb.Push(ERROR_MISALIGNED_ADDRESS); +        rb.Push<u32>(0);          return;      }      if (cro_size & Memory::PAGE_MASK) {          LOG_ERROR(Service_LDR, "CRO size is not aligned"); -        cmd_buff[1] = ERROR_MISALIGNED_SIZE.raw; +        rb.Push(ERROR_MISALIGNED_SIZE); +        rb.Push<u32>(0);          return;      }      if (!VerifyBufferState(cro_buffer_ptr, cro_size)) {          LOG_ERROR(Service_LDR, "CRO original buffer is in invalid state"); -        cmd_buff[1] = ERROR_INVALID_MEMORY_STATE.raw; +        rb.Push(ERROR_INVALID_MEMORY_STATE); +        rb.Push<u32>(0);          return;      }      if (cro_address < Memory::PROCESS_IMAGE_VADDR ||          cro_address + cro_size > Memory::PROCESS_IMAGE_VADDR_END) {          LOG_ERROR(Service_LDR, "CRO mapping address is not in the process image region"); -        cmd_buff[1] = ERROR_ILLEGAL_ADDRESS.raw; +        rb.Push(ERROR_ILLEGAL_ADDRESS); +        rb.Push<u32>(0);          return;      }      if (zero) {          LOG_ERROR(Service_LDR, "Zero is not zero %d", zero); -        cmd_buff[1] = ResultCode(static_cast<ErrorDescription>(29), ErrorModule::RO, -                                 ErrorSummary::Internal, ErrorLevel::Usage) -                          .raw; +        rb.Push(ResultCode(static_cast<ErrorDescription>(29), ErrorModule::RO, +                           ErrorSummary::Internal, ErrorLevel::Usage)); +        rb.Push<u32>(0);          return;      } @@ -371,7 +344,8 @@ static void LoadCRO(Interface* self, bool link_on_load_bug_fix) {                       .Code();          if (result.IsError()) {              LOG_ERROR(Service_LDR, "Error mapping memory block %08X", result.raw); -            cmd_buff[1] = result.raw; +            rb.Push(result); +            rb.Push<u32>(0);              return;          } @@ -380,7 +354,8 @@ static void LoadCRO(Interface* self, bool link_on_load_bug_fix) {          if (result.IsError()) {              LOG_ERROR(Service_LDR, "Error reprotecting memory block %08X", result.raw);              Kernel::g_current_process->vm_manager.UnmapRange(cro_address, cro_size); -            cmd_buff[1] = result.raw; +            rb.Push(result); +            rb.Push<u32>(0);              return;          } @@ -400,7 +375,8 @@ static void LoadCRO(Interface* self, bool link_on_load_bug_fix) {      if (result.IsError()) {          LOG_ERROR(Service_LDR, "Error verifying CRO in CRR %08X", result.raw);          Kernel::g_current_process->vm_manager.UnmapRange(cro_address, cro_size); -        cmd_buff[1] = result.raw; +        rb.Push(result); +        rb.Push<u32>(0);          return;      } @@ -409,7 +385,8 @@ static void LoadCRO(Interface* self, bool link_on_load_bug_fix) {      if (result.IsError()) {          LOG_ERROR(Service_LDR, "Error rebasing CRO %08X", result.raw);          Kernel::g_current_process->vm_manager.UnmapRange(cro_address, cro_size); -        cmd_buff[1] = result.raw; +        rb.Push(result); +        rb.Push<u32>(0);          return;      } @@ -417,7 +394,8 @@ static void LoadCRO(Interface* self, bool link_on_load_bug_fix) {      if (result.IsError()) {          LOG_ERROR(Service_LDR, "Error linking CRO %08X", result.raw);          Kernel::g_current_process->vm_manager.UnmapRange(cro_address, cro_size); -        cmd_buff[1] = result.raw; +        rb.Push(result); +        rb.Push<u32>(0);          return;      } @@ -435,7 +413,8 @@ static void LoadCRO(Interface* self, bool link_on_load_bug_fix) {              if (result.IsError()) {                  LOG_ERROR(Service_LDR, "Error unmapping memory block %08X", result.raw);                  Kernel::g_current_process->vm_manager.UnmapRange(cro_address, cro_size); -                cmd_buff[1] = result.raw; +                rb.Push(result); +                rb.Push<u32>(0);                  return;              }          } @@ -453,7 +432,8 @@ static void LoadCRO(Interface* self, bool link_on_load_bug_fix) {          if (result.IsError()) {              LOG_ERROR(Service_LDR, "Error reprotecting memory block %08X", result.raw);              Kernel::g_current_process->vm_manager.UnmapRange(cro_address, fix_size); -            cmd_buff[1] = result.raw; +            rb.Push(result); +            rb.Push<u32>(0);              return;          }      } @@ -463,8 +443,7 @@ static void LoadCRO(Interface* self, bool link_on_load_bug_fix) {      LOG_INFO(Service_LDR, "CRO \"%s\" loaded at 0x%08X, fixed_end=0x%08X", cro.ModuleName().data(),               cro_address, cro_address + fix_size); -    cmd_buff[1] = RESULT_SUCCESS.raw; -    cmd_buff[2] = fix_size; +    rb.Push(RESULT_SUCCESS, fix_size);  }  template <bool link_on_load_bug_fix> @@ -486,43 +465,35 @@ static void LoadCRO(Interface* self) {   *      1 : Result of function, 0 on success, otherwise error code   */  static void UnloadCRO(Interface* self) { -    u32* cmd_buff = Kernel::GetCommandBuffer(); -    VAddr cro_address = cmd_buff[1]; -    u32 zero = cmd_buff[2]; -    VAddr cro_buffer_ptr = cmd_buff[3]; -    u32 descriptor = cmd_buff[4]; -    u32 process = cmd_buff[5]; - -    LOG_DEBUG(Service_LDR, "called, cro_address=0x%08X, zero=%d, cro_buffer_ptr=0x%08X, " -                           "descriptor=0x%08X, process=0x%08X", -              cro_address, zero, cro_buffer_ptr, descriptor, process); - -    if (descriptor != 0) { -        LOG_ERROR(Service_LDR, "IPC handle descriptor failed validation (0x%X)", descriptor); -        cmd_buff[0] = IPC::MakeHeader(0, 1, 0); -        cmd_buff[1] = ERROR_INVALID_DESCRIPTOR.raw; -        return; -    } +    IPC::RequestParser rp(Kernel::GetCommandBuffer(), 0x05, 3, 2); +    VAddr cro_address = rp.Pop<u32>(); +    u32 zero = rp.Pop<u32>(); +    VAddr cro_buffer_ptr = rp.Pop<u32>(); +    Kernel::Handle process = rp.PopHandle(); + +    LOG_DEBUG(Service_LDR, +              "called, cro_address=0x%08X, zero=%d, cro_buffer_ptr=0x%08X, process=0x%08X", +              cro_address, zero, cro_buffer_ptr, process);      CROHelper cro(cro_address); -    cmd_buff[0] = IPC::MakeHeader(5, 1, 0); +    IPC::RequestBuilder rb = rp.MakeBuilder(1, 0);      if (loaded_crs == 0) {          LOG_ERROR(Service_LDR, "Not initialized"); -        cmd_buff[1] = ERROR_NOT_INITIALIZED.raw; +        rb.Push(ERROR_NOT_INITIALIZED);          return;      }      if (cro_address & Memory::PAGE_MASK) {          LOG_ERROR(Service_LDR, "CRO address is not aligned"); -        cmd_buff[1] = ERROR_MISALIGNED_ADDRESS.raw; +        rb.Push(ERROR_MISALIGNED_ADDRESS);          return;      }      if (!cro.IsLoaded()) {          LOG_ERROR(Service_LDR, "Invalid or not loaded CRO"); -        cmd_buff[1] = ERROR_NOT_LOADED.raw; +        rb.Push(ERROR_NOT_LOADED);          return;      } @@ -535,7 +506,7 @@ static void UnloadCRO(Interface* self) {      ResultCode result = cro.Unlink(loaded_crs);      if (result.IsError()) {          LOG_ERROR(Service_LDR, "Error unlinking CRO %08X", result.raw); -        cmd_buff[1] = result.raw; +        rb.Push(result);          return;      } @@ -545,7 +516,7 @@ static void UnloadCRO(Interface* self) {          result = cro.ClearRelocations();          if (result.IsError()) {              LOG_ERROR(Service_LDR, "Error clearing relocations %08X", result.raw); -            cmd_buff[1] = result.raw; +            rb.Push(result);              return;          }      } @@ -565,7 +536,7 @@ static void UnloadCRO(Interface* self) {      Core::CPU().ClearInstructionCache(); -    cmd_buff[1] = result.raw; +    rb.Push(result);  }  /** @@ -580,40 +551,31 @@ static void UnloadCRO(Interface* self) {   *      1 : Result of function, 0 on success, otherwise error code   */  static void LinkCRO(Interface* self) { -    u32* cmd_buff = Kernel::GetCommandBuffer(); -    VAddr cro_address = cmd_buff[1]; -    u32 descriptor = cmd_buff[2]; -    u32 process = cmd_buff[3]; - -    LOG_DEBUG(Service_LDR, "called, cro_address=0x%08X, descriptor=0x%08X, process=0x%08X", -              cro_address, descriptor, process); - -    if (descriptor != 0) { -        LOG_ERROR(Service_LDR, "IPC handle descriptor failed validation (0x%X)", descriptor); -        cmd_buff[0] = IPC::MakeHeader(0, 1, 0); -        cmd_buff[1] = ERROR_INVALID_DESCRIPTOR.raw; -        return; -    } +    IPC::RequestParser rp(Kernel::GetCommandBuffer(), 0x06, 1, 2); +    VAddr cro_address = rp.Pop<u32>(); +    Kernel::Handle process = rp.PopHandle(); + +    LOG_DEBUG(Service_LDR, "called, cro_address=0x%08X, process=0x%08X", cro_address, process);      CROHelper cro(cro_address); -    cmd_buff[0] = IPC::MakeHeader(6, 1, 0); +    IPC::RequestBuilder rb = rp.MakeBuilder(1, 0);      if (loaded_crs == 0) {          LOG_ERROR(Service_LDR, "Not initialized"); -        cmd_buff[1] = ERROR_NOT_INITIALIZED.raw; +        rb.Push(ERROR_NOT_INITIALIZED);          return;      }      if (cro_address & Memory::PAGE_MASK) {          LOG_ERROR(Service_LDR, "CRO address is not aligned"); -        cmd_buff[1] = ERROR_MISALIGNED_ADDRESS.raw; +        rb.Push(ERROR_MISALIGNED_ADDRESS);          return;      }      if (!cro.IsLoaded()) {          LOG_ERROR(Service_LDR, "Invalid or not loaded CRO"); -        cmd_buff[1] = ERROR_NOT_LOADED.raw; +        rb.Push(ERROR_NOT_LOADED);          return;      } @@ -627,7 +589,7 @@ static void LinkCRO(Interface* self) {      memory_synchronizer.SynchronizeOriginalMemory();      Core::CPU().ClearInstructionCache(); -    cmd_buff[1] = result.raw; +    rb.Push(result);  }  /** @@ -642,40 +604,31 @@ static void LinkCRO(Interface* self) {   *      1 : Result of function, 0 on success, otherwise error code   */  static void UnlinkCRO(Interface* self) { -    u32* cmd_buff = Kernel::GetCommandBuffer(); -    VAddr cro_address = cmd_buff[1]; -    u32 descriptor = cmd_buff[2]; -    u32 process = cmd_buff[3]; - -    LOG_DEBUG(Service_LDR, "called, cro_address=0x%08X, descriptor=0x%08X, process=0x%08X", -              cro_address, descriptor, process); - -    if (descriptor != 0) { -        LOG_ERROR(Service_LDR, "IPC handle descriptor failed validation (0x%X)", descriptor); -        cmd_buff[0] = IPC::MakeHeader(0, 1, 0); -        cmd_buff[1] = ERROR_INVALID_DESCRIPTOR.raw; -        return; -    } +    IPC::RequestParser rp(Kernel::GetCommandBuffer(), 0x07, 1, 2); +    VAddr cro_address = rp.Pop<u32>(); +    Kernel::Handle process = rp.PopHandle(); + +    LOG_DEBUG(Service_LDR, "called, cro_address=0x%08X, process=0x%08X", cro_address, process);      CROHelper cro(cro_address); -    cmd_buff[0] = IPC::MakeHeader(7, 1, 0); +    IPC::RequestBuilder rb = rp.MakeBuilder(1, 0);      if (loaded_crs == 0) {          LOG_ERROR(Service_LDR, "Not initialized"); -        cmd_buff[1] = ERROR_NOT_INITIALIZED.raw; +        rb.Push(ERROR_NOT_INITIALIZED);          return;      }      if (cro_address & Memory::PAGE_MASK) {          LOG_ERROR(Service_LDR, "CRO address is not aligned"); -        cmd_buff[1] = ERROR_MISALIGNED_ADDRESS.raw; +        rb.Push(ERROR_MISALIGNED_ADDRESS);          return;      }      if (!cro.IsLoaded()) {          LOG_ERROR(Service_LDR, "Invalid or not loaded CRO"); -        cmd_buff[1] = ERROR_NOT_LOADED.raw; +        rb.Push(ERROR_NOT_LOADED);          return;      } @@ -689,7 +642,7 @@ static void UnlinkCRO(Interface* self) {      memory_synchronizer.SynchronizeOriginalMemory();      Core::CPU().ClearInstructionCache(); -    cmd_buff[1] = result.raw; +    rb.Push(result);  }  /** @@ -704,29 +657,21 @@ static void UnlinkCRO(Interface* self) {   *      1 : Result of function, 0 on success, otherwise error code   */  static void Shutdown(Interface* self) { -    u32* cmd_buff = Kernel::GetCommandBuffer(); -    VAddr crs_buffer_ptr = cmd_buff[1]; -    u32 descriptor = cmd_buff[2]; -    u32 process = cmd_buff[3]; - -    LOG_DEBUG(Service_LDR, "called, crs_buffer_ptr=0x%08X, descriptor=0x%08X, process=0x%08X", -              crs_buffer_ptr, descriptor, process); - -    if (descriptor != 0) { -        LOG_ERROR(Service_LDR, "IPC handle descriptor failed validation (0x%X)", descriptor); -        cmd_buff[0] = IPC::MakeHeader(0, 1, 0); -        cmd_buff[1] = ERROR_INVALID_DESCRIPTOR.raw; -        return; -    } +    IPC::RequestParser rp(Kernel::GetCommandBuffer(), 0x08, 1, 2); +    VAddr crs_buffer_ptr = rp.Pop<u32>(); +    Kernel::Handle process = rp.PopHandle(); + +    LOG_DEBUG(Service_LDR, "called, crs_buffer_ptr=0x%08X, process=0x%08X", crs_buffer_ptr, +              process); + +    IPC::RequestBuilder rb = rp.MakeBuilder(1, 0);      if (loaded_crs == 0) {          LOG_ERROR(Service_LDR, "Not initialized"); -        cmd_buff[1] = ERROR_NOT_INITIALIZED.raw; +        rb.Push(ERROR_NOT_INITIALIZED);          return;      } -    cmd_buff[0] = IPC::MakeHeader(8, 1, 0); -      CROHelper crs(loaded_crs);      crs.Unrebase(true); @@ -744,7 +689,7 @@ static void Shutdown(Interface* self) {      }      loaded_crs = 0; -    cmd_buff[1] = result.raw; +    rb.Push(result);  }  const Interface::FunctionInfo FunctionTable[] = { diff --git a/src/core/hle/service/nwm/nwm_uds.cpp b/src/core/hle/service/nwm/nwm_uds.cpp index 08fade320..ef6c5ebe3 100644 --- a/src/core/hle/service/nwm/nwm_uds.cpp +++ b/src/core/hle/service/nwm/nwm_uds.cpp @@ -1,16 +1,49 @@ -// Copyright 2014 Citra Emulator Project +// Copyright 2017 Citra Emulator Project  // Licensed under GPLv2 or any later version  // Refer to the license.txt file included. +#include <cstring> +#include <unordered_map> +#include <vector>  #include "common/common_types.h"  #include "common/logging/log.h" +#include "core/core_timing.h"  #include "core/hle/kernel/event.h" +#include "core/hle/kernel/shared_memory.h" +#include "core/hle/result.h"  #include "core/hle/service/nwm/nwm_uds.h" +#include "core/memory.h"  namespace Service {  namespace NWM { -static Kernel::SharedPtr<Kernel::Event> uds_handle_event; +// Event that is signaled every time the connection status changes. +static Kernel::SharedPtr<Kernel::Event> connection_status_event; + +// Shared memory provided by the application to store the receive buffer. +// This is not currently used. +static Kernel::SharedPtr<Kernel::SharedMemory> recv_buffer_memory; + +// Connection status of this 3DS. +static ConnectionStatus connection_status{}; + +// Node information about the current 3DS. +// TODO(Subv): Keep an array of all nodes connected to the network, +// that data has to be retransmitted in every beacon frame. +static NodeInfo node_info; + +// Mapping of bind node ids to their respective events. +static std::unordered_map<u32, Kernel::SharedPtr<Kernel::Event>> bind_node_events; + +// The WiFi network channel that the network is currently on. +// Since we're not actually interacting with physical radio waves, this is just a dummy value. +static u8 network_channel = DefaultNetworkChannel; + +// Information about the network that we're currently connected to. +static NetworkInfo network_info; + +// Event that will generate and send the 802.11 beacon frames. +static int beacon_broadcast_event;  /**   * NWM_UDS::Shutdown service function @@ -32,14 +65,14 @@ static void Shutdown(Interface* self) {  /**   * NWM_UDS::RecvBeaconBroadcastData service function + * Returns the raw beacon data for nearby networks that match the supplied WlanCommId.   *  Inputs:   *      1 : Output buffer max size - *      2 : Unknown - *      3 : Unknown - *      4 : MAC address? - *   6-14 : Unknown, usually zero / uninitialized? - *     15 : WLan Comm ID - *     16 : This is the ID also located at offset 0xE in the CTR-generation structure. + *    2-3 : Unknown + *    4-5 : Host MAC address. + *   6-14 : Unused + *     15 : WLan Comm Id + *     16 : Id   *     17 : Value 0   *     18 : Input handle   *     19 : (Size<<4) | 12 @@ -77,42 +110,274 @@ static void RecvBeaconBroadcastData(Interface* self) {  /**   * NWM_UDS::Initialize service function   *  Inputs: - *      1 : Unknown - *   2-11 : Input Structure - *     12 : Unknown u16 + *      1 : Shared memory size + *   2-11 : Input NodeInfo Structure + *     12 : 2-byte Version   *     13 : Value 0 - *     14 : Handle + *     14 : Shared memory handle   *  Outputs:   *      0 : Return header   *      1 : Result of function, 0 on success, otherwise error code   *      2 : Value 0 - *      3 : Output handle + *      3 : Output event handle   */  static void InitializeWithVersion(Interface* self) { -    u32* cmd_buff = Kernel::GetCommandBuffer(); -    u32 unk1 = cmd_buff[1]; -    u32 unk2 = cmd_buff[12]; -    u32 value = cmd_buff[13]; -    u32 handle = cmd_buff[14]; - -    // Because NWM service is not implemented at all, we stub the Initialize function with an error -    // code instead of success to prevent games from using the service and from causing more issues. -    // The error code is from a real 3DS with wifi off, thus believed to be "network disabled". -    /* -    cmd_buff[1] = RESULT_SUCCESS.raw; -    cmd_buff[2] = 0; -    cmd_buff[3] = Kernel::g_handle_table.Create(uds_handle_event) -                      .MoveFrom(); // TODO(purpasmart): Verify if this is a event handle -    */ -    cmd_buff[0] = IPC::MakeHeader(0x1B, 1, 2); -    cmd_buff[1] = ResultCode(static_cast<ErrorDescription>(2), ErrorModule::UDS, -                             ErrorSummary::StatusChanged, ErrorLevel::Status) -                      .raw; -    cmd_buff[2] = 0; -    cmd_buff[3] = 0; - -    LOG_WARNING(Service_NWM, "(STUBBED) called unk1=0x%08X, unk2=0x%08X, value=%u, handle=0x%08X", -                unk1, unk2, value, handle); +    IPC::RequestParser rp(Kernel::GetCommandBuffer(), 0x1B, 12, 2); + +    u32 sharedmem_size = rp.Pop<u32>(); + +    // Update the node information with the data the game gave us. +    rp.PopRaw(node_info); + +    u16 version; +    rp.PopRaw(version); +    Kernel::Handle sharedmem_handle = rp.PopHandle(); + +    recv_buffer_memory = Kernel::g_handle_table.Get<Kernel::SharedMemory>(sharedmem_handle); + +    ASSERT_MSG(recv_buffer_memory->size == sharedmem_size, "Invalid shared memory size."); + +    // Reset the connection status, it contains all zeros after initialization, +    // except for the actual status value. +    connection_status = {}; +    connection_status.status = static_cast<u32>(NetworkStatus::NotConnected); + +    IPC::RequestBuilder rb = rp.MakeBuilder(1, 2); +    rb.Push(RESULT_SUCCESS); +    rb.PushCopyHandles(Kernel::g_handle_table.Create(connection_status_event).MoveFrom()); + +    LOG_DEBUG(Service_NWM, "called sharedmem_size=0x%08X, version=0x%08X, sharedmem_handle=0x%08X", +              sharedmem_size, version, sharedmem_handle); +} + +/** + * NWM_UDS::GetConnectionStatus service function. + * Returns the connection status structure for the currently open network connection. + * This structure contains information about the connection, + * like the number of connected nodes, etc. + *  Inputs: + *      0 : Command header. + *  Outputs: + *      0 : Return header + *      1 : Result of function, 0 on success, otherwise error code + *      2-13 : Channel of the current WiFi network connection. + */ +static void GetConnectionStatus(Interface* self) { +    IPC::RequestParser rp(Kernel::GetCommandBuffer(), 0xB, 0, 0); +    IPC::RequestBuilder rb = rp.MakeBuilder(13, 0); + +    rb.Push(RESULT_SUCCESS); +    rb.PushRaw(connection_status); + +    LOG_DEBUG(Service_NWM, "called"); +} + +/** + * NWM_UDS::Bind service function. + * Binds a BindNodeId to a data channel and retrieves a data event. + *  Inputs: + *      1 : BindNodeId + *      2 : Receive buffer size. + *      3 : u8 Data channel to bind to. + *      4 : Network node id. + *  Outputs: + *      0 : Return header + *      1 : Result of function, 0 on success, otherwise error code + *      2 : Copy handle descriptor. + *      3 : Data available event handle. + */ +static void Bind(Interface* self) { +    IPC::RequestParser rp(Kernel::GetCommandBuffer(), 0x12, 4, 0); + +    u32 bind_node_id = rp.Pop<u32>(); +    u32 recv_buffer_size = rp.Pop<u32>(); +    u8 data_channel; +    rp.PopRaw(data_channel); +    u16 network_node_id; +    rp.PopRaw(network_node_id); + +    // TODO(Subv): Store the data channel and verify it when receiving data frames. + +    LOG_DEBUG(Service_NWM, "called"); + +    if (data_channel == 0) { +        IPC::RequestBuilder rb = rp.MakeBuilder(1, 0); +        rb.Push(ResultCode(ErrorDescription::NotAuthorized, ErrorModule::UDS, +                           ErrorSummary::WrongArgument, ErrorLevel::Usage)); +        return; +    } + +    // Create a new event for this bind node. +    // TODO(Subv): Signal this event when new data is received on this data channel. +    auto event = Kernel::Event::Create(Kernel::ResetType::OneShot, +                                       "NWM::BindNodeEvent" + std::to_string(bind_node_id)); +    bind_node_events[bind_node_id] = event; + +    IPC::RequestBuilder rb = rp.MakeBuilder(1, 2); + +    rb.Push(RESULT_SUCCESS); +    rb.PushCopyHandles(Kernel::g_handle_table.Create(event).MoveFrom()); +} + +/** + * NWM_UDS::BeginHostingNetwork service function. + * Creates a network and starts broadcasting its presence. + *  Inputs: + *      1 : Passphrase buffer size. + *      3 : VAddr of the NetworkInfo structure. + *      5 : VAddr of the passphrase. + *  Outputs: + *      0 : Return header + *      1 : Result of function, 0 on success, otherwise error code + */ +static void BeginHostingNetwork(Interface* self) { +    IPC::RequestParser rp(Kernel::GetCommandBuffer(), 0x1D, 1, 4); + +    const u32 passphrase_size = rp.Pop<u32>(); + +    size_t desc_size; +    const VAddr network_info_address = rp.PopStaticBuffer(&desc_size, false); +    ASSERT(desc_size == sizeof(NetworkInfo)); +    const VAddr passphrase_address = rp.PopStaticBuffer(&desc_size, false); +    ASSERT(desc_size == passphrase_size); + +    // TODO(Subv): Store the passphrase and verify it when attempting a connection. + +    LOG_DEBUG(Service_NWM, "called"); + +    Memory::ReadBlock(network_info_address, &network_info, sizeof(NetworkInfo)); + +    // The real UDS module throws a fatal error if this assert fails. +    ASSERT_MSG(network_info.max_nodes > 1, "Trying to host a network of only one member."); + +    connection_status.status = static_cast<u32>(NetworkStatus::ConnectedAsHost); +    connection_status.max_nodes = network_info.max_nodes; + +    // There's currently only one node in the network (the host). +    connection_status.total_nodes = 1; +    // The host is always the first node +    connection_status.network_node_id = 1; +    node_info.network_node_id = 1; +    // Set the bit 0 in the nodes bitmask to indicate that node 1 is already taken. +    connection_status.node_bitmask |= 1; + +    // If the game has a preferred channel, use that instead. +    if (network_info.channel != 0) +        network_channel = network_info.channel; + +    connection_status_event->Signal(); + +    // Start broadcasting the network, send a beacon frame every 102.4ms. +    CoreTiming::ScheduleEvent(msToCycles(DefaultBeaconInterval * MillisecondsPerTU), +                              beacon_broadcast_event, 0); + +    LOG_WARNING(Service_NWM, +                "An UDS network has been created, but broadcasting it is unimplemented."); + +    IPC::RequestBuilder rb = rp.MakeBuilder(1, 0); +    rb.Push(RESULT_SUCCESS); +} + +/** + * NWM_UDS::DestroyNetwork service function. + * Closes the network that we're currently hosting. + *  Inputs: + *      0 : Command header. + *  Outputs: + *      0 : Return header + *      1 : Result of function, 0 on success, otherwise error code + */ +static void DestroyNetwork(Interface* self) { +    IPC::RequestParser rp(Kernel::GetCommandBuffer(), 0x08, 0, 0); + +    // TODO(Subv): Find out what happens if this is called while +    // no network is being hosted. + +    // Unschedule the beacon broadcast event. +    CoreTiming::UnscheduleEvent(beacon_broadcast_event, 0); + +    connection_status.status = static_cast<u8>(NetworkStatus::NotConnected); +    connection_status_event->Signal(); + +    IPC::RequestBuilder rb = rp.MakeBuilder(1, 0); + +    rb.Push(RESULT_SUCCESS); + +    LOG_WARNING(Service_NWM, "called"); +} + +/** + * NWM_UDS::GetChannel service function. + * Returns the WiFi channel in which the network we're connected to is transmitting. + *  Inputs: + *      0 : Command header. + *  Outputs: + *      0 : Return header + *      1 : Result of function, 0 on success, otherwise error code + *      2 : Channel of the current WiFi network connection. + */ +static void GetChannel(Interface* self) { +    IPC::RequestParser rp(Kernel::GetCommandBuffer(), 0x1A, 0, 0); +    IPC::RequestBuilder rb = rp.MakeBuilder(2, 0); + +    bool is_connected = connection_status.status != static_cast<u32>(NetworkStatus::NotConnected); + +    u8 channel = is_connected ? network_channel : 0; + +    rb.Push(RESULT_SUCCESS); +    rb.PushRaw(channel); + +    LOG_DEBUG(Service_NWM, "called"); +} + +/** + * NWM_UDS::SetApplicationData service function. + * Updates the application data that is being broadcast in the beacon frames + * for the network that we're hosting. + *  Inputs: + *      1 : Data size. + *      3 : VAddr of the data. + *  Outputs: + *      0 : Return header + *      1 : Result of function, 0 on success, otherwise error code + *      2 : Channel of the current WiFi network connection. + */ +static void SetApplicationData(Interface* self) { +    IPC::RequestParser rp(Kernel::GetCommandBuffer(), 0x1A, 1, 2); + +    u32 size = rp.Pop<u32>(); + +    size_t desc_size; +    const VAddr address = rp.PopStaticBuffer(&desc_size, false); +    ASSERT(desc_size == size); + +    LOG_DEBUG(Service_NWM, "called"); + +    IPC::RequestBuilder rb = rp.MakeBuilder(1, 0); + +    if (size > ApplicationDataSize) { +        rb.Push(ResultCode(ErrorDescription::TooLarge, ErrorModule::UDS, +                           ErrorSummary::WrongArgument, ErrorLevel::Usage)); +        return; +    } + +    network_info.application_data_size = size; +    Memory::ReadBlock(address, network_info.application_data.data(), size); + +    rb.Push(RESULT_SUCCESS); +} + +// Sends a 802.11 beacon frame with information about the current network. +static void BeaconBroadcastCallback(u64 userdata, int cycles_late) { +    // Don't do anything if we're not actually hosting a network +    if (connection_status.status != static_cast<u32>(NetworkStatus::ConnectedAsHost)) +        return; + +    // TODO(Subv): Actually generate the beacon and send it. + +    // Start broadcasting the network, send a beacon frame every 102.4ms. +    CoreTiming::ScheduleEvent(msToCycles(DefaultBeaconInterval * MillisecondsPerTU) - cycles_late, +                              beacon_broadcast_event, 0);  }  const Interface::FunctionInfo FunctionTable[] = { @@ -123,23 +388,23 @@ const Interface::FunctionInfo FunctionTable[] = {      {0x00050040, nullptr, "EjectClient"},      {0x00060000, nullptr, "EjectSpectator"},      {0x00070080, nullptr, "UpdateNetworkAttribute"}, -    {0x00080000, nullptr, "DestroyNetwork"}, +    {0x00080000, DestroyNetwork, "DestroyNetwork"},      {0x00090442, nullptr, "ConnectNetwork (deprecated)"},      {0x000A0000, nullptr, "DisconnectNetwork"}, -    {0x000B0000, nullptr, "GetConnectionStatus"}, +    {0x000B0000, GetConnectionStatus, "GetConnectionStatus"},      {0x000D0040, nullptr, "GetNodeInformation"},      {0x000E0006, nullptr, "DecryptBeaconData (deprecated)"},      {0x000F0404, RecvBeaconBroadcastData, "RecvBeaconBroadcastData"}, -    {0x00100042, nullptr, "SetApplicationData"}, +    {0x00100042, SetApplicationData, "SetApplicationData"},      {0x00110040, nullptr, "GetApplicationData"}, -    {0x00120100, nullptr, "Bind"}, +    {0x00120100, Bind, "Bind"},      {0x00130040, nullptr, "Unbind"},      {0x001400C0, nullptr, "PullPacket"},      {0x00150080, nullptr, "SetMaxSendDelay"},      {0x00170182, nullptr, "SendTo"}, -    {0x001A0000, nullptr, "GetChannel"}, +    {0x001A0000, GetChannel, "GetChannel"},      {0x001B0302, InitializeWithVersion, "InitializeWithVersion"}, -    {0x001D0044, nullptr, "BeginHostingNetwork"}, +    {0x001D0044, BeginHostingNetwork, "BeginHostingNetwork"},      {0x001E0084, nullptr, "ConnectToNetwork"},      {0x001F0006, nullptr, "DecryptBeaconData"},      {0x00200040, nullptr, "Flush"}, @@ -148,13 +413,25 @@ const Interface::FunctionInfo FunctionTable[] = {  };  NWM_UDS::NWM_UDS() { -    uds_handle_event = Kernel::Event::Create(Kernel::ResetType::OneShot, "NWM::uds_handle_event"); +    connection_status_event = +        Kernel::Event::Create(Kernel::ResetType::OneShot, "NWM::connection_status_event");      Register(FunctionTable); + +    beacon_broadcast_event = +        CoreTiming::RegisterEvent("UDS::BeaconBroadcastCallback", BeaconBroadcastCallback);  }  NWM_UDS::~NWM_UDS() { -    uds_handle_event = nullptr; +    network_info = {}; +    bind_node_events.clear(); +    connection_status_event = nullptr; +    recv_buffer_memory = nullptr; + +    connection_status = {}; +    connection_status.status = static_cast<u32>(NetworkStatus::NotConnected); + +    CoreTiming::UnscheduleEvent(beacon_broadcast_event, 0);  }  } // namespace NWM diff --git a/src/core/hle/service/nwm/nwm_uds.h b/src/core/hle/service/nwm/nwm_uds.h index 55db748f6..65349f9fd 100644 --- a/src/core/hle/service/nwm/nwm_uds.h +++ b/src/core/hle/service/nwm/nwm_uds.h @@ -4,6 +4,10 @@  #pragma once +#include <array> +#include <cstddef> +#include "common/common_types.h" +#include "common/swap.h"  #include "core/hle/service/service.h"  // Local-WLAN service @@ -11,6 +15,68 @@  namespace Service {  namespace NWM { +const size_t ApplicationDataSize = 0xC8; +const u8 DefaultNetworkChannel = 11; + +// Number of milliseconds in a TU. +const double MillisecondsPerTU = 1.024; +// Interval measured in TU, the default value is 100TU = 102.4ms +const u16 DefaultBeaconInterval = 100; + +struct NodeInfo { +    u64_le friend_code_seed; +    std::array<u16_le, 10> username; +    INSERT_PADDING_BYTES(4); +    u16_le network_node_id; +    INSERT_PADDING_BYTES(6); +}; + +static_assert(sizeof(NodeInfo) == 40, "NodeInfo has incorrect size."); + +enum class NetworkStatus { +    NotConnected = 3, +    ConnectedAsHost = 6, +    ConnectedAsClient = 9, +    ConnectedAsSpectator = 10, +}; + +struct ConnectionStatus { +    u32_le status; +    INSERT_PADDING_WORDS(1); +    u16_le network_node_id; +    INSERT_PADDING_BYTES(2); +    INSERT_PADDING_BYTES(32); +    u8 total_nodes; +    u8 max_nodes; +    u16_le node_bitmask; +}; + +static_assert(sizeof(ConnectionStatus) == 0x30, "ConnectionStatus has incorrect size."); + +struct NetworkInfo { +    std::array<u8, 6> host_mac_address; +    u8 channel; +    INSERT_PADDING_BYTES(1); +    u8 initialized; +    INSERT_PADDING_BYTES(3); +    std::array<u8, 3> oui_value; +    u8 oui_type; +    // This field is received as BigEndian from the game. +    u32_be wlan_comm_id; +    u8 id; +    INSERT_PADDING_BYTES(1); +    u16_be attributes; +    u32_be network_id; +    u8 total_nodes; +    u8 max_nodes; +    INSERT_PADDING_BYTES(2); +    INSERT_PADDING_BYTES(0x1F); +    u8 application_data_size; +    std::array<u8, ApplicationDataSize> application_data; +}; + +static_assert(sizeof(NetworkInfo) == 0x108, "NetworkInfo has incorrect size."); +  class NWM_UDS final : public Interface {  public:      NWM_UDS(); diff --git a/src/input_common/sdl/sdl.cpp b/src/input_common/sdl/sdl.cpp index ae0206909..756ee58b7 100644 --- a/src/input_common/sdl/sdl.cpp +++ b/src/input_common/sdl/sdl.cpp @@ -8,6 +8,7 @@  #include <tuple>  #include <unordered_map>  #include <SDL.h> +#include "common/logging/log.h"  #include "common/math_util.h"  #include "input_common/sdl/sdl.h" @@ -40,12 +41,16 @@ public:          return SDL_JoystickGetButton(joystick.get(), button) == 1;      } -    std::tuple<float, float> GetAnalog(int axis_x, int axis_y) const { +    float GetAxis(int axis) const {          if (!joystick)              return {};          SDL_JoystickUpdate(); -        float x = SDL_JoystickGetAxis(joystick.get(), axis_x) / 32767.0f; -        float y = SDL_JoystickGetAxis(joystick.get(), axis_y) / 32767.0f; +        return SDL_JoystickGetAxis(joystick.get(), axis) / 32767.0f; +    } + +    std::tuple<float, float> GetAnalog(int axis_x, int axis_y) const { +        float x = GetAxis(axis_x); +        float y = GetAxis(axis_y);          y = -y; // 3DS uses an y-axis inverse from SDL          // Make sure the coordinates are in the unit circle, @@ -97,6 +102,27 @@ private:      Uint8 direction;  }; +class SDLAxisButton final : public Input::ButtonDevice { +public: +    explicit SDLAxisButton(std::shared_ptr<SDLJoystick> joystick_, int axis_, float threshold_, +                           bool trigger_if_greater_) +        : joystick(joystick_), axis(axis_), threshold(threshold_), +          trigger_if_greater(trigger_if_greater_) {} + +    bool GetStatus() const override { +        float axis_value = joystick->GetAxis(axis); +        if (trigger_if_greater) +            return axis_value > threshold; +        return axis_value < threshold; +    } + +private: +    std::shared_ptr<SDLJoystick> joystick; +    int axis; +    float threshold; +    bool trigger_if_greater; +}; +  class SDLAnalog final : public Input::AnalogDevice {  public:      SDLAnalog(std::shared_ptr<SDLJoystick> joystick_, int axis_x_, int axis_y_) @@ -130,8 +156,14 @@ public:       *     - "joystick": the index of the joystick to bind       *     - "button"(optional): the index of the button to bind       *     - "hat"(optional): the index of the hat to bind as direction buttons +     *     - "axis"(optional): the index of the axis to bind       *     - "direction"(only used for hat): the direction name of the hat to bind. Can be "up", -     *                                     "down", "left" or "right" +     *         "down", "left" or "right" +     *     - "threshould"(only used for axis): a float value in (-1.0, 1.0) which the button is +     *         triggered if the axis value crosses +     *     - "direction"(only used for axis): "+" means the button is triggered when the axis value +     *         is greater than the threshold; "-" means the button is triggered when the axis value +     *         is smaller than the threshold       */      std::unique_ptr<Input::ButtonDevice> Create(const Common::ParamPackage& params) override {          const int joystick_index = params.Get("joystick", 0); @@ -155,6 +187,23 @@ public:                                                          direction);          } +        if (params.Has("axis")) { +            const int axis = params.Get("axis", 0); +            const float threshold = params.Get("threshold", 0.5f); +            const std::string direction_name = params.Get("direction", ""); +            bool trigger_if_greater; +            if (direction_name == "+") { +                trigger_if_greater = true; +            } else if (direction_name == "-") { +                trigger_if_greater = false; +            } else { +                trigger_if_greater = true; +                LOG_ERROR(Input, "Unknown direction %s", direction_name.c_str()); +            } +            return std::make_unique<SDLAxisButton>(GetJoystick(joystick_index), axis, threshold, +                                                   trigger_if_greater); +        } +          const int button = params.Get("button", 0);          return std::make_unique<SDLButton>(GetJoystick(joystick_index), button);      } diff --git a/src/video_core/regs_framebuffer.h b/src/video_core/regs_framebuffer.h index 366782080..9ddc79243 100644 --- a/src/video_core/regs_framebuffer.h +++ b/src/video_core/regs_framebuffer.h @@ -89,8 +89,8 @@ struct FramebufferRegs {          };          union { -            BitField<0, 8, BlendEquation> blend_equation_rgb; -            BitField<8, 8, BlendEquation> blend_equation_a; +            BitField<0, 3, BlendEquation> blend_equation_rgb; +            BitField<8, 3, BlendEquation> blend_equation_a;              BitField<16, 4, BlendFactor> factor_source_rgb;              BitField<20, 4, BlendFactor> factor_dest_rgb; diff --git a/src/video_core/regs_texturing.h b/src/video_core/regs_texturing.h index be8bc6826..0b62da145 100644 --- a/src/video_core/regs_texturing.h +++ b/src/video_core/regs_texturing.h @@ -199,7 +199,7 @@ struct TexturingRegs {              Lerp = 4,              Subtract = 5,              Dot3_RGB = 6, - +            Dot3_RGBA = 7,              MultiplyThenAdd = 8,              AddThenMultiply = 9,          }; diff --git a/src/video_core/renderer_opengl/gl_rasterizer.cpp b/src/video_core/renderer_opengl/gl_rasterizer.cpp index de1d5eba7..a47307099 100644 --- a/src/video_core/renderer_opengl/gl_rasterizer.cpp +++ b/src/video_core/renderer_opengl/gl_rasterizer.cpp @@ -20,7 +20,6 @@  #include "video_core/regs_texturing.h"  #include "video_core/renderer_opengl/gl_rasterizer.h"  #include "video_core/renderer_opengl/gl_shader_gen.h" -#include "video_core/renderer_opengl/gl_shader_util.h"  #include "video_core/renderer_opengl/pica_to_gl.h"  #include "video_core/renderer_opengl/renderer_opengl.h" @@ -1005,7 +1004,7 @@ void RasterizerOpenGL::SamplerInfo::SyncWithConfig(  }  void RasterizerOpenGL::SetShader() { -    PicaShaderConfig config = PicaShaderConfig::CurrentConfig(); +    auto config = GLShader::PicaShaderConfig::BuildFromRegs(Pica::g_state.regs);      std::unique_ptr<PicaShader> shader = std::make_unique<PicaShader>();      // Find (or generate) the GLSL shader for the current TEV state diff --git a/src/video_core/renderer_opengl/gl_rasterizer.h b/src/video_core/renderer_opengl/gl_rasterizer.h index ecf737438..3e1770d77 100644 --- a/src/video_core/renderer_opengl/gl_rasterizer.h +++ b/src/video_core/renderer_opengl/gl_rasterizer.h @@ -25,210 +25,13 @@  #include "video_core/regs_texturing.h"  #include "video_core/renderer_opengl/gl_rasterizer_cache.h"  #include "video_core/renderer_opengl/gl_resource_manager.h" +#include "video_core/renderer_opengl/gl_shader_gen.h"  #include "video_core/renderer_opengl/gl_state.h"  #include "video_core/renderer_opengl/pica_to_gl.h"  #include "video_core/shader/shader.h"  struct ScreenInfo; -/** - * This struct contains all state used to generate the GLSL shader program that emulates the current - * Pica register configuration. This struct is used as a cache key for generated GLSL shader - * programs. The functions in gl_shader_gen.cpp should retrieve state from this struct only, not by - * directly accessing Pica registers. This should reduce the risk of bugs in shader generation where - * Pica state is not being captured in the shader cache key, thereby resulting in (what should be) - * two separate shaders sharing the same key. - * - * We use a union because "implicitly-defined copy/move constructor for a union X copies the object - * representation of X." and "implicitly-defined copy assignment operator for a union X copies the - * object representation (3.9) of X." = Bytewise copy instead of memberwise copy. This is important - * because the padding bytes are included in the hash and comparison between objects. - */ -union PicaShaderConfig { - -    /// Construct a PicaShaderConfig with the current Pica register configuration. -    static PicaShaderConfig CurrentConfig() { -        PicaShaderConfig res; - -        auto& state = res.state; -        std::memset(&state, 0, sizeof(PicaShaderConfig::State)); - -        const auto& regs = Pica::g_state.regs; - -        state.scissor_test_mode = regs.rasterizer.scissor_test.mode; - -        state.depthmap_enable = regs.rasterizer.depthmap_enable; - -        state.alpha_test_func = regs.framebuffer.output_merger.alpha_test.enable -                                    ? regs.framebuffer.output_merger.alpha_test.func.Value() -                                    : Pica::FramebufferRegs::CompareFunc::Always; - -        state.texture0_type = regs.texturing.texture0.type; - -        // Copy relevant tev stages fields. -        // We don't sync const_color here because of the high variance, it is a -        // shader uniform instead. -        const auto& tev_stages = regs.texturing.GetTevStages(); -        DEBUG_ASSERT(state.tev_stages.size() == tev_stages.size()); -        for (size_t i = 0; i < tev_stages.size(); i++) { -            const auto& tev_stage = tev_stages[i]; -            state.tev_stages[i].sources_raw = tev_stage.sources_raw; -            state.tev_stages[i].modifiers_raw = tev_stage.modifiers_raw; -            state.tev_stages[i].ops_raw = tev_stage.ops_raw; -            state.tev_stages[i].scales_raw = tev_stage.scales_raw; -        } - -        state.fog_mode = regs.texturing.fog_mode; -        state.fog_flip = regs.texturing.fog_flip != 0; - -        state.combiner_buffer_input = -            regs.texturing.tev_combiner_buffer_input.update_mask_rgb.Value() | -            regs.texturing.tev_combiner_buffer_input.update_mask_a.Value() << 4; - -        // Fragment lighting - -        state.lighting.enable = !regs.lighting.disable; -        state.lighting.src_num = regs.lighting.max_light_index + 1; - -        for (unsigned light_index = 0; light_index < state.lighting.src_num; ++light_index) { -            unsigned num = regs.lighting.light_enable.GetNum(light_index); -            const auto& light = regs.lighting.light[num]; -            state.lighting.light[light_index].num = num; -            state.lighting.light[light_index].directional = light.config.directional != 0; -            state.lighting.light[light_index].two_sided_diffuse = -                light.config.two_sided_diffuse != 0; -            state.lighting.light[light_index].dist_atten_enable = -                !regs.lighting.IsDistAttenDisabled(num); -        } - -        state.lighting.lut_d0.enable = regs.lighting.config1.disable_lut_d0 == 0; -        state.lighting.lut_d0.abs_input = regs.lighting.abs_lut_input.disable_d0 == 0; -        state.lighting.lut_d0.type = regs.lighting.lut_input.d0.Value(); -        state.lighting.lut_d0.scale = regs.lighting.lut_scale.GetScale(regs.lighting.lut_scale.d0); - -        state.lighting.lut_d1.enable = regs.lighting.config1.disable_lut_d1 == 0; -        state.lighting.lut_d1.abs_input = regs.lighting.abs_lut_input.disable_d1 == 0; -        state.lighting.lut_d1.type = regs.lighting.lut_input.d1.Value(); -        state.lighting.lut_d1.scale = regs.lighting.lut_scale.GetScale(regs.lighting.lut_scale.d1); - -        state.lighting.lut_fr.enable = regs.lighting.config1.disable_lut_fr == 0; -        state.lighting.lut_fr.abs_input = regs.lighting.abs_lut_input.disable_fr == 0; -        state.lighting.lut_fr.type = regs.lighting.lut_input.fr.Value(); -        state.lighting.lut_fr.scale = regs.lighting.lut_scale.GetScale(regs.lighting.lut_scale.fr); - -        state.lighting.lut_rr.enable = regs.lighting.config1.disable_lut_rr == 0; -        state.lighting.lut_rr.abs_input = regs.lighting.abs_lut_input.disable_rr == 0; -        state.lighting.lut_rr.type = regs.lighting.lut_input.rr.Value(); -        state.lighting.lut_rr.scale = regs.lighting.lut_scale.GetScale(regs.lighting.lut_scale.rr); - -        state.lighting.lut_rg.enable = regs.lighting.config1.disable_lut_rg == 0; -        state.lighting.lut_rg.abs_input = regs.lighting.abs_lut_input.disable_rg == 0; -        state.lighting.lut_rg.type = regs.lighting.lut_input.rg.Value(); -        state.lighting.lut_rg.scale = regs.lighting.lut_scale.GetScale(regs.lighting.lut_scale.rg); - -        state.lighting.lut_rb.enable = regs.lighting.config1.disable_lut_rb == 0; -        state.lighting.lut_rb.abs_input = regs.lighting.abs_lut_input.disable_rb == 0; -        state.lighting.lut_rb.type = regs.lighting.lut_input.rb.Value(); -        state.lighting.lut_rb.scale = regs.lighting.lut_scale.GetScale(regs.lighting.lut_scale.rb); - -        state.lighting.config = regs.lighting.config0.config; -        state.lighting.fresnel_selector = regs.lighting.config0.fresnel_selector; -        state.lighting.bump_mode = regs.lighting.config0.bump_mode; -        state.lighting.bump_selector = regs.lighting.config0.bump_selector; -        state.lighting.bump_renorm = regs.lighting.config0.disable_bump_renorm == 0; -        state.lighting.clamp_highlights = regs.lighting.config0.clamp_highlights != 0; - -        return res; -    } - -    bool TevStageUpdatesCombinerBufferColor(unsigned stage_index) const { -        return (stage_index < 4) && (state.combiner_buffer_input & (1 << stage_index)); -    } - -    bool TevStageUpdatesCombinerBufferAlpha(unsigned stage_index) const { -        return (stage_index < 4) && ((state.combiner_buffer_input >> 4) & (1 << stage_index)); -    } - -    bool operator==(const PicaShaderConfig& o) const { -        return std::memcmp(&state, &o.state, sizeof(PicaShaderConfig::State)) == 0; -    }; - -    // NOTE: MSVC15 (Update 2) doesn't think `delete`'d constructors and operators are TC. -    //       This makes BitField not TC when used in a union or struct so we have to resort -    //       to this ugly hack. -    //       Once that bug is fixed we can use Pica::Regs::TevStageConfig here. -    //       Doesn't include const_color because we don't sync it, see comment in CurrentConfig() -    struct TevStageConfigRaw { -        u32 sources_raw; -        u32 modifiers_raw; -        u32 ops_raw; -        u32 scales_raw; -        explicit operator Pica::TexturingRegs::TevStageConfig() const noexcept { -            Pica::TexturingRegs::TevStageConfig stage; -            stage.sources_raw = sources_raw; -            stage.modifiers_raw = modifiers_raw; -            stage.ops_raw = ops_raw; -            stage.const_color = 0; -            stage.scales_raw = scales_raw; -            return stage; -        } -    }; - -    struct State { -        Pica::FramebufferRegs::CompareFunc alpha_test_func; -        Pica::RasterizerRegs::ScissorMode scissor_test_mode; -        Pica::TexturingRegs::TextureConfig::TextureType texture0_type; -        std::array<TevStageConfigRaw, 6> tev_stages; -        u8 combiner_buffer_input; - -        Pica::RasterizerRegs::DepthBuffering depthmap_enable; -        Pica::TexturingRegs::FogMode fog_mode; -        bool fog_flip; - -        struct { -            struct { -                unsigned num; -                bool directional; -                bool two_sided_diffuse; -                bool dist_atten_enable; -            } light[8]; - -            bool enable; -            unsigned src_num; -            Pica::LightingRegs::LightingBumpMode bump_mode; -            unsigned bump_selector; -            bool bump_renorm; -            bool clamp_highlights; - -            Pica::LightingRegs::LightingConfig config; -            Pica::LightingRegs::LightingFresnelSelector fresnel_selector; - -            struct { -                bool enable; -                bool abs_input; -                Pica::LightingRegs::LightingLutInput type; -                float scale; -            } lut_d0, lut_d1, lut_fr, lut_rr, lut_rg, lut_rb; -        } lighting; - -    } state; -}; -#if (__GNUC__ >= 5) || defined(__clang__) || defined(_MSC_VER) -static_assert(std::is_trivially_copyable<PicaShaderConfig::State>::value, -              "PicaShaderConfig::State must be trivially copyable"); -#endif - -namespace std { - -template <> -struct hash<PicaShaderConfig> { -    size_t operator()(const PicaShaderConfig& k) const { -        return Common::ComputeHash64(&k.state, sizeof(PicaShaderConfig::State)); -    } -}; - -} // namespace std -  class RasterizerOpenGL : public VideoCore::RasterizerInterface {  public:      RasterizerOpenGL(); @@ -437,7 +240,7 @@ private:      std::vector<HardwareVertex> vertex_batch; -    std::unordered_map<PicaShaderConfig, std::unique_ptr<PicaShader>> shader_cache; +    std::unordered_map<GLShader::PicaShaderConfig, std::unique_ptr<PicaShader>> shader_cache;      const PicaShader* current_shader = nullptr;      bool shader_dirty; diff --git a/src/video_core/renderer_opengl/gl_shader_gen.cpp b/src/video_core/renderer_opengl/gl_shader_gen.cpp index 7abdeba05..0f889b172 100644 --- a/src/video_core/renderer_opengl/gl_shader_gen.cpp +++ b/src/video_core/renderer_opengl/gl_shader_gen.cpp @@ -4,6 +4,7 @@  #include <array>  #include <cstddef> +#include <cstring>  #include "common/assert.h"  #include "common/bit_field.h"  #include "common/logging/log.h" @@ -23,6 +24,97 @@ using TevStageConfig = TexturingRegs::TevStageConfig;  namespace GLShader { +PicaShaderConfig PicaShaderConfig::BuildFromRegs(const Pica::Regs& regs) { +    PicaShaderConfig res; + +    auto& state = res.state; +    std::memset(&state, 0, sizeof(PicaShaderConfig::State)); + +    state.scissor_test_mode = regs.rasterizer.scissor_test.mode; + +    state.depthmap_enable = regs.rasterizer.depthmap_enable; + +    state.alpha_test_func = regs.framebuffer.output_merger.alpha_test.enable +                                ? regs.framebuffer.output_merger.alpha_test.func.Value() +                                : Pica::FramebufferRegs::CompareFunc::Always; + +    state.texture0_type = regs.texturing.texture0.type; + +    // Copy relevant tev stages fields. +    // We don't sync const_color here because of the high variance, it is a +    // shader uniform instead. +    const auto& tev_stages = regs.texturing.GetTevStages(); +    DEBUG_ASSERT(state.tev_stages.size() == tev_stages.size()); +    for (size_t i = 0; i < tev_stages.size(); i++) { +        const auto& tev_stage = tev_stages[i]; +        state.tev_stages[i].sources_raw = tev_stage.sources_raw; +        state.tev_stages[i].modifiers_raw = tev_stage.modifiers_raw; +        state.tev_stages[i].ops_raw = tev_stage.ops_raw; +        state.tev_stages[i].scales_raw = tev_stage.scales_raw; +    } + +    state.fog_mode = regs.texturing.fog_mode; +    state.fog_flip = regs.texturing.fog_flip != 0; + +    state.combiner_buffer_input = regs.texturing.tev_combiner_buffer_input.update_mask_rgb.Value() | +                                  regs.texturing.tev_combiner_buffer_input.update_mask_a.Value() +                                      << 4; + +    // Fragment lighting + +    state.lighting.enable = !regs.lighting.disable; +    state.lighting.src_num = regs.lighting.max_light_index + 1; + +    for (unsigned light_index = 0; light_index < state.lighting.src_num; ++light_index) { +        unsigned num = regs.lighting.light_enable.GetNum(light_index); +        const auto& light = regs.lighting.light[num]; +        state.lighting.light[light_index].num = num; +        state.lighting.light[light_index].directional = light.config.directional != 0; +        state.lighting.light[light_index].two_sided_diffuse = light.config.two_sided_diffuse != 0; +        state.lighting.light[light_index].dist_atten_enable = +            !regs.lighting.IsDistAttenDisabled(num); +    } + +    state.lighting.lut_d0.enable = regs.lighting.config1.disable_lut_d0 == 0; +    state.lighting.lut_d0.abs_input = regs.lighting.abs_lut_input.disable_d0 == 0; +    state.lighting.lut_d0.type = regs.lighting.lut_input.d0.Value(); +    state.lighting.lut_d0.scale = regs.lighting.lut_scale.GetScale(regs.lighting.lut_scale.d0); + +    state.lighting.lut_d1.enable = regs.lighting.config1.disable_lut_d1 == 0; +    state.lighting.lut_d1.abs_input = regs.lighting.abs_lut_input.disable_d1 == 0; +    state.lighting.lut_d1.type = regs.lighting.lut_input.d1.Value(); +    state.lighting.lut_d1.scale = regs.lighting.lut_scale.GetScale(regs.lighting.lut_scale.d1); + +    state.lighting.lut_fr.enable = regs.lighting.config1.disable_lut_fr == 0; +    state.lighting.lut_fr.abs_input = regs.lighting.abs_lut_input.disable_fr == 0; +    state.lighting.lut_fr.type = regs.lighting.lut_input.fr.Value(); +    state.lighting.lut_fr.scale = regs.lighting.lut_scale.GetScale(regs.lighting.lut_scale.fr); + +    state.lighting.lut_rr.enable = regs.lighting.config1.disable_lut_rr == 0; +    state.lighting.lut_rr.abs_input = regs.lighting.abs_lut_input.disable_rr == 0; +    state.lighting.lut_rr.type = regs.lighting.lut_input.rr.Value(); +    state.lighting.lut_rr.scale = regs.lighting.lut_scale.GetScale(regs.lighting.lut_scale.rr); + +    state.lighting.lut_rg.enable = regs.lighting.config1.disable_lut_rg == 0; +    state.lighting.lut_rg.abs_input = regs.lighting.abs_lut_input.disable_rg == 0; +    state.lighting.lut_rg.type = regs.lighting.lut_input.rg.Value(); +    state.lighting.lut_rg.scale = regs.lighting.lut_scale.GetScale(regs.lighting.lut_scale.rg); + +    state.lighting.lut_rb.enable = regs.lighting.config1.disable_lut_rb == 0; +    state.lighting.lut_rb.abs_input = regs.lighting.abs_lut_input.disable_rb == 0; +    state.lighting.lut_rb.type = regs.lighting.lut_input.rb.Value(); +    state.lighting.lut_rb.scale = regs.lighting.lut_scale.GetScale(regs.lighting.lut_scale.rb); + +    state.lighting.config = regs.lighting.config0.config; +    state.lighting.fresnel_selector = regs.lighting.config0.fresnel_selector; +    state.lighting.bump_mode = regs.lighting.config0.bump_mode; +    state.lighting.bump_selector = regs.lighting.config0.bump_selector; +    state.lighting.bump_renorm = regs.lighting.config0.disable_bump_renorm == 0; +    state.lighting.clamp_highlights = regs.lighting.config0.clamp_highlights != 0; + +    return res; +} +  /// Detects if a TEV stage is configured to be skipped (to avoid generating unnecessary code)  static bool IsPassThroughTevStage(const TevStageConfig& stage) {      return (stage.color_op == TevStageConfig::Operation::Replace && @@ -214,8 +306,6 @@ static void AppendColorCombiner(std::string& out, TevStageConfig::Operation oper          out += variable_name + "[0] + " + variable_name + "[1] - vec3(0.5)";          break;      case Operation::Lerp: -        // TODO(bunnei): Verify if HW actually does this per-component, otherwise we can just use -        // builtin lerp          out += variable_name + "[0] * " + variable_name + "[2] + " + variable_name +                 "[1] * (vec3(1.0) - " + variable_name + "[2])";          break; @@ -230,6 +320,7 @@ static void AppendColorCombiner(std::string& out, TevStageConfig::Operation oper                 variable_name + "[2]";          break;      case Operation::Dot3_RGB: +    case Operation::Dot3_RGBA:          out += "vec3(dot(" + variable_name + "[0] - vec3(0.5), " + variable_name +                 "[1] - vec3(0.5)) * 4.0)";          break; @@ -329,17 +420,25 @@ static void WriteTevStage(std::string& out, const PicaShaderConfig& config, unsi          AppendColorCombiner(out, stage.color_op, "color_results_" + index_name);          out += ";\n"; -        out += "float alpha_results_" + index_name + "[3] = float[3]("; -        AppendAlphaModifier(out, config, stage.alpha_modifier1, stage.alpha_source1, index_name); -        out += ", "; -        AppendAlphaModifier(out, config, stage.alpha_modifier2, stage.alpha_source2, index_name); -        out += ", "; -        AppendAlphaModifier(out, config, stage.alpha_modifier3, stage.alpha_source3, index_name); -        out += ");\n"; - -        out += "float alpha_output_" + index_name + " = "; -        AppendAlphaCombiner(out, stage.alpha_op, "alpha_results_" + index_name); -        out += ";\n"; +        if (stage.color_op == TevStageConfig::Operation::Dot3_RGBA) { +            // result of Dot3_RGBA operation is also placed to the alpha component +            out += "float alpha_output_" + index_name + " = color_output_" + index_name + "[0];\n"; +        } else { +            out += "float alpha_results_" + index_name + "[3] = float[3]("; +            AppendAlphaModifier(out, config, stage.alpha_modifier1, stage.alpha_source1, +                                index_name); +            out += ", "; +            AppendAlphaModifier(out, config, stage.alpha_modifier2, stage.alpha_source2, +                                index_name); +            out += ", "; +            AppendAlphaModifier(out, config, stage.alpha_modifier3, stage.alpha_source3, +                                index_name); +            out += ");\n"; + +            out += "float alpha_output_" + index_name + " = "; +            AppendAlphaCombiner(out, stage.alpha_op, "alpha_results_" + index_name); +            out += ";\n"; +        }          out += "last_tex_env_out = vec4("                 "clamp(color_output_" + diff --git a/src/video_core/renderer_opengl/gl_shader_gen.h b/src/video_core/renderer_opengl/gl_shader_gen.h index bef3249cf..921d976a1 100644 --- a/src/video_core/renderer_opengl/gl_shader_gen.h +++ b/src/video_core/renderer_opengl/gl_shader_gen.h @@ -4,12 +4,121 @@  #pragma once +#include <array> +#include <cstring> +#include <functional>  #include <string> - -union PicaShaderConfig; +#include <type_traits> +#include "video_core/regs.h"  namespace GLShader { +enum Attributes { +    ATTRIBUTE_POSITION, +    ATTRIBUTE_COLOR, +    ATTRIBUTE_TEXCOORD0, +    ATTRIBUTE_TEXCOORD1, +    ATTRIBUTE_TEXCOORD2, +    ATTRIBUTE_TEXCOORD0_W, +    ATTRIBUTE_NORMQUAT, +    ATTRIBUTE_VIEW, +}; + +/** + * This struct contains all state used to generate the GLSL shader program that emulates the current + * Pica register configuration. This struct is used as a cache key for generated GLSL shader + * programs. The functions in gl_shader_gen.cpp should retrieve state from this struct only, not by + * directly accessing Pica registers. This should reduce the risk of bugs in shader generation where + * Pica state is not being captured in the shader cache key, thereby resulting in (what should be) + * two separate shaders sharing the same key. + * + * We use a union because "implicitly-defined copy/move constructor for a union X copies the object + * representation of X." and "implicitly-defined copy assignment operator for a union X copies the + * object representation (3.9) of X." = Bytewise copy instead of memberwise copy. This is important + * because the padding bytes are included in the hash and comparison between objects. + */ +union PicaShaderConfig { + +    /// Construct a PicaShaderConfig with the given Pica register configuration. +    static PicaShaderConfig BuildFromRegs(const Pica::Regs& regs); + +    bool TevStageUpdatesCombinerBufferColor(unsigned stage_index) const { +        return (stage_index < 4) && (state.combiner_buffer_input & (1 << stage_index)); +    } + +    bool TevStageUpdatesCombinerBufferAlpha(unsigned stage_index) const { +        return (stage_index < 4) && ((state.combiner_buffer_input >> 4) & (1 << stage_index)); +    } + +    bool operator==(const PicaShaderConfig& o) const { +        return std::memcmp(&state, &o.state, sizeof(PicaShaderConfig::State)) == 0; +    }; + +    // NOTE: MSVC15 (Update 2) doesn't think `delete`'d constructors and operators are TC. +    //       This makes BitField not TC when used in a union or struct so we have to resort +    //       to this ugly hack. +    //       Once that bug is fixed we can use Pica::Regs::TevStageConfig here. +    //       Doesn't include const_color because we don't sync it, see comment in BuildFromRegs() +    struct TevStageConfigRaw { +        u32 sources_raw; +        u32 modifiers_raw; +        u32 ops_raw; +        u32 scales_raw; +        explicit operator Pica::TexturingRegs::TevStageConfig() const noexcept { +            Pica::TexturingRegs::TevStageConfig stage; +            stage.sources_raw = sources_raw; +            stage.modifiers_raw = modifiers_raw; +            stage.ops_raw = ops_raw; +            stage.const_color = 0; +            stage.scales_raw = scales_raw; +            return stage; +        } +    }; + +    struct State { +        Pica::FramebufferRegs::CompareFunc alpha_test_func; +        Pica::RasterizerRegs::ScissorMode scissor_test_mode; +        Pica::TexturingRegs::TextureConfig::TextureType texture0_type; +        std::array<TevStageConfigRaw, 6> tev_stages; +        u8 combiner_buffer_input; + +        Pica::RasterizerRegs::DepthBuffering depthmap_enable; +        Pica::TexturingRegs::FogMode fog_mode; +        bool fog_flip; + +        struct { +            struct { +                unsigned num; +                bool directional; +                bool two_sided_diffuse; +                bool dist_atten_enable; +            } light[8]; + +            bool enable; +            unsigned src_num; +            Pica::LightingRegs::LightingBumpMode bump_mode; +            unsigned bump_selector; +            bool bump_renorm; +            bool clamp_highlights; + +            Pica::LightingRegs::LightingConfig config; +            Pica::LightingRegs::LightingFresnelSelector fresnel_selector; + +            struct { +                bool enable; +                bool abs_input; +                Pica::LightingRegs::LightingLutInput type; +                float scale; +            } lut_d0, lut_d1, lut_fr, lut_rr, lut_rg, lut_rb; +        } lighting; + +    } state; +}; +#if (__GNUC__ >= 5) || defined(__clang__) || defined(_MSC_VER) +static_assert(std::is_trivially_copyable<PicaShaderConfig::State>::value, +              "PicaShaderConfig::State must be trivially copyable"); +#endif +  /**   * Generates the GLSL vertex shader program source code for the current Pica state   * @returns String of the shader source code @@ -25,3 +134,12 @@ std::string GenerateVertexShader();  std::string GenerateFragmentShader(const PicaShaderConfig& config);  } // namespace GLShader + +namespace std { +template <> +struct hash<GLShader::PicaShaderConfig> { +    size_t operator()(const GLShader::PicaShaderConfig& k) const { +        return Common::ComputeHash64(&k.state, sizeof(GLShader::PicaShaderConfig::State)); +    } +}; +} // namespace std diff --git a/src/video_core/renderer_opengl/gl_shader_util.h b/src/video_core/renderer_opengl/gl_shader_util.h index f59912f79..c66e8acd3 100644 --- a/src/video_core/renderer_opengl/gl_shader_util.h +++ b/src/video_core/renderer_opengl/gl_shader_util.h @@ -8,17 +8,6 @@  namespace GLShader { -enum Attributes { -    ATTRIBUTE_POSITION, -    ATTRIBUTE_COLOR, -    ATTRIBUTE_TEXCOORD0, -    ATTRIBUTE_TEXCOORD1, -    ATTRIBUTE_TEXCOORD2, -    ATTRIBUTE_TEXCOORD0_W, -    ATTRIBUTE_NORMQUAT, -    ATTRIBUTE_VIEW, -}; -  /**   * Utility function to create and compile an OpenGL GLSL shader program (vertex + fragment shader)   * @param vertex_shader String of the GLSL vertex shader program diff --git a/src/video_core/swrasterizer/rasterizer.cpp b/src/video_core/swrasterizer/rasterizer.cpp index 7557fcb89..cb1b90a81 100644 --- a/src/video_core/swrasterizer/rasterizer.cpp +++ b/src/video_core/swrasterizer/rasterizer.cpp @@ -403,13 +403,22 @@ static void ProcessTriangleInternal(const Vertex& v0, const Vertex& v1, const Ve                  };                  auto color_output = ColorCombine(tev_stage.color_op, color_result); -                // alpha combiner -                std::array<u8, 3> alpha_result = {{ -                    GetAlphaModifier(tev_stage.alpha_modifier1, GetSource(tev_stage.alpha_source1)), -                    GetAlphaModifier(tev_stage.alpha_modifier2, GetSource(tev_stage.alpha_source2)), -                    GetAlphaModifier(tev_stage.alpha_modifier3, GetSource(tev_stage.alpha_source3)), -                }}; -                auto alpha_output = AlphaCombine(tev_stage.alpha_op, alpha_result); +                u8 alpha_output; +                if (tev_stage.color_op == TexturingRegs::TevStageConfig::Operation::Dot3_RGBA) { +                    // result of Dot3_RGBA operation is also placed to the alpha component +                    alpha_output = color_output.x; +                } else { +                    // alpha combiner +                    std::array<u8, 3> alpha_result = {{ +                        GetAlphaModifier(tev_stage.alpha_modifier1, +                                         GetSource(tev_stage.alpha_source1)), +                        GetAlphaModifier(tev_stage.alpha_modifier2, +                                         GetSource(tev_stage.alpha_source2)), +                        GetAlphaModifier(tev_stage.alpha_modifier3, +                                         GetSource(tev_stage.alpha_source3)), +                    }}; +                    alpha_output = AlphaCombine(tev_stage.alpha_op, alpha_result); +                }                  combiner_output[0] =                      std::min((unsigned)255, color_output.r() * tev_stage.GetColorMultiplier()); diff --git a/src/video_core/swrasterizer/texturing.cpp b/src/video_core/swrasterizer/texturing.cpp index eb18e4ba4..aeb6aeb8c 100644 --- a/src/video_core/swrasterizer/texturing.cpp +++ b/src/video_core/swrasterizer/texturing.cpp @@ -169,7 +169,8 @@ Math::Vec3<u8> ColorCombine(TevStageConfig::Operation op, const Math::Vec3<u8> i          result = (result * input[2].Cast<int>()) / 255;          return result.Cast<u8>();      } -    case Operation::Dot3_RGB: { +    case Operation::Dot3_RGB: +    case Operation::Dot3_RGBA: {          // Not fully accurate.  Worst case scenario seems to yield a +/-3 error.  Some HW results          // indicate that the per-component computation can't have a higher precision than 1/256,          // while dot3_rgb((0x80,g0,b0), (0x7F,g1,b1)) and dot3_rgb((0x80,g0,b0), (0x80,g1,b1)) give  | 
