2
0

Shader.cpp 5.8 KB

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