Material.cpp 14 KB

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