3
0

EditorMaterialComponentExporter.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  1. /*
  2. * Copyright (c) Contributors to the Open 3D Engine Project.
  3. * For complete copyright and license terms please see the LICENSE at the root of this distribution.
  4. *
  5. * SPDX-License-Identifier: Apache-2.0 OR MIT
  6. *
  7. */
  8. #include <Material/EditorMaterialComponentExporter.h>
  9. #include <Material/EditorMaterialComponentUtil.h>
  10. #include <AzFramework/API/ApplicationAPI.h>
  11. #include <AzQtComponents/Components/Widgets/BrowseEdit.h>
  12. #include <AzQtComponents/Components/Widgets/FileDialog.h>
  13. #include <AzToolsFramework/API/EditorAssetSystemAPI.h>
  14. #include <AzToolsFramework/API/EditorWindowRequestBus.h>
  15. #include <AzToolsFramework/API/ToolsApplicationAPI.h>
  16. #include <Atom/RPI.Edit/Common/AssetUtils.h>
  17. AZ_PUSH_DISABLE_WARNING(4251 4800, "-Wunknown-warning-option") // disable warnings spawned by QT
  18. #include <QApplication>
  19. #include <QCheckBox>
  20. #include <QComboBox>
  21. #include <QDialogButtonBox>
  22. #include <QHBoxLayout>
  23. #include <QHeaderView>
  24. #include <QLabel>
  25. #include <QPushButton>
  26. #include <QTableWidget>
  27. #include <QVBoxLayout>
  28. AZ_POP_DISABLE_WARNING
  29. namespace AZ
  30. {
  31. namespace Render
  32. {
  33. namespace EditorMaterialComponentExporter
  34. {
  35. AZStd::string GetExportPathByAssetId(const AZ::Data::AssetId& assetId, const AZStd::string& materialSlotName)
  36. {
  37. if (assetId.IsValid())
  38. {
  39. // Exported materials will be created in the same folder, using the same base name, as the originating source asset for
  40. // the material being converted. We need to get the source asset path from the asset ID and then remove the extension and
  41. // any invalid characters.
  42. AZ::IO::FixedMaxPath path{ AZ::RPI::AssetUtils::GetSourcePathByAssetId(assetId) };
  43. AZStd::string filename = path.Stem().Native();
  44. // The material slot name is appended to the base file name. Material slot names should be guaranteed to be unique. This
  45. // will ensure that the generated files are also unique and that it is easy to identify the corresponding material.
  46. filename += "_";
  47. filename += materialSlotName;
  48. // Explicitly replacing dots in file names with underscores because not all builders or code is set up to handle extra
  49. // dots and file names when determining extensions. The sanitized function does not currently remove dots from file
  50. // names.
  51. AZ::StringFunc::Replace(filename, ".", "_");
  52. filename = AZ::RPI::AssetUtils::SanitizeFileName(filename);
  53. // The originating source file could have been an fbx or other model format. Therefore, the extension must be replaced
  54. // with the material source data extension.
  55. filename += ".";
  56. filename += AZ::RPI::MaterialSourceData::Extension;
  57. path.ReplaceFilename(AZ::IO::PathView{ filename });
  58. return path.LexicallyNormal().String();
  59. }
  60. return {};
  61. }
  62. bool OpenExportDialog(ExportItemsContainer& exportItems)
  63. {
  64. // Sort material entries so they are ordered by name in the table
  65. AZStd::sort(exportItems.begin(), exportItems.end(),
  66. [](const auto& a, const auto& b) { return a.GetMaterialSlotName() < b.GetMaterialSlotName(); });
  67. QWidget* activeWindow = nullptr;
  68. AzToolsFramework::EditorWindowRequestBus::BroadcastResult(activeWindow, &AzToolsFramework::EditorWindowRequests::GetAppMainWindow);
  69. // Constructing a dialog with a table to display all configurable material export items
  70. QDialog dialog(activeWindow);
  71. dialog.setWindowTitle("Generate/Manage Source Materials");
  72. const QStringList headerLabels = { "Material Slot", "Material Filename", "Overwrite" };
  73. const int MaterialSlotColumn = 0;
  74. const int MaterialFileColumn = 1;
  75. const int OverwriteFileColumn = 2;
  76. // Create a table widget that will be filled with all of the data and options for each exported material
  77. QTableWidget* tableWidget = new QTableWidget(&dialog);
  78. tableWidget->setColumnCount(headerLabels.size());
  79. tableWidget->setRowCount((int)exportItems.size());
  80. tableWidget->setHorizontalHeaderLabels(headerLabels);
  81. tableWidget->setSortingEnabled(false);
  82. tableWidget->setAlternatingRowColors(true);
  83. tableWidget->setCornerButtonEnabled(false);
  84. tableWidget->setContextMenuPolicy(Qt::DefaultContextMenu);
  85. tableWidget->setSelectionBehavior(QAbstractItemView::SelectRows);
  86. tableWidget->setSelectionMode(QAbstractItemView::SingleSelection);
  87. tableWidget->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding);
  88. // Force the table to stretch its header to fill the entire width of the dialog
  89. tableWidget->horizontalHeader()->setSectionResizeMode(MaterialSlotColumn, QHeaderView::ResizeToContents);
  90. tableWidget->horizontalHeader()->setSectionResizeMode(MaterialFileColumn, QHeaderView::Stretch);
  91. tableWidget->horizontalHeader()->setSectionResizeMode(OverwriteFileColumn, QHeaderView::ResizeToContents);
  92. tableWidget->horizontalHeader()->setStretchLastSection(false);
  93. // Hide row numbers
  94. tableWidget->verticalHeader()->setVisible(false);
  95. int row = 0;
  96. for (ExportItem& exportItem : exportItems)
  97. {
  98. // Configuring initial settings based on whether or not the target file already exists
  99. QFileInfo fileInfo(exportItem.GetExportPath().c_str());
  100. exportItem.SetExists(fileInfo.exists());
  101. exportItem.SetOverwrite(false);
  102. // Populate the table with data for every column
  103. tableWidget->setItem(row, MaterialSlotColumn, new QTableWidgetItem());
  104. tableWidget->setItem(row, MaterialFileColumn, new QTableWidgetItem());
  105. tableWidget->setItem(row, OverwriteFileColumn, new QTableWidgetItem());
  106. // Create a check box for toggling the enabled state of this item
  107. QCheckBox* materialSlotCheckBox = new QCheckBox(tableWidget);
  108. materialSlotCheckBox->setChecked(exportItem.GetEnabled());
  109. materialSlotCheckBox->setText(exportItem.GetMaterialSlotName().c_str());
  110. tableWidget->setCellWidget(row, MaterialSlotColumn, materialSlotCheckBox);
  111. // Create a file picker widget for selecting the save path for the exported material
  112. AzQtComponents::BrowseEdit* materialFileWidget = new AzQtComponents::BrowseEdit(tableWidget);
  113. materialFileWidget->setLineEditReadOnly(true);
  114. materialFileWidget->setClearButtonEnabled(false);
  115. materialFileWidget->setEnabled(exportItem.GetEnabled());
  116. materialFileWidget->setText(fileInfo.fileName());
  117. tableWidget->setCellWidget(row, MaterialFileColumn, materialFileWidget);
  118. // Create a check box for toggling the overwrite state of this item
  119. QWidget* overwriteCheckBoxContainer = new QWidget(tableWidget);
  120. QCheckBox* overwriteCheckBox = new QCheckBox(overwriteCheckBoxContainer);
  121. overwriteCheckBox->setChecked(exportItem.GetOverwrite());
  122. overwriteCheckBox->setEnabled(exportItem.GetEnabled() && exportItem.GetExists());
  123. overwriteCheckBoxContainer->setLayout(new QHBoxLayout(overwriteCheckBoxContainer));
  124. overwriteCheckBoxContainer->layout()->addWidget(overwriteCheckBox);
  125. overwriteCheckBoxContainer->layout()->setAlignment(Qt::AlignCenter);
  126. overwriteCheckBoxContainer->layout()->setContentsMargins(0, 0, 0, 0);
  127. tableWidget->setCellWidget(row, OverwriteFileColumn, overwriteCheckBoxContainer);
  128. // Whenever the selection is updated, automatically apply the change to the export item
  129. QObject::connect(materialSlotCheckBox, &QCheckBox::stateChanged, materialSlotCheckBox, [&exportItem, materialFileWidget, materialSlotCheckBox, overwriteCheckBox]([[maybe_unused]] int state) {
  130. exportItem.SetEnabled(materialSlotCheckBox->isChecked());
  131. materialFileWidget->setEnabled(exportItem.GetEnabled());
  132. overwriteCheckBox->setEnabled(exportItem.GetEnabled() && exportItem.GetExists());
  133. });
  134. // Whenever the overwrite check box is updated, automatically apply the change to the export item
  135. QObject::connect(overwriteCheckBox, &QCheckBox::stateChanged, overwriteCheckBox, [&exportItem, overwriteCheckBox]([[maybe_unused]] int state) {
  136. exportItem.SetOverwrite(overwriteCheckBox->isChecked());
  137. });
  138. // Whenever the browse button is clicked, open a save file dialog in the same location as the current export file setting
  139. QObject::connect(materialFileWidget, &AzQtComponents::BrowseEdit::attachedButtonTriggered, materialFileWidget, [&dialog, &exportItem, materialFileWidget, overwriteCheckBox]() {
  140. QFileInfo fileInfo = AzQtComponents::FileDialog::GetSaveFileName(&dialog,
  141. QString("Select Material Filename"),
  142. exportItem.GetExportPath().c_str(),
  143. QString("Material (*.material)"),
  144. nullptr,
  145. QFileDialog::DontConfirmOverwrite);
  146. // Only update the export data if a valid path and filename was selected
  147. if (!fileInfo.absoluteFilePath().isEmpty())
  148. {
  149. exportItem.SetExportPath(fileInfo.absoluteFilePath().toUtf8().constData());
  150. exportItem.SetExists(fileInfo.exists());
  151. exportItem.SetOverwrite(fileInfo.exists());
  152. // Update the controls to display the new state
  153. materialFileWidget->setText(fileInfo.fileName());
  154. overwriteCheckBox->setChecked(exportItem.GetOverwrite());
  155. overwriteCheckBox->setEnabled(exportItem.GetEnabled() && exportItem.GetExists());
  156. }
  157. });
  158. ++row;
  159. }
  160. tableWidget->sortItems(MaterialSlotColumn);
  161. // Create the bottom row of the dialog with action buttons for exporting or canceling the operation
  162. QDialogButtonBox* buttonBox = new QDialogButtonBox(&dialog);
  163. buttonBox->setStandardButtons(QDialogButtonBox::Cancel | QDialogButtonBox::Ok);
  164. QObject::connect(buttonBox, &QDialogButtonBox::accepted, &dialog, &QDialog::accept);
  165. QObject::connect(buttonBox, &QDialogButtonBox::rejected, &dialog, &QDialog::reject);
  166. // Create a heading label for the top of the dialog
  167. QLabel* labelWidget = new QLabel("\nSelect the material slots that you want to generate new source materials for. Edit the material file name and location using the file picker.\n", &dialog);
  168. labelWidget->setWordWrap(true);
  169. QVBoxLayout* dialogLayout = new QVBoxLayout(&dialog);
  170. dialogLayout->addWidget(labelWidget);
  171. dialogLayout->addWidget(tableWidget);
  172. dialogLayout->addWidget(buttonBox);
  173. dialog.setLayout(dialogLayout);
  174. dialog.setModal(true);
  175. // Forcing the initial dialog size to accomodate typical content.
  176. // Temporarily settng fixed size because dialog.show/exec invokes WindowDecorationWrapper::showEvent.
  177. // This forces the dialog to be centered and sized based on the layout of content.
  178. // Resizing the dialog after show will not be centered and moving the dialog programatically doesn't m0ve the custmk frame.
  179. dialog.setFixedSize(500, 200);
  180. dialog.show();
  181. // Removing fixed size to allow drag resizing
  182. dialog.setMinimumSize(0, 0);
  183. dialog.setMaximumSize(QWIDGETSIZE_MAX, QWIDGETSIZE_MAX);
  184. // Return true if the user press the export button
  185. return dialog.exec() == QDialog::Accepted;
  186. }
  187. bool ExportMaterialSourceData(const ExportItem& exportItem)
  188. {
  189. if (!exportItem.GetEnabled() || exportItem.GetExportPath().empty())
  190. {
  191. return false;
  192. }
  193. if (exportItem.GetExists() && !exportItem.GetOverwrite())
  194. {
  195. return true;
  196. }
  197. EditorMaterialComponentUtil::MaterialEditData editData;
  198. if (!EditorMaterialComponentUtil::LoadMaterialEditDataFromAssetId(exportItem.GetOriginalAssetId(), editData))
  199. {
  200. AZ_Warning("AZ::Render::EditorMaterialComponentExporter", false, "Failed to load material data.");
  201. return false;
  202. }
  203. if (!EditorMaterialComponentUtil::SaveSourceMaterialFromEditData(exportItem.GetExportPath(), editData))
  204. {
  205. AZ_Warning("AZ::Render::EditorMaterialComponentExporter", false, "Failed to save material data.");
  206. return false;
  207. }
  208. return true;
  209. }
  210. ProgressDialog::ProgressDialog(const AZStd::string& title, const AZStd::string& label, const int itemCount)
  211. {
  212. QWidget* activeWindow = nullptr;
  213. AzToolsFramework::EditorWindowRequestBus::BroadcastResult(
  214. activeWindow, &AzToolsFramework::EditorWindowRequests::GetAppMainWindow);
  215. m_progressDialog.reset(new QProgressDialog(activeWindow));
  216. m_progressDialog->setWindowFlags(m_progressDialog->windowFlags() & ~Qt::WindowCloseButtonHint);
  217. m_progressDialog->setWindowTitle(QObject::tr(title.c_str()));
  218. m_progressDialog->setLabelText(QObject::tr(label.c_str()));
  219. m_progressDialog->setWindowModality(Qt::WindowModal);
  220. m_progressDialog->setMaximumSize(400, 100);
  221. m_progressDialog->setMinimum(0);
  222. m_progressDialog->setMaximum(itemCount);
  223. m_progressDialog->setMinimumDuration(0);
  224. m_progressDialog->setAutoClose(false);
  225. m_progressDialog->show();
  226. }
  227. AZ::Data::AssetInfo ProgressDialog::ProcessItem(const ExportItem& exportItem)
  228. {
  229. while (true)
  230. {
  231. AZ::Data::AssetInfo assetInfo{};
  232. if (m_progressDialog->wasCanceled())
  233. {
  234. // The user canceled the operation from the progress dialog.
  235. return assetInfo;
  236. }
  237. // Attempt to resolve the asset info from the anticipated asset id.
  238. if (const auto& assetIdOutcome = AZ::RPI::AssetUtils::MakeAssetId(exportItem.GetExportPath(), 0); assetIdOutcome)
  239. {
  240. if (const auto& assetId = assetIdOutcome.GetValue(); assetId.IsValid())
  241. {
  242. AZ::Data::AssetCatalogRequestBus::BroadcastResult(
  243. assetInfo, &AZ::Data::AssetCatalogRequestBus::Events::GetAssetInfoById, assetId);
  244. if (assetInfo.m_assetId.IsValid())
  245. {
  246. // The asset is only valid and loadable once it has been added to the asset catalog.
  247. return assetInfo;
  248. }
  249. }
  250. }
  251. // Process other application events while waiting in this loop
  252. QApplication::processEvents();
  253. AZStd::this_thread::sleep_for(AZStd::chrono::milliseconds(100));
  254. }
  255. return {};
  256. }
  257. void ProgressDialog::CompleteItem()
  258. {
  259. m_progressDialog->setValue(m_progressDialog->value() + 1);
  260. QApplication::processEvents();
  261. }
  262. } // namespace EditorMaterialComponentExporter
  263. } // namespace Render
  264. } // namespace AZ