D3D11ShaderVariation.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504
  1. //
  2. // Copyright (c) 2008-2016 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 Atomic
  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 = path + "Cache/" + 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(), 0, (ID3D11VertexShader**)&object_.ptr_);
  82. if (FAILED(hr))
  83. {
  84. ATOMIC_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(), 0, (ID3D11PixelShader**)&object_.ptr_);
  96. if (FAILED(hr))
  97. {
  98. ATOMIC_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_ != 0;
  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(0, 0);
  118. }
  119. else
  120. {
  121. if (graphics_->GetPixelShader() == this)
  122. graphics_->SetShaders(0, 0);
  123. }
  124. ATOMIC_SAFE_RELEASE(object_.ptr_);
  125. }
  126. compilerOutput_.Clear();
  127. for (unsigned i = 0; i < MAX_TEXTURE_UNITS; ++i)
  128. useTextureUnit_[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. // ATOMIC BEGIN
  146. // ATOMIC: Disable shader cache until we can bring in configuration updates for writeable paths:
  147. // https://github.com/urho3d/Urho3D/commit/a1e2bc9bd3fe0966bb1aae1e911b96b006d155ce
  148. #ifndef ATOMIC_DEV_BUILD
  149. return false;
  150. #endif
  151. // ATOMIC END
  152. ResourceCache* cache = owner_->GetSubsystem<ResourceCache>();
  153. if (!cache->Exists(binaryShaderName))
  154. return false;
  155. FileSystem* fileSystem = owner_->GetSubsystem<FileSystem>();
  156. unsigned sourceTimeStamp = owner_->GetTimeStamp();
  157. // If source code is loaded from a package, its timestamp will be zero. Else check that binary is not older
  158. // than source
  159. if (sourceTimeStamp && fileSystem->GetLastModifiedTime(cache->GetResourceFileName(binaryShaderName)) < sourceTimeStamp)
  160. return false;
  161. SharedPtr<File> file = cache->GetFile(binaryShaderName);
  162. if (!file || file->ReadFileID() != "USHD")
  163. {
  164. ATOMIC_LOGERROR(binaryShaderName + " is not a valid shader bytecode file");
  165. return false;
  166. }
  167. /// \todo Check that shader type and model match
  168. /*unsigned short shaderType = */file->ReadUShort();
  169. /*unsigned short shaderModel = */file->ReadUShort();
  170. elementHash_ = file->ReadUInt();
  171. elementHash_ <<= 32;
  172. unsigned numParameters = file->ReadUInt();
  173. for (unsigned i = 0; i < numParameters; ++i)
  174. {
  175. String name = file->ReadString();
  176. unsigned buffer = file->ReadUByte();
  177. unsigned offset = file->ReadUInt();
  178. unsigned size = file->ReadUInt();
  179. ShaderParameter parameter;
  180. parameter.type_ = type_;
  181. parameter.name_ = name;
  182. parameter.buffer_ = buffer;
  183. parameter.offset_ = offset;
  184. parameter.size_ = size;
  185. parameters_[StringHash(name)] = parameter;
  186. }
  187. unsigned numTextureUnits = file->ReadUInt();
  188. for (unsigned i = 0; i < numTextureUnits; ++i)
  189. {
  190. /*String unitName = */file->ReadString();
  191. unsigned reg = file->ReadUByte();
  192. if (reg < MAX_TEXTURE_UNITS)
  193. useTextureUnit_[reg] = true;
  194. }
  195. unsigned byteCodeSize = file->ReadUInt();
  196. if (byteCodeSize)
  197. {
  198. byteCode_.Resize(byteCodeSize);
  199. file->Read(&byteCode_[0], byteCodeSize);
  200. if (type_ == VS)
  201. ATOMIC_LOGDEBUG("Loaded cached vertex shader " + GetFullName());
  202. else
  203. ATOMIC_LOGDEBUG("Loaded cached pixel shader " + GetFullName());
  204. CalculateConstantBufferSizes();
  205. return true;
  206. }
  207. else
  208. {
  209. ATOMIC_LOGERROR(binaryShaderName + " has zero length bytecode");
  210. return false;
  211. }
  212. }
  213. bool ShaderVariation::Compile()
  214. {
  215. const String& sourceCode = owner_->GetSourceCode(type_);
  216. Vector<String> defines = defines_.Split(' ');
  217. // Set the entrypoint, profile and flags according to the shader being compiled
  218. const char* entryPoint = 0;
  219. const char* profile = 0;
  220. unsigned flags = D3DCOMPILE_OPTIMIZATION_LEVEL3;
  221. defines.Push("D3D11");
  222. if (type_ == VS)
  223. {
  224. entryPoint = "VS";
  225. defines.Push("COMPILEVS");
  226. profile = "vs_4_0";
  227. }
  228. else
  229. {
  230. entryPoint = "PS";
  231. defines.Push("COMPILEPS");
  232. profile = "ps_4_0";
  233. flags |= D3DCOMPILE_PREFER_FLOW_CONTROL;
  234. }
  235. defines.Push("MAXBONES=" + String(Graphics::GetMaxBones()));
  236. // Collect defines into macros
  237. Vector<String> defineValues;
  238. PODVector<D3D_SHADER_MACRO> macros;
  239. for (unsigned i = 0; i < defines.Size(); ++i)
  240. {
  241. unsigned equalsPos = defines[i].Find('=');
  242. if (equalsPos != String::NPOS)
  243. {
  244. defineValues.Push(defines[i].Substring(equalsPos + 1));
  245. defines[i].Resize(equalsPos);
  246. }
  247. else
  248. defineValues.Push("1");
  249. }
  250. for (unsigned i = 0; i < defines.Size(); ++i)
  251. {
  252. D3D_SHADER_MACRO macro;
  253. macro.Name = defines[i].CString();
  254. macro.Definition = defineValues[i].CString();
  255. macros.Push(macro);
  256. // In debug mode, check that all defines are referenced by the shader code
  257. #ifdef _DEBUG
  258. if (sourceCode.Find(defines[i]) == String::NPOS)
  259. ATOMIC_LOGWARNING("Shader " + GetFullName() + " does not use the define " + defines[i]);
  260. #endif
  261. }
  262. D3D_SHADER_MACRO endMacro;
  263. endMacro.Name = 0;
  264. endMacro.Definition = 0;
  265. macros.Push(endMacro);
  266. // Compile using D3DCompile
  267. ID3DBlob* shaderCode = 0;
  268. ID3DBlob* errorMsgs = 0;
  269. HRESULT hr = D3DCompile(sourceCode.CString(), sourceCode.Length(), owner_->GetName().CString(), &macros.Front(), 0,
  270. entryPoint, profile, flags, 0, &shaderCode, &errorMsgs);
  271. if (FAILED(hr))
  272. {
  273. // Do not include end zero unnecessarily
  274. compilerOutput_ = String((const char*)errorMsgs->GetBufferPointer(), (unsigned)errorMsgs->GetBufferSize() - 1);
  275. }
  276. else
  277. {
  278. if (type_ == VS)
  279. ATOMIC_LOGDEBUG("Compiled vertex shader " + GetFullName());
  280. else
  281. ATOMIC_LOGDEBUG("Compiled pixel shader " + GetFullName());
  282. unsigned char* bufData = (unsigned char*)shaderCode->GetBufferPointer();
  283. unsigned bufSize = (unsigned)shaderCode->GetBufferSize();
  284. // Use the original bytecode to reflect the parameters
  285. ParseParameters(bufData, bufSize);
  286. CalculateConstantBufferSizes();
  287. // Then strip everything not necessary to use the shader
  288. ID3DBlob* strippedCode = 0;
  289. D3DStripShader(bufData, bufSize,
  290. D3DCOMPILER_STRIP_REFLECTION_DATA | D3DCOMPILER_STRIP_DEBUG_INFO | D3DCOMPILER_STRIP_TEST_BLOBS, &strippedCode);
  291. byteCode_.Resize((unsigned)strippedCode->GetBufferSize());
  292. memcpy(&byteCode_[0], strippedCode->GetBufferPointer(), byteCode_.Size());
  293. strippedCode->Release();
  294. }
  295. ATOMIC_SAFE_RELEASE(shaderCode);
  296. ATOMIC_SAFE_RELEASE(errorMsgs);
  297. return !byteCode_.Empty();
  298. }
  299. void ShaderVariation::ParseParameters(unsigned char* bufData, unsigned bufSize)
  300. {
  301. ID3D11ShaderReflection* reflection = 0;
  302. D3D11_SHADER_DESC shaderDesc;
  303. HRESULT hr = D3DReflect(bufData, bufSize, IID_ID3D11ShaderReflection, (void**)&reflection);
  304. if (FAILED(hr) || !reflection)
  305. {
  306. ATOMIC_SAFE_RELEASE(reflection);
  307. ATOMIC_LOGD3DERROR("Failed to reflect vertex shader's input signature", hr);
  308. return;
  309. }
  310. reflection->GetDesc(&shaderDesc);
  311. if (type_ == VS)
  312. {
  313. for (unsigned i = 0; i < shaderDesc.InputParameters; ++i)
  314. {
  315. D3D11_SIGNATURE_PARAMETER_DESC paramDesc;
  316. reflection->GetInputParameterDesc((UINT)i, &paramDesc);
  317. VertexElementSemantic semantic = (VertexElementSemantic)GetStringListIndex(paramDesc.SemanticName, elementSemanticNames, MAX_VERTEX_ELEMENT_SEMANTICS, true);
  318. if (semantic != MAX_VERTEX_ELEMENT_SEMANTICS)
  319. {
  320. elementHash_ <<= 4;
  321. elementHash_ += ((int)semantic + 1) * (paramDesc.SemanticIndex + 1);
  322. }
  323. }
  324. elementHash_ <<= 32;
  325. }
  326. HashMap<String, unsigned> cbRegisterMap;
  327. for (unsigned i = 0; i < shaderDesc.BoundResources; ++i)
  328. {
  329. D3D11_SHADER_INPUT_BIND_DESC resourceDesc;
  330. reflection->GetResourceBindingDesc(i, &resourceDesc);
  331. String resourceName(resourceDesc.Name);
  332. if (resourceDesc.Type == D3D_SIT_CBUFFER)
  333. cbRegisterMap[resourceName] = resourceDesc.BindPoint;
  334. else if (resourceDesc.Type == D3D_SIT_SAMPLER && resourceDesc.BindPoint < MAX_TEXTURE_UNITS)
  335. useTextureUnit_[resourceDesc.BindPoint] = true;
  336. }
  337. for (unsigned i = 0; i < shaderDesc.ConstantBuffers; ++i)
  338. {
  339. ID3D11ShaderReflectionConstantBuffer* cb = reflection->GetConstantBufferByIndex(i);
  340. D3D11_SHADER_BUFFER_DESC cbDesc;
  341. cb->GetDesc(&cbDesc);
  342. unsigned cbRegister = cbRegisterMap[String(cbDesc.Name)];
  343. for (unsigned j = 0; j < cbDesc.Variables; ++j)
  344. {
  345. ID3D11ShaderReflectionVariable* var = cb->GetVariableByIndex(j);
  346. D3D11_SHADER_VARIABLE_DESC varDesc;
  347. var->GetDesc(&varDesc);
  348. String varName(varDesc.Name);
  349. if (varName[0] == 'c')
  350. {
  351. varName = varName.Substring(1); // Strip the c to follow Urho3D constant naming convention
  352. ShaderParameter parameter;
  353. parameter.type_ = type_;
  354. parameter.name_ = varName;
  355. parameter.buffer_ = cbRegister;
  356. parameter.offset_ = varDesc.StartOffset;
  357. parameter.size_ = varDesc.Size;
  358. parameters_[varName] = parameter;
  359. }
  360. }
  361. }
  362. reflection->Release();
  363. }
  364. void ShaderVariation::SaveByteCode(const String& binaryShaderName)
  365. {
  366. // ATOMIC BEGIN
  367. // ATOMIC: Disable shader cache until we can bring in configuration updates for writeable paths:
  368. // https://github.com/urho3d/Urho3D/commit/a1e2bc9bd3fe0966bb1aae1e911b96b006d155ce
  369. #ifndef ATOMIC_DEV_BUILD
  370. return;
  371. #endif
  372. // ATOMIC END
  373. ResourceCache* cache = owner_->GetSubsystem<ResourceCache>();
  374. FileSystem* fileSystem = owner_->GetSubsystem<FileSystem>();
  375. String path = GetPath(cache->GetResourceFileName(owner_->GetName())) + "Cache/";
  376. String fullName = path + GetFileNameAndExtension(binaryShaderName);
  377. if (!fileSystem->DirExists(path))
  378. fileSystem->CreateDir(path);
  379. SharedPtr<File> file(new File(owner_->GetContext(), fullName, FILE_WRITE));
  380. if (!file->IsOpen())
  381. return;
  382. file->WriteFileID("USHD");
  383. file->WriteShort((unsigned short)type_);
  384. file->WriteShort(4);
  385. file->WriteUInt(elementHash_ >> 32);
  386. file->WriteUInt(parameters_.Size());
  387. for (HashMap<StringHash, ShaderParameter>::ConstIterator i = parameters_.Begin(); i != parameters_.End(); ++i)
  388. {
  389. file->WriteString(i->second_.name_);
  390. file->WriteUByte((unsigned char)i->second_.buffer_);
  391. file->WriteUInt(i->second_.offset_);
  392. file->WriteUInt(i->second_.size_);
  393. }
  394. unsigned usedTextureUnits = 0;
  395. for (unsigned i = 0; i < MAX_TEXTURE_UNITS; ++i)
  396. {
  397. if (useTextureUnit_[i])
  398. ++usedTextureUnits;
  399. }
  400. file->WriteUInt(usedTextureUnits);
  401. for (unsigned i = 0; i < MAX_TEXTURE_UNITS; ++i)
  402. {
  403. if (useTextureUnit_[i])
  404. {
  405. file->WriteString(graphics_->GetTextureUnitName((TextureUnit)i));
  406. file->WriteUByte((unsigned char)i);
  407. }
  408. }
  409. file->WriteUInt(byteCode_.Size());
  410. if (byteCode_.Size())
  411. file->Write(&byteCode_[0], byteCode_.Size());
  412. }
  413. void ShaderVariation::CalculateConstantBufferSizes()
  414. {
  415. for (unsigned i = 0; i < MAX_SHADER_PARAMETER_GROUPS; ++i)
  416. constantBufferSizes_[i] = 0;
  417. for (HashMap<StringHash, ShaderParameter>::ConstIterator i = parameters_.Begin(); i != parameters_.End(); ++i)
  418. {
  419. if (i->second_.buffer_ < MAX_SHADER_PARAMETER_GROUPS)
  420. {
  421. unsigned oldSize = constantBufferSizes_[i->second_.buffer_];
  422. unsigned paramEnd = i->second_.offset_ + i->second_.size_;
  423. if (paramEnd > oldSize)
  424. constantBufferSizes_[i->second_.buffer_] = paramEnd;
  425. }
  426. }
  427. }
  428. }