D3D9Shader.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317
  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. SharedPtr<XMLFile> xml(new XMLFile(context_));
  103. if (!xml->Load(source))
  104. return false;
  105. Vector<String> globalDefines;
  106. Vector<String> globalDefineValues;
  107. if (graphics->GetSM3Support())
  108. {
  109. globalDefines.Push("SM3");
  110. globalDefineValues.Push("1");
  111. }
  112. if (!vsParser_.Parse(VS, xml->GetRoot("shaders"), globalDefines, globalDefineValues))
  113. {
  114. LOGERROR("VS: " + vsParser_.GetErrorMessage());
  115. return false;
  116. }
  117. if (!psParser_.Parse(PS, xml->GetRoot("shaders"), globalDefines, globalDefineValues))
  118. {
  119. LOGERROR("PS: " + psParser_.GetErrorMessage());
  120. return false;
  121. }
  122. // If variations had already been created, clear their bytecode
  123. for (HashMap<StringHash, SharedPtr<ShaderVariation> >::Iterator i = vsVariations_.Begin(); i != vsVariations_.End(); ++i)
  124. {
  125. i->second_->Release();
  126. i->second_->SetByteCode(SharedArrayPtr<unsigned char>());
  127. }
  128. for (HashMap<StringHash, SharedPtr<ShaderVariation> >::Iterator i = psVariations_.Begin(); i != psVariations_.End(); ++i)
  129. {
  130. i->second_->Release();
  131. i->second_->SetByteCode(SharedArrayPtr<unsigned char>());
  132. }
  133. SetMemoryUse(sizeof(Shader) + 2 * sizeof(ShaderParser) + (vsVariations_.Size() + psVariations_.Size()) *
  134. sizeof(ShaderVariation));
  135. return true;
  136. }
  137. ShaderVariation* Shader::GetVariation(ShaderType type, const String& name)
  138. {
  139. Graphics* graphics = GetSubsystem<Graphics>();
  140. if (!graphics)
  141. return 0;
  142. StringHash nameHash(name);
  143. if (type == VS)
  144. {
  145. if (vsParser_.HasCombination(name))
  146. {
  147. HashMap<StringHash, SharedPtr<ShaderVariation> >::Iterator i = vsVariations_.Find(nameHash);
  148. // Create the shader variation now if not created yet
  149. if (i == vsVariations_.End())
  150. {
  151. String path, fileName, extension;
  152. SplitPath(GetName(), path, fileName, extension);
  153. String compiledShaderName = path + fileName;
  154. if (!name.Empty())
  155. compiledShaderName += "_" + name;
  156. compiledShaderName += graphics->GetSM3Support() ? ".vs3" : ".vs2";
  157. i = vsVariations_.Insert(MakePair(nameHash, SharedPtr<ShaderVariation>(new ShaderVariation(this, VS))));
  158. i->second_->SetName(compiledShaderName);
  159. SetMemoryUse(GetMemoryUse() + sizeof(ShaderVariation));
  160. }
  161. return i->second_;
  162. }
  163. else
  164. return 0;
  165. }
  166. else
  167. {
  168. if (psParser_.HasCombination(name))
  169. {
  170. HashMap<StringHash, SharedPtr<ShaderVariation> >::Iterator i = psVariations_.Find(nameHash);
  171. // Create the shader variation now if not created yet
  172. if (i == psVariations_.End())
  173. {
  174. String path, fileName, extension;
  175. SplitPath(GetName(), path, fileName, extension);
  176. String compiledShaderName = path + fileName;
  177. if (!name.Empty())
  178. compiledShaderName += "_" + name;
  179. compiledShaderName += graphics->GetSM3Support() ? ".ps3" : ".ps2";
  180. i = psVariations_.Insert(MakePair(nameHash, SharedPtr<ShaderVariation>(new ShaderVariation(this, PS))));
  181. i->second_->SetName(compiledShaderName);
  182. SetMemoryUse(GetMemoryUse() + sizeof(ShaderVariation));
  183. }
  184. return i->second_;
  185. }
  186. else
  187. return 0;
  188. }
  189. }
  190. bool Shader::PrepareVariation(ShaderVariation* variation)
  191. {
  192. if (!variation)
  193. return false;
  194. FileSystem* fileSystem = GetSubsystem<FileSystem>();
  195. Graphics* graphics = GetSubsystem<Graphics>();
  196. ResourceCache* cache = GetSubsystem<ResourceCache>();
  197. if (!fileSystem || !graphics || !cache)
  198. return false;
  199. String shaderName = variation->GetName();
  200. String variationName = GetFileName(shaderName);
  201. unsigned pos = variationName.Find('_');
  202. if (pos != String::NPOS)
  203. variationName = variationName.Substring(pos + 1);
  204. else
  205. variationName.Clear();
  206. if (!fullFileName_.Empty())
  207. {
  208. if (fileSystem->GetLastModifiedTime(cache->GetResourceFileName(shaderName)) < sourceModifiedTime_)
  209. {
  210. PROFILE(CompileShader);
  211. LOGINFO("Compiling shader " + shaderName);
  212. Vector<String> arguments;
  213. arguments.Push("\"" + fullFileName_ + "\"");
  214. arguments.Push(variation->GetShaderType() == VS ? "-tVS" : "-tPS");
  215. arguments.Push("-v" + variationName);
  216. if (graphics->GetSM3Support())
  217. arguments.Push("-dSM3");
  218. if (fileSystem->SystemRun(fileSystem->GetProgramDir() + "ShaderCompiler", arguments) != 0)
  219. {
  220. LOGERROR("Failed to compile shader " + shaderName);
  221. return false;
  222. }
  223. }
  224. }
  225. SharedPtr<File> file(cache->GetFile(shaderName));
  226. if (!file)
  227. return false;
  228. if (file->ReadFileID() != "USHD")
  229. {
  230. LOGERROR(shaderName + " is not a valid shader bytecode file");
  231. return false;
  232. }
  233. /// \todo Check that shader type and model match
  234. unsigned short shaderType = file->ReadUShort();
  235. unsigned short shaderModel = file->ReadUShort();
  236. unsigned numParameters = file->ReadUInt();
  237. for (unsigned i = 0; i < numParameters; ++i)
  238. {
  239. String paramName = file->ReadString();
  240. unsigned reg = file->ReadUByte();
  241. unsigned regCount = file->ReadUByte();
  242. StringHash nameHash(paramName);
  243. ShaderParameter parameter(variation->GetShaderType(), reg, regCount);
  244. variation->AddParameter(nameHash, parameter);
  245. // Register the parameter globally
  246. graphics->RegisterShaderParameter(nameHash, parameter);
  247. }
  248. unsigned numTextureUnits = file->ReadUInt();
  249. for (unsigned i = 0; i < numTextureUnits; ++i)
  250. {
  251. String unitName = file->ReadString();
  252. unsigned sampler = file->ReadUByte();
  253. TextureUnit tuIndex = graphics->GetTextureUnit(unitName);
  254. if (tuIndex != MAX_TEXTURE_UNITS)
  255. variation->AddTextureUnit(tuIndex);
  256. else if (sampler < MAX_TEXTURE_UNITS)
  257. variation->AddTextureUnit((TextureUnit)sampler);
  258. }
  259. unsigned byteCodeSize = file->ReadUInt();
  260. if (byteCodeSize)
  261. {
  262. SharedArrayPtr<unsigned char> byteCode(new unsigned char[byteCodeSize]);
  263. file->Read(byteCode.Get(), byteCodeSize);
  264. variation->SetByteCode(byteCode);
  265. SetMemoryUse(GetMemoryUse() + byteCodeSize);
  266. return true;
  267. }
  268. else
  269. {
  270. LOGERROR("Shader " + shaderName + " has zero length bytecode");
  271. return false;
  272. }
  273. }