D3D11ShaderVariation.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481
  1. //
  2. // Copyright (c) 2008-2020 the Urho3D project.
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to deal
  6. // in the Software without restriction, including without limitation the rights
  7. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. // copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. // THE SOFTWARE.
  21. //
  22. #include "../../Precompiled.h"
  23. #include "../../Graphics/Graphics.h"
  24. #include "../../Graphics/GraphicsImpl.h"
  25. #include "../../Graphics/Shader.h"
  26. #include "../../Graphics/VertexBuffer.h"
  27. #include "../../IO/File.h"
  28. #include "../../IO/FileSystem.h"
  29. #include "../../IO/Log.h"
  30. #include "../../Resource/ResourceCache.h"
  31. #include <d3dcompiler.h>
  32. #include "../../DebugNew.h"
  33. namespace Urho3D
  34. {
  35. const char* ShaderVariation::elementSemanticNames[] =
  36. {
  37. "POSITION",
  38. "NORMAL",
  39. "BINORMAL",
  40. "TANGENT",
  41. "TEXCOORD",
  42. "COLOR",
  43. "BLENDWEIGHT",
  44. "BLENDINDICES",
  45. "OBJECTINDEX"
  46. };
  47. void ShaderVariation::OnDeviceLost()
  48. {
  49. // No-op on Direct3D11
  50. }
  51. bool ShaderVariation::Create()
  52. {
  53. Release();
  54. if (!graphics_)
  55. return false;
  56. if (!owner_)
  57. {
  58. compilerOutput_ = "Owner shader has expired";
  59. return false;
  60. }
  61. // Check for up-to-date bytecode on disk
  62. String path, name, extension;
  63. SplitPath(owner_->GetName(), path, name, extension);
  64. extension = type_ == VS ? ".vs4" : ".ps4";
  65. String binaryShaderName = graphics_->GetShaderCacheDir() + name + "_" + StringHash(defines_).ToString() + extension;
  66. if (!LoadByteCode(binaryShaderName))
  67. {
  68. // Compile shader if don't have valid bytecode
  69. if (!Compile())
  70. return false;
  71. // Save the bytecode after successful compile, but not if the source is from a package
  72. if (owner_->GetTimeStamp())
  73. SaveByteCode(binaryShaderName);
  74. }
  75. // Then create shader from the bytecode
  76. ID3D11Device* device = graphics_->GetImpl()->GetDevice();
  77. if (type_ == VS)
  78. {
  79. if (device && byteCode_.Size())
  80. {
  81. HRESULT hr = device->CreateVertexShader(&byteCode_[0], byteCode_.Size(), nullptr, (ID3D11VertexShader**)&object_.ptr_);
  82. if (FAILED(hr))
  83. {
  84. URHO3D_SAFE_RELEASE(object_.ptr_);
  85. compilerOutput_ = "Could not create vertex shader (HRESULT " + ToStringHex((unsigned)hr) + ")";
  86. }
  87. }
  88. else
  89. compilerOutput_ = "Could not create vertex shader, empty bytecode";
  90. }
  91. else
  92. {
  93. if (device && byteCode_.Size())
  94. {
  95. HRESULT hr = device->CreatePixelShader(&byteCode_[0], byteCode_.Size(), nullptr, (ID3D11PixelShader**)&object_.ptr_);
  96. if (FAILED(hr))
  97. {
  98. URHO3D_SAFE_RELEASE(object_.ptr_);
  99. compilerOutput_ = "Could not create pixel shader (HRESULT " + ToStringHex((unsigned)hr) + ")";
  100. }
  101. }
  102. else
  103. compilerOutput_ = "Could not create pixel shader, empty bytecode";
  104. }
  105. return object_.ptr_ != nullptr;
  106. }
  107. void ShaderVariation::Release()
  108. {
  109. if (object_.ptr_)
  110. {
  111. if (!graphics_)
  112. return;
  113. graphics_->CleanupShaderPrograms(this);
  114. if (type_ == VS)
  115. {
  116. if (graphics_->GetVertexShader() == this)
  117. graphics_->SetShaders(nullptr, nullptr);
  118. }
  119. else
  120. {
  121. if (graphics_->GetPixelShader() == this)
  122. graphics_->SetShaders(nullptr, nullptr);
  123. }
  124. URHO3D_SAFE_RELEASE(object_.ptr_);
  125. }
  126. compilerOutput_.Clear();
  127. for (unsigned i = 0; i < MAX_TEXTURE_UNITS; ++i)
  128. useTextureUnits_[i] = false;
  129. for (unsigned i = 0; i < MAX_SHADER_PARAMETER_GROUPS; ++i)
  130. constantBufferSizes_[i] = 0;
  131. parameters_.Clear();
  132. byteCode_.Clear();
  133. elementHash_ = 0;
  134. }
  135. void ShaderVariation::SetDefines(const String& defines)
  136. {
  137. defines_ = defines;
  138. // Internal mechanism for appending the CLIPPLANE define, prevents runtime (every frame) string manipulation
  139. definesClipPlane_ = defines;
  140. if (!definesClipPlane_.EndsWith(" CLIPPLANE"))
  141. definesClipPlane_ += " CLIPPLANE";
  142. }
  143. bool ShaderVariation::LoadByteCode(const String& binaryShaderName)
  144. {
  145. ResourceCache* cache = owner_->GetSubsystem<ResourceCache>();
  146. if (!cache->Exists(binaryShaderName))
  147. return false;
  148. FileSystem* fileSystem = owner_->GetSubsystem<FileSystem>();
  149. unsigned sourceTimeStamp = owner_->GetTimeStamp();
  150. // If source code is loaded from a package, its timestamp will be zero. Else check that binary is not older
  151. // than source
  152. if (sourceTimeStamp && fileSystem->GetLastModifiedTime(cache->GetResourceFileName(binaryShaderName)) < sourceTimeStamp)
  153. return false;
  154. SharedPtr<File> file = cache->GetFile(binaryShaderName);
  155. if (!file || file->ReadFileID() != "USHD")
  156. {
  157. URHO3D_LOGERROR(binaryShaderName + " is not a valid shader bytecode file");
  158. return false;
  159. }
  160. /// \todo Check that shader type and model match
  161. /*unsigned short shaderType = */file->ReadUShort();
  162. /*unsigned short shaderModel = */file->ReadUShort();
  163. elementHash_ = file->ReadUInt();
  164. elementHash_ <<= 32;
  165. unsigned numParameters = file->ReadUInt();
  166. for (unsigned i = 0; i < numParameters; ++i)
  167. {
  168. String name = file->ReadString();
  169. unsigned buffer = file->ReadUByte();
  170. unsigned offset = file->ReadUInt();
  171. unsigned size = file->ReadUInt();
  172. parameters_[StringHash(name)] = ShaderParameter{type_, name, offset, size, buffer};
  173. }
  174. unsigned numTextureUnits = file->ReadUInt();
  175. for (unsigned i = 0; i < numTextureUnits; ++i)
  176. {
  177. /*String unitName = */file->ReadString();
  178. unsigned reg = file->ReadUByte();
  179. if (reg < MAX_TEXTURE_UNITS)
  180. useTextureUnits_[reg] = true;
  181. }
  182. unsigned byteCodeSize = file->ReadUInt();
  183. if (byteCodeSize)
  184. {
  185. byteCode_.Resize(byteCodeSize);
  186. file->Read(&byteCode_[0], byteCodeSize);
  187. if (type_ == VS)
  188. URHO3D_LOGDEBUG("Loaded cached vertex shader " + GetFullName());
  189. else
  190. URHO3D_LOGDEBUG("Loaded cached pixel shader " + GetFullName());
  191. CalculateConstantBufferSizes();
  192. return true;
  193. }
  194. else
  195. {
  196. URHO3D_LOGERROR(binaryShaderName + " has zero length bytecode");
  197. return false;
  198. }
  199. }
  200. bool ShaderVariation::Compile()
  201. {
  202. const String& sourceCode = owner_->GetSourceCode(type_);
  203. Vector<String> defines = defines_.Split(' ');
  204. // Set the entrypoint, profile and flags according to the shader being compiled
  205. const char* entryPoint = nullptr;
  206. const char* profile = nullptr;
  207. unsigned flags = D3DCOMPILE_OPTIMIZATION_LEVEL3;
  208. defines.Push("D3D11");
  209. if (type_ == VS)
  210. {
  211. entryPoint = "VS";
  212. defines.Push("COMPILEVS");
  213. profile = "vs_4_0";
  214. }
  215. else
  216. {
  217. entryPoint = "PS";
  218. defines.Push("COMPILEPS");
  219. profile = "ps_4_0";
  220. flags |= D3DCOMPILE_PREFER_FLOW_CONTROL;
  221. }
  222. defines.Push("MAXBONES=" + String(Graphics::GetMaxBones()));
  223. // Collect defines into macros
  224. Vector<String> defineValues;
  225. PODVector<D3D_SHADER_MACRO> macros;
  226. for (unsigned i = 0; i < defines.Size(); ++i)
  227. {
  228. unsigned equalsPos = defines[i].Find('=');
  229. if (equalsPos != String::NPOS)
  230. {
  231. defineValues.Push(defines[i].Substring(equalsPos + 1));
  232. defines[i].Resize(equalsPos);
  233. }
  234. else
  235. defineValues.Push("1");
  236. }
  237. for (unsigned i = 0; i < defines.Size(); ++i)
  238. {
  239. D3D_SHADER_MACRO macro;
  240. macro.Name = defines[i].CString();
  241. macro.Definition = defineValues[i].CString();
  242. macros.Push(macro);
  243. // In debug mode, check that all defines are referenced by the shader code
  244. #ifdef _DEBUG
  245. if (sourceCode.Find(defines[i]) == String::NPOS)
  246. URHO3D_LOGWARNING("Shader " + GetFullName() + " does not use the define " + defines[i]);
  247. #endif
  248. }
  249. D3D_SHADER_MACRO endMacro;
  250. endMacro.Name = nullptr;
  251. endMacro.Definition = nullptr;
  252. macros.Push(endMacro);
  253. // Compile using D3DCompile
  254. ID3DBlob* shaderCode = nullptr;
  255. ID3DBlob* errorMsgs = nullptr;
  256. HRESULT hr = D3DCompile(sourceCode.CString(), sourceCode.Length(), owner_->GetName().CString(), &macros.Front(), nullptr,
  257. entryPoint, profile, flags, 0, &shaderCode, &errorMsgs);
  258. if (FAILED(hr))
  259. {
  260. // Do not include end zero unnecessarily
  261. compilerOutput_ = String((const char*)errorMsgs->GetBufferPointer(), (unsigned)errorMsgs->GetBufferSize() - 1);
  262. }
  263. else
  264. {
  265. if (type_ == VS)
  266. URHO3D_LOGDEBUG("Compiled vertex shader " + GetFullName());
  267. else
  268. URHO3D_LOGDEBUG("Compiled pixel shader " + GetFullName());
  269. unsigned char* bufData = (unsigned char*)shaderCode->GetBufferPointer();
  270. unsigned bufSize = (unsigned)shaderCode->GetBufferSize();
  271. // Use the original bytecode to reflect the parameters
  272. ParseParameters(bufData, bufSize);
  273. CalculateConstantBufferSizes();
  274. // Then strip everything not necessary to use the shader
  275. ID3DBlob* strippedCode = nullptr;
  276. D3DStripShader(bufData, bufSize,
  277. D3DCOMPILER_STRIP_REFLECTION_DATA | D3DCOMPILER_STRIP_DEBUG_INFO | D3DCOMPILER_STRIP_TEST_BLOBS, &strippedCode);
  278. byteCode_.Resize((unsigned)strippedCode->GetBufferSize());
  279. memcpy(&byteCode_[0], strippedCode->GetBufferPointer(), byteCode_.Size());
  280. strippedCode->Release();
  281. }
  282. URHO3D_SAFE_RELEASE(shaderCode);
  283. URHO3D_SAFE_RELEASE(errorMsgs);
  284. return !byteCode_.Empty();
  285. }
  286. void ShaderVariation::ParseParameters(unsigned char* bufData, unsigned bufSize)
  287. {
  288. ID3D11ShaderReflection* reflection = nullptr;
  289. D3D11_SHADER_DESC shaderDesc;
  290. HRESULT hr = D3DReflect(bufData, bufSize, IID_ID3D11ShaderReflection, (void**)&reflection);
  291. if (FAILED(hr) || !reflection)
  292. {
  293. URHO3D_SAFE_RELEASE(reflection);
  294. URHO3D_LOGD3DERROR("Failed to reflect vertex shader's input signature", hr);
  295. return;
  296. }
  297. reflection->GetDesc(&shaderDesc);
  298. if (type_ == VS)
  299. {
  300. unsigned elementHash = 0;
  301. for (unsigned i = 0; i < shaderDesc.InputParameters; ++i)
  302. {
  303. D3D11_SIGNATURE_PARAMETER_DESC paramDesc;
  304. reflection->GetInputParameterDesc((UINT)i, &paramDesc);
  305. VertexElementSemantic semantic = (VertexElementSemantic)GetStringListIndex(paramDesc.SemanticName, elementSemanticNames, MAX_VERTEX_ELEMENT_SEMANTICS, true);
  306. if (semantic != MAX_VERTEX_ELEMENT_SEMANTICS)
  307. {
  308. CombineHash(elementHash, semantic);
  309. CombineHash(elementHash, paramDesc.SemanticIndex);
  310. }
  311. }
  312. elementHash_ = elementHash;
  313. elementHash_ <<= 32;
  314. }
  315. HashMap<String, unsigned> cbRegisterMap;
  316. for (unsigned i = 0; i < shaderDesc.BoundResources; ++i)
  317. {
  318. D3D11_SHADER_INPUT_BIND_DESC resourceDesc;
  319. reflection->GetResourceBindingDesc(i, &resourceDesc);
  320. String resourceName(resourceDesc.Name);
  321. if (resourceDesc.Type == D3D_SIT_CBUFFER)
  322. cbRegisterMap[resourceName] = resourceDesc.BindPoint;
  323. else if (resourceDesc.Type == D3D_SIT_SAMPLER && resourceDesc.BindPoint < MAX_TEXTURE_UNITS)
  324. useTextureUnits_[resourceDesc.BindPoint] = true;
  325. }
  326. for (unsigned i = 0; i < shaderDesc.ConstantBuffers; ++i)
  327. {
  328. ID3D11ShaderReflectionConstantBuffer* cb = reflection->GetConstantBufferByIndex(i);
  329. D3D11_SHADER_BUFFER_DESC cbDesc;
  330. cb->GetDesc(&cbDesc);
  331. unsigned cbRegister = cbRegisterMap[String(cbDesc.Name)];
  332. for (unsigned j = 0; j < cbDesc.Variables; ++j)
  333. {
  334. ID3D11ShaderReflectionVariable* var = cb->GetVariableByIndex(j);
  335. D3D11_SHADER_VARIABLE_DESC varDesc;
  336. var->GetDesc(&varDesc);
  337. String varName(varDesc.Name);
  338. if (varName[0] == 'c')
  339. {
  340. varName = varName.Substring(1); // Strip the c to follow Urho3D constant naming convention
  341. parameters_[varName] = ShaderParameter{type_, varName, varDesc.StartOffset, varDesc.Size, cbRegister};
  342. }
  343. }
  344. }
  345. reflection->Release();
  346. }
  347. void ShaderVariation::SaveByteCode(const String& binaryShaderName)
  348. {
  349. ResourceCache* cache = owner_->GetSubsystem<ResourceCache>();
  350. FileSystem* fileSystem = owner_->GetSubsystem<FileSystem>();
  351. // Filename may or may not be inside the resource system
  352. String fullName = binaryShaderName;
  353. if (!IsAbsolutePath(fullName))
  354. {
  355. // If not absolute, use the resource dir of the shader
  356. String shaderFileName = cache->GetResourceFileName(owner_->GetName());
  357. if (shaderFileName.Empty())
  358. return;
  359. fullName = shaderFileName.Substring(0, shaderFileName.Find(owner_->GetName())) + binaryShaderName;
  360. }
  361. String path = GetPath(fullName);
  362. if (!fileSystem->DirExists(path))
  363. fileSystem->CreateDir(path);
  364. SharedPtr<File> file(new File(owner_->GetContext(), fullName, FILE_WRITE));
  365. if (!file->IsOpen())
  366. return;
  367. file->WriteFileID("USHD");
  368. file->WriteShort((unsigned short)type_);
  369. file->WriteShort(4);
  370. file->WriteUInt(elementHash_ >> 32);
  371. file->WriteUInt(parameters_.Size());
  372. for (HashMap<StringHash, ShaderParameter>::ConstIterator i = parameters_.Begin(); i != parameters_.End(); ++i)
  373. {
  374. file->WriteString(i->second_.name_);
  375. file->WriteUByte((unsigned char)i->second_.buffer_);
  376. file->WriteUInt(i->second_.offset_);
  377. file->WriteUInt(i->second_.size_);
  378. }
  379. unsigned usedTextureUnits = 0;
  380. for (unsigned i = 0; i < MAX_TEXTURE_UNITS; ++i)
  381. {
  382. if (useTextureUnits_[i])
  383. ++usedTextureUnits;
  384. }
  385. file->WriteUInt(usedTextureUnits);
  386. for (unsigned i = 0; i < MAX_TEXTURE_UNITS; ++i)
  387. {
  388. if (useTextureUnits_[i])
  389. {
  390. file->WriteString(graphics_->GetTextureUnitName((TextureUnit)i));
  391. file->WriteUByte((unsigned char)i);
  392. }
  393. }
  394. file->WriteUInt(byteCode_.Size());
  395. if (byteCode_.Size())
  396. file->Write(&byteCode_[0], byteCode_.Size());
  397. }
  398. void ShaderVariation::CalculateConstantBufferSizes()
  399. {
  400. for (unsigned i = 0; i < MAX_SHADER_PARAMETER_GROUPS; ++i)
  401. constantBufferSizes_[i] = 0;
  402. for (HashMap<StringHash, ShaderParameter>::ConstIterator i = parameters_.Begin(); i != parameters_.End(); ++i)
  403. {
  404. if (i->second_.buffer_ < MAX_SHADER_PARAMETER_GROUPS)
  405. {
  406. unsigned oldSize = constantBufferSizes_[i->second_.buffer_];
  407. unsigned paramEnd = i->second_.offset_ + i->second_.size_;
  408. if (paramEnd > oldSize)
  409. constantBufferSizes_[i->second_.buffer_] = paramEnd;
  410. }
  411. }
  412. }
  413. }