D3D9ShaderVariation.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434
  1. //
  2. // Copyright (c) 2008-2015 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 "../../IO/File.h"
  23. #include "../../IO/FileSystem.h"
  24. #include "../../Graphics/Graphics.h"
  25. #include "../../Graphics/GraphicsImpl.h"
  26. #include "../../IO/Log.h"
  27. #include "../../Resource/ResourceCache.h"
  28. #include "../../Graphics/Shader.h"
  29. #include "../../Graphics/ShaderVariation.h"
  30. #include <windows.h>
  31. #include <d3dcompiler.h>
  32. #include <MojoShader/mojoshader.h>
  33. #include "../../DebugNew.h"
  34. namespace Atomic
  35. {
  36. ShaderVariation::ShaderVariation(Shader* owner, ShaderType type) :
  37. GPUObject(owner->GetSubsystem<Graphics>()),
  38. owner_(owner),
  39. type_(type)
  40. {
  41. for (unsigned i = 0; i < MAX_TEXTURE_UNITS; ++i)
  42. useTextureUnit_[i] = false;
  43. }
  44. ShaderVariation::~ShaderVariation()
  45. {
  46. Release();
  47. }
  48. bool ShaderVariation::Create()
  49. {
  50. Release();
  51. if (!graphics_)
  52. return false;
  53. if (!owner_)
  54. {
  55. compilerOutput_ = "Owner shader has expired";
  56. return false;
  57. }
  58. // Check for up-to-date bytecode on disk
  59. bool useSM3 = graphics_->GetSM3Support();
  60. String path, name, extension;
  61. SplitPath(owner_->GetName(), path, name, extension);
  62. if (useSM3)
  63. extension = type_ == VS ? ".vs3" : ".ps3";
  64. else
  65. extension = type_ == VS ? ".vs2" : ".ps2";
  66. String binaryShaderName = path + "Cache/" + name + "_" + StringHash(defines_).ToString() + extension;
  67. PODVector<unsigned> byteCode;
  68. if (!LoadByteCode(byteCode, binaryShaderName))
  69. {
  70. // Compile shader if don't have valid bytecode
  71. if (!Compile(byteCode))
  72. return false;
  73. // Save the bytecode after successful compile, but not if the source is from a package
  74. if (owner_->GetTimeStamp())
  75. SaveByteCode(byteCode, binaryShaderName);
  76. }
  77. // Then create shader from the bytecode
  78. IDirect3DDevice9* device = graphics_->GetImpl()->GetDevice();
  79. if (type_ == VS)
  80. {
  81. if (!device || FAILED(device->CreateVertexShader(
  82. (const DWORD*)&byteCode[0],
  83. (IDirect3DVertexShader9**)&object_)))
  84. compilerOutput_ = "Could not create vertex shader";
  85. }
  86. else
  87. {
  88. if (!device || FAILED(device->CreatePixelShader(
  89. (const DWORD*)&byteCode[0],
  90. (IDirect3DPixelShader9**)&object_)))
  91. compilerOutput_ = "Could not create pixel shader";
  92. }
  93. return object_ != 0;
  94. }
  95. void ShaderVariation::Release()
  96. {
  97. if (object_)
  98. {
  99. if (!graphics_)
  100. return;
  101. graphics_->CleanupShaderParameters(this);
  102. if (type_ == VS)
  103. {
  104. if (graphics_->GetVertexShader() == this)
  105. graphics_->SetShaders(0, 0);
  106. ((IDirect3DVertexShader9*)object_)->Release();
  107. }
  108. else
  109. {
  110. if (graphics_->GetPixelShader() == this)
  111. graphics_->SetShaders(0, 0);
  112. ((IDirect3DPixelShader9*)object_)->Release();
  113. }
  114. object_ = 0;
  115. }
  116. compilerOutput_.Clear();
  117. for (unsigned i = 0; i < MAX_TEXTURE_UNITS; ++i)
  118. useTextureUnit_[i] = false;
  119. parameters_.Clear();
  120. }
  121. void ShaderVariation::SetName(const String& name)
  122. {
  123. name_ = name;
  124. }
  125. void ShaderVariation::SetDefines(const String& defines)
  126. {
  127. defines_ = defines;
  128. }
  129. Shader* ShaderVariation::GetOwner() const
  130. {
  131. return owner_;
  132. }
  133. bool ShaderVariation::LoadByteCode(PODVector<unsigned>& byteCode, const String& binaryShaderName)
  134. {
  135. ResourceCache* cache = owner_->GetSubsystem<ResourceCache>();
  136. if (!cache->Exists(binaryShaderName))
  137. return false;
  138. FileSystem* fileSystem = owner_->GetSubsystem<FileSystem>();
  139. unsigned sourceTimeStamp = owner_->GetTimeStamp();
  140. // If source code is loaded from a package, its timestamp will be zero. Else check that binary is not older
  141. // than source
  142. if (sourceTimeStamp && fileSystem->GetLastModifiedTime(cache->GetResourceFileName(binaryShaderName)) <
  143. sourceTimeStamp)
  144. return false;
  145. SharedPtr<File> file = cache->GetFile(binaryShaderName);
  146. if (!file || file->ReadFileID() != "USHD")
  147. {
  148. LOGERROR(binaryShaderName + " is not a valid shader bytecode file");
  149. return false;
  150. }
  151. /// \todo Check that shader type and model match
  152. unsigned short shaderType = file->ReadUShort();
  153. unsigned short shaderModel = file->ReadUShort();
  154. unsigned numParameters = file->ReadUInt();
  155. for (unsigned i = 0; i < numParameters; ++i)
  156. {
  157. String name = file->ReadString();
  158. unsigned reg = file->ReadUByte();
  159. unsigned regCount = file->ReadUByte();
  160. ShaderParameter parameter(type_, name, reg, regCount);
  161. parameters_[StringHash(name)] = parameter;
  162. }
  163. unsigned numTextureUnits = file->ReadUInt();
  164. for (unsigned i = 0; i < numTextureUnits; ++i)
  165. {
  166. String unitName = file->ReadString();
  167. unsigned reg = file->ReadUByte();
  168. if (reg < MAX_TEXTURE_UNITS)
  169. useTextureUnit_[reg] = true;
  170. }
  171. unsigned byteCodeSize = file->ReadUInt();
  172. if (byteCodeSize)
  173. {
  174. byteCode.Resize(byteCodeSize >> 2);
  175. file->Read(&byteCode[0], byteCodeSize);
  176. if (type_ == VS)
  177. LOGDEBUG("Loaded cached vertex shader " + GetFullName());
  178. else
  179. LOGDEBUG("Loaded cached pixel shader " + GetFullName());
  180. return true;
  181. }
  182. else
  183. {
  184. LOGERROR(binaryShaderName + " has zero length bytecode");
  185. return false;
  186. }
  187. }
  188. bool ShaderVariation::Compile(PODVector<unsigned>& byteCode)
  189. {
  190. const String& sourceCode = owner_->GetSourceCode(type_);
  191. Vector<String> defines = defines_.Split(' ');
  192. // Set the entrypoint, profile and flags according to the shader being compiled
  193. const char* entryPoint = 0;
  194. const char* profile = 0;
  195. unsigned flags = D3DCOMPILE_OPTIMIZATION_LEVEL3;
  196. bool useSM3 = graphics_->GetSM3Support();
  197. if (type_ == VS)
  198. {
  199. entryPoint = "VS";
  200. defines.Push("COMPILEVS");
  201. if (!useSM3)
  202. profile = "vs_2_0";
  203. else
  204. profile = "vs_3_0";
  205. }
  206. else
  207. {
  208. entryPoint = "PS";
  209. defines.Push("COMPILEPS");
  210. if (!useSM3)
  211. profile = "ps_2_0";
  212. else
  213. {
  214. profile = "ps_3_0";
  215. flags |= D3DCOMPILE_PREFER_FLOW_CONTROL;
  216. }
  217. }
  218. if (useSM3)
  219. defines.Push("SM3");
  220. // Collect defines into macros
  221. Vector<String> defineValues;
  222. PODVector<D3D_SHADER_MACRO> macros;
  223. for (unsigned i = 0; i < defines.Size(); ++i)
  224. {
  225. unsigned equalsPos = defines[i].Find('=');
  226. if (equalsPos != String::NPOS)
  227. {
  228. defineValues.Push(defines[i].Substring(equalsPos + 1));
  229. defines[i].Resize(equalsPos);
  230. }
  231. else
  232. defineValues.Push("1");
  233. }
  234. for (unsigned i = 0; i < defines.Size(); ++i)
  235. {
  236. D3D_SHADER_MACRO macro;
  237. macro.Name = defines[i].CString();
  238. macro.Definition = defineValues[i].CString();
  239. macros.Push(macro);
  240. // In debug mode, check that all defines are referenced by the shader code
  241. #ifdef _DEBUG
  242. if (sourceCode.Find(defines[i]) == String::NPOS)
  243. LOGWARNING("Shader " + GetFullName() + " does not use the define " + defines[i]);
  244. #endif
  245. }
  246. D3D_SHADER_MACRO endMacro;
  247. endMacro.Name = 0;
  248. endMacro.Definition = 0;
  249. macros.Push(endMacro);
  250. // Compile using D3DCompile
  251. LPD3DBLOB shaderCode = 0;
  252. LPD3DBLOB errorMsgs = 0;
  253. if (FAILED(D3DCompile(sourceCode.CString(), sourceCode.Length(), owner_->GetName().CString(), &macros.Front(), 0,
  254. entryPoint, profile, flags, 0, &shaderCode, &errorMsgs)))
  255. compilerOutput_ = String((const char*)errorMsgs->GetBufferPointer(), errorMsgs->GetBufferSize());
  256. else
  257. {
  258. if (type_ == VS)
  259. LOGDEBUG("Compiled vertex shader " + GetFullName());
  260. else
  261. LOGDEBUG("Compiled pixel shader " + GetFullName());
  262. // Inspect the produced bytecode using MojoShader, then strip and store it
  263. unsigned char* bufData = (unsigned char*)shaderCode->GetBufferPointer();
  264. unsigned bufSize = shaderCode->GetBufferSize();
  265. ParseParameters(bufData, bufSize);
  266. CopyStrippedCode(byteCode, bufData, bufSize);
  267. }
  268. if (shaderCode)
  269. shaderCode->Release();
  270. if (errorMsgs)
  271. errorMsgs->Release();
  272. return !byteCode.Empty();
  273. }
  274. void ShaderVariation::ParseParameters(unsigned char* bufData, unsigned bufSize)
  275. {
  276. MOJOSHADER_parseData const *parseData = MOJOSHADER_parse("bytecode", bufData, bufSize, 0, 0, 0, 0, 0, 0, 0);
  277. for (int i = 0; i < parseData->symbol_count; i++)
  278. {
  279. MOJOSHADER_symbol const& symbol = parseData->symbols[i];
  280. String name(symbol.name);
  281. unsigned reg = symbol.register_index;
  282. unsigned regCount = symbol.register_count;
  283. // Check if the parameter is a constant or a texture sampler
  284. bool isSampler = (name[0] == 's');
  285. name = name.Substring(1);
  286. if (isSampler)
  287. {
  288. // Skip if it's a G-buffer sampler, which are aliases for the standard texture units
  289. if (reg < MAX_TEXTURE_UNITS)
  290. {
  291. if (name != "AlbedoBuffer" && name != "NormalBuffer" && name != "DepthBuffer" && name != "LightBuffer")
  292. useTextureUnit_[reg] = true;
  293. }
  294. }
  295. else
  296. {
  297. ShaderParameter newParam(type_, name, reg, regCount);
  298. parameters_[StringHash(name)] = newParam;
  299. }
  300. }
  301. MOJOSHADER_freeParseData(parseData);
  302. }
  303. void ShaderVariation::CopyStrippedCode(PODVector<unsigned>& byteCode, unsigned char* bufData, unsigned bufSize)
  304. {
  305. unsigned const D3DSIO_COMMENT = 0xFFFE;
  306. unsigned* srcWords = (unsigned*)bufData;
  307. unsigned srcWordSize = bufSize >> 2;
  308. for (unsigned i = 0; i < srcWordSize; ++i)
  309. {
  310. unsigned opcode = srcWords[i] & 0xffff;
  311. unsigned paramLength = (srcWords[i] & 0x0f000000) >> 24;
  312. unsigned commentLength = srcWords[i] >> 16;
  313. // For now, skip comment only at fixed position to prevent false positives
  314. if (i == 1 && opcode == D3DSIO_COMMENT)
  315. {
  316. // Skip the comment
  317. i += commentLength;
  318. }
  319. else
  320. {
  321. // Not a comment, copy the data
  322. byteCode.Push(srcWords[i]);
  323. }
  324. }
  325. }
  326. void ShaderVariation::SaveByteCode(const PODVector<unsigned>& byteCode, const String& binaryShaderName)
  327. {
  328. ResourceCache* cache = owner_->GetSubsystem<ResourceCache>();
  329. FileSystem* fileSystem = owner_->GetSubsystem<FileSystem>();
  330. String path = GetPath(cache->GetResourceFileName(owner_->GetName())) + "Cache/";
  331. String fullName = path + GetFileNameAndExtension(binaryShaderName);
  332. if (!fileSystem->DirExists(path))
  333. fileSystem->CreateDir(path);
  334. SharedPtr<File> file(new File(owner_->GetContext(), fullName, FILE_WRITE));
  335. if (!file->IsOpen())
  336. return;
  337. file->WriteFileID("USHD");
  338. file->WriteShort((unsigned short)type_);
  339. file->WriteShort(graphics_->GetSM3Support() ? 3 : 2);
  340. file->WriteUInt(parameters_.Size());
  341. for (HashMap<StringHash, ShaderParameter>::ConstIterator i = parameters_.Begin(); i != parameters_.End(); ++i)
  342. {
  343. file->WriteString(i->second_.name_);
  344. file->WriteUByte(i->second_.register_);
  345. file->WriteUByte(i->second_.regCount_);
  346. }
  347. unsigned usedTextureUnits = 0;
  348. for (unsigned i = 0; i < MAX_TEXTURE_UNITS; ++i)
  349. {
  350. if (useTextureUnit_[i])
  351. ++usedTextureUnits;
  352. }
  353. file->WriteUInt(usedTextureUnits);
  354. for (unsigned i = 0; i < MAX_TEXTURE_UNITS; ++i)
  355. {
  356. if (useTextureUnit_[i])
  357. {
  358. file->WriteString(graphics_->GetTextureUnitName((TextureUnit)i));
  359. file->WriteUByte(i);
  360. }
  361. }
  362. unsigned dataSize = byteCode.Size() << 2;
  363. file->WriteUInt(dataSize);
  364. if (dataSize)
  365. file->Write(&byteCode[0], dataSize);
  366. }
  367. }