Material.cpp 25 KB

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