Material.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405
  1. //
  2. // Urho3D Engine
  3. // Copyright (c) 2008-2011 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 "FileSystem.h"
  26. #include "Graphics.h"
  27. #include "Log.h"
  28. #include "Material.h"
  29. #include "Matrix3x4.h"
  30. #include "Profiler.h"
  31. #include "ResourceCache.h"
  32. #include "StringUtils.h"
  33. #include "Technique.h"
  34. #include "Texture2D.h"
  35. #include "TextureCube.h"
  36. #include "XMLFile.h"
  37. #include "DebugNew.h"
  38. static const String textureUnitNames[] =
  39. {
  40. "diffuse",
  41. "normal",
  42. "specular",
  43. "detail",
  44. "environment",
  45. "emissive",
  46. "lightramp", // Not defined by materials
  47. "lightspot", // Not defined by materials
  48. ""
  49. };
  50. static const String cullModeNames[] =
  51. {
  52. "none",
  53. "ccw",
  54. "cw",
  55. ""
  56. };
  57. TechniqueEntry::TechniqueEntry() :
  58. qualityLevel_(0),
  59. lodDistance_(0.0f)
  60. {
  61. }
  62. TechniqueEntry::TechniqueEntry(Technique* technique, unsigned qualityLevel, float lodDistance) :
  63. technique_(technique),
  64. qualityLevel_(qualityLevel),
  65. lodDistance_(lodDistance)
  66. {
  67. }
  68. TechniqueEntry::~TechniqueEntry()
  69. {
  70. }
  71. OBJECTTYPESTATIC(Material);
  72. Material::Material(Context* context) :
  73. Resource(context),
  74. cullMode_(CULL_CCW),
  75. shadowCullMode_(CULL_CCW),
  76. auxViewFrameNumber_(0),
  77. occlusion_(true)
  78. {
  79. SetNumTechniques(1);
  80. textures_.Resize(MAX_MATERIAL_TEXTURE_UNITS);
  81. // Setup often used default parameters
  82. SetShaderParameter("UOffset", Vector4(1.0f, 0.0f, 0.0f, 0.0f));
  83. SetShaderParameter("VOffset", Vector4(0.0f, 1.0f, 0.0f, 0.0f));
  84. SetShaderParameter("MatDiffColor", Vector4::UNITY);
  85. SetShaderParameter("MatEmissiveColor", Vector4::ZERO);
  86. SetShaderParameter("MatSpecProperties", Vector4::ZERO);
  87. }
  88. Material::~Material()
  89. {
  90. }
  91. void Material::RegisterObject(Context* context)
  92. {
  93. context->RegisterFactory<Material>();
  94. }
  95. bool Material::Load(Deserializer& source)
  96. {
  97. PROFILE(LoadMaterial);
  98. // In headless mode, do not actually load the material, just return success
  99. Graphics* graphics = GetSubsystem<Graphics>();
  100. if (!graphics)
  101. return true;
  102. ResourceCache* cache = GetSubsystem<ResourceCache>();
  103. SharedPtr<XMLFile> xml(new XMLFile(context_));
  104. if (!xml->Load(source))
  105. return false;
  106. XMLElement rootElem = xml->GetRoot();
  107. XMLElement techniqueElem = rootElem.GetChild("technique");
  108. techniques_.Clear();
  109. while (techniqueElem)
  110. {
  111. Technique* technique = cache->GetResource<Technique>(techniqueElem.GetString("name"));
  112. if (technique)
  113. {
  114. TechniqueEntry newTechnique;
  115. newTechnique.technique_ = technique;
  116. if (techniqueElem.HasAttribute("quality"))
  117. newTechnique.qualityLevel_ = techniqueElem.GetInt("quality");
  118. if (techniqueElem.HasAttribute("loddistance"))
  119. newTechnique.lodDistance_ = techniqueElem.GetFloat("loddistance");
  120. techniques_.Push(newTechnique);
  121. }
  122. techniqueElem = techniqueElem.GetNext("technique");
  123. }
  124. XMLElement textureElem = rootElem.GetChild("texture");
  125. while (textureElem)
  126. {
  127. TextureUnit unit = TU_DIFFUSE;
  128. if (textureElem.HasAttribute("unit"))
  129. {
  130. String unitName = textureElem.GetStringLower("unit");
  131. unit = (TextureUnit)GetStringListIndex(unitName, textureUnitNames, MAX_MATERIAL_TEXTURE_UNITS);
  132. if (unitName == "diff")
  133. unit = TU_DIFFUSE;
  134. if (unitName == "norm")
  135. unit = TU_NORMAL;
  136. if (unitName == "spec")
  137. unit = TU_SPECULAR;
  138. if (unitName == "env")
  139. unit = TU_ENVIRONMENT;
  140. if (unit == MAX_MATERIAL_TEXTURE_UNITS)
  141. LOGERROR("Unknown texture unit " + unitName);
  142. }
  143. if (unit != MAX_MATERIAL_TEXTURE_UNITS)
  144. {
  145. String name = textureElem.GetString("name");
  146. // Detect cube maps by file extension: they are defined by an XML file
  147. if (GetExtension(name) == ".xml")
  148. SetTexture(unit, cache->GetResource<TextureCube>(name));
  149. else
  150. SetTexture(unit, cache->GetResource<Texture2D>(name));
  151. }
  152. textureElem = textureElem.GetNext("texture");
  153. }
  154. XMLElement parameterElem = rootElem.GetChild("parameter");
  155. while (parameterElem)
  156. {
  157. String name = parameterElem.GetString("name");
  158. Vector4 value = parameterElem.GetVector("value");
  159. SetShaderParameter(name, value);
  160. parameterElem = parameterElem.GetNext("parameter");
  161. }
  162. XMLElement cullElem = rootElem.GetChild("cull");
  163. if (cullElem)
  164. SetCullMode((CullMode)GetStringListIndex(cullElem.GetString("value"), cullModeNames, CULL_CCW));
  165. XMLElement shadowCullElem = rootElem.GetChild("shadowcull");
  166. if (shadowCullElem)
  167. SetShadowCullMode((CullMode)GetStringListIndex(shadowCullElem.GetString("value"), cullModeNames, CULL_CCW));
  168. // Calculate memory use
  169. unsigned memoryUse = 0;
  170. memoryUse += sizeof(Material);
  171. memoryUse += techniques_.Size() * sizeof(TechniqueEntry);
  172. memoryUse += textures_.Size() * sizeof(SharedPtr<Texture>);
  173. memoryUse += shaderParameters_.Size() * sizeof(MaterialShaderParameter);
  174. SetMemoryUse(memoryUse);
  175. CheckOcclusion();
  176. return true;
  177. }
  178. bool Material::Save(Serializer& dest)
  179. {
  180. SharedPtr<XMLFile> xml(new XMLFile(context_));
  181. XMLElement materialElem = xml->CreateRoot("material");
  182. // Write techniques
  183. for (unsigned i = 0; i < techniques_.Size(); ++i)
  184. {
  185. TechniqueEntry& entry = techniques_[i];
  186. if (!entry.technique_)
  187. continue;
  188. XMLElement techniqueElem = materialElem.CreateChild("technique");
  189. techniqueElem.SetString("name", entry.technique_->GetName());
  190. techniqueElem.SetInt("quality", entry.qualityLevel_);
  191. techniqueElem.SetFloat("loddistance", entry.lodDistance_);
  192. }
  193. // Write texture units
  194. for (unsigned j = 0; j < MAX_MATERIAL_TEXTURE_UNITS; ++j)
  195. {
  196. Texture* texture = GetTexture((TextureUnit)j);
  197. if (texture)
  198. {
  199. XMLElement textureElem = materialElem.CreateChild("texture");
  200. textureElem.SetString("unit", textureUnitNames[j]);
  201. textureElem.SetString("name", texture->GetName());
  202. }
  203. }
  204. // Write shader parameters
  205. for (HashMap<StringHash, MaterialShaderParameter>::ConstIterator j = shaderParameters_.Begin(); j != shaderParameters_.End(); ++j)
  206. {
  207. XMLElement parameterElem = materialElem.CreateChild("parameter");
  208. parameterElem.SetString("name", j->second_.name_);
  209. parameterElem.SetVector4("value", j->second_.value_);
  210. }
  211. return xml->Save(dest);
  212. }
  213. void Material::SetNumTechniques(unsigned num)
  214. {
  215. if (!num)
  216. return;
  217. techniques_.Resize(num);
  218. }
  219. void Material::SetTechnique(unsigned index, Technique* technique, unsigned qualityLevel, float lodDistance)
  220. {
  221. if (index >= techniques_.Size())
  222. return;
  223. techniques_[index] = TechniqueEntry(technique, qualityLevel, lodDistance);
  224. CheckOcclusion();
  225. }
  226. void Material::SetShaderParameter(const String& name, const Vector4& value)
  227. {
  228. MaterialShaderParameter newParam;
  229. newParam.name_ = name;
  230. newParam.value_ = value;
  231. shaderParameters_[StringHash(name)] = newParam;
  232. }
  233. void Material::SetTexture(TextureUnit unit, Texture* texture)
  234. {
  235. if (unit >= MAX_MATERIAL_TEXTURE_UNITS)
  236. return;
  237. textures_[unit] = texture;
  238. }
  239. void Material::SetUVTransform(const Vector2& offset, float rotation, const Vector2& repeat)
  240. {
  241. Matrix3x4 transform(Matrix3x4::IDENTITY);
  242. transform.m00_ = repeat.x_;
  243. transform.m11_ = repeat.y_;
  244. transform.m03_ = -0.5f * transform.m00_ + 0.5f;
  245. transform.m13_ = -0.5f * transform.m11_ + 0.5f;
  246. Matrix3x4 rotationMatrix(Matrix3x4::IDENTITY);
  247. float angleRad = rotation * M_DEGTORAD;
  248. rotationMatrix.m00_ = cosf(angleRad);
  249. rotationMatrix.m01_ = sinf(angleRad);
  250. rotationMatrix.m10_ = -rotationMatrix.m01_;
  251. rotationMatrix.m11_ = rotationMatrix.m00_;
  252. rotationMatrix.m03_ = 0.5f - 0.5f * (rotationMatrix.m00_ + rotationMatrix.m01_);
  253. rotationMatrix.m13_ = 0.5f - 0.5f * (rotationMatrix.m10_ + rotationMatrix.m11_);
  254. transform = rotationMatrix * transform;
  255. Matrix3x4 offsetMatrix = Matrix3x4::IDENTITY;
  256. offsetMatrix.m03_ = offset.x_;
  257. offsetMatrix.m13_ = offset.y_;
  258. transform = offsetMatrix * transform;
  259. SetShaderParameter("UOffset", Vector4(transform.m00_, transform.m01_, transform.m02_, transform.m03_));
  260. SetShaderParameter("VOffset", Vector4(transform.m10_, transform.m11_, transform.m12_, transform.m13_));
  261. }
  262. void Material::SetUVTransform(const Vector2& offset, float rotation, float repeat)
  263. {
  264. SetUVTransform(offset, rotation, Vector2(repeat, repeat));
  265. }
  266. void Material::SetCullMode(CullMode mode)
  267. {
  268. cullMode_ = mode;
  269. }
  270. void Material::SetShadowCullMode(CullMode mode)
  271. {
  272. shadowCullMode_ = mode;
  273. }
  274. void Material::RemoveShaderParameter(const String& name)
  275. {
  276. shaderParameters_.Erase(StringHash(name));
  277. }
  278. void Material::ReleaseShaders()
  279. {
  280. for (unsigned i = 0; i < techniques_.Size(); ++i)
  281. {
  282. Technique* technique = techniques_[i].technique_;
  283. if (technique)
  284. technique->ReleaseShaders();
  285. }
  286. }
  287. SharedPtr<Material> Material::Clone(const String& cloneName) const
  288. {
  289. SharedPtr<Material> ret(new Material(context_));
  290. ret->SetName(cloneName);
  291. ret->techniques_ = techniques_;
  292. ret->shaderParameters_ = shaderParameters_;
  293. ret->textures_ = textures_;
  294. ret->occlusion_ = occlusion_;
  295. ret->cullMode_ = cullMode_;
  296. ret->shadowCullMode_ = shadowCullMode_;
  297. return ret;
  298. }
  299. void Material::MarkForAuxView(unsigned frameNumber)
  300. {
  301. auxViewFrameNumber_ = frameNumber;
  302. }
  303. const TechniqueEntry& Material::GetTechniqueEntry(unsigned index) const
  304. {
  305. TechniqueEntry noEntry;
  306. return index < techniques_.Size() ? techniques_[index] : noEntry;
  307. }
  308. Technique* Material::GetTechnique(unsigned index) const
  309. {
  310. return index < techniques_.Size() ? techniques_[index].technique_ : (Technique*)0;
  311. }
  312. Pass* Material::GetPass(unsigned index, PassType pass) const
  313. {
  314. Technique* technique = index < techniques_.Size() ? techniques_[index].technique_ : (Technique*)0;
  315. return technique ? technique->GetPass(pass) : 0;
  316. }
  317. Texture* Material::GetTexture(TextureUnit unit) const
  318. {
  319. return (unsigned)unit < textures_.Size() ? textures_[unit] : (Texture*)0;
  320. }
  321. const String& Material::GetTextureUnitName(TextureUnit unit)
  322. {
  323. return textureUnitNames[unit];
  324. }
  325. void Material::CheckOcclusion()
  326. {
  327. // Determine occlusion by checking the first pass of each technique
  328. occlusion_ = false;
  329. for (unsigned i = 0; i < techniques_.Size(); ++i)
  330. {
  331. Technique* technique = techniques_[i].technique_;
  332. if (!technique)
  333. continue;
  334. const Map<PassType, Pass>& passes = technique->GetPasses();
  335. if (!passes.Empty())
  336. {
  337. // If pass writes depth, enable occlusion
  338. const Pass& pass = passes.Begin()->second_;
  339. if (pass.GetDepthWrite())
  340. {
  341. occlusion_ = true;
  342. break;
  343. }
  344. }
  345. }
  346. }