D3D9ShaderVariation.cpp 14 KB

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