Material.cpp 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761
  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 "ValueAnimation.h"
  35. #include "XMLFile.h"
  36. #include "DebugNew.h"
  37. namespace Urho3D
  38. {
  39. extern const char* wrapModeNames[];
  40. static const char* textureUnitNames[] =
  41. {
  42. "diffuse",
  43. "normal",
  44. "specular",
  45. "emissive",
  46. "environment",
  47. "lightramp",
  48. "lightshape",
  49. "shadowmap",
  50. "faceselect",
  51. "indirection",
  52. "depth",
  53. "light",
  54. "volume",
  55. "zone",
  56. 0
  57. };
  58. static const char* cullModeNames[] =
  59. {
  60. "none",
  61. "ccw",
  62. "cw",
  63. 0
  64. };
  65. TextureUnit ParseTextureUnitName(String name)
  66. {
  67. name = name.ToLower().Trimmed();
  68. TextureUnit unit = (TextureUnit)GetStringListIndex(name.CString(), textureUnitNames, MAX_TEXTURE_UNITS);
  69. if (unit == MAX_TEXTURE_UNITS)
  70. {
  71. // Check also for shorthand names
  72. if (name == "diff")
  73. unit = TU_DIFFUSE;
  74. else if (name == "albedo")
  75. unit = TU_DIFFUSE;
  76. else if (name == "norm")
  77. unit = TU_NORMAL;
  78. else if (name == "spec")
  79. unit = TU_SPECULAR;
  80. else if (name == "env")
  81. unit = TU_ENVIRONMENT;
  82. // Finally check for specifying the texture unit directly as a number
  83. else if (name.Length() < 3)
  84. unit = (TextureUnit)Clamp(ToInt(name), 0, MAX_TEXTURE_UNITS);
  85. }
  86. if (unit == MAX_TEXTURE_UNITS)
  87. LOGERROR("Unknown texture unit name " + name);
  88. return unit;
  89. }
  90. static TechniqueEntry noEntry;
  91. bool CompareTechniqueEntries(const TechniqueEntry& lhs, const TechniqueEntry& rhs)
  92. {
  93. if (lhs.lodDistance_ != rhs.lodDistance_)
  94. return lhs.lodDistance_ > rhs.lodDistance_;
  95. else
  96. return lhs.qualityLevel_ > rhs.qualityLevel_;
  97. }
  98. TechniqueEntry::TechniqueEntry() :
  99. qualityLevel_(0),
  100. lodDistance_(0.0f)
  101. {
  102. }
  103. TechniqueEntry::TechniqueEntry(Technique* tech, unsigned qualityLevel, float lodDistance) :
  104. technique_(tech),
  105. qualityLevel_(qualityLevel),
  106. lodDistance_(lodDistance)
  107. {
  108. }
  109. TechniqueEntry::~TechniqueEntry()
  110. {
  111. }
  112. ShaderParameterAnimationInfo::ShaderParameterAnimationInfo(Material* target, const String& name, ValueAnimation* attributeAnimation, WrapMode wrapMode, float speed) :
  113. ValueAnimationInfo(target, attributeAnimation, wrapMode, speed),
  114. name_(name)
  115. {
  116. }
  117. ShaderParameterAnimationInfo::ShaderParameterAnimationInfo(const ShaderParameterAnimationInfo& other) :
  118. ValueAnimationInfo(other),
  119. name_(other.name_)
  120. {
  121. }
  122. ShaderParameterAnimationInfo::~ShaderParameterAnimationInfo()
  123. {
  124. }
  125. void ShaderParameterAnimationInfo::ApplyValue(const Variant& newValue)
  126. {
  127. static_cast<Material*>(target_.Get())->SetShaderParameter(name_, newValue);
  128. }
  129. Material::Material(Context* context) :
  130. Resource(context),
  131. auxViewFrameNumber_(0),
  132. occlusion_(true),
  133. specular_(false),
  134. animationFrameNumber_(0)
  135. {
  136. ResetToDefaults();
  137. }
  138. Material::~Material()
  139. {
  140. }
  141. void Material::RegisterObject(Context* context)
  142. {
  143. context->RegisterFactory<Material>();
  144. }
  145. bool Material::BeginLoad(Deserializer& source)
  146. {
  147. // In headless mode, do not actually load the material, just return success
  148. Graphics* graphics = GetSubsystem<Graphics>();
  149. if (!graphics)
  150. return true;
  151. loadXMLFile_ = new XMLFile(context_);
  152. if (loadXMLFile_->Load(source))
  153. {
  154. // If async loading, scan the XML content beforehand for technique & texture resources
  155. // and request them to also be loaded. Can not do anything else at this point
  156. if (GetAsyncLoadState() == ASYNC_LOADING)
  157. {
  158. ResourceCache* cache = GetSubsystem<ResourceCache>();
  159. XMLElement rootElem = loadXMLFile_->GetRoot();
  160. XMLElement techniqueElem = rootElem.GetChild("technique");
  161. while (techniqueElem)
  162. {
  163. cache->BackgroundLoadResource<Technique>(techniqueElem.GetAttribute("name"), true, this);
  164. techniqueElem = techniqueElem.GetNext("technique");
  165. }
  166. XMLElement textureElem = rootElem.GetChild("texture");
  167. while (textureElem)
  168. {
  169. String name = textureElem.GetAttribute("name");
  170. // Detect cube maps by file extension: they are defined by an XML file
  171. /// \todo Differentiate with 3D textures by actually reading the XML content
  172. if (GetExtension(name) == ".xml")
  173. cache->BackgroundLoadResource<TextureCube>(name, true, this);
  174. else
  175. cache->BackgroundLoadResource<Texture2D>(name, true, this);
  176. textureElem = textureElem.GetNext("texture");
  177. }
  178. }
  179. return true;
  180. }
  181. else
  182. {
  183. ResetToDefaults();
  184. loadXMLFile_.Reset();
  185. return false;
  186. }
  187. }
  188. bool Material::EndLoad()
  189. {
  190. // In headless mode, do not actually load the material, just return success
  191. Graphics* graphics = GetSubsystem<Graphics>();
  192. if (!graphics)
  193. return true;
  194. bool success = false;
  195. if (loadXMLFile_)
  196. {
  197. // If async loading, get the techniques / textures which should be ready now
  198. XMLElement rootElem = loadXMLFile_->GetRoot();
  199. success = Load(rootElem);
  200. }
  201. loadXMLFile_.Reset();
  202. return success;
  203. }
  204. bool Material::Save(Serializer& dest) const
  205. {
  206. SharedPtr<XMLFile> xml(new XMLFile(context_));
  207. XMLElement materialElem = xml->CreateRoot("material");
  208. Save(materialElem);
  209. return xml->Save(dest);
  210. }
  211. bool Material::Load(const XMLElement& source)
  212. {
  213. ResetToDefaults();
  214. if (source.IsNull())
  215. {
  216. LOGERROR("Can not load material from null XML element");
  217. return false;
  218. }
  219. ResourceCache* cache = GetSubsystem<ResourceCache>();
  220. XMLElement techniqueElem = source.GetChild("technique");
  221. techniques_.Clear();
  222. while (techniqueElem)
  223. {
  224. Technique* tech = cache->GetResource<Technique>(techniqueElem.GetAttribute("name"));
  225. if (tech)
  226. {
  227. TechniqueEntry newTechnique;
  228. newTechnique.technique_ = tech;
  229. if (techniqueElem.HasAttribute("quality"))
  230. newTechnique.qualityLevel_ = techniqueElem.GetInt("quality");
  231. if (techniqueElem.HasAttribute("loddistance"))
  232. newTechnique.lodDistance_ = techniqueElem.GetFloat("loddistance");
  233. techniques_.Push(newTechnique);
  234. }
  235. techniqueElem = techniqueElem.GetNext("technique");
  236. }
  237. SortTechniques();
  238. XMLElement textureElem = source.GetChild("texture");
  239. while (textureElem)
  240. {
  241. TextureUnit unit = TU_DIFFUSE;
  242. if (textureElem.HasAttribute("unit"))
  243. unit = ParseTextureUnitName(textureElem.GetAttribute("unit"));
  244. if (unit < MAX_MATERIAL_TEXTURE_UNITS)
  245. {
  246. String name = textureElem.GetAttribute("name");
  247. // Detect cube maps by file extension: they are defined by an XML file
  248. /// \todo Differentiate with 3D textures by actually reading the XML content
  249. if (GetExtension(name) == ".xml")
  250. SetTexture(unit, cache->GetResource<TextureCube>(name));
  251. else
  252. SetTexture(unit, cache->GetResource<Texture2D>(name));
  253. }
  254. textureElem = textureElem.GetNext("texture");
  255. }
  256. XMLElement parameterElem = source.GetChild("parameter");
  257. while (parameterElem)
  258. {
  259. String name = parameterElem.GetAttribute("name");
  260. SetShaderParameter(name, ParseShaderParameterValue(parameterElem.GetAttribute("value")));
  261. parameterElem = parameterElem.GetNext("parameter");
  262. }
  263. XMLElement parameterAnimationElem = source.GetChild("parameteranimation");
  264. while (parameterAnimationElem)
  265. {
  266. String name = parameterAnimationElem.GetAttribute("name");
  267. SharedPtr<ValueAnimation> animation(new ValueAnimation(context_));
  268. if (!animation->LoadXML(parameterAnimationElem))
  269. {
  270. LOGERROR("Could not load parameter animation");
  271. return false;
  272. }
  273. String wrapModeString = parameterAnimationElem.GetAttribute("wrapmode");
  274. WrapMode wrapMode = WM_LOOP;
  275. for (int i = 0; i <= WM_CLAMP; ++i)
  276. {
  277. if (wrapModeString == wrapModeNames[i])
  278. {
  279. wrapMode = (WrapMode)i;
  280. break;
  281. }
  282. }
  283. float speed = parameterAnimationElem.GetFloat("speed");
  284. SetShaderParameterAnimation(name, animation, wrapMode, speed);
  285. parameterAnimationElem = parameterAnimationElem.GetNext("parameteranimation");
  286. }
  287. XMLElement cullElem = source.GetChild("cull");
  288. if (cullElem)
  289. SetCullMode((CullMode)GetStringListIndex(cullElem.GetAttribute("value").CString(), cullModeNames, CULL_CCW));
  290. XMLElement shadowCullElem = source.GetChild("shadowcull");
  291. if (shadowCullElem)
  292. SetShadowCullMode((CullMode)GetStringListIndex(shadowCullElem.GetAttribute("value").CString(), cullModeNames, CULL_CCW));
  293. XMLElement depthBiasElem = source.GetChild("depthbias");
  294. if (depthBiasElem)
  295. SetDepthBias(BiasParameters(depthBiasElem.GetFloat("constant"), depthBiasElem.GetFloat("slopescaled")));
  296. // Calculate memory use
  297. RefreshMemoryUse();
  298. CheckOcclusion();
  299. return true;
  300. }
  301. bool Material::Save(XMLElement& dest) const
  302. {
  303. if (dest.IsNull())
  304. {
  305. LOGERROR("Can not save material to null XML element");
  306. return false;
  307. }
  308. // Write techniques
  309. for (unsigned i = 0; i < techniques_.Size(); ++i)
  310. {
  311. const TechniqueEntry& entry = techniques_[i];
  312. if (!entry.technique_)
  313. continue;
  314. XMLElement techniqueElem = dest.CreateChild("technique");
  315. techniqueElem.SetString("name", entry.technique_->GetName());
  316. techniqueElem.SetInt("quality", entry.qualityLevel_);
  317. techniqueElem.SetFloat("loddistance", entry.lodDistance_);
  318. }
  319. // Write texture units
  320. for (unsigned j = 0; j < MAX_MATERIAL_TEXTURE_UNITS; ++j)
  321. {
  322. Texture* texture = GetTexture((TextureUnit)j);
  323. if (texture)
  324. {
  325. XMLElement textureElem = dest.CreateChild("texture");
  326. textureElem.SetString("unit", textureUnitNames[j]);
  327. textureElem.SetString("name", texture->GetName());
  328. }
  329. }
  330. // Write shader parameters
  331. for (HashMap<StringHash, MaterialShaderParameter>::ConstIterator j = shaderParameters_.Begin(); j != shaderParameters_.End(); ++j)
  332. {
  333. XMLElement parameterElem = dest.CreateChild("parameter");
  334. parameterElem.SetString("name", j->second_.name_);
  335. parameterElem.SetVectorVariant("value", j->second_.value_);
  336. }
  337. // Write shader parameter animations
  338. for (HashMap<StringHash, SharedPtr<ShaderParameterAnimationInfo> >::ConstIterator j = shaderParameterAnimationInfos_.Begin(); j != shaderParameterAnimationInfos_.End(); ++j)
  339. {
  340. ShaderParameterAnimationInfo* info = j->second_;
  341. XMLElement parameterAnimationElem = dest.CreateChild("parameteranimation");
  342. parameterAnimationElem.SetString("name", info->GetName());
  343. if (!info->GetAnimation()->SaveXML(parameterAnimationElem))
  344. return false;
  345. parameterAnimationElem.SetAttribute("wrapmode", wrapModeNames[info->GetWrapMode()]);
  346. parameterAnimationElem.SetFloat("speed", info->GetSpeed());
  347. }
  348. // Write culling modes
  349. XMLElement cullElem = dest.CreateChild("cull");
  350. cullElem.SetString("value", cullModeNames[cullMode_]);
  351. XMLElement shadowCullElem = dest.CreateChild("shadowcull");
  352. shadowCullElem.SetString("value", cullModeNames[shadowCullMode_]);
  353. // Write depth bias
  354. XMLElement depthBiasElem = dest.CreateChild("depthbias");
  355. depthBiasElem.SetFloat("constant", depthBias_.constantBias_);
  356. depthBiasElem.SetFloat("slopescaled", depthBias_.slopeScaledBias_);
  357. return true;
  358. }
  359. void Material::SetNumTechniques(unsigned num)
  360. {
  361. if (!num)
  362. return;
  363. techniques_.Resize(num);
  364. RefreshMemoryUse();
  365. }
  366. void Material::SetTechnique(unsigned index, Technique* tech, unsigned qualityLevel, float lodDistance)
  367. {
  368. if (index >= techniques_.Size())
  369. return;
  370. techniques_[index] = TechniqueEntry(tech, qualityLevel, lodDistance);
  371. CheckOcclusion();
  372. }
  373. void Material::SetShaderParameter(const String& name, const Variant& value)
  374. {
  375. MaterialShaderParameter newParam;
  376. newParam.name_ = name;
  377. newParam.value_ = value;
  378. StringHash nameHash(name);
  379. shaderParameters_[nameHash] = newParam;
  380. if (nameHash == PSP_MATSPECCOLOR)
  381. {
  382. VariantType type = value.GetType();
  383. if (type == VAR_VECTOR3)
  384. {
  385. const Vector3& vec = value.GetVector3();
  386. specular_ = vec.x_ > 0.0f || vec.y_ > 0.0f || vec.z_ > 0.0f;
  387. }
  388. else if (type == VAR_VECTOR4)
  389. {
  390. const Vector4& vec = value.GetVector4();
  391. specular_ = vec.x_ > 0.0f || vec.y_ > 0.0f || vec.z_ > 0.0f;
  392. }
  393. }
  394. RefreshMemoryUse();
  395. }
  396. void Material::SetShaderParameterAnimation(const String& name, ValueAnimation* animation, WrapMode wrapMode, float speed)
  397. {
  398. ShaderParameterAnimationInfo* info = GetShaderParameterAnimationInfo(name);
  399. if (animation)
  400. {
  401. if (info && info->GetAnimation() == animation)
  402. {
  403. info->SetWrapMode(wrapMode);
  404. info->SetSpeed(speed);
  405. return;
  406. }
  407. if (shaderParameters_.Find(name) == shaderParameters_.End())
  408. {
  409. LOGERROR(GetName() + " has no shader parameter: " + name);
  410. return;
  411. }
  412. StringHash nameHash(name);
  413. shaderParameterAnimationInfos_[nameHash] = new ShaderParameterAnimationInfo(this, name, animation, wrapMode, speed);
  414. }
  415. else
  416. {
  417. if (info)
  418. {
  419. StringHash nameHash(name);
  420. shaderParameterAnimationInfos_.Erase(nameHash);
  421. }
  422. }
  423. }
  424. void Material::SetShaderParameterAnimationWrapMode(const String& name, WrapMode wrapMode)
  425. {
  426. ShaderParameterAnimationInfo* info = GetShaderParameterAnimationInfo(name);
  427. if (info)
  428. info->SetWrapMode(wrapMode);
  429. }
  430. void Material::SetShaderParameterAnimationSpeed(const String& name, float speed)
  431. {
  432. ShaderParameterAnimationInfo* info = GetShaderParameterAnimationInfo(name);
  433. if (info)
  434. info->SetSpeed(speed);
  435. }
  436. void Material::SetTexture(TextureUnit unit, Texture* texture)
  437. {
  438. if (unit < MAX_MATERIAL_TEXTURE_UNITS)
  439. textures_[unit] = texture;
  440. }
  441. void Material::SetUVTransform(const Vector2& offset, float rotation, const Vector2& repeat)
  442. {
  443. Matrix3x4 transform(Matrix3x4::IDENTITY);
  444. transform.m00_ = repeat.x_;
  445. transform.m11_ = repeat.y_;
  446. transform.m03_ = -0.5f * transform.m00_ + 0.5f;
  447. transform.m13_ = -0.5f * transform.m11_ + 0.5f;
  448. Matrix3x4 rotationMatrix(Matrix3x4::IDENTITY);
  449. rotationMatrix.m00_ = Cos(rotation);
  450. rotationMatrix.m01_ = Sin(rotation);
  451. rotationMatrix.m10_ = -rotationMatrix.m01_;
  452. rotationMatrix.m11_ = rotationMatrix.m00_;
  453. rotationMatrix.m03_ = 0.5f - 0.5f * (rotationMatrix.m00_ + rotationMatrix.m01_);
  454. rotationMatrix.m13_ = 0.5f - 0.5f * (rotationMatrix.m10_ + rotationMatrix.m11_);
  455. transform = rotationMatrix * transform;
  456. Matrix3x4 offsetMatrix = Matrix3x4::IDENTITY;
  457. offsetMatrix.m03_ = offset.x_;
  458. offsetMatrix.m13_ = offset.y_;
  459. transform = offsetMatrix * transform;
  460. SetShaderParameter("UOffset", Vector4(transform.m00_, transform.m01_, transform.m02_, transform.m03_));
  461. SetShaderParameter("VOffset", Vector4(transform.m10_, transform.m11_, transform.m12_, transform.m13_));
  462. }
  463. void Material::SetUVTransform(const Vector2& offset, float rotation, float repeat)
  464. {
  465. SetUVTransform(offset, rotation, Vector2(repeat, repeat));
  466. }
  467. void Material::SetCullMode(CullMode mode)
  468. {
  469. cullMode_ = mode;
  470. }
  471. void Material::SetShadowCullMode(CullMode mode)
  472. {
  473. shadowCullMode_ = mode;
  474. }
  475. void Material::SetDepthBias(const BiasParameters& parameters)
  476. {
  477. depthBias_ = parameters;
  478. depthBias_.Validate();
  479. }
  480. void Material::RemoveShaderParameter(const String& name)
  481. {
  482. StringHash nameHash(name);
  483. shaderParameters_.Erase(nameHash);
  484. if (nameHash == PSP_MATSPECCOLOR)
  485. specular_ = false;
  486. RefreshMemoryUse();
  487. }
  488. void Material::ReleaseShaders()
  489. {
  490. for (unsigned i = 0; i < techniques_.Size(); ++i)
  491. {
  492. Technique* tech = techniques_[i].technique_;
  493. if (tech)
  494. tech->ReleaseShaders();
  495. }
  496. }
  497. SharedPtr<Material> Material::Clone(const String& cloneName) const
  498. {
  499. SharedPtr<Material> ret(new Material(context_));
  500. ret->SetName(cloneName);
  501. ret->techniques_ = techniques_;
  502. ret->shaderParameters_ = shaderParameters_;
  503. for (unsigned i = 0; i < MAX_MATERIAL_TEXTURE_UNITS; ++i)
  504. ret->textures_[i] = textures_[i];
  505. ret->occlusion_ = occlusion_;
  506. ret->specular_ = specular_;
  507. ret->cullMode_ = cullMode_;
  508. ret->shadowCullMode_ = shadowCullMode_;
  509. ret->RefreshMemoryUse();
  510. return ret;
  511. }
  512. void Material::SortTechniques()
  513. {
  514. Sort(techniques_.Begin(), techniques_.End(), CompareTechniqueEntries);
  515. }
  516. void Material::MarkForAuxView(unsigned frameNumber)
  517. {
  518. auxViewFrameNumber_ = frameNumber;
  519. }
  520. void Material::UpdateShaderParameterAnimations()
  521. {
  522. if (shaderParameterAnimationInfos_.Empty())
  523. return;
  524. Time* time = GetSubsystem<Time>();
  525. if (time->GetFrameNumber() == animationFrameNumber_)
  526. return;
  527. animationFrameNumber_ = time->GetFrameNumber();
  528. float timeStep = time->GetTimeStep();
  529. Vector<String> finishedNames;
  530. for (HashMap<StringHash, SharedPtr<ShaderParameterAnimationInfo> >::ConstIterator i = shaderParameterAnimationInfos_.Begin(); i != shaderParameterAnimationInfos_.End(); ++i)
  531. {
  532. if (i->second_->Update(timeStep))
  533. finishedNames.Push(i->second_->GetName());
  534. }
  535. // Remove finished animation
  536. for (unsigned i = 0; i < finishedNames.Size(); ++i)
  537. SetShaderParameterAnimation(finishedNames[i], 0);
  538. }
  539. const TechniqueEntry& Material::GetTechniqueEntry(unsigned index) const
  540. {
  541. return index < techniques_.Size() ? techniques_[index] : noEntry;
  542. }
  543. Technique* Material::GetTechnique(unsigned index) const
  544. {
  545. return index < techniques_.Size() ? techniques_[index].technique_ : (Technique*)0;
  546. }
  547. Pass* Material::GetPass(unsigned index, StringHash passType) const
  548. {
  549. Technique* tech = index < techniques_.Size() ? techniques_[index].technique_ : (Technique*)0;
  550. return tech ? tech->GetPass(passType) : 0;
  551. }
  552. Texture* Material::GetTexture(TextureUnit unit) const
  553. {
  554. return unit < MAX_MATERIAL_TEXTURE_UNITS ? textures_[unit] : (Texture*)0;
  555. }
  556. const Variant& Material::GetShaderParameter(const String& name) const
  557. {
  558. HashMap<StringHash, MaterialShaderParameter>::ConstIterator i = shaderParameters_.Find(name);
  559. return i != shaderParameters_.End() ? i->second_.value_ : Variant::EMPTY;
  560. }
  561. ValueAnimation* Material::GetShaderParameterAnimation(const String& name) const
  562. {
  563. ShaderParameterAnimationInfo* info = GetShaderParameterAnimationInfo(name);
  564. return info == 0 ? 0 : info->GetAnimation();
  565. }
  566. WrapMode Material::GetShaderParameterAnimationWrapMode(const String& name) const
  567. {
  568. ShaderParameterAnimationInfo* info = GetShaderParameterAnimationInfo(name);
  569. return info == 0 ? WM_LOOP : info->GetWrapMode();
  570. }
  571. float Material::GetShaderParameterAnimationSpeed(const String& name) const
  572. {
  573. ShaderParameterAnimationInfo* info = GetShaderParameterAnimationInfo(name);
  574. return info == 0 ? 0 : info->GetSpeed();
  575. }
  576. String Material::GetTextureUnitName(TextureUnit unit)
  577. {
  578. return textureUnitNames[unit];
  579. }
  580. Variant Material::ParseShaderParameterValue(const String& value)
  581. {
  582. String valueTrimmed = value.Trimmed();
  583. if (valueTrimmed.Length() && IsAlpha(valueTrimmed[0]))
  584. return Variant(ToBool(valueTrimmed));
  585. else
  586. return ToVectorVariant(valueTrimmed);
  587. }
  588. void Material::CheckOcclusion()
  589. {
  590. // Determine occlusion by checking the base pass of each technique
  591. occlusion_ = false;
  592. for (unsigned i = 0; i < techniques_.Size(); ++i)
  593. {
  594. Technique* tech = techniques_[i].technique_;
  595. if (tech)
  596. {
  597. Pass* pass = tech->GetPass(PASS_BASE);
  598. if (pass && pass->GetDepthWrite() && !pass->GetAlphaMask())
  599. occlusion_ = true;
  600. }
  601. }
  602. }
  603. void Material::ResetToDefaults()
  604. {
  605. // Needs to be a no-op when async loading, as this does a GetResource() which is not allowed from worker threads
  606. if (!Thread::IsMainThread())
  607. return;
  608. SetNumTechniques(1);
  609. SetTechnique(0, GetSubsystem<ResourceCache>()->GetResource<Technique>("Techniques/NoTexture.xml"));
  610. for (unsigned i = 0; i < MAX_MATERIAL_TEXTURE_UNITS; ++i)
  611. textures_[i] = 0;
  612. shaderParameters_.Clear();
  613. SetShaderParameter("UOffset", Vector4(1.0f, 0.0f, 0.0f, 0.0f));
  614. SetShaderParameter("VOffset", Vector4(0.0f, 1.0f, 0.0f, 0.0f));
  615. SetShaderParameter("MatDiffColor", Vector4::ONE);
  616. SetShaderParameter("MatEmissiveColor", Vector3::ZERO);
  617. SetShaderParameter("MatEnvMapColor", Vector3::ONE);
  618. SetShaderParameter("MatSpecColor", Vector4(0.0f, 0.0f, 0.0f, 1.0f));
  619. cullMode_ = CULL_CCW;
  620. shadowCullMode_ = CULL_CCW;
  621. depthBias_ = BiasParameters(0.0f, 0.0f);
  622. RefreshMemoryUse();
  623. }
  624. void Material::RefreshMemoryUse()
  625. {
  626. unsigned memoryUse = sizeof(Material);
  627. memoryUse += techniques_.Size() * sizeof(TechniqueEntry);
  628. memoryUse += MAX_MATERIAL_TEXTURE_UNITS * sizeof(SharedPtr<Texture>);
  629. memoryUse += shaderParameters_.Size() * sizeof(MaterialShaderParameter);
  630. SetMemoryUse(memoryUse);
  631. }
  632. ShaderParameterAnimationInfo* Material::GetShaderParameterAnimationInfo(const String& name) const
  633. {
  634. StringHash nameHash(name);
  635. HashMap<StringHash, SharedPtr<ShaderParameterAnimationInfo> >::ConstIterator i = shaderParameterAnimationInfos_.Find(nameHash);
  636. if (i == shaderParameterAnimationInfos_.End())
  637. return 0;
  638. return i->second_;
  639. }
  640. }