3
0

ShaderVariantAssetBuilder.cpp 63 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190
  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 <ShaderVariantAssetBuilder.h>
  9. #include <Atom/RPI.Reflect/Shader/ShaderAsset.h>
  10. #include <Atom/RPI.Reflect/Shader/ShaderVariantAsset.h>
  11. #include <Atom/RPI.Reflect/Shader/ShaderVariantTreeAsset.h>
  12. #include <Atom/RPI.Reflect/Shader/ShaderOptionGroup.h>
  13. #include <Atom/RPI.Edit/Shader/ShaderVariantAssetCreator.h>
  14. #include <Atom/RPI.Edit/Shader/ShaderVariantTreeAssetCreator.h>
  15. #include <Atom/RPI.Edit/Common/JsonUtils.h>
  16. #include <AzCore/Serialization/Json/JsonUtils.h>
  17. #include <Atom/RPI.Reflect/Shader/ShaderVariantKey.h>
  18. #include <Atom/RHI.Edit/Utils.h>
  19. #include <Atom/RHI.Edit/ShaderPlatformInterface.h>
  20. #include <Atom/RPI.Edit/Common/JsonReportingHelper.h>
  21. #include <Atom/RPI.Edit/Common/AssetUtils.h>
  22. #include <Atom/RHI.Reflect/ConstantsLayout.h>
  23. #include <Atom/RHI.Reflect/PipelineLayoutDescriptor.h>
  24. #include <Atom/RHI.Reflect/ShaderStageFunction.h>
  25. #include <Atom/RHI/RHIUtils.h>
  26. #include <AzToolsFramework/API/EditorAssetSystemAPI.h>
  27. #include <AzToolsFramework/Debug/TraceContext.h>
  28. #include <AzFramework/API/ApplicationAPI.h>
  29. #include <AzFramework/IO/LocalFileIO.h>
  30. #include <AzFramework/Platform/PlatformDefaults.h>
  31. #include <AzFramework/Process/ProcessCommunicator.h>
  32. #include <AzFramework/Process/ProcessWatcher.h>
  33. #include <AzCore/Asset/AssetManager.h>
  34. #include <AzCore/JSON/document.h>
  35. #include <AzCore/IO/FileIO.h>
  36. #include <AzCore/IO/IOUtils.h>
  37. #include <AzCore/IO/SystemFile.h>
  38. #include <AzCore/std/algorithm.h>
  39. #include <AzCore/std/string/string.h>
  40. #include <AzCore/std/sort.h>
  41. #include <AzCore/std/time.h>
  42. #include <AzCore/Serialization/Json/JsonSerialization.h>
  43. #include <AzCore/StringFunc/StringFunc.h>
  44. #include "HashedVariantListSourceData.h"
  45. #include "ShaderAssetBuilder.h"
  46. #include "ShaderBuilderUtility.h"
  47. #include "SrgLayoutUtility.h"
  48. #include "AzslData.h"
  49. #include "AzslCompiler.h"
  50. #include <CommonFiles/Preprocessor.h>
  51. #include <ShaderPlatformInterfaceRequest.h>
  52. #include "ShaderBuildArgumentsManager.h"
  53. namespace AZ
  54. {
  55. namespace ShaderBuilder
  56. {
  57. static constexpr char ShaderVariantAssetBuilderName[] = "ShaderVariantAssetBuilder";
  58. AZStd::string ShaderVariantAssetBuilder::GetShaderVariantTreeAssetJobKey()
  59. {
  60. return AZStd::string::format("%s_varianttree", ShaderVariantAssetBuilderJobKeyPrefix);
  61. }
  62. AZStd::string ShaderVariantAssetBuilder::GetShaderVariantAssetJobKey()
  63. {
  64. return AZStd::string::format("%s_variant", ShaderVariantAssetBuilderJobKeyPrefix);
  65. }
  66. void ShaderVariantAssetBuilder::CreateJobs(const AssetBuilderSDK::CreateJobsRequest& request, AssetBuilderSDK::CreateJobsResponse& response) const
  67. {
  68. // Please see comments in the header file for the core principles of this builder.
  69. // Is this a *.hashedvariantlist? if so We need to create the ShaderVariantTreeAsset
  70. AZStd::string fileExtension;
  71. AzFramework::StringFunc::Path::GetExtension(request.m_sourceFile.c_str(), fileExtension, false /*includeDot*/);
  72. if (fileExtension == HashedVariantListSourceData::Extension)
  73. {
  74. CreateShaderVariantTreeJobs(request, response);
  75. return;
  76. }
  77. else if (fileExtension == HashedVariantInfoSourceData::Extension)
  78. {
  79. CreateShaderVariantJobs(request, response);
  80. return;
  81. }
  82. AZ_Error(ShaderVariantAssetBuilderName, false, "Unsupported file extension: %s", fileExtension.c_str());
  83. response.m_result = AssetBuilderSDK::CreateJobsResultCode::Failed;
  84. } // CreateJobs
  85. void ShaderVariantAssetBuilder::CreateShaderVariantTreeJobs(const AssetBuilderSDK::CreateJobsRequest& request, AssetBuilderSDK::CreateJobsResponse& response) const
  86. {
  87. AZStd::string variantListRelativePath(request.m_sourceFile.data());
  88. AZStd::string hashedVariantListFullPath;
  89. AZ::StringFunc::Path::ConstructFull(request.m_watchFolder.data(), request.m_sourceFile.data(), hashedVariantListFullPath, true);
  90. AZ_TracePrintf(ShaderVariantAssetBuilderName, "CreateShaderVariantTreeJob for Hashed Shader Variant List \"%s\"\n", hashedVariantListFullPath.data());
  91. HashedVariantListSourceData hashedVariantListDescriptor;
  92. if (!RPI::JsonUtils::LoadObjectFromFile(hashedVariantListFullPath, hashedVariantListDescriptor, AZStd::numeric_limits<size_t>::max()))
  93. {
  94. AZ_Assert(false, "Failed to parse Hashed Variant List Descriptor JSON [%s]", hashedVariantListFullPath.c_str());
  95. response.m_result = AssetBuilderSDK::CreateJobsResultCode::Failed;
  96. return;
  97. }
  98. for (const AssetBuilderSDK::PlatformInfo& info : request.m_enabledPlatforms)
  99. {
  100. AZ_TraceContext("For platform", info.m_identifier.data());
  101. AssetBuilderSDK::JobDescriptor jobDescriptor;
  102. // The ShaderVariantTreeAsset is high priority, but must be generated after the ShaderAsset
  103. jobDescriptor.m_priority = 1;
  104. jobDescriptor.m_critical = false;
  105. jobDescriptor.m_jobKey = GetShaderVariantTreeAssetJobKey();
  106. jobDescriptor.SetPlatformIdentifier(info.m_identifier.data());
  107. // Declare job dependency on the .azshader, this way the ShaderAsset must be built before
  108. // the ShaderVariantTreeAsset.
  109. AssetBuilderSDK::JobDependency jobDependency;
  110. jobDependency.m_jobKey = ShaderAssetBuilder::ShaderAssetBuilderJobKey;
  111. jobDependency.m_platformIdentifier = info.m_identifier;
  112. jobDependency.m_type = AssetBuilderSDK::JobDependencyType::Order;
  113. jobDependency.m_sourceFile.m_sourceFileDependencyPath = hashedVariantListDescriptor.m_shaderPath;
  114. jobDescriptor.m_jobDependencyList.push_back(jobDependency);
  115. response.m_createJobOutputs.push_back(jobDescriptor);
  116. }
  117. response.m_result = AssetBuilderSDK::CreateJobsResultCode::Success;
  118. }
  119. // For a file with the following name: <shaderName>_<StableId>.hashedvariantinfo
  120. // returns the absolute path that looks like: <shaderName>.hashedvariantlist
  121. static AZStd::string GetHashedVariantListPathFromVariantInfoPath(const AZStd::string& hashedVariantInfoParentPath, const AZStd::string& hashedVariantInfoRelativePath)
  122. {
  123. size_t charPos = AZ::StringFunc::Find(hashedVariantInfoRelativePath, "_", 0, true /* reverse*/);
  124. AZStd::string pathBefore_ = hashedVariantInfoRelativePath.substr(0, charPos);
  125. return AZStd::string::format("%s%s%s.%s", hashedVariantInfoParentPath.c_str(), AZ_CORRECT_FILESYSTEM_SEPARATOR_STRING, pathBefore_.c_str(), HashedVariantListSourceData::Extension);
  126. }
  127. void ShaderVariantAssetBuilder::CreateShaderVariantJobs([[maybe_unused]] const AssetBuilderSDK::CreateJobsRequest& request,
  128. [[maybe_unused]] AssetBuilderSDK::CreateJobsResponse& response) const
  129. {
  130. AZStd::string hashedVariantInfoRelativePath(request.m_sourceFile.data());
  131. AZStd::string hashedVariantInfoFullPath;
  132. AZ::StringFunc::Path::ConstructFull(request.m_watchFolder.data(), request.m_sourceFile.data(), hashedVariantInfoFullPath, true);
  133. AZ_TracePrintf(ShaderVariantAssetBuilderName, "CreateShaderVariantJobs for Hashed Variant Info [%s]\n", hashedVariantInfoFullPath.data());
  134. HashedVariantInfoSourceData hashedVariantInfoDescriptor;
  135. if (!RPI::JsonUtils::LoadObjectFromFile(hashedVariantInfoFullPath, hashedVariantInfoDescriptor, AZStd::numeric_limits<size_t>::max()))
  136. {
  137. AZ_Assert(false, "Failed to parse Hashed Variant Info Descriptor JSON [%s]", hashedVariantInfoFullPath.c_str());
  138. response.m_result = AssetBuilderSDK::CreateJobsResultCode::Failed;
  139. return;
  140. }
  141. AZStd::string hashedVariantInfoDescriptorString;
  142. RPI::JsonUtils::SaveObjectToJsonString(hashedVariantInfoDescriptor, hashedVariantInfoDescriptorString);
  143. AZStd::string hashedVariantInfoParentPath(request.m_watchFolder.data());
  144. AZStd::string hashedVariantListFullPath = GetHashedVariantListPathFromVariantInfoPath(hashedVariantInfoParentPath, hashedVariantInfoRelativePath);
  145. for (const AssetBuilderSDK::PlatformInfo& info : request.m_enabledPlatforms)
  146. {
  147. AZ_TraceContext("For platform", info.m_identifier.data());
  148. AssetBuilderSDK::JobDescriptor jobDescriptor;
  149. // There can be tens/hundreds of thousands of shader variants. By default each shader will get
  150. // a root variant that can be used at runtime. In order to prevent the AssetProcessor from
  151. // being overwhelmed by shader variant compilation We mark all non-root shader variant generation
  152. // as non critical and very low priority.
  153. jobDescriptor.m_priority = -5000;
  154. jobDescriptor.m_critical = false;
  155. jobDescriptor.m_jobKey = GetShaderVariantAssetJobKey();
  156. jobDescriptor.SetPlatformIdentifier(info.m_identifier.data());
  157. // Add the content of the hashedVariantInfo file as a parameter to avoid reading it again.
  158. jobDescriptor.m_jobParameters.emplace(ShaderVariantInfoJobParam, hashedVariantInfoDescriptorString);
  159. // The ShaderVariantAssets should be built AFTER the ShaderVariantTreeAsset.
  160. // With "OrderOnly" dependency, We make sure ShaderVariantTreeAsset completes before ShaderVariantAsset runs,
  161. // but don't re-run ShaderVariantAsset just because ShaderVariantTreeAsset ran.
  162. //
  163. AssetBuilderSDK::JobDependency variantTreeJobDependency;
  164. variantTreeJobDependency.m_jobKey = GetShaderVariantTreeAssetJobKey();
  165. variantTreeJobDependency.m_platformIdentifier = info.m_identifier;
  166. variantTreeJobDependency.m_sourceFile.m_sourceFileDependencyPath = hashedVariantListFullPath;
  167. variantTreeJobDependency.m_type = AssetBuilderSDK::JobDependencyType::OrderOnly;
  168. jobDescriptor.m_jobDependencyList.emplace_back(variantTreeJobDependency);
  169. // If the *.shader file changes, all the variants need to be rebuilt.
  170. AssetBuilderSDK::JobDependency shaderAssetJobDependency;
  171. shaderAssetJobDependency.m_jobKey = ShaderAssetBuilder::ShaderAssetBuilderJobKey;
  172. shaderAssetJobDependency.m_platformIdentifier = info.m_identifier;
  173. shaderAssetJobDependency.m_sourceFile.m_sourceFileDependencyPath = hashedVariantInfoDescriptor.m_shaderPath;
  174. shaderAssetJobDependency.m_type = AssetBuilderSDK::JobDependencyType::Order;
  175. jobDescriptor.m_jobDependencyList.emplace_back(shaderAssetJobDependency);
  176. response.m_createJobOutputs.push_back(jobDescriptor);
  177. }
  178. response.m_result = AssetBuilderSDK::CreateJobsResultCode::Success;
  179. }
  180. void ShaderVariantAssetBuilder::ProcessJob(const AssetBuilderSDK::ProcessJobRequest& request, AssetBuilderSDK::ProcessJobResponse& response) const
  181. {
  182. if (request.m_jobDescription.m_jobKey == GetShaderVariantTreeAssetJobKey())
  183. {
  184. ProcessShaderVariantTreeJob(request, response);
  185. }
  186. else
  187. {
  188. ProcessShaderVariantJob(request, response);
  189. }
  190. }
  191. static RPI::Ptr<RPI::ShaderOptionGroupLayout> LoadShaderOptionsGroupLayoutFromShaderAssetBuilder(
  192. const RHI::ShaderPlatformInterface* shaderPlatformInterface,
  193. const AssetBuilderSDK::PlatformInfo& platformInfo,
  194. const AzslCompiler& azslCompiler,
  195. const AZStd::string& shaderSourceFileFullPath,
  196. const RPI::SupervariantIndex supervariantIndex,
  197. bool& useSpecializationConstants)
  198. {
  199. auto optionsGroupPathOutcome = ShaderBuilderUtility::ObtainBuildArtifactPathFromShaderAssetBuilder(
  200. shaderPlatformInterface->GetAPIUniqueIndex(), platformInfo.m_identifier, shaderSourceFileFullPath, supervariantIndex.GetIndex(),
  201. AZ::RPI::ShaderAssetSubId::OptionsJson);
  202. if (!optionsGroupPathOutcome.IsSuccess())
  203. {
  204. AZ_Error(ShaderVariantAssetBuilderName, false, "%s", optionsGroupPathOutcome.GetError().c_str());
  205. return nullptr;
  206. }
  207. auto optionsGroupJsonPath = optionsGroupPathOutcome.TakeValue();
  208. RPI::Ptr<RPI::ShaderOptionGroupLayout> shaderOptionGroupLayout = RPI::ShaderOptionGroupLayout::Create();
  209. // The shader options define what options are available, what are the allowed values/range
  210. // for each option and what is its default value.
  211. auto jsonOutcome = JsonSerializationUtils::ReadJsonFile(optionsGroupJsonPath, AZ::RPI::JsonUtils::DefaultMaxFileSize);
  212. if (!jsonOutcome.IsSuccess())
  213. {
  214. AZ_Error(ShaderVariantAssetBuilderName, false, "%s", jsonOutcome.GetError().c_str());
  215. return nullptr;
  216. }
  217. if (!azslCompiler.ParseOptionsPopulateOptionGroupLayout(
  218. jsonOutcome.GetValue(), shaderOptionGroupLayout, useSpecializationConstants))
  219. {
  220. AZ_Error(ShaderVariantAssetBuilderName, false, "Failed to find a valid list of shader options!");
  221. return nullptr;
  222. }
  223. return shaderOptionGroupLayout;
  224. }
  225. static void LoadShaderFunctionsFromShaderAssetBuilder(
  226. const RHI::ShaderPlatformInterface* shaderPlatformInterface, const AssetBuilderSDK::PlatformInfo& platformInfo,
  227. const AzslCompiler& azslCompiler, const AZStd::string& shaderSourceFileFullPath,
  228. const RPI::SupervariantIndex supervariantIndex,
  229. AzslFunctions& functions)
  230. {
  231. auto functionsJsonPathOutcome = ShaderBuilderUtility::ObtainBuildArtifactPathFromShaderAssetBuilder(
  232. shaderPlatformInterface->GetAPIUniqueIndex(), platformInfo.m_identifier, shaderSourceFileFullPath, supervariantIndex.GetIndex(),
  233. AZ::RPI::ShaderAssetSubId::IaJson);
  234. if (!functionsJsonPathOutcome.IsSuccess())
  235. {
  236. AZ_Error(ShaderVariantAssetBuilderName, false, "%s", functionsJsonPathOutcome.GetError().c_str());
  237. return;
  238. }
  239. auto functionsJsonPath = functionsJsonPathOutcome.TakeValue();
  240. auto jsonOutcome = JsonSerializationUtils::ReadJsonFile(functionsJsonPath, AZ::RPI::JsonUtils::DefaultMaxFileSize);
  241. if (!jsonOutcome.IsSuccess())
  242. {
  243. AZ_Error(ShaderVariantAssetBuilderName, false, "%s", jsonOutcome.GetError().c_str());
  244. return;
  245. }
  246. if (!azslCompiler.ParseIaPopulateFunctionData(jsonOutcome.GetValue(), functions))
  247. {
  248. functions.clear();
  249. AZ_Error(ShaderVariantAssetBuilderName, false, "Failed to find shader functions.");
  250. return;
  251. }
  252. }
  253. static bool LoadSrgLayoutListFromShaderAssetBuilder(
  254. const RHI::ShaderPlatformInterface* shaderPlatformInterface,
  255. const AssetBuilderSDK::PlatformInfo& platformInfo,
  256. const AzslCompiler& azslCompiler, const AZStd::string& shaderSourceFileFullPath,
  257. const RPI::SupervariantIndex supervariantIndex,
  258. RPI::ShaderResourceGroupLayoutList& srgLayoutList,
  259. RootConstantData& rootConstantData)
  260. {
  261. auto srgJsonPathOutcome = ShaderBuilderUtility::ObtainBuildArtifactPathFromShaderAssetBuilder(
  262. shaderPlatformInterface->GetAPIUniqueIndex(), platformInfo.m_identifier, shaderSourceFileFullPath, supervariantIndex.GetIndex(), AZ::RPI::ShaderAssetSubId::SrgJson);
  263. if (!srgJsonPathOutcome.IsSuccess())
  264. {
  265. AZ_Error(ShaderVariantAssetBuilderName, false, "%s", srgJsonPathOutcome.GetError().c_str());
  266. return false;
  267. }
  268. auto srgJsonPath = srgJsonPathOutcome.TakeValue();
  269. auto jsonOutcome = JsonSerializationUtils::ReadJsonFile(srgJsonPath, AZ::RPI::JsonUtils::DefaultMaxFileSize);
  270. if (!jsonOutcome.IsSuccess())
  271. {
  272. AZ_Error(ShaderVariantAssetBuilderName, false, "%s", jsonOutcome.GetError().c_str());
  273. return false;
  274. }
  275. SrgDataContainer srgData;
  276. if (!azslCompiler.ParseSrgPopulateSrgData(jsonOutcome.GetValue(), srgData))
  277. {
  278. AZ_Error(ShaderVariantAssetBuilderName, false, "Failed to parse srg data");
  279. return false;
  280. }
  281. // Add all Shader Resource Group Assets that were defined in the shader code to the shader asset
  282. if (!SrgLayoutUtility::LoadShaderResourceGroupLayouts(ShaderVariantAssetBuilderName, srgData, srgLayoutList))
  283. {
  284. AZ_Error(ShaderVariantAssetBuilderName, false, "Failed to load ShaderResourceGroupLayouts");
  285. return false;
  286. }
  287. for (auto srgLayout : srgLayoutList)
  288. {
  289. if (!srgLayout->Finalize())
  290. {
  291. AZ_Error(ShaderVariantAssetBuilderName, false,
  292. "Failed to finalize SrgLayout %s", srgLayout->GetName().GetCStr());
  293. return false;
  294. }
  295. }
  296. // Access the root constants reflection
  297. if (!azslCompiler.ParseSrgPopulateRootConstantData(
  298. jsonOutcome.GetValue(),
  299. rootConstantData)) // consuming data from --srg ("RootConstantBuffer" subjson section)
  300. {
  301. AZ_Error(ShaderVariantAssetBuilderName, false, "Failed to obtain root constant data reflection");
  302. return false;
  303. }
  304. return true;
  305. }
  306. static bool LoadBindingDependenciesFromShaderAssetBuilder(
  307. const RHI::ShaderPlatformInterface* shaderPlatformInterface,
  308. const AssetBuilderSDK::PlatformInfo& platformInfo,
  309. const AzslCompiler& azslCompiler, const AZStd::string& shaderSourceFileFullPath,
  310. const RPI::SupervariantIndex supervariantIndex,
  311. BindingDependencies& bindingDependencies)
  312. {
  313. auto bindingsJsonPathOutcome = ShaderBuilderUtility::ObtainBuildArtifactPathFromShaderAssetBuilder(
  314. shaderPlatformInterface->GetAPIUniqueIndex(), platformInfo.m_identifier, shaderSourceFileFullPath, supervariantIndex.GetIndex(), AZ::RPI::ShaderAssetSubId::BindingdepJson);
  315. if (!bindingsJsonPathOutcome.IsSuccess())
  316. {
  317. AZ_Error(ShaderVariantAssetBuilderName, false, "%s", bindingsJsonPathOutcome.GetError().c_str());
  318. return false;
  319. }
  320. auto bindingsJsonPath = bindingsJsonPathOutcome.TakeValue();
  321. auto jsonOutcome = JsonSerializationUtils::ReadJsonFile(bindingsJsonPath, AZ::RPI::JsonUtils::DefaultMaxFileSize);
  322. if (!jsonOutcome.IsSuccess())
  323. {
  324. AZ_Error(ShaderVariantAssetBuilderName, false, "%s", jsonOutcome.GetError().c_str());
  325. return false;
  326. }
  327. if (!azslCompiler.ParseBindingdepPopulateBindingDependencies(jsonOutcome.GetValue(), bindingDependencies))
  328. {
  329. AZ_Error(ShaderVariantAssetBuilderName, false, "Failed to parse binding dependencies data");
  330. return false;
  331. }
  332. return true;
  333. }
  334. // Returns the content of the hlsl file for the given supervariant as produced by ShaderAsssetBuilder.
  335. // In addition to the content it also returns the full path of the hlsl file in @hlslSourcePath.
  336. static AZStd::string LoadHlslFileFromShaderAssetBuilder(
  337. const RHI::ShaderPlatformInterface* shaderPlatformInterface, const AssetBuilderSDK::PlatformInfo& platformInfo,
  338. const AZStd::string& shaderSourceFileFullPath, const RPI::SupervariantIndex supervariantIndex, AZStd::string& hlslSourcePath)
  339. {
  340. auto hlslSourcePathOutcome = ShaderBuilderUtility::ObtainBuildArtifactPathFromShaderAssetBuilder(
  341. shaderPlatformInterface->GetAPIUniqueIndex(), platformInfo.m_identifier, shaderSourceFileFullPath, supervariantIndex.GetIndex(),
  342. AZ::RPI::ShaderAssetSubId::GeneratedHlslSource);
  343. if (!hlslSourcePathOutcome.IsSuccess())
  344. {
  345. AZ_Error(ShaderVariantAssetBuilderName, false, "%s", hlslSourcePathOutcome.GetError().c_str());
  346. return "";
  347. }
  348. hlslSourcePath = hlslSourcePathOutcome.TakeValue();
  349. Outcome<AZStd::string, AZStd::string> hlslSourceOutcome = Utils::ReadFile(hlslSourcePath, AZ::RPI::JsonUtils::DefaultMaxFileSize);
  350. if (!hlslSourceOutcome.IsSuccess())
  351. {
  352. AZ_Error(
  353. ShaderVariantAssetBuilderName, false, "Failed to obtain shader source from %s. [%s]", hlslSourcePath.c_str(),
  354. hlslSourceOutcome.TakeError().c_str());
  355. return "";
  356. }
  357. return hlslSourceOutcome.TakeValue();
  358. }
  359. void ShaderVariantAssetBuilder::ProcessShaderVariantTreeJob(const AssetBuilderSDK::ProcessJobRequest& request, AssetBuilderSDK::ProcessJobResponse& response) const
  360. {
  361. AssetBuilderSDK::JobCancelListener jobCancelListener(request.m_jobId);
  362. if (jobCancelListener.IsCancelled())
  363. {
  364. response.m_resultCode = AssetBuilderSDK::ProcessJobResult_Cancelled;
  365. return;
  366. }
  367. AZStd::string hashedVariantListFullPath;
  368. AZ::StringFunc::Path::ConstructFull(request.m_watchFolder.data(), request.m_sourceFile.data(), hashedVariantListFullPath, true);
  369. HashedVariantListSourceData hashedVariantListDescriptor;
  370. if (!RPI::JsonUtils::LoadObjectFromFile(hashedVariantListFullPath, hashedVariantListDescriptor, AZStd::numeric_limits<size_t>::max()))
  371. {
  372. AZ_Error(ShaderVariantAssetBuilderName, false, "Failed to parse Hashed Variant List Descriptor JSON [%s]", hashedVariantListFullPath.c_str());
  373. response.m_resultCode = AssetBuilderSDK::ProcessJobResult_Failed;
  374. return;
  375. }
  376. const AZStd::string& shaderSourceFileFullPath = hashedVariantListDescriptor.m_shaderPath;
  377. AZStd::string shaderName;
  378. AZ::StringFunc::Path::GetFileName(shaderSourceFileFullPath.c_str(), shaderName);
  379. auto descriptorParseOutcome = ShaderBuilderUtility::LoadShaderDataJson(shaderSourceFileFullPath);
  380. if (!descriptorParseOutcome.IsSuccess())
  381. {
  382. AZ_Error(ShaderVariantAssetBuilderName, false, "Failed to parse shader file [%s]", shaderSourceFileFullPath.c_str());
  383. response.m_resultCode = AssetBuilderSDK::ProcessJobResult_Failed;
  384. return;
  385. }
  386. RPI::ShaderSourceData shaderSourceDescriptor = descriptorParseOutcome.TakeValue();
  387. RPI::Ptr<RPI::ShaderOptionGroupLayout> shaderOptionGroupLayout;
  388. // Request the list of valid shader platform interfaces for the target platform.
  389. AZStd::vector<RHI::ShaderPlatformInterface*> platformInterfaces =
  390. ShaderBuilderUtility::DiscoverEnabledShaderPlatformInterfaces(request.m_platformInfo, shaderSourceDescriptor);
  391. if (platformInterfaces.empty())
  392. {
  393. // No work to do. Exit gracefully.
  394. AZ_TracePrintf(
  395. ShaderVariantAssetBuilderName,
  396. "No azshadervarianttree is produced on behalf of %s because all valid RHI backends were disabled for this shader.\n",
  397. shaderSourceFileFullPath.c_str());
  398. response.m_resultCode = AssetBuilderSDK::ProcessJobResult_Success;
  399. return;
  400. }
  401. // set the input file for eventual error messages, but the compiler won't be called on it.
  402. AZStd::string azslFullPath;
  403. ShaderBuilderUtility::GetAbsolutePathToAzslFile(shaderSourceFileFullPath, shaderSourceDescriptor.m_source, azslFullPath);
  404. AzslCompiler azslc(azslFullPath, request.m_tempDirPath);
  405. auto supervariantList = ShaderBuilderUtility::GetSupervariantListFromShaderSourceData(shaderSourceDescriptor);
  406. AZStd::string previousLoopApiName;
  407. bool usesVariants = false;
  408. for (RHI::ShaderPlatformInterface* shaderPlatformInterface : platformInterfaces)
  409. {
  410. auto thisLoopApiName = shaderPlatformInterface->GetAPIName().GetStringView();
  411. for (uint32_t supervariantIndexCounter = 0; supervariantIndexCounter < supervariantList.size(); ++supervariantIndexCounter)
  412. {
  413. RPI::SupervariantIndex supervariantIndex(supervariantIndexCounter);
  414. bool usesSpecialization = false;
  415. RPI::Ptr<RPI::ShaderOptionGroupLayout> loopLocal_ShaderOptionGroupLayout =
  416. LoadShaderOptionsGroupLayoutFromShaderAssetBuilder(
  417. shaderPlatformInterface,
  418. request.m_platformInfo,
  419. azslc,
  420. shaderSourceFileFullPath,
  421. supervariantIndex,
  422. usesSpecialization);
  423. if (!loopLocal_ShaderOptionGroupLayout)
  424. {
  425. response.m_resultCode = AssetBuilderSDK::ProcessJobResult_Failed;
  426. return;
  427. }
  428. if (shaderOptionGroupLayout && shaderOptionGroupLayout->GetHash() != loopLocal_ShaderOptionGroupLayout->GetHash())
  429. {
  430. AZ_Error(
  431. ShaderVariantAssetBuilderName,
  432. false,
  433. "There was a discrepancy in shader options between %s and %s",
  434. previousLoopApiName.c_str(),
  435. thisLoopApiName.data());
  436. response.m_resultCode = AssetBuilderSDK::ProcessJobResult_Failed;
  437. return;
  438. }
  439. // Check if there's a supervariant that needs to generate the variants
  440. if (!usesSpecialization || !loopLocal_ShaderOptionGroupLayout->IsFullySpecialized())
  441. {
  442. usesVariants = true;
  443. }
  444. shaderOptionGroupLayout = loopLocal_ShaderOptionGroupLayout;
  445. }
  446. previousLoopApiName = thisLoopApiName;
  447. }
  448. if (!usesVariants)
  449. {
  450. // No need to create the variant tree since all supervariants are fully specialized. Exit gracefully.
  451. AZ_TracePrintf(
  452. ShaderVariantAssetBuilderName,
  453. "No azshadervarianttree is produced on behalf of %s because all valid RHI backends are using specialization constants for shader options.\n",
  454. shaderSourceFileFullPath.c_str());
  455. response.m_resultCode = AssetBuilderSDK::ProcessJobResult_Success;
  456. return;
  457. }
  458. AZStd::vector<RPI::ShaderVariantListSourceData::VariantInfo> variantInfos;
  459. variantInfos.reserve(hashedVariantListDescriptor.m_hashedVariants.size());
  460. for (const auto& hashedVariantInfo : hashedVariantListDescriptor.m_hashedVariants)
  461. {
  462. variantInfos.push_back(hashedVariantInfo.m_variantInfo);
  463. }
  464. RPI::ShaderVariantTreeAssetCreator shaderVariantTreeAssetCreator;
  465. shaderVariantTreeAssetCreator.Begin(Uuid::CreateRandom());
  466. shaderVariantTreeAssetCreator.SetShaderOptionGroupLayout(*shaderOptionGroupLayout);
  467. shaderVariantTreeAssetCreator.SetVariantInfos(variantInfos);
  468. Data::Asset<RPI::ShaderVariantTreeAsset> shaderVariantTreeAsset;
  469. if (!shaderVariantTreeAssetCreator.End(shaderVariantTreeAsset))
  470. {
  471. AZ_Error(ShaderVariantAssetBuilderName, false, "Failed to build Shader Variant Tree Asset");
  472. response.m_resultCode = AssetBuilderSDK::ProcessJobResult_Failed;
  473. return;
  474. }
  475. AZStd::string filename = AZStd::string::format("%s.%s", shaderName.c_str(), RPI::ShaderVariantTreeAsset::Extension);
  476. AZStd::string assetPath;
  477. AZ::StringFunc::Path::ConstructFull(request.m_tempDirPath.c_str(), filename.c_str(), assetPath, true);
  478. if (!AZ::Utils::SaveObjectToFile(assetPath, AZ::DataStream::ST_BINARY, shaderVariantTreeAsset.Get()))
  479. {
  480. AZ_Error(ShaderVariantAssetBuilderName, false, "Failed to save Shader Variant Tree Asset to \"%s\"", assetPath.c_str());
  481. response.m_resultCode = AssetBuilderSDK::ProcessJobResult_Failed;
  482. return;
  483. }
  484. AssetBuilderSDK::JobProduct assetProduct;
  485. assetProduct.m_productSubID = RPI::ShaderVariantTreeAsset::ProductSubID;
  486. assetProduct.m_productFileName = assetPath;
  487. assetProduct.m_productAssetType = azrtti_typeid<RPI::ShaderVariantTreeAsset>();
  488. assetProduct.m_dependenciesHandled = true; // This builder has no dependencies to output
  489. response.m_outputProducts.push_back(assetProduct);
  490. AZ_TracePrintf(ShaderVariantAssetBuilderName, "Shader Variant Tree Asset [%s] compiled successfully.\n", assetPath.c_str());
  491. response.m_resultCode = AssetBuilderSDK::ProcessJobResult_Success;
  492. }
  493. void ShaderVariantAssetBuilder::ProcessShaderVariantJob(const AssetBuilderSDK::ProcessJobRequest& request, AssetBuilderSDK::ProcessJobResponse& response) const
  494. {
  495. AssetBuilderSDK::JobCancelListener jobCancelListener(request.m_jobId);
  496. AZStd::string hashedVariantInfoFullPath;
  497. AZ::StringFunc::Path::ConstructFull(request.m_watchFolder.data(), request.m_sourceFile.data(), hashedVariantInfoFullPath, true);
  498. AZStd::string hashedVariantInfoDescriptorString;
  499. if (!request.m_jobDescription.m_jobParameters.contains(ShaderVariantInfoJobParam))
  500. {
  501. AZ_Error(ShaderVariantAssetBuilderName, false, "Missing job Parameter: ShaderVariantInfoJobParam");
  502. response.m_resultCode = AssetBuilderSDK::ProcessJobResult_Failed;
  503. return;
  504. }
  505. hashedVariantInfoDescriptorString = request.m_jobDescription.m_jobParameters.at(ShaderVariantInfoJobParam);
  506. HashedVariantInfoSourceData hashedVariantInfoDescriptor;
  507. if (!RPI::JsonUtils::LoadObjectFromJsonString(hashedVariantInfoDescriptorString, hashedVariantInfoDescriptor))
  508. {
  509. AZ_Assert(false, "Failed to parse Hashed Variant Info Descriptor JSON [%s]", hashedVariantInfoFullPath.c_str());
  510. response.m_resultCode = AssetBuilderSDK::ProcessJobResult_Failed;
  511. return;
  512. }
  513. const RPI::ShaderVariantListSourceData::VariantInfo& variantInfo = hashedVariantInfoDescriptor.m_variantInfo;
  514. const AZStd::string& shaderSourceFileFullPath = hashedVariantInfoDescriptor.m_shaderPath;
  515. AZStd::string shaderFileName;
  516. AZ::StringFunc::Path::GetFileName(shaderSourceFileFullPath.c_str(), shaderFileName);
  517. RPI::ShaderSourceData shaderSourceDescriptor;
  518. AZStd::shared_ptr<ShaderFiles> sources = ShaderBuilderUtility::PrepareSourceInput(ShaderVariantAssetBuilderName, shaderSourceFileFullPath, shaderSourceDescriptor);
  519. // set the input file for eventual error messages, but the compiler won't be called on it.
  520. AzslCompiler azslc(sources->m_azslSourceFullPath, request.m_tempDirPath);
  521. // Request the list of valid shader platform interfaces for the target platform.
  522. AZStd::vector<RHI::ShaderPlatformInterface*> platformInterfaces =
  523. ShaderBuilderUtility::DiscoverEnabledShaderPlatformInterfaces(request.m_platformInfo, shaderSourceDescriptor);
  524. if (platformInterfaces.empty())
  525. {
  526. // No work to do. Exit gracefully.
  527. AZ_TracePrintf(ShaderVariantAssetBuilderName,
  528. "No azshader is produced on behalf of %s because all valid RHI backends were disabled for this shader.\n",
  529. shaderSourceFileFullPath.c_str());
  530. response.m_resultCode = AssetBuilderSDK::ProcessJobResult_Success;
  531. return;
  532. }
  533. auto supervariantList = ShaderBuilderUtility::GetSupervariantListFromShaderSourceData(shaderSourceDescriptor);
  534. ShaderBuildArgumentsManager buildArgsManager;
  535. buildArgsManager.Init();
  536. // A job always runs on behalf of an Asset Processing platform (aka PlatformInfo).
  537. // Let's merge the shader build arguments of the current PlatformInfo with the global
  538. // set of arguments.
  539. const auto platformName = ShaderBuilderUtility::GetPlatformNameFromPlatformInfo(request.m_platformInfo);
  540. buildArgsManager.PushArgumentScope(platformName);
  541. //! The ShaderOptionGroupLayout is common across all RHIs & Supervariants
  542. RPI::Ptr<RPI::ShaderOptionGroupLayout> shaderOptionGroupLayout = nullptr;
  543. // Generate shaders for each of those ShaderPlatformInterfaces.
  544. for (RHI::ShaderPlatformInterface* shaderPlatformInterface : platformInterfaces)
  545. {
  546. AZStd::string apiName(shaderPlatformInterface->GetAPIName().GetCStr());
  547. AZ_TraceContext("Platform API", apiName);
  548. buildArgsManager.PushArgumentScope(apiName);
  549. buildArgsManager.PushArgumentScope(
  550. shaderSourceDescriptor.m_removeBuildArguments,
  551. shaderSourceDescriptor.m_addBuildArguments,
  552. shaderSourceDescriptor.m_definitions);
  553. // Loop through all the Supervariants.
  554. for (uint32_t supervariantIndexCounter = 0;
  555. supervariantIndexCounter < supervariantList.size();
  556. ++supervariantIndexCounter)
  557. {
  558. const auto& supervariantInfo = supervariantList[supervariantIndexCounter];
  559. RPI::SupervariantIndex supervariantIndex(supervariantIndexCounter);
  560. // Check if we were canceled before we do any heavy processing of
  561. // the shader variant data.
  562. if (jobCancelListener.IsCancelled())
  563. {
  564. response.m_resultCode = AssetBuilderSDK::ProcessJobResult_Cancelled;
  565. return;
  566. }
  567. buildArgsManager.PushArgumentScope(
  568. supervariantInfo.m_removeBuildArguments, supervariantInfo.m_addBuildArguments, supervariantInfo.m_definitions);
  569. AZStd::string shaderStemNamePrefix = shaderFileName;
  570. if (supervariantIndex.GetIndex() > 0)
  571. {
  572. shaderStemNamePrefix += AZStd::string::format("-%s", supervariantInfo.m_name.GetCStr());
  573. }
  574. // We need these additional pieces of information To build a shader variant asset:
  575. // 1- ShaderOptionsGroupLayout (Need to load it once, because it's the same acrosss all supervariants + RHIs)
  576. // 2- entryFunctions
  577. // 3- hlsl code.
  578. // 1- ShaderOptionsGroupLayout
  579. // The ShaderOptionsGroupLayout is the same for all platforms and supervariants, but the each supervariant
  580. // can have the use of specialization constants on or off.
  581. bool usesSpecializationConstants = false;
  582. shaderOptionGroupLayout = LoadShaderOptionsGroupLayoutFromShaderAssetBuilder(
  583. shaderPlatformInterface,
  584. request.m_platformInfo,
  585. azslc,
  586. shaderSourceFileFullPath,
  587. supervariantIndex,
  588. usesSpecializationConstants);
  589. if (!shaderOptionGroupLayout)
  590. {
  591. response.m_resultCode = AssetBuilderSDK::ProcessJobResult_Failed;
  592. return;
  593. }
  594. if (usesSpecializationConstants && shaderOptionGroupLayout->IsFullySpecialized())
  595. {
  596. // No need to create the shader variants since all supervariants are fully specialized.
  597. AZ_TracePrintf(
  598. ShaderVariantAssetBuilderName,
  599. "No azshaderVariant is produced on behalf of %s, super variant %s, because it's using specialization "
  600. "constants "
  601. "for shader options.\n",
  602. shaderSourceFileFullPath.c_str(),
  603. supervariantInfo.m_name.GetCStr());
  604. buildArgsManager.PopArgumentScope();
  605. continue;
  606. }
  607. // 2- entryFunctions.
  608. AzslFunctions azslFunctions;
  609. LoadShaderFunctionsFromShaderAssetBuilder(
  610. shaderPlatformInterface, request.m_platformInfo, azslc, shaderSourceFileFullPath, supervariantIndex, azslFunctions);
  611. if (azslFunctions.empty())
  612. {
  613. response.m_resultCode = AssetBuilderSDK::ProcessJobResult_Failed;
  614. return;
  615. }
  616. MapOfStringToStageType shaderEntryPoints;
  617. if (shaderSourceDescriptor.m_programSettings.m_entryPoints.empty())
  618. {
  619. AZ_Error(ShaderVariantAssetBuilderName, false, "ProgramSettings must specify entry points.");
  620. response.m_resultCode = AssetBuilderSDK::ProcessJobResult_Failed;
  621. return;
  622. }
  623. for (const auto& entryPoint : shaderSourceDescriptor.m_programSettings.m_entryPoints)
  624. {
  625. shaderEntryPoints[entryPoint.m_name] = entryPoint.m_type;
  626. }
  627. // 3- hlslCode
  628. AZStd::string hlslSourcePath;
  629. AZStd::string hlslCode = LoadHlslFileFromShaderAssetBuilder(
  630. shaderPlatformInterface, request.m_platformInfo, shaderSourceFileFullPath, supervariantIndex, hlslSourcePath);
  631. if (hlslCode.empty() || hlslSourcePath.empty())
  632. {
  633. response.m_resultCode = AssetBuilderSDK::ProcessJobResult_Failed;
  634. return;
  635. }
  636. //! It is important to keep this refcounted pointer outside of the if block to prevent it from being destroyed.
  637. RHI::Ptr<RHI::PipelineLayoutDescriptor> pipelineLayoutDescriptor;
  638. if (shaderPlatformInterface->VariantCompilationRequiresSrgLayoutData())
  639. {
  640. RPI::ShaderResourceGroupLayoutList srgLayoutList;
  641. RootConstantData rootConstantData;
  642. if (!LoadSrgLayoutListFromShaderAssetBuilder(
  643. shaderPlatformInterface, request.m_platformInfo, azslc, shaderSourceFileFullPath, supervariantIndex,
  644. srgLayoutList, rootConstantData))
  645. {
  646. response.m_resultCode = AssetBuilderSDK::ProcessJobResult_Failed;
  647. return;
  648. }
  649. BindingDependencies bindingDependencies;
  650. if (!LoadBindingDependenciesFromShaderAssetBuilder(
  651. shaderPlatformInterface, request.m_platformInfo, azslc, shaderSourceFileFullPath, supervariantIndex,
  652. bindingDependencies))
  653. {
  654. response.m_resultCode = AssetBuilderSDK::ProcessJobResult_Failed;
  655. return;
  656. }
  657. pipelineLayoutDescriptor =
  658. ShaderBuilderUtility::BuildPipelineLayoutDescriptorForApi(
  659. ShaderVariantAssetBuilderName, srgLayoutList, shaderEntryPoints, buildArgsManager.GetCurrentArguments(), rootConstantData,
  660. shaderPlatformInterface, bindingDependencies);
  661. if (!pipelineLayoutDescriptor)
  662. {
  663. AZ_Error(
  664. ShaderVariantAssetBuilderName, false, "Failed to build pipeline layout descriptor for api=[%s]",
  665. shaderPlatformInterface->GetAPIName().GetCStr());
  666. response.m_resultCode = AssetBuilderSDK::ProcessJobResult_Failed;
  667. return;
  668. }
  669. }
  670. // Setup the shader variant creation context:
  671. ShaderVariantCreationContext shaderVariantCreationContext = { *shaderPlatformInterface,
  672. request.m_platformInfo,
  673. buildArgsManager.GetCurrentArguments(),
  674. request.m_tempDirPath,
  675. shaderSourceDescriptor,
  676. *shaderOptionGroupLayout.get(),
  677. shaderEntryPoints,
  678. Uuid::CreateRandom(),
  679. shaderStemNamePrefix,
  680. hlslSourcePath,
  681. hlslCode,
  682. usesSpecializationConstants };
  683. // Preserve the Temp folder when shaders are compiled with debug symbols
  684. // or because the ShaderSourceData has m_keepTempFolder set to true.
  685. response.m_keepTempFolder |= shaderVariantCreationContext.m_shaderBuildArguments.m_generateDebugInfo
  686. || shaderSourceDescriptor.m_keepTempFolder || RHI::IsGraphicsDevModeEnabled();
  687. AZStd::optional<RHI::ShaderPlatformInterface::ByProducts> outputByproducts;
  688. auto shaderVariantAssetOutcome = CreateShaderVariantAsset(variantInfo, shaderVariantCreationContext, outputByproducts);
  689. if (!shaderVariantAssetOutcome.IsSuccess())
  690. {
  691. AZ_Error(ShaderVariantAssetBuilderName, false, "%s\n", shaderVariantAssetOutcome.GetError().c_str());
  692. response.m_resultCode = AssetBuilderSDK::ProcessJobResult_Failed;
  693. return;
  694. }
  695. Data::Asset<RPI::ShaderVariantAsset> shaderVariantAsset = shaderVariantAssetOutcome.TakeValue();
  696. // Time to save the asset in the tmp folder so it ends up in the Cache folder.
  697. const uint32_t productSubID = RPI::ShaderVariantAsset::MakeAssetProductSubId(
  698. shaderPlatformInterface->GetAPIUniqueIndex(), supervariantIndex.GetIndex(),
  699. shaderVariantAsset->GetStableId());
  700. AssetBuilderSDK::JobProduct assetProduct;
  701. if (!SerializeOutShaderVariantAsset(shaderVariantAsset, shaderStemNamePrefix,
  702. request.m_tempDirPath, *shaderPlatformInterface, productSubID,
  703. assetProduct))
  704. {
  705. response.m_resultCode = AssetBuilderSDK::ProcessJobResult_Failed;
  706. return;
  707. }
  708. response.m_outputProducts.push_back(assetProduct);
  709. if (outputByproducts)
  710. {
  711. // add byproducts as job output products:
  712. uint32_t subProductType = RPI::ShaderVariantAsset::ShaderVariantAssetSubProductType;
  713. for (const AZStd::string& byproduct : outputByproducts.value().m_intermediatePaths)
  714. {
  715. AssetBuilderSDK::JobProduct jobProduct;
  716. jobProduct.m_productFileName = byproduct;
  717. jobProduct.m_productAssetType = Uuid::CreateName("DebugInfoByProduct-PdbOrDxilTxt");
  718. jobProduct.m_productSubID = RPI::ShaderVariantAsset::MakeAssetProductSubId(
  719. shaderPlatformInterface->GetAPIUniqueIndex(), supervariantIndex.GetIndex(), shaderVariantAsset->GetStableId(),
  720. subProductType++);
  721. response.m_outputProducts.push_back(AZStd::move(jobProduct));
  722. }
  723. }
  724. buildArgsManager.PopArgumentScope(); // Pop the supervariant build arguments.
  725. } // End of supervariant for block
  726. buildArgsManager.PopArgumentScope(); // Pop the .shader build arguments.
  727. buildArgsManager.PopArgumentScope(); // Pop the RHI build arguments.
  728. }
  729. response.m_resultCode = AssetBuilderSDK::ProcessJobResult_Success;
  730. }
  731. bool ShaderVariantAssetBuilder::SerializeOutShaderVariantAsset(
  732. const Data::Asset<RPI::ShaderVariantAsset> shaderVariantAsset, const AZStd::string& shaderStemNamePrefix,
  733. const AZStd::string& tempDirPath,
  734. const RHI::ShaderPlatformInterface& shaderPlatformInterface, const uint32_t productSubID, AssetBuilderSDK::JobProduct& assetProduct)
  735. {
  736. AZStd::string filename = AZStd::string::format(
  737. "%s_%s_%u.%s", shaderStemNamePrefix.c_str(), shaderPlatformInterface.GetAPIName().GetCStr(),
  738. shaderVariantAsset->GetStableId().GetIndex(), RPI::ShaderVariantAsset::Extension);
  739. AZStd::string assetPath;
  740. AZ::StringFunc::Path::ConstructFull(tempDirPath.c_str(), filename.c_str(), assetPath, true);
  741. if (!AZ::Utils::SaveObjectToFile(assetPath, AZ::DataStream::ST_BINARY, shaderVariantAsset.Get()))
  742. {
  743. AZ_Error(ShaderVariantAssetBuilderName, false, "Failed to save Shader Variant Asset to \"%s\"", assetPath.c_str());
  744. return false;
  745. }
  746. assetProduct.m_productSubID = productSubID;
  747. assetProduct.m_productFileName = assetPath;
  748. assetProduct.m_productAssetType = azrtti_typeid<RPI::ShaderVariantAsset>();
  749. assetProduct.m_dependenciesHandled = true; // This builder has no dependencies to output
  750. AZ_TracePrintf(ShaderVariantAssetBuilderName, "Shader Variant Asset [%s] compiled successfully.\n", assetPath.c_str());
  751. return true;
  752. }
  753. AZ::Outcome<Data::Asset<RPI::ShaderVariantAsset>, AZStd::string> ShaderVariantAssetBuilder::CreateShaderVariantAsset(
  754. const RPI::ShaderVariantListSourceData::VariantInfo& shaderVariantInfo,
  755. ShaderVariantCreationContext& creationContext,
  756. AZStd::optional<RHI::ShaderPlatformInterface::ByProducts>& outputByproducts)
  757. {
  758. // Temporary structure used for sorting and caching intermediate results
  759. struct OptionCache
  760. {
  761. AZ::Name m_optionName;
  762. AZ::Name m_valueName;
  763. RPI::ShaderOptionIndex m_optionIndex; // Cached m_optionName
  764. RPI::ShaderOptionValue m_value; // Cached m_valueName
  765. };
  766. AZStd::vector<OptionCache> optionList;
  767. // We can not have more options than the number of options in the layout:
  768. optionList.reserve(creationContext.m_shaderOptionGroupLayout.GetShaderOptionCount());
  769. // This loop will validate and cache the indices for each option value:
  770. for (const auto& shaderOption : shaderVariantInfo.m_options)
  771. {
  772. Name optionName{shaderOption.first};
  773. Name optionValue{shaderOption.second};
  774. RPI::ShaderOptionIndex optionIndex = creationContext.m_shaderOptionGroupLayout.FindShaderOptionIndex(optionName);
  775. if (optionIndex.IsNull())
  776. {
  777. return AZ::Failure(AZStd::string::format("Invalid shader option: %s", optionName.GetCStr()));
  778. }
  779. const RPI::ShaderOptionDescriptor& option = creationContext.m_shaderOptionGroupLayout.GetShaderOption(optionIndex);
  780. RPI::ShaderOptionValue value = option.FindValue(optionValue);
  781. if (value.IsNull())
  782. {
  783. return AZ::Failure(
  784. AZStd::string::format("Invalid value (%s) for shader option: %s", optionValue.GetCStr(), optionName.GetCStr()));
  785. }
  786. optionList.push_back(OptionCache{optionName, optionValue, optionIndex, value});
  787. }
  788. // Create one instance of the shader variant
  789. RPI::ShaderOptionGroup optionGroup(&creationContext.m_shaderOptionGroupLayout);
  790. //! Contains the series of #define macro values that define a variant. Can be empty (root variant).
  791. //! If this string is NOT empty, a new temporary hlsl file will be created that will be the combination
  792. //! of this string + @m_hlslSourceContent.
  793. AZStd::string hlslCodeToPrependForVariant;
  794. // We want to go over all options listed in the variant and set their respective values
  795. // This loop will populate the optionGroup and m_shaderCodePrefix in order of the option priority
  796. for (const auto& optionCache : optionList)
  797. {
  798. const RPI::ShaderOptionDescriptor& option = creationContext.m_shaderOptionGroupLayout.GetShaderOption(optionCache.m_optionIndex);
  799. // Assign the option value specified in the variant:
  800. option.Set(optionGroup, optionCache.m_value);
  801. // Populate all shader option defines. We have already confirmed they're valid.
  802. hlslCodeToPrependForVariant += AZStd::string::format(
  803. "#define %s_OPTION_DEF %s\n", optionCache.m_optionName.GetCStr(), optionCache.m_valueName.GetCStr());
  804. }
  805. AZStd::string variantShaderSourcePath;
  806. // Check if we need to prepend any code prefix
  807. if (!hlslCodeToPrependForVariant.empty())
  808. {
  809. // Prepend any shader code prefix that we should apply to this variant
  810. // and save it back to a file.
  811. AZStd::string variantShaderSourceString(hlslCodeToPrependForVariant);
  812. variantShaderSourceString += creationContext.m_hlslSourceContent;
  813. AZStd::string shaderAssetName = AZStd::string::format(
  814. "%s_%s_%u.hlsl", creationContext.m_shaderStemNamePrefix.c_str(),
  815. creationContext.m_shaderPlatformInterface.GetAPIName().GetCStr(), shaderVariantInfo.m_stableId);
  816. AZ::StringFunc::Path::Join(
  817. creationContext.m_tempDirPath.c_str(), shaderAssetName.c_str(), variantShaderSourcePath, true, true);
  818. auto outcome = Utils::WriteFile(variantShaderSourceString, variantShaderSourcePath);
  819. if (!outcome.IsSuccess())
  820. {
  821. return AZ::Failure(AZStd::string::format("Failed to create file %s", variantShaderSourcePath.c_str()));
  822. }
  823. }
  824. else
  825. {
  826. variantShaderSourcePath = creationContext.m_hlslSourcePath;
  827. }
  828. AZ_TracePrintf(ShaderVariantAssetBuilderName, "Variant StableId: %u", shaderVariantInfo.m_stableId);
  829. AZ_TracePrintf(ShaderVariantAssetBuilderName, "Variant Shader Options: %s", optionGroup.ToString().c_str());
  830. const RPI::ShaderVariantStableId shaderVariantStableId{shaderVariantInfo.m_stableId};
  831. // By this time the optionGroup was populated with all option values for the variant and
  832. // the m_shaderCodePrefix contains all option related preprocessing macros
  833. // Let's add the requested variant:
  834. RPI::ShaderVariantAssetCreator variantCreator;
  835. RPI::ShaderOptionGroup shaderOptions{&creationContext.m_shaderOptionGroupLayout, optionGroup.GetShaderVariantId()};
  836. variantCreator.Begin(
  837. creationContext.m_shaderVariantAssetId, optionGroup.GetShaderVariantId(), shaderVariantStableId,
  838. shaderOptions.IsFullySpecified());
  839. const AZStd::unordered_map<AZStd::string, RPI::ShaderStageType>& shaderEntryPoints = creationContext.m_shaderEntryPoints;
  840. for (const auto& shaderEntryPoint : shaderEntryPoints)
  841. {
  842. auto shaderEntryName = shaderEntryPoint.first;
  843. auto shaderStageType = shaderEntryPoint.second;
  844. AZ_TracePrintf(ShaderVariantAssetBuilderName, "Entry Point: %s", shaderEntryName.c_str());
  845. AZ_TracePrintf(ShaderVariantAssetBuilderName, "Begin compiling shader function \"%s\"", shaderEntryName.c_str());
  846. auto assetBuilderShaderType = ShaderBuilderUtility::ToAssetBuilderShaderType(shaderStageType);
  847. // Compile HLSL to the platform specific shader.
  848. RHI::ShaderPlatformInterface::StageDescriptor descriptor;
  849. bool shaderWasCompiled = creationContext.m_shaderPlatformInterface.CompilePlatformInternal(
  850. creationContext.m_platformInfo, variantShaderSourcePath, shaderEntryName, assetBuilderShaderType,
  851. creationContext.m_tempDirPath,
  852. descriptor,
  853. creationContext.m_shaderBuildArguments,
  854. creationContext.m_useSpecializationConstants);
  855. if (!shaderWasCompiled)
  856. {
  857. return AZ::Failure(AZStd::string::format("Could not compile the shader function %s", shaderEntryName.c_str()));
  858. }
  859. // bubble up the byproducts to the caller by moving them to the context.
  860. outputByproducts.emplace(AZStd::move(descriptor.m_byProducts));
  861. RHI::Ptr<RHI::ShaderStageFunction> shaderStageFunction = creationContext.m_shaderPlatformInterface.CreateShaderStageFunction(descriptor);
  862. variantCreator.SetShaderFunction(ToRHIShaderStage(assetBuilderShaderType), shaderStageFunction);
  863. if (descriptor.m_byProducts.m_dynamicBranchCount != AZ::RHI::ShaderPlatformInterface::ByProducts::UnknownDynamicBranchCount)
  864. {
  865. AZ_TracePrintf(
  866. ShaderVariantAssetBuilderName, "Finished compiling shader function. Number of dynamic branches: %u",
  867. descriptor.m_byProducts.m_dynamicBranchCount);
  868. }
  869. else
  870. {
  871. AZ_TracePrintf(
  872. ShaderVariantAssetBuilderName, "Finished compiling shader function. Number of dynamic branches: unknown");
  873. }
  874. }
  875. if (shaderVariantInfo.m_enableRegisterAnalysis)
  876. {
  877. if (creationContext.m_shaderPlatformInterface.GetAPIName().GetStringView() == "vulkan")
  878. {
  879. AZ::IO::FixedMaxPath projectBuildPath = AZ::Utils::GetExecutableDirectory();
  880. projectBuildPath = projectBuildPath.RemoveFilename(); // profile
  881. projectBuildPath = projectBuildPath.RemoveFilename(); // bin
  882. AZ::IO::FixedMaxPath spirvPath(AZStd::string_view(creationContext.m_tempDirPath));
  883. spirvPath /= AZ::IO::FixedMaxPathString::format(
  884. "%s_vulkan_%u.spirv.bin", creationContext.m_shaderStemNamePrefix.c_str(), shaderVariantInfo.m_stableId);
  885. AZStd::string rgaCommand = AZStd::string::format(
  886. "-s vk-spv-offline --isa ./disassem_%u.txt --livereg ./livereg_%u.txt --asic %s",
  887. shaderVariantInfo.m_stableId,
  888. shaderVariantInfo.m_stableId,
  889. shaderVariantInfo.m_asic.c_str());
  890. AZStd::string RgaPath;
  891. if (creationContext.m_platformInfo.m_identifier == "pc")
  892. {
  893. RgaPath = "\\_deps\\rga-src\\rga.exe";
  894. }
  895. else
  896. {
  897. RgaPath = "/_deps/rga-src/rga";
  898. }
  899. AZStd::string command = AZStd::string::format(
  900. "%s%s %s %s", projectBuildPath.c_str(), RgaPath.c_str(), rgaCommand.c_str(), spirvPath.c_str());
  901. AZ_TracePrintf(ShaderVariantAssetBuilderName, "Rga command %s\n", command.c_str());
  902. AZStd::vector<AZStd::string> fullCommand;
  903. fullCommand.push_back(command);
  904. AZStd::string failMessage;
  905. if (LaunchRadeonGPUAnalyzer(fullCommand, creationContext.m_tempDirPath, failMessage))
  906. {
  907. // add rga output to the by product list
  908. outputByproducts->m_intermediatePaths.insert(AZStd::string::format(
  909. "./%s_disassem_%u_frag.txt", shaderVariantInfo.m_asic.c_str(), shaderVariantInfo.m_stableId));
  910. outputByproducts->m_intermediatePaths.insert(AZStd::string::format(
  911. "./%s_livereg_%u_frag.txt", shaderVariantInfo.m_asic.c_str(), shaderVariantInfo.m_stableId));
  912. }
  913. else
  914. {
  915. AZ_Warning(ShaderVariantAssetBuilderName, false, "%s", failMessage.c_str());
  916. }
  917. }
  918. else
  919. {
  920. AZ_Warning(
  921. ShaderVariantAssetBuilderName,
  922. false,
  923. "Current platform is %s, register analysis is only available on Vulkan for now.",
  924. creationContext.m_shaderPlatformInterface.GetAPIName().GetCStr());
  925. }
  926. }
  927. Data::Asset<RPI::ShaderVariantAsset> shaderVariantAsset;
  928. variantCreator.End(shaderVariantAsset);
  929. return AZ::Success(AZStd::move(shaderVariantAsset));
  930. }
  931. bool ShaderVariantAssetBuilder::LaunchRadeonGPUAnalyzer(AZStd::vector<AZStd::string> command, const AZStd::string& workingDirectory, AZStd::string& failMessage)
  932. {
  933. AzFramework::ProcessLauncher::ProcessLaunchInfo processLaunchInfo;
  934. processLaunchInfo.m_commandlineParameters.emplace<AZStd::vector<AZStd::string>>(AZStd::move(command));
  935. processLaunchInfo.m_workingDirectory = workingDirectory;
  936. processLaunchInfo.m_showWindow = false;
  937. AzFramework::ProcessWatcher* watcher =
  938. AzFramework::ProcessWatcher::LaunchProcess(processLaunchInfo, AzFramework::COMMUNICATOR_TYPE_STDINOUT);
  939. if (!watcher)
  940. {
  941. failMessage = AZStd::string("Rga executable can not be launched");
  942. return false;
  943. }
  944. AZStd::unique_ptr<AzFramework::ProcessWatcher> watcherPtr = AZStd::unique_ptr<AzFramework::ProcessWatcher>(watcher);
  945. AZStd::string errorMessages;
  946. AZStd::string outputMessages;
  947. auto pumpOuputStreams = [&watcherPtr, &errorMessages, &outputMessages]()
  948. {
  949. auto communicator = watcherPtr->GetCommunicator();
  950. // Instead of collecting all the output in a giant string, it would be better to report
  951. // the chunks of messages as they arrive, but this should be good enough for now.
  952. if (auto byteCount = communicator->PeekError())
  953. {
  954. AZStd::string chunk;
  955. chunk.resize(byteCount);
  956. communicator->ReadError(chunk.data(), byteCount);
  957. errorMessages += chunk;
  958. }
  959. if (auto byteCount = communicator->PeekOutput())
  960. {
  961. AZStd::string chunk;
  962. chunk.resize(byteCount);
  963. communicator->ReadOutput(chunk.data(), byteCount);
  964. outputMessages += chunk;
  965. }
  966. };
  967. uint32_t exitCode = 0;
  968. bool timedOut = false;
  969. const AZStd::sys_time_t maxWaitTimeSeconds = 5;
  970. const AZStd::sys_time_t startTimeSeconds = AZStd::GetTimeNowSecond();
  971. while (watcherPtr->IsProcessRunning(&exitCode))
  972. {
  973. const AZStd::sys_time_t currentTimeSeconds = AZStd::GetTimeNowSecond();
  974. if (currentTimeSeconds - startTimeSeconds > maxWaitTimeSeconds)
  975. {
  976. timedOut = true;
  977. static const uint32_t TimeOutExitCode = 121;
  978. exitCode = TimeOutExitCode;
  979. watcherPtr->TerminateProcess(TimeOutExitCode);
  980. break;
  981. }
  982. else
  983. {
  984. pumpOuputStreams();
  985. }
  986. }
  987. AZ_Assert(!watcherPtr->IsProcessRunning(), "Rga execution failed to terminate");
  988. // Pump one last time to make sure the streams have been flushed
  989. pumpOuputStreams();
  990. if (timedOut)
  991. {
  992. failMessage = AZStd::string("Rga execution timed out");
  993. return false;
  994. }
  995. if (exitCode != 0)
  996. {
  997. failMessage = AZStd::string::format("Rga process failed, exit code %u", exitCode);
  998. return false;
  999. }
  1000. if (!errorMessages.empty())
  1001. {
  1002. failMessage = AZStd::string::format("Rga report error message %s", errorMessages.c_str());
  1003. return false;
  1004. }
  1005. if (!outputMessages.empty() && outputMessages.contains("Error"))
  1006. {
  1007. failMessage = AZStd::string::format("Rga report error message %s", outputMessages.c_str());
  1008. return false;
  1009. }
  1010. return true;
  1011. }
  1012. } // ShaderBuilder
  1013. } // AZ