D3D9Shader.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330
  1. //
  2. // Copyright (c) 2008-2013 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 "Context.h"
  24. #include "Deserializer.h"
  25. #include "File.h"
  26. #include "FileSystem.h"
  27. #include "Graphics.h"
  28. #include "GraphicsImpl.h"
  29. #include "Log.h"
  30. #include "Profiler.h"
  31. #include "ResourceCache.h"
  32. #include "Shader.h"
  33. #include "ShaderVariation.h"
  34. #include "XMLFile.h"
  35. #include "DebugNew.h"
  36. namespace Urho3D
  37. {
  38. Shader::Shader(Context* context) :
  39. Resource(context),
  40. sourceModifiedTime_(0)
  41. {
  42. }
  43. Shader::~Shader()
  44. {
  45. ResourceCache* cache = GetSubsystem<ResourceCache>();
  46. if (cache)
  47. cache->ResetDependencies(this);
  48. }
  49. void Shader::RegisterObject(Context* context)
  50. {
  51. context->RegisterFactory<Shader>();
  52. }
  53. bool Shader::Load(Deserializer& source)
  54. {
  55. PROFILE(LoadShader);
  56. ResourceCache* cache = GetSubsystem<ResourceCache>();
  57. cache->ResetDependencies(this);
  58. Graphics* graphics = GetSubsystem<Graphics>();
  59. if (!graphics)
  60. return false;
  61. if (graphics->GetSM3Support())
  62. {
  63. vsExtension_ = ".vs3";
  64. psExtension_ = ".ps3";
  65. subDir_ = "SM3/";
  66. }
  67. else
  68. {
  69. vsExtension_ = ".vs2";
  70. psExtension_ = ".ps2";
  71. subDir_ = "SM2/";
  72. }
  73. // Get absolute file name of the shader in case we need to invoke ShaderCompiler. This only works if the shader was not
  74. // loaded from a package file
  75. fullFileName_.Clear();
  76. sourceModifiedTime_ = 0;
  77. File* sourceFile = dynamic_cast<File*>(&source);
  78. if (sourceFile && !sourceFile->IsPackaged())
  79. {
  80. PROFILE(CheckTimestamps);
  81. FileSystem* fileSystem = GetSubsystem<FileSystem>();
  82. if (fileSystem && !fileSystem->HasRegisteredPaths())
  83. {
  84. fullFileName_ = cache->GetResourceFileName(GetName());
  85. if (!fullFileName_.Empty())
  86. {
  87. // Get last modified time of the main HLSL source file
  88. String path, fileName, extension;
  89. SplitPath(fullFileName_, path, fileName, extension);
  90. String hlslFileName = path + fileName + ".hlsl";
  91. sourceModifiedTime_ = fileSystem->GetLastModifiedTime(hlslFileName);
  92. String resourcePath = GetPath(GetName());
  93. cache->StoreResourceDependency(this, resourcePath + fileName + ".hlsl");
  94. // Check also timestamps of any included files and the shader description file
  95. if (sourceModifiedTime_)
  96. {
  97. SharedPtr<File> file(new File(context_, hlslFileName));
  98. while (file->IsOpen() && !file->IsEof())
  99. {
  100. String line = file->ReadLine();
  101. if (line.StartsWith("#include"))
  102. {
  103. String includeName = line.Substring(9).Replaced("\"", "").Trimmed();
  104. String includeFullName = path + includeName;
  105. cache->StoreResourceDependency(this, resourcePath + includeName);
  106. unsigned includeFileTime = fileSystem->GetLastModifiedTime(includeFullName);
  107. if (includeFileTime > sourceModifiedTime_)
  108. sourceModifiedTime_ = includeFileTime;
  109. }
  110. }
  111. unsigned descriptionFileTime = fileSystem->GetLastModifiedTime(fullFileName_);
  112. if (descriptionFileTime > sourceModifiedTime_)
  113. sourceModifiedTime_ = descriptionFileTime;
  114. }
  115. else
  116. {
  117. // If the HLSL file was not found, do not attempt to compile shaders
  118. fullFileName_.Clear();
  119. }
  120. }
  121. }
  122. }
  123. SharedPtr<XMLFile> xml(new XMLFile(context_));
  124. if (!xml->Load(source))
  125. return false;
  126. XMLElement shaders = xml->GetRoot("shaders");
  127. if (!shaders)
  128. {
  129. LOGERROR("No shaders element in " + source.GetName());
  130. return false;
  131. }
  132. Vector<String> globalDefines;
  133. Vector<String> globalDefineValues;
  134. if (graphics->GetSM3Support())
  135. {
  136. globalDefines.Push("SM3");
  137. globalDefineValues.Push("1");
  138. }
  139. {
  140. PROFILE(ParseShaderDefinition);
  141. if (!vsParser_.Parse(VS, shaders, globalDefines, globalDefineValues))
  142. {
  143. LOGERROR("VS: " + vsParser_.GetErrorMessage());
  144. return false;
  145. }
  146. if (!psParser_.Parse(PS, shaders, globalDefines, globalDefineValues))
  147. {
  148. LOGERROR("PS: " + psParser_.GetErrorMessage());
  149. return false;
  150. }
  151. }
  152. // If variations had already been created, clear their bytecode
  153. for (HashMap<StringHash, SharedPtr<ShaderVariation> >::Iterator i = vsVariations_.Begin(); i != vsVariations_.End(); ++i)
  154. {
  155. i->second_->Release();
  156. i->second_->SetByteCode(SharedArrayPtr<unsigned char>());
  157. }
  158. for (HashMap<StringHash, SharedPtr<ShaderVariation> >::Iterator i = psVariations_.Begin(); i != psVariations_.End(); ++i)
  159. {
  160. i->second_->Release();
  161. i->second_->SetByteCode(SharedArrayPtr<unsigned char>());
  162. }
  163. SetMemoryUse(sizeof(Shader) + 2 * sizeof(ShaderParser) + (vsVariations_.Size() + psVariations_.Size()) *
  164. sizeof(ShaderVariation));
  165. return true;
  166. }
  167. ShaderVariation* Shader::GetVariation(ShaderType type, const String& name)
  168. {
  169. Graphics* graphics = GetSubsystem<Graphics>();
  170. if (!graphics)
  171. return 0;
  172. StringHash nameHash(name);
  173. ShaderParser& parser = type == VS ? vsParser_ : psParser_;
  174. HashMap<StringHash, SharedPtr<ShaderVariation> >& variations = type == VS ? vsVariations_ : psVariations_;
  175. if (parser.HasCombination(name))
  176. {
  177. HashMap<StringHash, SharedPtr<ShaderVariation> >::Iterator i = variations.Find(nameHash);
  178. // Create the shader variation now if not created yet
  179. if (i == variations.End())
  180. {
  181. String path, fileName, extension;
  182. SplitPath(GetName(), path, fileName, extension);
  183. String compiledShaderName = path + subDir_ + fileName;
  184. if (!name.Empty())
  185. compiledShaderName += "_" + name;
  186. compiledShaderName += type == VS ? vsExtension_ : psExtension_;
  187. i = variations.Insert(MakePair(nameHash, SharedPtr<ShaderVariation>(new ShaderVariation(this, type))));
  188. i->second_->SetName(compiledShaderName);
  189. SetMemoryUse(GetMemoryUse() + sizeof(ShaderVariation));
  190. }
  191. return i->second_;
  192. }
  193. else
  194. return 0;
  195. }
  196. bool Shader::PrepareVariation(ShaderVariation* variation)
  197. {
  198. if (!variation)
  199. return false;
  200. FileSystem* fileSystem = GetSubsystem<FileSystem>();
  201. Graphics* graphics = GetSubsystem<Graphics>();
  202. ResourceCache* cache = GetSubsystem<ResourceCache>();
  203. if (!fileSystem || !graphics || !cache)
  204. return false;
  205. String shaderName = variation->GetName();
  206. String variationName = GetFileName(shaderName);
  207. unsigned pos = variationName.Find('_');
  208. if (pos != String::NPOS)
  209. variationName = variationName.Substring(pos + 1);
  210. else
  211. variationName.Clear();
  212. if (!fullFileName_.Empty())
  213. {
  214. if (fileSystem->GetLastModifiedTime(cache->GetResourceFileName(shaderName)) < sourceModifiedTime_)
  215. {
  216. PROFILE(CompileShader);
  217. LOGINFO("Compiling shader " + shaderName);
  218. Vector<String> arguments;
  219. arguments.Push("\"" + fullFileName_ + "\"");
  220. arguments.Push("\"" + GetPath(fullFileName_) + subDir_ + "\"");
  221. arguments.Push(variation->GetShaderType() == VS ? "-t VS" : "-t PS");
  222. arguments.Push("-v \"" + variationName + "\"");
  223. if (graphics->GetSM3Support())
  224. arguments.Push("-d SM3");
  225. if (fileSystem->SystemRun(fileSystem->GetProgramDir() + "ShaderCompiler", arguments) != 0)
  226. {
  227. LOGERROR("Failed to compile shader " + shaderName);
  228. return false;
  229. }
  230. }
  231. }
  232. SharedPtr<File> file(cache->GetFile(shaderName));
  233. if (!file)
  234. return false;
  235. if (file->ReadFileID() != "USHD")
  236. {
  237. LOGERROR(shaderName + " is not a valid shader bytecode file");
  238. return false;
  239. }
  240. /// \todo Check that shader type and model match
  241. unsigned short shaderType = file->ReadUShort();
  242. unsigned short shaderModel = file->ReadUShort();
  243. unsigned numParameters = file->ReadUInt();
  244. for (unsigned i = 0; i < numParameters; ++i)
  245. {
  246. String paramName = file->ReadString();
  247. unsigned reg = file->ReadUByte();
  248. unsigned regCount = file->ReadUByte();
  249. StringHash nameHash(paramName);
  250. ShaderParameter parameter(variation->GetShaderType(), reg, regCount);
  251. variation->AddParameter(nameHash, parameter);
  252. // Register the parameter globally
  253. graphics->RegisterShaderParameter(nameHash, parameter);
  254. }
  255. unsigned numTextureUnits = file->ReadUInt();
  256. for (unsigned i = 0; i < numTextureUnits; ++i)
  257. {
  258. String unitName = file->ReadString();
  259. unsigned sampler = file->ReadUByte();
  260. TextureUnit tuIndex = graphics->GetTextureUnit(unitName);
  261. if (tuIndex < MAX_TEXTURE_UNITS)
  262. variation->AddTextureUnit(tuIndex);
  263. else if (sampler < MAX_TEXTURE_UNITS)
  264. variation->AddTextureUnit((TextureUnit)sampler);
  265. }
  266. unsigned byteCodeSize = file->ReadUInt();
  267. if (byteCodeSize)
  268. {
  269. SharedArrayPtr<unsigned char> byteCode(new unsigned char[byteCodeSize]);
  270. file->Read(byteCode.Get(), byteCodeSize);
  271. variation->SetByteCode(byteCode);
  272. SetMemoryUse(GetMemoryUse() + byteCodeSize);
  273. return true;
  274. }
  275. else
  276. {
  277. LOGERROR("Shader " + shaderName + " has zero length bytecode");
  278. return false;
  279. }
  280. }
  281. }