D3D9ShaderVariation.cpp 13 KB

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