D3D9ShaderVariation.cpp 14 KB

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