Material.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534
  1. //
  2. // Copyright (c) 2008-2013 the Urho3D project.
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to deal
  6. // in the Software without restriction, including without limitation the rights
  7. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. // copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. // THE SOFTWARE.
  21. //
  22. #include "Precompiled.h"
  23. #include "Context.h"
  24. #include "FileSystem.h"
  25. #include "Graphics.h"
  26. #include "Log.h"
  27. #include "Material.h"
  28. #include "Matrix3x4.h"
  29. #include "Profiler.h"
  30. #include "ResourceCache.h"
  31. #include "Technique.h"
  32. #include "Texture2D.h"
  33. #include "TextureCube.h"
  34. #include "XMLFile.h"
  35. #include "DebugNew.h"
  36. namespace Urho3D
  37. {
  38. static const char* textureUnitNames[] =
  39. {
  40. "diffuse",
  41. "normal",
  42. "specular",
  43. "emissive",
  44. "environment",
  45. "lightramp",
  46. "lightshape",
  47. "shadowmap",
  48. "faceselect",
  49. "indirection",
  50. "depth",
  51. "light",
  52. 0
  53. };
  54. static const char* cullModeNames[] =
  55. {
  56. "none",
  57. "ccw",
  58. "cw",
  59. 0
  60. };
  61. TextureUnit ParseTextureUnitName(const String& name)
  62. {
  63. TextureUnit unit = (TextureUnit)GetStringListIndex(name.CString(), textureUnitNames, MAX_TEXTURE_UNITS);
  64. if (name == "diff")
  65. unit = TU_DIFFUSE;
  66. else if (name == "albedo")
  67. unit = TU_DIFFUSE;
  68. else if (name == "norm")
  69. unit = TU_NORMAL;
  70. else if (name == "spec")
  71. unit = TU_SPECULAR;
  72. else if (name == "env")
  73. unit = TU_ENVIRONMENT;
  74. return unit;
  75. }
  76. static TechniqueEntry noEntry;
  77. bool CompareTechniqueEntries(const TechniqueEntry& lhs, const TechniqueEntry& rhs)
  78. {
  79. if (lhs.lodDistance_ != rhs.lodDistance_)
  80. return lhs.lodDistance_ > rhs.lodDistance_;
  81. else
  82. return lhs.qualityLevel_ > rhs.qualityLevel_;
  83. }
  84. TechniqueEntry::TechniqueEntry() :
  85. qualityLevel_(0),
  86. lodDistance_(0.0f)
  87. {
  88. }
  89. TechniqueEntry::TechniqueEntry(Technique* tech, unsigned qualityLevel, float lodDistance) :
  90. technique_(tech),
  91. qualityLevel_(qualityLevel),
  92. lodDistance_(lodDistance)
  93. {
  94. }
  95. TechniqueEntry::~TechniqueEntry()
  96. {
  97. }
  98. Material::Material(Context* context) :
  99. Resource(context),
  100. auxViewFrameNumber_(0),
  101. occlusion_(true),
  102. specular_(false)
  103. {
  104. SetNumTechniques(1);
  105. ResetToDefaults();
  106. RefreshMemoryUse();
  107. }
  108. Material::~Material()
  109. {
  110. }
  111. void Material::RegisterObject(Context* context)
  112. {
  113. context->RegisterFactory<Material>();
  114. }
  115. bool Material::Load(Deserializer& source)
  116. {
  117. PROFILE(LoadMaterial);
  118. // In headless mode, do not actually load the material, just return success
  119. Graphics* graphics = GetSubsystem<Graphics>();
  120. if (!graphics)
  121. return true;
  122. SharedPtr<XMLFile> xml(new XMLFile(context_));
  123. if (!xml->Load(source))
  124. return false;
  125. XMLElement rootElem = xml->GetRoot();
  126. return Load(rootElem);
  127. }
  128. bool Material::Save(Serializer& dest) const
  129. {
  130. SharedPtr<XMLFile> xml(new XMLFile(context_));
  131. XMLElement materialElem = xml->CreateRoot("material");
  132. Save(materialElem);
  133. return xml->Save(dest);
  134. }
  135. bool Material::Load(const XMLElement& source)
  136. {
  137. ResetToDefaults();
  138. if (source.IsNull())
  139. {
  140. LOGERROR("Can not load material from null XML element");
  141. return false;
  142. }
  143. ResourceCache* cache = GetSubsystem<ResourceCache>();
  144. XMLElement techniqueElem = source.GetChild("technique");
  145. techniques_.Clear();
  146. while (techniqueElem)
  147. {
  148. Technique* tech = cache->GetResource<Technique>(techniqueElem.GetAttribute("name"));
  149. if (tech)
  150. {
  151. TechniqueEntry newTechnique;
  152. newTechnique.technique_ = tech;
  153. if (techniqueElem.HasAttribute("quality"))
  154. newTechnique.qualityLevel_ = techniqueElem.GetInt("quality");
  155. if (techniqueElem.HasAttribute("loddistance"))
  156. newTechnique.lodDistance_ = techniqueElem.GetFloat("loddistance");
  157. techniques_.Push(newTechnique);
  158. }
  159. techniqueElem = techniqueElem.GetNext("technique");
  160. }
  161. SortTechniques();
  162. XMLElement textureElem = source.GetChild("texture");
  163. while (textureElem)
  164. {
  165. TextureUnit unit = TU_DIFFUSE;
  166. if (textureElem.HasAttribute("unit"))
  167. {
  168. String unitName = textureElem.GetAttributeLower("unit");
  169. if (unitName.Length() > 1)
  170. {
  171. unit = ParseTextureUnitName(unitName);
  172. if (unit >= MAX_MATERIAL_TEXTURE_UNITS)
  173. LOGERROR("Unknown or illegal texture unit " + unitName);
  174. }
  175. else
  176. unit = (TextureUnit)Clamp(ToInt(unitName), 0, MAX_MATERIAL_TEXTURE_UNITS - 1);
  177. }
  178. if (unit != MAX_MATERIAL_TEXTURE_UNITS)
  179. {
  180. String name = textureElem.GetAttribute("name");
  181. // Detect cube maps by file extension: they are defined by an XML file
  182. if (GetExtension(name) == ".xml")
  183. SetTexture(unit, cache->GetResource<TextureCube>(name));
  184. else
  185. SetTexture(unit, cache->GetResource<Texture2D>(name));
  186. }
  187. textureElem = textureElem.GetNext("texture");
  188. }
  189. XMLElement parameterElem = source.GetChild("parameter");
  190. while (parameterElem)
  191. {
  192. String name = parameterElem.GetAttribute("name");
  193. SetShaderParameter(name, ParseShaderParameterValue(parameterElem.GetAttribute("value")));
  194. parameterElem = parameterElem.GetNext("parameter");
  195. }
  196. XMLElement cullElem = source.GetChild("cull");
  197. if (cullElem)
  198. SetCullMode((CullMode)GetStringListIndex(cullElem.GetAttribute("value").CString(), cullModeNames, CULL_CCW));
  199. XMLElement shadowCullElem = source.GetChild("shadowcull");
  200. if (shadowCullElem)
  201. SetShadowCullMode((CullMode)GetStringListIndex(shadowCullElem.GetAttribute("value").CString(), cullModeNames, CULL_CCW));
  202. XMLElement depthBiasElem = source.GetChild("depthbias");
  203. if (depthBiasElem)
  204. SetDepthBias(BiasParameters(depthBiasElem.GetFloat("constant"), depthBiasElem.GetFloat("slopescaled")));
  205. // Calculate memory use
  206. RefreshMemoryUse();
  207. CheckOcclusion();
  208. return true;
  209. }
  210. bool Material::Save(XMLElement& dest) const
  211. {
  212. if (dest.IsNull())
  213. {
  214. LOGERROR("Can not save material to null XML element");
  215. return false;
  216. }
  217. // Write techniques
  218. for (unsigned i = 0; i < techniques_.Size(); ++i)
  219. {
  220. const TechniqueEntry& entry = techniques_[i];
  221. if (!entry.technique_)
  222. continue;
  223. XMLElement techniqueElem = dest.CreateChild("technique");
  224. techniqueElem.SetString("name", entry.technique_->GetName());
  225. techniqueElem.SetInt("quality", entry.qualityLevel_);
  226. techniqueElem.SetFloat("loddistance", entry.lodDistance_);
  227. }
  228. // Write texture units
  229. for (unsigned j = 0; j < MAX_MATERIAL_TEXTURE_UNITS; ++j)
  230. {
  231. Texture* texture = GetTexture((TextureUnit)j);
  232. if (texture)
  233. {
  234. XMLElement textureElem = dest.CreateChild("texture");
  235. textureElem.SetString("unit", textureUnitNames[j]);
  236. textureElem.SetString("name", texture->GetName());
  237. }
  238. }
  239. // Write shader parameters
  240. for (HashMap<StringHash, MaterialShaderParameter>::ConstIterator j = shaderParameters_.Begin(); j != shaderParameters_.End(); ++j)
  241. {
  242. XMLElement parameterElem = dest.CreateChild("parameter");
  243. parameterElem.SetString("name", j->second_.name_);
  244. parameterElem.SetVectorVariant("value", j->second_.value_);
  245. }
  246. // Write culling modes
  247. XMLElement cullElem = dest.CreateChild("cull");
  248. cullElem.SetString("value", cullModeNames[cullMode_]);
  249. XMLElement shadowCullElem = dest.CreateChild("shadowcull");
  250. shadowCullElem.SetString("value", cullModeNames[shadowCullMode_]);
  251. // Write depth bias
  252. XMLElement depthBiasElem = dest.CreateChild("depthbias");
  253. depthBiasElem.SetFloat("constant", depthBias_.constantBias_);
  254. depthBiasElem.SetFloat("slopescaled", depthBias_.slopeScaledBias_);
  255. return true;
  256. }
  257. void Material::SetNumTechniques(unsigned num)
  258. {
  259. if (!num)
  260. return;
  261. techniques_.Resize(num);
  262. RefreshMemoryUse();
  263. }
  264. void Material::SetTechnique(unsigned index, Technique* tech, unsigned qualityLevel, float lodDistance)
  265. {
  266. if (index >= techniques_.Size())
  267. return;
  268. techniques_[index] = TechniqueEntry(tech, qualityLevel, lodDistance);
  269. CheckOcclusion();
  270. }
  271. void Material::SetShaderParameter(const String& name, const Variant& value)
  272. {
  273. MaterialShaderParameter newParam;
  274. newParam.name_ = name;
  275. newParam.value_ = value;
  276. StringHash nameHash(name);
  277. shaderParameters_[nameHash] = newParam;
  278. if (nameHash == PSP_MATSPECCOLOR)
  279. {
  280. VariantType type = value.GetType();
  281. if (type == VAR_VECTOR3)
  282. {
  283. const Vector3& vec = value.GetVector3();
  284. specular_ = vec.x_ > 0.0f || vec.y_ > 0.0f || vec.z_ > 0.0f;
  285. }
  286. else if (type == VAR_VECTOR4)
  287. {
  288. const Vector4& vec = value.GetVector4();
  289. specular_ = vec.x_ > 0.0f || vec.y_ > 0.0f || vec.z_ > 0.0f;
  290. }
  291. }
  292. RefreshMemoryUse();
  293. }
  294. void Material::SetTexture(TextureUnit unit, Texture* texture)
  295. {
  296. if (unit < MAX_MATERIAL_TEXTURE_UNITS)
  297. textures_[unit] = texture;
  298. }
  299. void Material::SetUVTransform(const Vector2& offset, float rotation, const Vector2& repeat)
  300. {
  301. Matrix3x4 transform(Matrix3x4::IDENTITY);
  302. transform.m00_ = repeat.x_;
  303. transform.m11_ = repeat.y_;
  304. transform.m03_ = -0.5f * transform.m00_ + 0.5f;
  305. transform.m13_ = -0.5f * transform.m11_ + 0.5f;
  306. Matrix3x4 rotationMatrix(Matrix3x4::IDENTITY);
  307. rotationMatrix.m00_ = Cos(rotation);
  308. rotationMatrix.m01_ = Sin(rotation);
  309. rotationMatrix.m10_ = -rotationMatrix.m01_;
  310. rotationMatrix.m11_ = rotationMatrix.m00_;
  311. rotationMatrix.m03_ = 0.5f - 0.5f * (rotationMatrix.m00_ + rotationMatrix.m01_);
  312. rotationMatrix.m13_ = 0.5f - 0.5f * (rotationMatrix.m10_ + rotationMatrix.m11_);
  313. transform = rotationMatrix * transform;
  314. Matrix3x4 offsetMatrix = Matrix3x4::IDENTITY;
  315. offsetMatrix.m03_ = offset.x_;
  316. offsetMatrix.m13_ = offset.y_;
  317. transform = offsetMatrix * transform;
  318. SetShaderParameter("UOffset", Vector4(transform.m00_, transform.m01_, transform.m02_, transform.m03_));
  319. SetShaderParameter("VOffset", Vector4(transform.m10_, transform.m11_, transform.m12_, transform.m13_));
  320. }
  321. void Material::SetUVTransform(const Vector2& offset, float rotation, float repeat)
  322. {
  323. SetUVTransform(offset, rotation, Vector2(repeat, repeat));
  324. }
  325. void Material::SetCullMode(CullMode mode)
  326. {
  327. cullMode_ = mode;
  328. }
  329. void Material::SetShadowCullMode(CullMode mode)
  330. {
  331. shadowCullMode_ = mode;
  332. }
  333. void Material::SetDepthBias(const BiasParameters& parameters)
  334. {
  335. depthBias_ = parameters;
  336. depthBias_.Validate();
  337. }
  338. void Material::RemoveShaderParameter(const String& name)
  339. {
  340. StringHash nameHash(name);
  341. shaderParameters_.Erase(nameHash);
  342. if (nameHash == PSP_MATSPECCOLOR)
  343. specular_ = false;
  344. RefreshMemoryUse();
  345. }
  346. void Material::ReleaseShaders()
  347. {
  348. for (unsigned i = 0; i < techniques_.Size(); ++i)
  349. {
  350. Technique* tech = techniques_[i].technique_;
  351. if (tech)
  352. tech->ReleaseShaders();
  353. }
  354. }
  355. SharedPtr<Material> Material::Clone(const String& cloneName) const
  356. {
  357. SharedPtr<Material> ret(new Material(context_));
  358. ret->SetName(cloneName);
  359. ret->techniques_ = techniques_;
  360. ret->shaderParameters_ = shaderParameters_;
  361. for (unsigned i = 0; i < MAX_MATERIAL_TEXTURE_UNITS; ++i)
  362. ret->textures_[i] = textures_[i];
  363. ret->occlusion_ = occlusion_;
  364. ret->specular_ = specular_;
  365. ret->cullMode_ = cullMode_;
  366. ret->shadowCullMode_ = shadowCullMode_;
  367. ret->RefreshMemoryUse();
  368. return ret;
  369. }
  370. void Material::SortTechniques()
  371. {
  372. Sort(techniques_.Begin(), techniques_.End(), CompareTechniqueEntries);
  373. }
  374. void Material::MarkForAuxView(unsigned frameNumber)
  375. {
  376. auxViewFrameNumber_ = frameNumber;
  377. }
  378. const TechniqueEntry& Material::GetTechniqueEntry(unsigned index) const
  379. {
  380. return index < techniques_.Size() ? techniques_[index] : noEntry;
  381. }
  382. Technique* Material::GetTechnique(unsigned index) const
  383. {
  384. return index < techniques_.Size() ? techniques_[index].technique_ : (Technique*)0;
  385. }
  386. Pass* Material::GetPass(unsigned index, StringHash passType) const
  387. {
  388. Technique* tech = index < techniques_.Size() ? techniques_[index].technique_ : (Technique*)0;
  389. return tech ? tech->GetPass(passType) : 0;
  390. }
  391. Texture* Material::GetTexture(TextureUnit unit) const
  392. {
  393. return unit < MAX_MATERIAL_TEXTURE_UNITS ? textures_[unit] : (Texture*)0;
  394. }
  395. const Variant& Material::GetShaderParameter(const String& name) const
  396. {
  397. HashMap<StringHash, MaterialShaderParameter>::ConstIterator i = shaderParameters_.Find(name);
  398. return i != shaderParameters_.End() ? i->second_.value_ : Variant::EMPTY;
  399. }
  400. String Material::GetTextureUnitName(TextureUnit unit)
  401. {
  402. return textureUnitNames[unit];
  403. }
  404. Variant Material::ParseShaderParameterValue(const String& value)
  405. {
  406. String valueTrimmed = value.Trimmed();
  407. if (valueTrimmed.Length() && IsAlpha(valueTrimmed[0]))
  408. return Variant(ToBool(valueTrimmed));
  409. else
  410. return ToVectorVariant(valueTrimmed);
  411. }
  412. void Material::CheckOcclusion()
  413. {
  414. // Determine occlusion by checking the base pass of each technique
  415. occlusion_ = false;
  416. for (unsigned i = 0; i < techniques_.Size(); ++i)
  417. {
  418. Technique* tech = techniques_[i].technique_;
  419. if (tech)
  420. {
  421. Pass* pass = tech->GetPass(PASS_BASE);
  422. if (pass && pass->GetDepthWrite() && !pass->GetAlphaMask())
  423. occlusion_ = true;
  424. }
  425. }
  426. }
  427. void Material::ResetToDefaults()
  428. {
  429. for (unsigned i = 0; i < MAX_MATERIAL_TEXTURE_UNITS; ++i)
  430. textures_[i] = 0;
  431. shaderParameters_.Clear();
  432. SetShaderParameter("UOffset", Vector4(1.0f, 0.0f, 0.0f, 0.0f));
  433. SetShaderParameter("VOffset", Vector4(0.0f, 1.0f, 0.0f, 0.0f));
  434. SetShaderParameter("MatDiffColor", Vector4::ONE);
  435. SetShaderParameter("MatEmissiveColor", Vector3::ZERO);
  436. SetShaderParameter("MatEnvMapColor", Vector3::ONE);
  437. SetShaderParameter("MatSpecColor", Vector4(0.0f, 0.0f, 0.0f, 1.0f));
  438. cullMode_ = CULL_CCW;
  439. shadowCullMode_ = CULL_CCW;
  440. depthBias_ = BiasParameters(0.0f, 0.0f);
  441. }
  442. void Material::RefreshMemoryUse()
  443. {
  444. unsigned memoryUse = sizeof(Material);
  445. memoryUse += techniques_.Size() * sizeof(TechniqueEntry);
  446. memoryUse += MAX_MATERIAL_TEXTURE_UNITS * sizeof(SharedPtr<Texture>);
  447. memoryUse += shaderParameters_.Size() * sizeof(MaterialShaderParameter);
  448. SetMemoryUse(memoryUse);
  449. }
  450. }