Material.cpp 14 KB

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