D3D9Shader.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343
  1. //
  2. // Urho3D Engine
  3. // Copyright (c) 2008-2012 Lasse Öörni
  4. //
  5. // Permission is hereby granted, free of charge, to any person obtaining a copy
  6. // of this software and associated documentation files (the "Software"), to deal
  7. // in the Software without restriction, including without limitation the rights
  8. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. // copies of the Software, and to permit persons to whom the Software is
  10. // furnished to do so, subject to the following conditions:
  11. //
  12. // The above copyright notice and this permission notice shall be included in
  13. // all copies or substantial portions of the Software.
  14. //
  15. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21. // THE SOFTWARE.
  22. //
  23. #include "Precompiled.h"
  24. #include "Context.h"
  25. #include "Deserializer.h"
  26. #include "File.h"
  27. #include "FileSystem.h"
  28. #include "Graphics.h"
  29. #include "GraphicsImpl.h"
  30. #include "Log.h"
  31. #include "Profiler.h"
  32. #include "ResourceCache.h"
  33. #include "Shader.h"
  34. #include "ShaderVariation.h"
  35. #include "XMLFile.h"
  36. #include "DebugNew.h"
  37. OBJECTTYPESTATIC(Shader);
  38. Shader::Shader(Context* context) :
  39. Resource(context),
  40. sourceModifiedTime_(0)
  41. {
  42. }
  43. Shader::~Shader()
  44. {
  45. }
  46. void Shader::RegisterObject(Context* context)
  47. {
  48. context->RegisterFactory<Shader>();
  49. }
  50. bool Shader::Load(Deserializer& source)
  51. {
  52. PROFILE(LoadShader);
  53. Graphics* graphics = GetSubsystem<Graphics>();
  54. if (!graphics)
  55. return false;
  56. // Get absolute file name of the shader in case we need to invoke ShaderCompiler. This only works if the shader was not
  57. // loaded from a package file
  58. fullFileName_.Clear();
  59. sourceModifiedTime_ = 0;
  60. File* sourceFile = dynamic_cast<File*>(&source);
  61. if (sourceFile && !sourceFile->IsPackaged())
  62. {
  63. ResourceCache* cache = GetSubsystem<ResourceCache>();
  64. FileSystem* fileSystem = GetSubsystem<FileSystem>();
  65. if (cache && fileSystem && !fileSystem->HasRegisteredPaths())
  66. {
  67. fullFileName_ = cache->GetResourceFileName(GetName());
  68. if (!fullFileName_.Empty())
  69. {
  70. // Get last modified time of the main HLSL source file
  71. String path, fileName, extension;
  72. SplitPath(fullFileName_, path, fileName, extension);
  73. String hlslFileName = path + fileName + ".hlsl";
  74. sourceModifiedTime_ = fileSystem->GetLastModifiedTime(hlslFileName);
  75. // Check also timestamps of any included files and the shader description file
  76. if (sourceModifiedTime_)
  77. {
  78. SharedPtr<File> file(new File(context_, hlslFileName));
  79. while (file->IsOpen() && !file->IsEof())
  80. {
  81. String line = file->ReadLine();
  82. if (line.StartsWith("#include"))
  83. {
  84. String includeFileName = path + line.Substring(9).Replaced("\"", "").Trimmed();
  85. unsigned includeFileTime = fileSystem->GetLastModifiedTime(includeFileName);
  86. if (includeFileTime > sourceModifiedTime_)
  87. sourceModifiedTime_ = includeFileTime;
  88. }
  89. }
  90. unsigned descriptionFileTime = fileSystem->GetLastModifiedTime(fullFileName_);
  91. if (descriptionFileTime > sourceModifiedTime_)
  92. sourceModifiedTime_ = descriptionFileTime;
  93. }
  94. else
  95. {
  96. // If the HLSL file was not found, do not attempt to compile shaders
  97. fullFileName_.Clear();
  98. }
  99. }
  100. }
  101. }
  102. unsigned memoryUse = sizeof(Shader);
  103. SharedPtr<XMLFile> xml(new XMLFile(context_));
  104. if (!xml->Load(source))
  105. return false;
  106. ShaderParser vsParser;
  107. ShaderParser psParser;
  108. Vector<String> globalDefines;
  109. Vector<String> globalDefineValues;
  110. if (graphics->GetSM3Support())
  111. {
  112. globalDefines.Push("SM3");
  113. globalDefineValues.Push("1");
  114. }
  115. if (!vsParser.Parse(VS, xml->GetRoot("shaders"), globalDefines, globalDefineValues))
  116. {
  117. LOGERROR("VS: " + vsParser.GetErrorMessage());
  118. return false;
  119. }
  120. if (!psParser.Parse(PS, xml->GetRoot("shaders"), globalDefines, globalDefineValues))
  121. {
  122. LOGERROR("PS: " + psParser.GetErrorMessage());
  123. return false;
  124. }
  125. // Do not create shader variations yet, but create space for them in the hash map
  126. const Vector<ShaderCombination>& vsCombinations = vsParser.GetCombinations();
  127. for (Vector<ShaderCombination>::ConstIterator i = vsCombinations.Begin(); i != vsCombinations.End(); ++i)
  128. {
  129. StringHash nameHash(i->name_);
  130. HashMap<StringHash, SharedPtr<ShaderVariation> >::Iterator j = vsVariations_.Find(nameHash);
  131. if (j == vsVariations_.End())
  132. j = vsVariations_.Insert(MakePair(nameHash, SharedPtr<ShaderVariation>()));
  133. else
  134. {
  135. // If shader variation already exists, release and reset bytecode
  136. j->second_->Release();
  137. j->second_->SetByteCode(SharedArrayPtr<unsigned char>());
  138. }
  139. }
  140. const Vector<ShaderCombination>& psCombinations = psParser.GetCombinations();
  141. for (Vector<ShaderCombination>::ConstIterator i = psCombinations.Begin(); i != psCombinations.End(); ++i)
  142. {
  143. StringHash nameHash(i->name_);
  144. HashMap<StringHash, SharedPtr<ShaderVariation> >::Iterator j = psVariations_.Find(nameHash);
  145. if (j == psVariations_.End())
  146. j = psVariations_.Insert(MakePair(nameHash, SharedPtr<ShaderVariation>()));
  147. else
  148. {
  149. // If shader variation already exists, release and reset bytecode
  150. j->second_->Release();
  151. j->second_->SetByteCode(SharedArrayPtr<unsigned char>());
  152. }
  153. }
  154. memoryUse += (vsVariations_.Size() + psVariations_.Size()) * sizeof(SharedPtr<ShaderVariation>);
  155. SetMemoryUse(memoryUse);
  156. return true;
  157. }
  158. ShaderVariation* Shader::GetVariation(ShaderType type, const String& name)
  159. {
  160. Graphics* graphics = GetSubsystem<Graphics>();
  161. if (!graphics)
  162. return 0;
  163. StringHash nameHash(name);
  164. if (type == VS)
  165. {
  166. HashMap<StringHash, SharedPtr<ShaderVariation> >::Iterator i = vsVariations_.Find(nameHash);
  167. if (i != vsVariations_.End())
  168. {
  169. // Create the shader variation now if not created yet
  170. if (!i->second_)
  171. {
  172. String path, fileName, extension;
  173. SplitPath(GetName(), path, fileName, extension);
  174. String compiledShaderName = path + fileName;
  175. if (!name.Empty())
  176. compiledShaderName += "_" + name;
  177. compiledShaderName += graphics->GetSM3Support() ? ".vs3" : ".vs2";
  178. i->second_ = new ShaderVariation(this, VS);
  179. i->second_->SetName(compiledShaderName);
  180. SetMemoryUse(GetMemoryUse() + sizeof(ShaderVariation));
  181. }
  182. return i->second_;
  183. }
  184. else
  185. return 0;
  186. }
  187. else
  188. {
  189. HashMap<StringHash, SharedPtr<ShaderVariation> >::Iterator i = psVariations_.Find(nameHash);
  190. if (i != psVariations_.End())
  191. {
  192. // Create the shader variation now if not created yet
  193. if (!i->second_)
  194. {
  195. String path, fileName, extension;
  196. SplitPath(GetName(), path, fileName, extension);
  197. String compiledShaderName = path + fileName;
  198. if (!name.Empty())
  199. compiledShaderName += "_" + name;
  200. compiledShaderName += graphics->GetSM3Support() ? ".ps3" : ".ps2";
  201. i->second_ = new ShaderVariation(this, PS);
  202. i->second_->SetName(compiledShaderName);
  203. SetMemoryUse(GetMemoryUse() + sizeof(ShaderVariation));
  204. }
  205. return i->second_;
  206. }
  207. else
  208. return 0;
  209. }
  210. }
  211. bool Shader::PrepareVariation(ShaderVariation* variation)
  212. {
  213. if (!variation)
  214. return false;
  215. FileSystem* fileSystem = GetSubsystem<FileSystem>();
  216. Graphics* graphics = GetSubsystem<Graphics>();
  217. ResourceCache* cache = GetSubsystem<ResourceCache>();
  218. if (!fileSystem || !graphics || !cache)
  219. return false;
  220. String shaderName = variation->GetName();
  221. String variationName = GetFileName(shaderName);
  222. unsigned pos = variationName.Find('_');
  223. if (pos != String::NPOS)
  224. variationName = variationName.Substring(pos + 1);
  225. else
  226. variationName.Clear();
  227. if (!fullFileName_.Empty())
  228. {
  229. if (fileSystem->GetLastModifiedTime(cache->GetResourceFileName(shaderName)) < sourceModifiedTime_)
  230. {
  231. PROFILE(CompileShader);
  232. LOGINFO("Compiling shader " + shaderName);
  233. Vector<String> arguments;
  234. arguments.Push("\"" + fullFileName_ + "\"");
  235. arguments.Push(variation->GetShaderType() == VS ? "-tVS" : "-tPS");
  236. arguments.Push("-v" + variationName);
  237. if (graphics->GetSM3Support())
  238. arguments.Push("-dSM3");
  239. if (fileSystem->SystemRun(fileSystem->GetProgramDir() + "ShaderCompiler", arguments) != 0)
  240. {
  241. LOGERROR("Failed to compile shader " + shaderName);
  242. return false;
  243. }
  244. }
  245. }
  246. SharedPtr<File> file(cache->GetFile(shaderName));
  247. if (!file)
  248. return false;
  249. if (file->ReadFileID() != "USHD")
  250. {
  251. LOGERROR(shaderName + " is not a valid shader bytecode file");
  252. return false;
  253. }
  254. /// \todo Check that shader type and model match
  255. unsigned short shaderType = file->ReadUShort();
  256. unsigned short shaderModel = file->ReadUShort();
  257. unsigned numParameters = file->ReadUInt();
  258. for (unsigned i = 0; i < numParameters; ++i)
  259. {
  260. String paramName = file->ReadString();
  261. unsigned reg = file->ReadUByte();
  262. unsigned regCount = file->ReadUByte();
  263. StringHash nameHash(paramName);
  264. ShaderParameter parameter(variation->GetShaderType(), reg, regCount);
  265. variation->AddParameter(nameHash, parameter);
  266. // Register the parameter globally
  267. graphics->RegisterShaderParameter(nameHash, parameter);
  268. }
  269. unsigned numTextureUnits = file->ReadUInt();
  270. for (unsigned i = 0; i < numTextureUnits; ++i)
  271. {
  272. String unitName = file->ReadString();
  273. unsigned sampler = file->ReadUByte();
  274. TextureUnit tuIndex = graphics->GetTextureUnit(unitName);
  275. if (tuIndex != MAX_TEXTURE_UNITS)
  276. variation->AddTextureUnit(tuIndex);
  277. else if (sampler < MAX_TEXTURE_UNITS)
  278. variation->AddTextureUnit((TextureUnit)sampler);
  279. }
  280. unsigned byteCodeSize = file->ReadUInt();
  281. if (byteCodeSize)
  282. {
  283. SharedArrayPtr<unsigned char> byteCode(new unsigned char[byteCodeSize]);
  284. file->Read(byteCode.Get(), byteCodeSize);
  285. variation->SetByteCode(byteCode);
  286. SetMemoryUse(GetMemoryUse() + byteCodeSize);
  287. return true;
  288. }
  289. else
  290. {
  291. LOGERROR("Shader " + shaderName + " has zero length bytecode");
  292. return false;
  293. }
  294. }