Material.cpp 13 KB

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