Material.cpp 41 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273
  1. //
  2. // Copyright (c) 2008-2016 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 "../Core/Context.h"
  24. #include "../Core/CoreEvents.h"
  25. #include "../Core/Profiler.h"
  26. #include "../Graphics/Graphics.h"
  27. #include "../Graphics/Material.h"
  28. #include "../Graphics/Renderer.h"
  29. #include "../Graphics/Technique.h"
  30. #include "../Graphics/Texture2D.h"
  31. #include "../Graphics/Texture2DArray.h"
  32. #include "../Graphics/Texture3D.h"
  33. #include "../Graphics/TextureCube.h"
  34. #include "../IO/FileSystem.h"
  35. #include "../IO/Log.h"
  36. #include "../IO/VectorBuffer.h"
  37. #include "../Resource/ResourceCache.h"
  38. #include "../Resource/XMLFile.h"
  39. #include "../Resource/JSONFile.h"
  40. #include "../Scene/Scene.h"
  41. #include "../Scene/SceneEvents.h"
  42. #include "../Scene/ValueAnimation.h"
  43. #include "../DebugNew.h"
  44. namespace Atomic
  45. {
  46. extern const char* wrapModeNames[];
  47. static const char* textureUnitNames[] =
  48. {
  49. "diffuse",
  50. "normal",
  51. "specular",
  52. "emissive",
  53. "environment",
  54. #ifdef DESKTOP_GRAPHICS
  55. "volume",
  56. "custom1",
  57. "custom2",
  58. "lightramp",
  59. "lightshape",
  60. "shadowmap",
  61. "faceselect",
  62. "indirection",
  63. "depth",
  64. "light",
  65. "zone",
  66. 0
  67. #else
  68. "lightramp",
  69. "lightshape",
  70. "shadowmap",
  71. 0
  72. #endif
  73. };
  74. const char* cullModeNames[] =
  75. {
  76. "none",
  77. "ccw",
  78. "cw",
  79. 0
  80. };
  81. static const char* fillModeNames[] =
  82. {
  83. "solid",
  84. "wireframe",
  85. "point",
  86. 0
  87. };
  88. TextureUnit ParseTextureUnitName(String name)
  89. {
  90. name = name.ToLower().Trimmed();
  91. TextureUnit unit = (TextureUnit)GetStringListIndex(name.CString(), textureUnitNames, MAX_TEXTURE_UNITS);
  92. if (unit == MAX_TEXTURE_UNITS)
  93. {
  94. // Check also for shorthand names
  95. if (name == "diff")
  96. unit = TU_DIFFUSE;
  97. else if (name == "albedo")
  98. unit = TU_DIFFUSE;
  99. else if (name == "norm")
  100. unit = TU_NORMAL;
  101. else if (name == "spec")
  102. unit = TU_SPECULAR;
  103. else if (name == "env")
  104. unit = TU_ENVIRONMENT;
  105. // Finally check for specifying the texture unit directly as a number
  106. else if (name.Length() < 3)
  107. unit = (TextureUnit)Clamp(ToInt(name), 0, MAX_TEXTURE_UNITS - 1);
  108. }
  109. if (unit == MAX_TEXTURE_UNITS)
  110. ATOMIC_LOGERROR("Unknown texture unit name " + name);
  111. return unit;
  112. }
  113. StringHash ParseTextureTypeName(String name)
  114. {
  115. name = name.ToLower().Trimmed();
  116. if (name == "texture")
  117. return Texture2D::GetTypeStatic();
  118. else if (name == "cubemap")
  119. return TextureCube::GetTypeStatic();
  120. else if (name == "texture3d")
  121. return Texture3D::GetTypeStatic();
  122. else if (name == "texturearray")
  123. return Texture2DArray::GetTypeStatic();
  124. return 0;
  125. }
  126. StringHash ParseTextureTypeXml(ResourceCache* cache, String filename)
  127. {
  128. StringHash type = 0;
  129. if (!cache)
  130. return type;
  131. SharedPtr<File> texXmlFile = cache->GetFile(filename, false);
  132. if (texXmlFile.NotNull())
  133. {
  134. SharedPtr<XMLFile> texXml(new XMLFile(cache->GetContext()));
  135. if (texXml->Load(*texXmlFile))
  136. type = ParseTextureTypeName(texXml->GetRoot().GetName());
  137. }
  138. return type;
  139. }
  140. static TechniqueEntry noEntry;
  141. bool CompareTechniqueEntries(const TechniqueEntry& lhs, const TechniqueEntry& rhs)
  142. {
  143. if (lhs.lodDistance_ != rhs.lodDistance_)
  144. return lhs.lodDistance_ > rhs.lodDistance_;
  145. else
  146. return lhs.qualityLevel_ > rhs.qualityLevel_;
  147. }
  148. TechniqueEntry::TechniqueEntry() :
  149. qualityLevel_(0),
  150. lodDistance_(0.0f)
  151. {
  152. }
  153. TechniqueEntry::TechniqueEntry(Technique* tech, unsigned qualityLevel, float lodDistance) :
  154. technique_(tech),
  155. qualityLevel_(qualityLevel),
  156. lodDistance_(lodDistance)
  157. {
  158. }
  159. TechniqueEntry::~TechniqueEntry()
  160. {
  161. }
  162. ShaderParameterAnimationInfo::ShaderParameterAnimationInfo(Material* target, const String& name, ValueAnimation* attributeAnimation,
  163. WrapMode wrapMode, float speed) :
  164. ValueAnimationInfo(target, attributeAnimation, wrapMode, speed),
  165. name_(name)
  166. {
  167. }
  168. ShaderParameterAnimationInfo::ShaderParameterAnimationInfo(const ShaderParameterAnimationInfo& other) :
  169. ValueAnimationInfo(other),
  170. name_(other.name_)
  171. {
  172. }
  173. ShaderParameterAnimationInfo::~ShaderParameterAnimationInfo()
  174. {
  175. }
  176. void ShaderParameterAnimationInfo::ApplyValue(const Variant& newValue)
  177. {
  178. static_cast<Material*>(target_.Get())->SetShaderParameter(name_, newValue);
  179. }
  180. Material::Material(Context* context) :
  181. Resource(context),
  182. auxViewFrameNumber_(0),
  183. shaderParameterHash_(0),
  184. occlusion_(true),
  185. specular_(false),
  186. subscribed_(false),
  187. batchedParameterUpdate_(false)
  188. {
  189. ResetToDefaults();
  190. }
  191. Material::~Material()
  192. {
  193. }
  194. void Material::RegisterObject(Context* context)
  195. {
  196. context->RegisterFactory<Material>();
  197. }
  198. bool Material::BeginLoad(Deserializer& source)
  199. {
  200. // In headless mode, do not actually load the material, just return success
  201. Graphics* graphics = GetSubsystem<Graphics>();
  202. if (!graphics)
  203. return true;
  204. String extension = GetExtension(source.GetName());
  205. bool success = false;
  206. // ATOMIC BEGIN
  207. if (extension == ".xml" || extension == ".material")
  208. {
  209. success = BeginLoadXML(source);
  210. if (!success)
  211. success = BeginLoadJSON(source);
  212. if (success)
  213. return true;
  214. }
  215. else // Load JSON file
  216. {
  217. success = BeginLoadJSON(source);
  218. if (!success)
  219. {
  220. // reset position
  221. source.Seek(0);
  222. success = BeginLoadXML(source);
  223. }
  224. if (success)
  225. return true;
  226. }
  227. // ATOMIC END
  228. // All loading failed
  229. ResetToDefaults();
  230. loadJSONFile_.Reset();
  231. return false;
  232. }
  233. bool Material::EndLoad()
  234. {
  235. // In headless mode, do not actually load the material, just return success
  236. Graphics* graphics = GetSubsystem<Graphics>();
  237. if (!graphics)
  238. return true;
  239. bool success = false;
  240. if (loadXMLFile_)
  241. {
  242. // If async loading, get the techniques / textures which should be ready now
  243. XMLElement rootElem = loadXMLFile_->GetRoot();
  244. success = Load(rootElem);
  245. }
  246. if (loadJSONFile_)
  247. {
  248. JSONValue rootVal = loadJSONFile_->GetRoot();
  249. success = Load(rootVal);
  250. }
  251. loadXMLFile_.Reset();
  252. loadJSONFile_.Reset();
  253. return success;
  254. }
  255. bool Material::BeginLoadXML(Deserializer& source)
  256. {
  257. ResetToDefaults();
  258. loadXMLFile_ = new XMLFile(context_);
  259. if (loadXMLFile_->Load(source))
  260. {
  261. // If async loading, scan the XML content beforehand for technique & texture resources
  262. // and request them to also be loaded. Can not do anything else at this point
  263. if (GetAsyncLoadState() == ASYNC_LOADING)
  264. {
  265. ResourceCache* cache = GetSubsystem<ResourceCache>();
  266. XMLElement rootElem = loadXMLFile_->GetRoot();
  267. XMLElement techniqueElem = rootElem.GetChild("technique");
  268. while (techniqueElem)
  269. {
  270. cache->BackgroundLoadResource<Technique>(techniqueElem.GetAttribute("name"), true, this);
  271. techniqueElem = techniqueElem.GetNext("technique");
  272. }
  273. XMLElement textureElem = rootElem.GetChild("texture");
  274. while (textureElem)
  275. {
  276. String name = textureElem.GetAttribute("name");
  277. // Detect cube maps and arrays by file extension: they are defined by an XML file
  278. if (GetExtension(name) == ".xml")
  279. {
  280. #ifdef DESKTOP_GRAPHICS
  281. StringHash type = ParseTextureTypeXml(cache, name);
  282. if (!type && textureElem.HasAttribute("unit"))
  283. {
  284. TextureUnit unit = ParseTextureUnitName(textureElem.GetAttribute("unit"));
  285. if (unit == TU_VOLUMEMAP)
  286. type = Texture3D::GetTypeStatic();
  287. }
  288. if (type == Texture3D::GetTypeStatic())
  289. cache->BackgroundLoadResource<Texture3D>(name, true, this);
  290. else if (type == Texture2DArray::GetTypeStatic())
  291. cache->BackgroundLoadResource<Texture2DArray>(name, true, this);
  292. else
  293. #endif
  294. cache->BackgroundLoadResource<TextureCube>(name, true, this);
  295. }
  296. else
  297. cache->BackgroundLoadResource<Texture2D>(name, true, this);
  298. textureElem = textureElem.GetNext("texture");
  299. }
  300. }
  301. return true;
  302. }
  303. return false;
  304. }
  305. bool Material::BeginLoadJSON(Deserializer& source)
  306. {
  307. // Attempt to load a JSON file
  308. ResetToDefaults();
  309. loadXMLFile_.Reset();
  310. // Attempt to load from JSON file instead
  311. loadJSONFile_ = new JSONFile(context_);
  312. if (loadJSONFile_->Load(source))
  313. {
  314. // If async loading, scan the XML content beforehand for technique & texture resources
  315. // and request them to also be loaded. Can not do anything else at this point
  316. if (GetAsyncLoadState() == ASYNC_LOADING)
  317. {
  318. ResourceCache* cache = GetSubsystem<ResourceCache>();
  319. const JSONValue& rootVal = loadJSONFile_->GetRoot();
  320. JSONArray techniqueArray = rootVal.Get("techniques").GetArray();
  321. for (unsigned i = 0; i < techniqueArray.Size(); i++)
  322. {
  323. const JSONValue& techVal = techniqueArray[i];
  324. cache->BackgroundLoadResource<Technique>(techVal.Get("name").GetString(), true, this);
  325. }
  326. JSONObject textureObject = rootVal.Get("textures").GetObject();
  327. for (JSONObject::ConstIterator it = textureObject.Begin(); it != textureObject.End(); it++)
  328. {
  329. String unitString = it->first_;
  330. String name = it->second_.GetString();
  331. // Detect cube maps and arrays by file extension: they are defined by an XML file
  332. if (GetExtension(name) == ".xml")
  333. {
  334. #ifdef DESKTOP_GRAPHICS
  335. StringHash type = ParseTextureTypeXml(cache, name);
  336. if (!type && !unitString.Empty())
  337. {
  338. TextureUnit unit = ParseTextureUnitName(unitString);
  339. if (unit == TU_VOLUMEMAP)
  340. type = Texture3D::GetTypeStatic();
  341. }
  342. if (type == Texture3D::GetTypeStatic())
  343. cache->BackgroundLoadResource<Texture3D>(name, true, this);
  344. else if (type == Texture2DArray::GetTypeStatic())
  345. cache->BackgroundLoadResource<Texture2DArray>(name, true, this);
  346. else
  347. #endif
  348. cache->BackgroundLoadResource<TextureCube>(name, true, this);
  349. }
  350. else
  351. cache->BackgroundLoadResource<Texture2D>(name, true, this);
  352. }
  353. }
  354. // JSON material was successfully loaded
  355. return true;
  356. }
  357. return false;
  358. }
  359. bool Material::Save(Serializer& dest) const
  360. {
  361. SharedPtr<XMLFile> xml(new XMLFile(context_));
  362. XMLElement materialElem = xml->CreateRoot("material");
  363. Save(materialElem);
  364. return xml->Save(dest);
  365. }
  366. bool Material::Load(const XMLElement& source)
  367. {
  368. ResetToDefaults();
  369. if (source.IsNull())
  370. {
  371. ATOMIC_LOGERROR("Can not load material from null XML element");
  372. return false;
  373. }
  374. ResourceCache* cache = GetSubsystem<ResourceCache>();
  375. XMLElement techniqueElem = source.GetChild("technique");
  376. techniques_.Clear();
  377. while (techniqueElem)
  378. {
  379. Technique* tech = cache->GetResource<Technique>(techniqueElem.GetAttribute("name"));
  380. if (tech)
  381. {
  382. TechniqueEntry newTechnique;
  383. newTechnique.technique_ = tech;
  384. if (techniqueElem.HasAttribute("quality"))
  385. newTechnique.qualityLevel_ = techniqueElem.GetInt("quality");
  386. if (techniqueElem.HasAttribute("loddistance"))
  387. newTechnique.lodDistance_ = techniqueElem.GetFloat("loddistance");
  388. techniques_.Push(newTechnique);
  389. }
  390. techniqueElem = techniqueElem.GetNext("technique");
  391. }
  392. SortTechniques();
  393. XMLElement textureElem = source.GetChild("texture");
  394. while (textureElem)
  395. {
  396. TextureUnit unit = TU_DIFFUSE;
  397. if (textureElem.HasAttribute("unit"))
  398. unit = ParseTextureUnitName(textureElem.GetAttribute("unit"));
  399. if (unit < MAX_TEXTURE_UNITS)
  400. {
  401. String name = textureElem.GetAttribute("name");
  402. // Detect cube maps and arrays by file extension: they are defined by an XML file
  403. if (GetExtension(name) == ".xml")
  404. {
  405. #ifdef DESKTOP_GRAPHICS
  406. StringHash type = ParseTextureTypeXml(cache, name);
  407. if (!type && unit == TU_VOLUMEMAP)
  408. type = Texture3D::GetTypeStatic();
  409. if (type == Texture3D::GetTypeStatic())
  410. SetTexture(unit, cache->GetResource<Texture3D>(name));
  411. else if (type == Texture2DArray::GetTypeStatic())
  412. SetTexture(unit, cache->GetResource<Texture2DArray>(name));
  413. else
  414. #endif
  415. SetTexture(unit, cache->GetResource<TextureCube>(name));
  416. }
  417. else
  418. SetTexture(unit, cache->GetResource<Texture2D>(name));
  419. }
  420. textureElem = textureElem.GetNext("texture");
  421. }
  422. batchedParameterUpdate_ = true;
  423. XMLElement parameterElem = source.GetChild("parameter");
  424. while (parameterElem)
  425. {
  426. String name = parameterElem.GetAttribute("name");
  427. if (!parameterElem.HasAttribute("type"))
  428. SetShaderParameter(name, ParseShaderParameterValue(parameterElem.GetAttribute("value")));
  429. else
  430. SetShaderParameter(name, Variant(parameterElem.GetAttribute("type"), parameterElem.GetAttribute("value")));
  431. parameterElem = parameterElem.GetNext("parameter");
  432. }
  433. batchedParameterUpdate_ = false;
  434. XMLElement parameterAnimationElem = source.GetChild("parameteranimation");
  435. while (parameterAnimationElem)
  436. {
  437. String name = parameterAnimationElem.GetAttribute("name");
  438. SharedPtr<ValueAnimation> animation(new ValueAnimation(context_));
  439. if (!animation->LoadXML(parameterAnimationElem))
  440. {
  441. ATOMIC_LOGERROR("Could not load parameter animation");
  442. return false;
  443. }
  444. String wrapModeString = parameterAnimationElem.GetAttribute("wrapmode");
  445. WrapMode wrapMode = WM_LOOP;
  446. for (int i = 0; i <= WM_CLAMP; ++i)
  447. {
  448. if (wrapModeString == wrapModeNames[i])
  449. {
  450. wrapMode = (WrapMode)i;
  451. break;
  452. }
  453. }
  454. float speed = parameterAnimationElem.GetFloat("speed");
  455. SetShaderParameterAnimation(name, animation, wrapMode, speed);
  456. parameterAnimationElem = parameterAnimationElem.GetNext("parameteranimation");
  457. }
  458. XMLElement cullElem = source.GetChild("cull");
  459. if (cullElem)
  460. SetCullMode((CullMode)GetStringListIndex(cullElem.GetAttribute("value").CString(), cullModeNames, CULL_CCW));
  461. XMLElement shadowCullElem = source.GetChild("shadowcull");
  462. if (shadowCullElem)
  463. SetShadowCullMode((CullMode)GetStringListIndex(shadowCullElem.GetAttribute("value").CString(), cullModeNames, CULL_CCW));
  464. XMLElement fillElem = source.GetChild("fill");
  465. if (fillElem)
  466. SetFillMode((FillMode)GetStringListIndex(fillElem.GetAttribute("value").CString(), fillModeNames, FILL_SOLID));
  467. XMLElement depthBiasElem = source.GetChild("depthbias");
  468. if (depthBiasElem)
  469. SetDepthBias(BiasParameters(depthBiasElem.GetFloat("constant"), depthBiasElem.GetFloat("slopescaled")));
  470. XMLElement renderOrderElem = source.GetChild("renderorder");
  471. if (renderOrderElem)
  472. SetRenderOrder((unsigned char)renderOrderElem.GetUInt("value"));
  473. RefreshShaderParameterHash();
  474. RefreshMemoryUse();
  475. CheckOcclusion();
  476. return true;
  477. }
  478. bool Material::Load(const JSONValue& source)
  479. {
  480. ResetToDefaults();
  481. if (source.IsNull())
  482. {
  483. ATOMIC_LOGERROR("Can not load material from null JSON element");
  484. return false;
  485. }
  486. ResourceCache* cache = GetSubsystem<ResourceCache>();
  487. // Load techniques
  488. JSONArray techniquesArray = source.Get("techniques").GetArray();
  489. techniques_.Clear();
  490. techniques_.Reserve(techniquesArray.Size());
  491. for (unsigned i = 0; i < techniquesArray.Size(); i++)
  492. {
  493. const JSONValue& techVal = techniquesArray[i];
  494. Technique* tech = cache->GetResource<Technique>(techVal.Get("name").GetString());
  495. if (tech)
  496. {
  497. TechniqueEntry newTechnique;
  498. newTechnique.technique_ = tech;
  499. JSONValue qualityVal = techVal.Get("quality");
  500. if (!qualityVal.IsNull())
  501. newTechnique.qualityLevel_ = qualityVal.GetInt();
  502. JSONValue lodDistanceVal = techVal.Get("loddistance");
  503. if (!lodDistanceVal.IsNull())
  504. newTechnique.lodDistance_ = lodDistanceVal.GetFloat();
  505. techniques_.Push(newTechnique);
  506. }
  507. }
  508. SortTechniques();
  509. // Load textures
  510. JSONObject textureObject = source.Get("textures").GetObject();
  511. for (JSONObject::ConstIterator it = textureObject.Begin(); it != textureObject.End(); it++)
  512. {
  513. String textureUnit = it->first_;
  514. String textureName = it->second_.GetString();
  515. TextureUnit unit = TU_DIFFUSE;
  516. unit = ParseTextureUnitName(textureUnit);
  517. if (unit < MAX_TEXTURE_UNITS)
  518. {
  519. // Detect cube maps and arrays by file extension: they are defined by an XML file
  520. if (GetExtension(textureName) == ".xml")
  521. {
  522. #ifdef DESKTOP_GRAPHICS
  523. StringHash type = ParseTextureTypeXml(cache, textureName);
  524. if (!type && unit == TU_VOLUMEMAP)
  525. type = Texture3D::GetTypeStatic();
  526. if (type == Texture3D::GetTypeStatic())
  527. SetTexture(unit, cache->GetResource<Texture3D>(textureName));
  528. else if (type == Texture2DArray::GetTypeStatic())
  529. SetTexture(unit, cache->GetResource<Texture2DArray>(textureName));
  530. else
  531. #endif
  532. SetTexture(unit, cache->GetResource<TextureCube>(textureName));
  533. }
  534. else
  535. SetTexture(unit, cache->GetResource<Texture2D>(textureName));
  536. }
  537. }
  538. // Get shader parameters
  539. batchedParameterUpdate_ = true;
  540. JSONObject parameterObject = source.Get("shaderParameters").GetObject();
  541. for (JSONObject::ConstIterator it = parameterObject.Begin(); it != parameterObject.End(); it++)
  542. {
  543. String name = it->first_;
  544. if (it->second_.IsString())
  545. SetShaderParameter(name, ParseShaderParameterValue(it->second_.GetString()));
  546. else if (it->second_.IsObject())
  547. {
  548. JSONObject valueObj = it->second_.GetObject();
  549. SetShaderParameter(name, Variant(valueObj["type"].GetString(), valueObj["value"].GetString()));
  550. }
  551. }
  552. batchedParameterUpdate_ = false;
  553. // Load shader parameter animationss
  554. JSONObject paramAnimationsObject = source.Get("shaderParameterAnimations").GetObject();
  555. for (JSONObject::ConstIterator it = paramAnimationsObject.Begin(); it != paramAnimationsObject.End(); it++)
  556. {
  557. String name = it->first_;
  558. JSONValue paramAnimVal = it->second_;
  559. SharedPtr<ValueAnimation> animation(new ValueAnimation(context_));
  560. if (!animation->LoadJSON(paramAnimVal))
  561. {
  562. ATOMIC_LOGERROR("Could not load parameter animation");
  563. return false;
  564. }
  565. String wrapModeString = paramAnimVal.Get("wrapmode").GetString();
  566. WrapMode wrapMode = WM_LOOP;
  567. for (int i = 0; i <= WM_CLAMP; ++i)
  568. {
  569. if (wrapModeString == wrapModeNames[i])
  570. {
  571. wrapMode = (WrapMode)i;
  572. break;
  573. }
  574. }
  575. float speed = paramAnimVal.Get("speed").GetFloat();
  576. SetShaderParameterAnimation(name, animation, wrapMode, speed);
  577. }
  578. JSONValue cullVal = source.Get("cull");
  579. if (!cullVal.IsNull())
  580. SetCullMode((CullMode)GetStringListIndex(cullVal.GetString().CString(), cullModeNames, CULL_CCW));
  581. JSONValue shadowCullVal = source.Get("shadowcull");
  582. if (!shadowCullVal.IsNull())
  583. SetShadowCullMode((CullMode)GetStringListIndex(shadowCullVal.GetString().CString(), cullModeNames, CULL_CCW));
  584. JSONValue fillVal = source.Get("fill");
  585. if (!fillVal.IsNull())
  586. SetFillMode((FillMode)GetStringListIndex(fillVal.GetString().CString(), fillModeNames, FILL_SOLID));
  587. JSONValue depthBiasVal = source.Get("depthbias");
  588. if (!depthBiasVal.IsNull())
  589. SetDepthBias(BiasParameters(depthBiasVal.Get("constant").GetFloat(), depthBiasVal.Get("slopescaled").GetFloat()));
  590. JSONValue renderOrderVal = source.Get("renderorder");
  591. if (!renderOrderVal.IsNull())
  592. SetRenderOrder((unsigned char)renderOrderVal.Get("value").GetUInt());
  593. RefreshShaderParameterHash();
  594. RefreshMemoryUse();
  595. CheckOcclusion();
  596. return true;
  597. }
  598. bool Material::Save(XMLElement& dest) const
  599. {
  600. if (dest.IsNull())
  601. {
  602. ATOMIC_LOGERROR("Can not save material to null XML element");
  603. return false;
  604. }
  605. // Write techniques
  606. for (unsigned i = 0; i < techniques_.Size(); ++i)
  607. {
  608. const TechniqueEntry& entry = techniques_[i];
  609. if (!entry.technique_)
  610. continue;
  611. XMLElement techniqueElem = dest.CreateChild("technique");
  612. techniqueElem.SetString("name", entry.technique_->GetName());
  613. techniqueElem.SetInt("quality", entry.qualityLevel_);
  614. techniqueElem.SetFloat("loddistance", entry.lodDistance_);
  615. }
  616. // Write texture units
  617. for (unsigned j = 0; j < MAX_TEXTURE_UNITS; ++j)
  618. {
  619. Texture* texture = GetTexture((TextureUnit)j);
  620. if (texture)
  621. {
  622. XMLElement textureElem = dest.CreateChild("texture");
  623. textureElem.SetString("unit", textureUnitNames[j]);
  624. textureElem.SetString("name", texture->GetName());
  625. }
  626. }
  627. // Write shader parameters
  628. for (HashMap<StringHash, MaterialShaderParameter>::ConstIterator j = shaderParameters_.Begin();
  629. j != shaderParameters_.End(); ++j)
  630. {
  631. XMLElement parameterElem = dest.CreateChild("parameter");
  632. parameterElem.SetString("name", j->second_.name_);
  633. if (j->second_.value_.GetType() != VAR_BUFFER)
  634. parameterElem.SetVectorVariant("value", j->second_.value_);
  635. else
  636. {
  637. parameterElem.SetAttribute("type", j->second_.value_.GetTypeName());
  638. parameterElem.SetAttribute("value", j->second_.value_.ToString());
  639. }
  640. }
  641. // Write shader parameter animations
  642. for (HashMap<StringHash, SharedPtr<ShaderParameterAnimationInfo> >::ConstIterator j = shaderParameterAnimationInfos_.Begin();
  643. j != shaderParameterAnimationInfos_.End(); ++j)
  644. {
  645. ShaderParameterAnimationInfo* info = j->second_;
  646. XMLElement parameterAnimationElem = dest.CreateChild("parameteranimation");
  647. parameterAnimationElem.SetString("name", info->GetName());
  648. if (!info->GetAnimation()->SaveXML(parameterAnimationElem))
  649. return false;
  650. parameterAnimationElem.SetAttribute("wrapmode", wrapModeNames[info->GetWrapMode()]);
  651. parameterAnimationElem.SetFloat("speed", info->GetSpeed());
  652. }
  653. // Write culling modes
  654. XMLElement cullElem = dest.CreateChild("cull");
  655. cullElem.SetString("value", cullModeNames[cullMode_]);
  656. XMLElement shadowCullElem = dest.CreateChild("shadowcull");
  657. shadowCullElem.SetString("value", cullModeNames[shadowCullMode_]);
  658. // Write fill mode
  659. XMLElement fillElem = dest.CreateChild("fill");
  660. fillElem.SetString("value", fillModeNames[fillMode_]);
  661. // Write depth bias
  662. XMLElement depthBiasElem = dest.CreateChild("depthbias");
  663. depthBiasElem.SetFloat("constant", depthBias_.constantBias_);
  664. depthBiasElem.SetFloat("slopescaled", depthBias_.slopeScaledBias_);
  665. // Write render order
  666. XMLElement renderOrderElem = dest.CreateChild("renderorder");
  667. renderOrderElem.SetUInt("value", renderOrder_);
  668. return true;
  669. }
  670. bool Material::Save(JSONValue& dest) const
  671. {
  672. // Write techniques
  673. JSONArray techniquesArray;
  674. techniquesArray.Reserve(techniques_.Size());
  675. for (unsigned i = 0; i < techniques_.Size(); ++i)
  676. {
  677. const TechniqueEntry& entry = techniques_[i];
  678. if (!entry.technique_)
  679. continue;
  680. JSONValue techniqueVal;
  681. techniqueVal.Set("name", entry.technique_->GetName());
  682. techniqueVal.Set("quality", (int) entry.qualityLevel_);
  683. techniqueVal.Set("loddistance", entry.lodDistance_);
  684. techniquesArray.Push(techniqueVal);
  685. }
  686. dest.Set("techniques", techniquesArray);
  687. // Write texture units
  688. JSONValue texturesValue;
  689. for (unsigned j = 0; j < MAX_TEXTURE_UNITS; ++j)
  690. {
  691. Texture* texture = GetTexture((TextureUnit)j);
  692. if (texture)
  693. texturesValue.Set(textureUnitNames[j], texture->GetName());
  694. }
  695. dest.Set("textures", texturesValue);
  696. // Write shader parameters
  697. JSONValue shaderParamsVal;
  698. for (HashMap<StringHash, MaterialShaderParameter>::ConstIterator j = shaderParameters_.Begin();
  699. j != shaderParameters_.End(); ++j)
  700. {
  701. if (j->second_.value_.GetType() != VAR_BUFFER)
  702. shaderParamsVal.Set(j->second_.name_, j->second_.value_.ToString());
  703. else
  704. {
  705. JSONObject valueObj;
  706. valueObj["type"] = j->second_.value_.GetTypeName();
  707. valueObj["value"] = j->second_.value_.ToString();
  708. shaderParamsVal.Set(j->second_.name_, valueObj);
  709. }
  710. }
  711. dest.Set("shaderParameters", shaderParamsVal);
  712. // Write shader parameter animations
  713. JSONValue shaderParamAnimationsVal;
  714. for (HashMap<StringHash, SharedPtr<ShaderParameterAnimationInfo> >::ConstIterator j = shaderParameterAnimationInfos_.Begin();
  715. j != shaderParameterAnimationInfos_.End(); ++j)
  716. {
  717. ShaderParameterAnimationInfo* info = j->second_;
  718. JSONValue paramAnimationVal;
  719. if (!info->GetAnimation()->SaveJSON(paramAnimationVal))
  720. return false;
  721. paramAnimationVal.Set("wrapmode", wrapModeNames[info->GetWrapMode()]);
  722. paramAnimationVal.Set("speed", info->GetSpeed());
  723. shaderParamAnimationsVal.Set(info->GetName(), paramAnimationVal);
  724. }
  725. dest.Set("shaderParameterAnimations", shaderParamAnimationsVal);
  726. // Write culling modes
  727. dest.Set("cull", cullModeNames[cullMode_]);
  728. dest.Set("shadowcull", cullModeNames[shadowCullMode_]);
  729. // Write fill mode
  730. dest.Set("fill", fillModeNames[fillMode_]);
  731. // Write depth bias
  732. JSONValue depthBiasValue;
  733. depthBiasValue.Set("constant", depthBias_.constantBias_);
  734. depthBiasValue.Set("slopescaled", depthBias_.slopeScaledBias_);
  735. // Write render order
  736. dest.Set("renderorder", (unsigned) renderOrder_);
  737. return true;
  738. }
  739. void Material::SetNumTechniques(unsigned num)
  740. {
  741. if (!num)
  742. return;
  743. techniques_.Resize(num);
  744. RefreshMemoryUse();
  745. }
  746. void Material::SetTechnique(unsigned index, Technique* tech, unsigned qualityLevel, float lodDistance)
  747. {
  748. if (index >= techniques_.Size())
  749. return;
  750. techniques_[index] = TechniqueEntry(tech, qualityLevel, lodDistance);
  751. CheckOcclusion();
  752. }
  753. void Material::SetShaderParameter(const String& name, const Variant& value)
  754. {
  755. MaterialShaderParameter newParam;
  756. newParam.name_ = name;
  757. newParam.value_ = value;
  758. StringHash nameHash(name);
  759. shaderParameters_[nameHash] = newParam;
  760. if (nameHash == PSP_MATSPECCOLOR)
  761. {
  762. VariantType type = value.GetType();
  763. if (type == VAR_VECTOR3)
  764. {
  765. const Vector3& vec = value.GetVector3();
  766. specular_ = vec.x_ > 0.0f || vec.y_ > 0.0f || vec.z_ > 0.0f;
  767. }
  768. else if (type == VAR_VECTOR4)
  769. {
  770. const Vector4& vec = value.GetVector4();
  771. specular_ = vec.x_ > 0.0f || vec.y_ > 0.0f || vec.z_ > 0.0f;
  772. }
  773. }
  774. if (!batchedParameterUpdate_)
  775. {
  776. RefreshShaderParameterHash();
  777. RefreshMemoryUse();
  778. }
  779. }
  780. void Material::SetShaderParameterAnimation(const String& name, ValueAnimation* animation, WrapMode wrapMode, float speed)
  781. {
  782. ShaderParameterAnimationInfo* info = GetShaderParameterAnimationInfo(name);
  783. if (animation)
  784. {
  785. if (info && info->GetAnimation() == animation)
  786. {
  787. info->SetWrapMode(wrapMode);
  788. info->SetSpeed(speed);
  789. return;
  790. }
  791. if (shaderParameters_.Find(name) == shaderParameters_.End())
  792. {
  793. ATOMIC_LOGERROR(GetName() + " has no shader parameter: " + name);
  794. return;
  795. }
  796. StringHash nameHash(name);
  797. shaderParameterAnimationInfos_[nameHash] = new ShaderParameterAnimationInfo(this, name, animation, wrapMode, speed);
  798. UpdateEventSubscription();
  799. }
  800. else
  801. {
  802. if (info)
  803. {
  804. StringHash nameHash(name);
  805. shaderParameterAnimationInfos_.Erase(nameHash);
  806. UpdateEventSubscription();
  807. }
  808. }
  809. }
  810. void Material::SetShaderParameterAnimationWrapMode(const String& name, WrapMode wrapMode)
  811. {
  812. ShaderParameterAnimationInfo* info = GetShaderParameterAnimationInfo(name);
  813. if (info)
  814. info->SetWrapMode(wrapMode);
  815. }
  816. void Material::SetShaderParameterAnimationSpeed(const String& name, float speed)
  817. {
  818. ShaderParameterAnimationInfo* info = GetShaderParameterAnimationInfo(name);
  819. if (info)
  820. info->SetSpeed(speed);
  821. }
  822. void Material::SetTexture(TextureUnit unit, Texture* texture)
  823. {
  824. if (unit < MAX_TEXTURE_UNITS)
  825. {
  826. if (texture)
  827. textures_[unit] = texture;
  828. else
  829. textures_.Erase(unit);
  830. }
  831. }
  832. void Material::SetUVTransform(const Vector2& offset, float rotation, const Vector2& repeat)
  833. {
  834. Matrix3x4 transform(Matrix3x4::IDENTITY);
  835. transform.m00_ = repeat.x_;
  836. transform.m11_ = repeat.y_;
  837. Matrix3x4 rotationMatrix(Matrix3x4::IDENTITY);
  838. rotationMatrix.m00_ = Cos(rotation);
  839. rotationMatrix.m01_ = Sin(rotation);
  840. rotationMatrix.m10_ = -rotationMatrix.m01_;
  841. rotationMatrix.m11_ = rotationMatrix.m00_;
  842. rotationMatrix.m03_ = 0.5f - 0.5f * (rotationMatrix.m00_ + rotationMatrix.m01_);
  843. rotationMatrix.m13_ = 0.5f - 0.5f * (rotationMatrix.m10_ + rotationMatrix.m11_);
  844. transform = transform * rotationMatrix;
  845. Matrix3x4 offsetMatrix = Matrix3x4::IDENTITY;
  846. offsetMatrix.m03_ = offset.x_;
  847. offsetMatrix.m13_ = offset.y_;
  848. transform = offsetMatrix * transform;
  849. SetShaderParameter("UOffset", Vector4(transform.m00_, transform.m01_, transform.m02_, transform.m03_));
  850. SetShaderParameter("VOffset", Vector4(transform.m10_, transform.m11_, transform.m12_, transform.m13_));
  851. }
  852. void Material::SetUVTransform(const Vector2& offset, float rotation, float repeat)
  853. {
  854. SetUVTransform(offset, rotation, Vector2(repeat, repeat));
  855. }
  856. void Material::SetCullMode(CullMode mode)
  857. {
  858. cullMode_ = mode;
  859. }
  860. void Material::SetShadowCullMode(CullMode mode)
  861. {
  862. shadowCullMode_ = mode;
  863. }
  864. void Material::SetFillMode(FillMode mode)
  865. {
  866. fillMode_ = mode;
  867. }
  868. void Material::SetDepthBias(const BiasParameters& parameters)
  869. {
  870. depthBias_ = parameters;
  871. depthBias_.Validate();
  872. }
  873. void Material::SetRenderOrder(unsigned char order)
  874. {
  875. renderOrder_ = order;
  876. }
  877. void Material::SetScene(Scene* scene)
  878. {
  879. UnsubscribeFromEvent(E_UPDATE);
  880. UnsubscribeFromEvent(E_ATTRIBUTEANIMATIONUPDATE);
  881. subscribed_ = false;
  882. scene_ = scene;
  883. UpdateEventSubscription();
  884. }
  885. void Material::RemoveShaderParameter(const String& name)
  886. {
  887. StringHash nameHash(name);
  888. shaderParameters_.Erase(nameHash);
  889. if (nameHash == PSP_MATSPECCOLOR)
  890. specular_ = false;
  891. RefreshShaderParameterHash();
  892. RefreshMemoryUse();
  893. }
  894. void Material::ReleaseShaders()
  895. {
  896. for (unsigned i = 0; i < techniques_.Size(); ++i)
  897. {
  898. Technique* tech = techniques_[i].technique_;
  899. if (tech)
  900. tech->ReleaseShaders();
  901. }
  902. }
  903. SharedPtr<Material> Material::Clone(const String& cloneName) const
  904. {
  905. SharedPtr<Material> ret(new Material(context_));
  906. ret->SetName(cloneName);
  907. ret->techniques_ = techniques_;
  908. ret->shaderParameters_ = shaderParameters_;
  909. ret->shaderParameterHash_ = shaderParameterHash_;
  910. ret->textures_ = textures_;
  911. ret->occlusion_ = occlusion_;
  912. ret->specular_ = specular_;
  913. ret->cullMode_ = cullMode_;
  914. ret->shadowCullMode_ = shadowCullMode_;
  915. ret->fillMode_ = fillMode_;
  916. ret->renderOrder_ = renderOrder_;
  917. ret->RefreshMemoryUse();
  918. return ret;
  919. }
  920. void Material::SortTechniques()
  921. {
  922. Sort(techniques_.Begin(), techniques_.End(), CompareTechniqueEntries);
  923. }
  924. void Material::MarkForAuxView(unsigned frameNumber)
  925. {
  926. auxViewFrameNumber_ = frameNumber;
  927. }
  928. const TechniqueEntry& Material::GetTechniqueEntry(unsigned index) const
  929. {
  930. return index < techniques_.Size() ? techniques_[index] : noEntry;
  931. }
  932. Technique* Material::GetTechnique(unsigned index) const
  933. {
  934. return index < techniques_.Size() ? techniques_[index].technique_ : (Technique*)0;
  935. }
  936. Pass* Material::GetPass(unsigned index, const String& passName) const
  937. {
  938. Technique* tech = index < techniques_.Size() ? techniques_[index].technique_ : (Technique*)0;
  939. return tech ? tech->GetPass(passName) : 0;
  940. }
  941. Texture* Material::GetTexture(TextureUnit unit) const
  942. {
  943. HashMap<TextureUnit, SharedPtr<Texture> >::ConstIterator i = textures_.Find(unit);
  944. return i != textures_.End() ? i->second_.Get() : (Texture*)0;
  945. }
  946. const Variant& Material::GetShaderParameter(const String& name) const
  947. {
  948. HashMap<StringHash, MaterialShaderParameter>::ConstIterator i = shaderParameters_.Find(name);
  949. return i != shaderParameters_.End() ? i->second_.value_ : Variant::EMPTY;
  950. }
  951. ValueAnimation* Material::GetShaderParameterAnimation(const String& name) const
  952. {
  953. ShaderParameterAnimationInfo* info = GetShaderParameterAnimationInfo(name);
  954. return info == 0 ? 0 : info->GetAnimation();
  955. }
  956. WrapMode Material::GetShaderParameterAnimationWrapMode(const String& name) const
  957. {
  958. ShaderParameterAnimationInfo* info = GetShaderParameterAnimationInfo(name);
  959. return info == 0 ? WM_LOOP : info->GetWrapMode();
  960. }
  961. float Material::GetShaderParameterAnimationSpeed(const String& name) const
  962. {
  963. ShaderParameterAnimationInfo* info = GetShaderParameterAnimationInfo(name);
  964. return info == 0 ? 0 : info->GetSpeed();
  965. }
  966. Scene* Material::GetScene() const
  967. {
  968. return scene_;
  969. }
  970. String Material::GetTextureUnitName(TextureUnit unit)
  971. {
  972. return textureUnitNames[unit];
  973. }
  974. Variant Material::ParseShaderParameterValue(const String& value)
  975. {
  976. String valueTrimmed = value.Trimmed();
  977. if (valueTrimmed.Length() && IsAlpha((unsigned)valueTrimmed[0]))
  978. return Variant(ToBool(valueTrimmed));
  979. else
  980. return ToVectorVariant(valueTrimmed);
  981. }
  982. void Material::CheckOcclusion()
  983. {
  984. // Determine occlusion by checking the base pass of each technique
  985. occlusion_ = false;
  986. for (unsigned i = 0; i < techniques_.Size(); ++i)
  987. {
  988. Technique* tech = techniques_[i].technique_;
  989. if (tech)
  990. {
  991. Pass* pass = tech->GetPass("base");
  992. if (pass && pass->GetDepthWrite() && !pass->GetAlphaMask())
  993. occlusion_ = true;
  994. }
  995. }
  996. }
  997. void Material::ResetToDefaults()
  998. {
  999. // Needs to be a no-op when async loading, as this does a GetResource() which is not allowed from worker threads
  1000. if (!Thread::IsMainThread())
  1001. return;
  1002. SetNumTechniques(1);
  1003. Renderer* renderer = GetSubsystem<Renderer>();
  1004. SetTechnique(0, renderer ? renderer->GetDefaultTechnique() :
  1005. GetSubsystem<ResourceCache>()->GetResource<Technique>("Techniques/NoTexture.xml"));
  1006. textures_.Clear();
  1007. batchedParameterUpdate_ = true;
  1008. shaderParameters_.Clear();
  1009. SetShaderParameter("UOffset", Vector4(1.0f, 0.0f, 0.0f, 0.0f));
  1010. SetShaderParameter("VOffset", Vector4(0.0f, 1.0f, 0.0f, 0.0f));
  1011. SetShaderParameter("MatDiffColor", Vector4::ONE);
  1012. SetShaderParameter("MatEmissiveColor", Vector3::ZERO);
  1013. SetShaderParameter("MatEnvMapColor", Vector3::ONE);
  1014. SetShaderParameter("MatSpecColor", Vector4(0.0f, 0.0f, 0.0f, 1.0f));
  1015. SetShaderParameter("Roughness", 0.5f);
  1016. SetShaderParameter("Metallic", 0.0f);
  1017. batchedParameterUpdate_ = false;
  1018. cullMode_ = CULL_CCW;
  1019. shadowCullMode_ = CULL_CCW;
  1020. fillMode_ = FILL_SOLID;
  1021. depthBias_ = BiasParameters(0.0f, 0.0f);
  1022. renderOrder_ = DEFAULT_RENDER_ORDER;
  1023. RefreshShaderParameterHash();
  1024. RefreshMemoryUse();
  1025. }
  1026. void Material::RefreshShaderParameterHash()
  1027. {
  1028. VectorBuffer temp;
  1029. for (HashMap<StringHash, MaterialShaderParameter>::ConstIterator i = shaderParameters_.Begin();
  1030. i != shaderParameters_.End(); ++i)
  1031. {
  1032. temp.WriteStringHash(i->first_);
  1033. temp.WriteVariant(i->second_.value_);
  1034. }
  1035. shaderParameterHash_ = 0;
  1036. const unsigned char* data = temp.GetData();
  1037. unsigned dataSize = temp.GetSize();
  1038. for (unsigned i = 0; i < dataSize; ++i)
  1039. shaderParameterHash_ = SDBMHash(shaderParameterHash_, data[i]);
  1040. }
  1041. void Material::RefreshMemoryUse()
  1042. {
  1043. unsigned memoryUse = sizeof(Material);
  1044. memoryUse += techniques_.Size() * sizeof(TechniqueEntry);
  1045. memoryUse += MAX_TEXTURE_UNITS * sizeof(SharedPtr<Texture>);
  1046. memoryUse += shaderParameters_.Size() * sizeof(MaterialShaderParameter);
  1047. SetMemoryUse(memoryUse);
  1048. }
  1049. ShaderParameterAnimationInfo* Material::GetShaderParameterAnimationInfo(const String& name) const
  1050. {
  1051. StringHash nameHash(name);
  1052. HashMap<StringHash, SharedPtr<ShaderParameterAnimationInfo> >::ConstIterator i = shaderParameterAnimationInfos_.Find(nameHash);
  1053. if (i == shaderParameterAnimationInfos_.End())
  1054. return 0;
  1055. return i->second_;
  1056. }
  1057. void Material::UpdateEventSubscription()
  1058. {
  1059. if (shaderParameterAnimationInfos_.Size() && !subscribed_)
  1060. {
  1061. if (scene_)
  1062. SubscribeToEvent(scene_, E_ATTRIBUTEANIMATIONUPDATE, ATOMIC_HANDLER(Material, HandleAttributeAnimationUpdate));
  1063. else
  1064. SubscribeToEvent(E_UPDATE, ATOMIC_HANDLER(Material, HandleAttributeAnimationUpdate));
  1065. subscribed_ = true;
  1066. }
  1067. else if (subscribed_ && shaderParameterAnimationInfos_.Empty())
  1068. {
  1069. UnsubscribeFromEvent(E_UPDATE);
  1070. UnsubscribeFromEvent(E_ATTRIBUTEANIMATIONUPDATE);
  1071. subscribed_ = false;
  1072. }
  1073. }
  1074. void Material::HandleAttributeAnimationUpdate(StringHash eventType, VariantMap& eventData)
  1075. {
  1076. // Timestep parameter is same no matter what event is being listened to
  1077. float timeStep = eventData[Update::P_TIMESTEP].GetFloat();
  1078. Vector<String> finishedNames;
  1079. for (HashMap<StringHash, SharedPtr<ShaderParameterAnimationInfo> >::ConstIterator i = shaderParameterAnimationInfos_.Begin();
  1080. i != shaderParameterAnimationInfos_.End(); ++i)
  1081. {
  1082. if (i->second_->Update(timeStep))
  1083. finishedNames.Push(i->second_->GetName());
  1084. }
  1085. // Remove finished animations
  1086. for (unsigned i = 0; i < finishedNames.Size(); ++i)
  1087. SetShaderParameterAnimation(finishedNames[i], 0);
  1088. }
  1089. }