Material.cpp 14 KB

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