Material.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543
  1. //
  2. // Copyright (c) 2008-2014 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. "volume",
  53. 0
  54. };
  55. static const char* cullModeNames[] =
  56. {
  57. "none",
  58. "ccw",
  59. "cw",
  60. 0
  61. };
  62. TextureUnit ParseTextureUnitName(String name)
  63. {
  64. name = name.ToLower().Trimmed();
  65. TextureUnit unit = (TextureUnit)GetStringListIndex(name.CString(), textureUnitNames, MAX_TEXTURE_UNITS);
  66. if (unit == MAX_TEXTURE_UNITS)
  67. {
  68. // Check also for shorthand names
  69. if (name == "diff")
  70. unit = TU_DIFFUSE;
  71. else if (name == "albedo")
  72. unit = TU_DIFFUSE;
  73. else if (name == "norm")
  74. unit = TU_NORMAL;
  75. else if (name == "spec")
  76. unit = TU_SPECULAR;
  77. else if (name == "env")
  78. unit = TU_ENVIRONMENT;
  79. // Finally check for specifying the texture unit directly as a number
  80. else if (name.Length() < 3)
  81. unit = (TextureUnit)Clamp(ToInt(name), 0, MAX_TEXTURE_UNITS);
  82. }
  83. if (unit == MAX_TEXTURE_UNITS)
  84. LOGERROR("Unknown texture unit name " + name);
  85. return unit;
  86. }
  87. static TechniqueEntry noEntry;
  88. bool CompareTechniqueEntries(const TechniqueEntry& lhs, const TechniqueEntry& rhs)
  89. {
  90. if (lhs.lodDistance_ != rhs.lodDistance_)
  91. return lhs.lodDistance_ > rhs.lodDistance_;
  92. else
  93. return lhs.qualityLevel_ > rhs.qualityLevel_;
  94. }
  95. TechniqueEntry::TechniqueEntry() :
  96. qualityLevel_(0),
  97. lodDistance_(0.0f)
  98. {
  99. }
  100. TechniqueEntry::TechniqueEntry(Technique* tech, unsigned qualityLevel, float lodDistance) :
  101. technique_(tech),
  102. qualityLevel_(qualityLevel),
  103. lodDistance_(lodDistance)
  104. {
  105. }
  106. TechniqueEntry::~TechniqueEntry()
  107. {
  108. }
  109. Material::Material(Context* context) :
  110. Resource(context),
  111. auxViewFrameNumber_(0),
  112. occlusion_(true),
  113. specular_(false)
  114. {
  115. ResetToDefaults();
  116. }
  117. Material::~Material()
  118. {
  119. }
  120. void Material::RegisterObject(Context* context)
  121. {
  122. context->RegisterFactory<Material>();
  123. }
  124. bool Material::Load(Deserializer& source)
  125. {
  126. PROFILE(LoadMaterial);
  127. // In headless mode, do not actually load the material, just return success
  128. Graphics* graphics = GetSubsystem<Graphics>();
  129. if (!graphics)
  130. return true;
  131. SharedPtr<XMLFile> xml(new XMLFile(context_));
  132. if (!xml->Load(source))
  133. {
  134. ResetToDefaults();
  135. return false;
  136. }
  137. XMLElement rootElem = xml->GetRoot();
  138. return Load(rootElem);
  139. }
  140. bool Material::Save(Serializer& dest) const
  141. {
  142. SharedPtr<XMLFile> xml(new XMLFile(context_));
  143. XMLElement materialElem = xml->CreateRoot("material");
  144. Save(materialElem);
  145. return xml->Save(dest);
  146. }
  147. bool Material::Load(const XMLElement& source)
  148. {
  149. ResetToDefaults();
  150. if (source.IsNull())
  151. {
  152. LOGERROR("Can not load material from null XML element");
  153. return false;
  154. }
  155. ResourceCache* cache = GetSubsystem<ResourceCache>();
  156. XMLElement techniqueElem = source.GetChild("technique");
  157. techniques_.Clear();
  158. while (techniqueElem)
  159. {
  160. Technique* tech = cache->GetResource<Technique>(techniqueElem.GetAttribute("name"));
  161. if (tech)
  162. {
  163. TechniqueEntry newTechnique;
  164. newTechnique.technique_ = tech;
  165. if (techniqueElem.HasAttribute("quality"))
  166. newTechnique.qualityLevel_ = techniqueElem.GetInt("quality");
  167. if (techniqueElem.HasAttribute("loddistance"))
  168. newTechnique.lodDistance_ = techniqueElem.GetFloat("loddistance");
  169. techniques_.Push(newTechnique);
  170. }
  171. techniqueElem = techniqueElem.GetNext("technique");
  172. }
  173. SortTechniques();
  174. XMLElement textureElem = source.GetChild("texture");
  175. while (textureElem)
  176. {
  177. TextureUnit unit = TU_DIFFUSE;
  178. if (textureElem.HasAttribute("unit"))
  179. unit = ParseTextureUnitName(textureElem.GetAttribute("unit"));
  180. if (unit < MAX_MATERIAL_TEXTURE_UNITS)
  181. {
  182. String name = textureElem.GetAttribute("name");
  183. // Detect cube maps by file extension: they are defined by an XML file
  184. if (GetExtension(name) == ".xml")
  185. SetTexture(unit, cache->GetResource<TextureCube>(name));
  186. else
  187. SetTexture(unit, cache->GetResource<Texture2D>(name));
  188. }
  189. textureElem = textureElem.GetNext("texture");
  190. }
  191. XMLElement parameterElem = source.GetChild("parameter");
  192. while (parameterElem)
  193. {
  194. String name = parameterElem.GetAttribute("name");
  195. SetShaderParameter(name, ParseShaderParameterValue(parameterElem.GetAttribute("value")));
  196. parameterElem = parameterElem.GetNext("parameter");
  197. }
  198. XMLElement cullElem = source.GetChild("cull");
  199. if (cullElem)
  200. SetCullMode((CullMode)GetStringListIndex(cullElem.GetAttribute("value").CString(), cullModeNames, CULL_CCW));
  201. XMLElement shadowCullElem = source.GetChild("shadowcull");
  202. if (shadowCullElem)
  203. SetShadowCullMode((CullMode)GetStringListIndex(shadowCullElem.GetAttribute("value").CString(), cullModeNames, CULL_CCW));
  204. XMLElement depthBiasElem = source.GetChild("depthbias");
  205. if (depthBiasElem)
  206. SetDepthBias(BiasParameters(depthBiasElem.GetFloat("constant"), depthBiasElem.GetFloat("slopescaled")));
  207. // Calculate memory use
  208. RefreshMemoryUse();
  209. CheckOcclusion();
  210. return true;
  211. }
  212. bool Material::Save(XMLElement& dest) const
  213. {
  214. if (dest.IsNull())
  215. {
  216. LOGERROR("Can not save material to null XML element");
  217. return false;
  218. }
  219. // Write techniques
  220. for (unsigned i = 0; i < techniques_.Size(); ++i)
  221. {
  222. const TechniqueEntry& entry = techniques_[i];
  223. if (!entry.technique_)
  224. continue;
  225. XMLElement techniqueElem = dest.CreateChild("technique");
  226. techniqueElem.SetString("name", entry.technique_->GetName());
  227. techniqueElem.SetInt("quality", entry.qualityLevel_);
  228. techniqueElem.SetFloat("loddistance", entry.lodDistance_);
  229. }
  230. // Write texture units
  231. for (unsigned j = 0; j < MAX_MATERIAL_TEXTURE_UNITS; ++j)
  232. {
  233. Texture* texture = GetTexture((TextureUnit)j);
  234. if (texture)
  235. {
  236. XMLElement textureElem = dest.CreateChild("texture");
  237. textureElem.SetString("unit", textureUnitNames[j]);
  238. textureElem.SetString("name", texture->GetName());
  239. }
  240. }
  241. // Write shader parameters
  242. for (HashMap<StringHash, MaterialShaderParameter>::ConstIterator j = shaderParameters_.Begin(); j != shaderParameters_.End(); ++j)
  243. {
  244. XMLElement parameterElem = dest.CreateChild("parameter");
  245. parameterElem.SetString("name", j->second_.name_);
  246. parameterElem.SetVectorVariant("value", j->second_.value_);
  247. }
  248. // Write culling modes
  249. XMLElement cullElem = dest.CreateChild("cull");
  250. cullElem.SetString("value", cullModeNames[cullMode_]);
  251. XMLElement shadowCullElem = dest.CreateChild("shadowcull");
  252. shadowCullElem.SetString("value", cullModeNames[shadowCullMode_]);
  253. // Write depth bias
  254. XMLElement depthBiasElem = dest.CreateChild("depthbias");
  255. depthBiasElem.SetFloat("constant", depthBias_.constantBias_);
  256. depthBiasElem.SetFloat("slopescaled", depthBias_.slopeScaledBias_);
  257. return true;
  258. }
  259. void Material::SetNumTechniques(unsigned num)
  260. {
  261. if (!num)
  262. return;
  263. techniques_.Resize(num);
  264. RefreshMemoryUse();
  265. }
  266. void Material::SetTechnique(unsigned index, Technique* tech, unsigned qualityLevel, float lodDistance)
  267. {
  268. if (index >= techniques_.Size())
  269. return;
  270. techniques_[index] = TechniqueEntry(tech, qualityLevel, lodDistance);
  271. CheckOcclusion();
  272. }
  273. void Material::SetShaderParameter(const String& name, const Variant& value)
  274. {
  275. MaterialShaderParameter newParam;
  276. newParam.name_ = name;
  277. newParam.value_ = value;
  278. StringHash nameHash(name);
  279. shaderParameters_[nameHash] = newParam;
  280. if (nameHash == PSP_MATSPECCOLOR)
  281. {
  282. VariantType type = value.GetType();
  283. if (type == VAR_VECTOR3)
  284. {
  285. const Vector3& vec = value.GetVector3();
  286. specular_ = vec.x_ > 0.0f || vec.y_ > 0.0f || vec.z_ > 0.0f;
  287. }
  288. else if (type == VAR_VECTOR4)
  289. {
  290. const Vector4& vec = value.GetVector4();
  291. specular_ = vec.x_ > 0.0f || vec.y_ > 0.0f || vec.z_ > 0.0f;
  292. }
  293. }
  294. RefreshMemoryUse();
  295. }
  296. void Material::SetTexture(TextureUnit unit, Texture* texture)
  297. {
  298. if (unit < MAX_MATERIAL_TEXTURE_UNITS)
  299. textures_[unit] = texture;
  300. }
  301. void Material::SetUVTransform(const Vector2& offset, float rotation, const Vector2& repeat)
  302. {
  303. Matrix3x4 transform(Matrix3x4::IDENTITY);
  304. transform.m00_ = repeat.x_;
  305. transform.m11_ = repeat.y_;
  306. transform.m03_ = -0.5f * transform.m00_ + 0.5f;
  307. transform.m13_ = -0.5f * transform.m11_ + 0.5f;
  308. Matrix3x4 rotationMatrix(Matrix3x4::IDENTITY);
  309. rotationMatrix.m00_ = Cos(rotation);
  310. rotationMatrix.m01_ = Sin(rotation);
  311. rotationMatrix.m10_ = -rotationMatrix.m01_;
  312. rotationMatrix.m11_ = rotationMatrix.m00_;
  313. rotationMatrix.m03_ = 0.5f - 0.5f * (rotationMatrix.m00_ + rotationMatrix.m01_);
  314. rotationMatrix.m13_ = 0.5f - 0.5f * (rotationMatrix.m10_ + rotationMatrix.m11_);
  315. transform = rotationMatrix * transform;
  316. Matrix3x4 offsetMatrix = Matrix3x4::IDENTITY;
  317. offsetMatrix.m03_ = offset.x_;
  318. offsetMatrix.m13_ = offset.y_;
  319. transform = offsetMatrix * transform;
  320. SetShaderParameter("UOffset", Vector4(transform.m00_, transform.m01_, transform.m02_, transform.m03_));
  321. SetShaderParameter("VOffset", Vector4(transform.m10_, transform.m11_, transform.m12_, transform.m13_));
  322. }
  323. void Material::SetUVTransform(const Vector2& offset, float rotation, float repeat)
  324. {
  325. SetUVTransform(offset, rotation, Vector2(repeat, repeat));
  326. }
  327. void Material::SetCullMode(CullMode mode)
  328. {
  329. cullMode_ = mode;
  330. }
  331. void Material::SetShadowCullMode(CullMode mode)
  332. {
  333. shadowCullMode_ = mode;
  334. }
  335. void Material::SetDepthBias(const BiasParameters& parameters)
  336. {
  337. depthBias_ = parameters;
  338. depthBias_.Validate();
  339. }
  340. void Material::RemoveShaderParameter(const String& name)
  341. {
  342. StringHash nameHash(name);
  343. shaderParameters_.Erase(nameHash);
  344. if (nameHash == PSP_MATSPECCOLOR)
  345. specular_ = false;
  346. RefreshMemoryUse();
  347. }
  348. void Material::ReleaseShaders()
  349. {
  350. for (unsigned i = 0; i < techniques_.Size(); ++i)
  351. {
  352. Technique* tech = techniques_[i].technique_;
  353. if (tech)
  354. tech->ReleaseShaders();
  355. }
  356. }
  357. SharedPtr<Material> Material::Clone(const String& cloneName) const
  358. {
  359. SharedPtr<Material> ret(new Material(context_));
  360. ret->SetName(cloneName);
  361. ret->techniques_ = techniques_;
  362. ret->shaderParameters_ = shaderParameters_;
  363. for (unsigned i = 0; i < MAX_MATERIAL_TEXTURE_UNITS; ++i)
  364. ret->textures_[i] = textures_[i];
  365. ret->occlusion_ = occlusion_;
  366. ret->specular_ = specular_;
  367. ret->cullMode_ = cullMode_;
  368. ret->shadowCullMode_ = shadowCullMode_;
  369. ret->RefreshMemoryUse();
  370. return ret;
  371. }
  372. void Material::SortTechniques()
  373. {
  374. Sort(techniques_.Begin(), techniques_.End(), CompareTechniqueEntries);
  375. }
  376. void Material::MarkForAuxView(unsigned frameNumber)
  377. {
  378. auxViewFrameNumber_ = frameNumber;
  379. }
  380. const TechniqueEntry& Material::GetTechniqueEntry(unsigned index) const
  381. {
  382. return index < techniques_.Size() ? techniques_[index] : noEntry;
  383. }
  384. Technique* Material::GetTechnique(unsigned index) const
  385. {
  386. return index < techniques_.Size() ? techniques_[index].technique_ : (Technique*)0;
  387. }
  388. Pass* Material::GetPass(unsigned index, StringHash passType) const
  389. {
  390. Technique* tech = index < techniques_.Size() ? techniques_[index].technique_ : (Technique*)0;
  391. return tech ? tech->GetPass(passType) : 0;
  392. }
  393. Texture* Material::GetTexture(TextureUnit unit) const
  394. {
  395. return unit < MAX_MATERIAL_TEXTURE_UNITS ? textures_[unit] : (Texture*)0;
  396. }
  397. const Variant& Material::GetShaderParameter(const String& name) const
  398. {
  399. HashMap<StringHash, MaterialShaderParameter>::ConstIterator i = shaderParameters_.Find(name);
  400. return i != shaderParameters_.End() ? i->second_.value_ : Variant::EMPTY;
  401. }
  402. String Material::GetTextureUnitName(TextureUnit unit)
  403. {
  404. return textureUnitNames[unit];
  405. }
  406. Variant Material::ParseShaderParameterValue(const String& value)
  407. {
  408. String valueTrimmed = value.Trimmed();
  409. if (valueTrimmed.Length() && IsAlpha(valueTrimmed[0]))
  410. return Variant(ToBool(valueTrimmed));
  411. else
  412. return ToVectorVariant(valueTrimmed);
  413. }
  414. void Material::CheckOcclusion()
  415. {
  416. // Determine occlusion by checking the base pass of each technique
  417. occlusion_ = false;
  418. for (unsigned i = 0; i < techniques_.Size(); ++i)
  419. {
  420. Technique* tech = techniques_[i].technique_;
  421. if (tech)
  422. {
  423. Pass* pass = tech->GetPass(PASS_BASE);
  424. if (pass && pass->GetDepthWrite() && !pass->GetAlphaMask())
  425. occlusion_ = true;
  426. }
  427. }
  428. }
  429. void Material::ResetToDefaults()
  430. {
  431. SetNumTechniques(1);
  432. SetTechnique(0, GetSubsystem<ResourceCache>()->GetResource<Technique>("Techniques/NoTexture.xml"));
  433. for (unsigned i = 0; i < MAX_MATERIAL_TEXTURE_UNITS; ++i)
  434. textures_[i] = 0;
  435. shaderParameters_.Clear();
  436. SetShaderParameter("UOffset", Vector4(1.0f, 0.0f, 0.0f, 0.0f));
  437. SetShaderParameter("VOffset", Vector4(0.0f, 1.0f, 0.0f, 0.0f));
  438. SetShaderParameter("MatDiffColor", Vector4::ONE);
  439. SetShaderParameter("MatEmissiveColor", Vector3::ZERO);
  440. SetShaderParameter("MatEnvMapColor", Vector3::ONE);
  441. SetShaderParameter("MatSpecColor", Vector4(0.0f, 0.0f, 0.0f, 1.0f));
  442. cullMode_ = CULL_CCW;
  443. shadowCullMode_ = CULL_CCW;
  444. depthBias_ = BiasParameters(0.0f, 0.0f);
  445. RefreshMemoryUse();
  446. }
  447. void Material::RefreshMemoryUse()
  448. {
  449. unsigned memoryUse = sizeof(Material);
  450. memoryUse += techniques_.Size() * sizeof(TechniqueEntry);
  451. memoryUse += MAX_MATERIAL_TEXTURE_UNITS * sizeof(SharedPtr<Texture>);
  452. memoryUse += shaderParameters_.Size() * sizeof(MaterialShaderParameter);
  453. SetMemoryUse(memoryUse);
  454. }
  455. }