Shader.cpp 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222
  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 "../Core/Context.h"
  24. #include "../IO/Deserializer.h"
  25. #include "../IO/FileSystem.h"
  26. #include "../Graphics/Graphics.h"
  27. #include "../IO/Log.h"
  28. #include "../Core/Profiler.h"
  29. #include "../Resource/ResourceCache.h"
  30. #include "../Graphics/Shader.h"
  31. #include "../Graphics/ShaderVariation.h"
  32. #include "../Container/Sort.h"
  33. #include "../Resource/XMLFile.h"
  34. #include "../DebugNew.h"
  35. namespace Atomic
  36. {
  37. void CommentOutFunction(String& code, const String& signature)
  38. {
  39. unsigned startPos = code.Find(signature);
  40. unsigned braceLevel = 0;
  41. if (startPos == String::NPOS)
  42. return;
  43. code.Insert(startPos, "/*");
  44. for (unsigned i = startPos + 2 + signature.Length(); i < code.Length(); ++i)
  45. {
  46. if (code[i] == '{')
  47. ++braceLevel;
  48. else if (code[i] == '}')
  49. {
  50. --braceLevel;
  51. if (braceLevel == 0)
  52. {
  53. code.Insert(i + 1, "*/");
  54. return;
  55. }
  56. }
  57. }
  58. }
  59. Shader::Shader(Context* context) :
  60. Resource(context),
  61. timeStamp_(0),
  62. numVariations_(0)
  63. {
  64. RefreshMemoryUse();
  65. }
  66. Shader::~Shader()
  67. {
  68. ResourceCache* cache = GetSubsystem<ResourceCache>();
  69. cache->ResetDependencies(this);
  70. }
  71. void Shader::RegisterObject(Context* context)
  72. {
  73. context->RegisterFactory<Shader>();
  74. }
  75. bool Shader::BeginLoad(Deserializer& source)
  76. {
  77. Graphics* graphics = GetSubsystem<Graphics>();
  78. if (!graphics)
  79. return false;
  80. // Load the shader source code and resolve any includes
  81. timeStamp_ = 0;
  82. String shaderCode;
  83. if (!ProcessSource(shaderCode, source))
  84. return false;
  85. // Comment out the unneeded shader function
  86. vsSourceCode_ = shaderCode;
  87. psSourceCode_ = shaderCode;
  88. CommentOutFunction(vsSourceCode_, "void PS(");
  89. CommentOutFunction(psSourceCode_, "void VS(");
  90. // OpenGL: rename either VS() or PS() to main(), comment out vertex attributes in pixel shaders
  91. #ifdef ATOMIC_OPENGL
  92. vsSourceCode_.Replace("void VS(", "void main(");
  93. psSourceCode_.Replace("void PS(", "void main(");
  94. psSourceCode_.Replace("attribute ", "// attribute ");
  95. #endif
  96. RefreshMemoryUse();
  97. return true;
  98. }
  99. bool Shader::EndLoad()
  100. {
  101. // If variations had already been created, release them and require recompile
  102. for (HashMap<StringHash, SharedPtr<ShaderVariation> >::Iterator i = vsVariations_.Begin(); i != vsVariations_.End(); ++i)
  103. i->second_->Release();
  104. for (HashMap<StringHash, SharedPtr<ShaderVariation> >::Iterator i = psVariations_.Begin(); i != psVariations_.End(); ++i)
  105. i->second_->Release();
  106. return true;
  107. }
  108. ShaderVariation* Shader::GetVariation(ShaderType type, const String& defines)
  109. {
  110. return GetVariation(type, defines.CString());
  111. }
  112. ShaderVariation* Shader::GetVariation(ShaderType type, const char* defines)
  113. {
  114. StringHash definesHash(defines);
  115. HashMap<StringHash, SharedPtr<ShaderVariation> > & variations(type == VS ? vsVariations_ : psVariations_);
  116. HashMap<StringHash, SharedPtr<ShaderVariation> >::Iterator i = variations.Find(definesHash);
  117. if (i == variations.End())
  118. {
  119. // If shader not found, normalize the defines (to prevent duplicates) and check again. In that case make an alias
  120. // so that further queries are faster
  121. String normalizedDefines = NormalizeDefines(defines);
  122. StringHash normalizedHash(normalizedDefines);
  123. i = variations.Find(normalizedHash);
  124. if (i != variations.End())
  125. variations.Insert(MakePair(definesHash, i->second_));
  126. else
  127. {
  128. // No shader variation found. Create new
  129. i = variations.Insert(MakePair(normalizedHash, SharedPtr<ShaderVariation>(new ShaderVariation(this, type))));
  130. if (definesHash != normalizedHash)
  131. variations.Insert(MakePair(definesHash, i->second_));
  132. i->second_->SetName(GetFileName(GetName()));
  133. i->second_->SetDefines(normalizedDefines);
  134. ++numVariations_;
  135. RefreshMemoryUse();
  136. }
  137. }
  138. return i->second_;
  139. }
  140. bool Shader::ProcessSource(String& code, Deserializer& source)
  141. {
  142. ResourceCache* cache = GetSubsystem<ResourceCache>();
  143. // If the source if a non-packaged file, store the timestamp
  144. File* file = dynamic_cast<File*>(&source);
  145. if (file && !file->IsPackaged())
  146. {
  147. FileSystem* fileSystem = GetSubsystem<FileSystem>();
  148. String fullName = cache->GetResourceFileName(file->GetName());
  149. unsigned fileTimeStamp = fileSystem->GetLastModifiedTime(fullName);
  150. if (fileTimeStamp > timeStamp_)
  151. timeStamp_ = fileTimeStamp;
  152. }
  153. // Store resource dependencies for includes so that we know to reload if any of them changes
  154. if (source.GetName() != GetName())
  155. cache->StoreResourceDependency(this, source.GetName());
  156. while (!source.IsEof())
  157. {
  158. String line = source.ReadLine();
  159. if (line.StartsWith("#include"))
  160. {
  161. String includeFileName = GetPath(source.GetName()) + line.Substring(9).Replaced("\"", "").Trimmed();
  162. SharedPtr<File> includeFile = cache->GetFile(includeFileName);
  163. if (!includeFile)
  164. return false;
  165. // Add the include file into the current code recursively
  166. if (!ProcessSource(code, *includeFile))
  167. return false;
  168. }
  169. else
  170. {
  171. code += line;
  172. code += "\n";
  173. }
  174. }
  175. // Finally insert an empty line to mark the space between files
  176. code += "\n";
  177. return true;
  178. }
  179. String Shader::NormalizeDefines(const String& defines)
  180. {
  181. Vector<String> definesVec = defines.ToUpper().Split(' ');
  182. Sort(definesVec.Begin(), definesVec.End());
  183. return String::Joined(definesVec, " ");
  184. }
  185. void Shader::RefreshMemoryUse()
  186. {
  187. SetMemoryUse(sizeof(Shader) + vsSourceCode_.Length() + psSourceCode_.Length() + numVariations_ * sizeof(ShaderVariation));
  188. }
  189. }