Material.cpp 45 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384
  1. //
  2. // Copyright (c) 2008-2020 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 Urho3D
  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. nullptr
  67. #else
  68. "lightramp",
  69. "lightshape",
  70. "shadowmap",
  71. nullptr
  72. #endif
  73. };
  74. const char* cullModeNames[] =
  75. {
  76. "none",
  77. "ccw",
  78. "cw",
  79. nullptr
  80. };
  81. static const char* fillModeNames[] =
  82. {
  83. "solid",
  84. "wireframe",
  85. "point",
  86. nullptr
  87. };
  88. TextureUnit ParseTextureUnitName(String name)
  89. {
  90. name = name.ToLower().Trimmed();
  91. auto 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. URHO3D_LOGERROR("Unknown texture unit name " + name);
  111. return unit;
  112. }
  113. StringHash ParseTextureTypeName(const String& name)
  114. {
  115. String lowerCaseName = name.ToLower().Trimmed();
  116. if (lowerCaseName == "texture")
  117. return Texture2D::GetTypeStatic();
  118. else if (lowerCaseName == "cubemap")
  119. return TextureCube::GetTypeStatic();
  120. else if (lowerCaseName == "texture3d")
  121. return Texture3D::GetTypeStatic();
  122. else if (lowerCaseName == "texturearray")
  123. return Texture2DArray::GetTypeStatic();
  124. return nullptr;
  125. }
  126. StringHash ParseTextureTypeXml(ResourceCache* cache, const String& filename)
  127. {
  128. StringHash type = nullptr;
  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() noexcept :
  149. qualityLevel_(QUALITY_LOW),
  150. lodDistance_(0.0f)
  151. {
  152. }
  153. TechniqueEntry::TechniqueEntry(Technique* tech, MaterialQuality qualityLevel, float lodDistance) noexcept :
  154. technique_(tech),
  155. original_(tech),
  156. qualityLevel_(qualityLevel),
  157. lodDistance_(lodDistance)
  158. {
  159. }
  160. ShaderParameterAnimationInfo::ShaderParameterAnimationInfo(Material* material, const String& name, ValueAnimation* attributeAnimation,
  161. WrapMode wrapMode, float speed) :
  162. ValueAnimationInfo(material, attributeAnimation, wrapMode, speed),
  163. name_(name)
  164. {
  165. }
  166. ShaderParameterAnimationInfo::ShaderParameterAnimationInfo(const ShaderParameterAnimationInfo& other) = default;
  167. ShaderParameterAnimationInfo::~ShaderParameterAnimationInfo() = default;
  168. void ShaderParameterAnimationInfo::ApplyValue(const Variant& newValue)
  169. {
  170. static_cast<Material*>(target_.Get())->SetShaderParameter(name_, newValue);
  171. }
  172. Material::Material(Context* context) :
  173. Resource(context)
  174. {
  175. ResetToDefaults();
  176. }
  177. Material::~Material() = default;
  178. void Material::RegisterObject(Context* context)
  179. {
  180. context->RegisterFactory<Material>();
  181. }
  182. bool Material::BeginLoad(Deserializer& source)
  183. {
  184. // In headless mode, do not actually load the material, just return success
  185. auto* graphics = GetSubsystem<Graphics>();
  186. if (!graphics)
  187. return true;
  188. String extension = GetExtension(source.GetName());
  189. bool success = false;
  190. if (extension == ".xml")
  191. {
  192. success = BeginLoadXML(source);
  193. if (!success)
  194. success = BeginLoadJSON(source);
  195. if (success)
  196. return true;
  197. }
  198. else // Load JSON file
  199. {
  200. success = BeginLoadJSON(source);
  201. if (!success)
  202. success = BeginLoadXML(source);
  203. if (success)
  204. return true;
  205. }
  206. // All loading failed
  207. ResetToDefaults();
  208. loadJSONFile_.Reset();
  209. return false;
  210. }
  211. bool Material::EndLoad()
  212. {
  213. // In headless mode, do not actually load the material, just return success
  214. auto* graphics = GetSubsystem<Graphics>();
  215. if (!graphics)
  216. return true;
  217. bool success = false;
  218. if (loadXMLFile_)
  219. {
  220. // If async loading, get the techniques / textures which should be ready now
  221. XMLElement rootElem = loadXMLFile_->GetRoot();
  222. success = Load(rootElem);
  223. }
  224. if (loadJSONFile_)
  225. {
  226. JSONValue rootVal = loadJSONFile_->GetRoot();
  227. success = Load(rootVal);
  228. }
  229. loadXMLFile_.Reset();
  230. loadJSONFile_.Reset();
  231. return success;
  232. }
  233. bool Material::BeginLoadXML(Deserializer& source)
  234. {
  235. ResetToDefaults();
  236. loadXMLFile_ = new XMLFile(context_);
  237. if (loadXMLFile_->Load(source))
  238. {
  239. // If async loading, scan the XML content beforehand for technique & texture resources
  240. // and request them to also be loaded. Can not do anything else at this point
  241. if (GetAsyncLoadState() == ASYNC_LOADING)
  242. {
  243. auto* cache = GetSubsystem<ResourceCache>();
  244. XMLElement rootElem = loadXMLFile_->GetRoot();
  245. XMLElement techniqueElem = rootElem.GetChild("technique");
  246. while (techniqueElem)
  247. {
  248. cache->BackgroundLoadResource<Technique>(techniqueElem.GetAttribute("name"), true, this);
  249. techniqueElem = techniqueElem.GetNext("technique");
  250. }
  251. XMLElement textureElem = rootElem.GetChild("texture");
  252. while (textureElem)
  253. {
  254. String name = textureElem.GetAttribute("name");
  255. // Detect cube maps and arrays by file extension: they are defined by an XML file
  256. if (GetExtension(name) == ".xml")
  257. {
  258. #ifdef DESKTOP_GRAPHICS
  259. StringHash type = ParseTextureTypeXml(cache, name);
  260. if (!type && textureElem.HasAttribute("unit"))
  261. {
  262. TextureUnit unit = ParseTextureUnitName(textureElem.GetAttribute("unit"));
  263. if (unit == TU_VOLUMEMAP)
  264. type = Texture3D::GetTypeStatic();
  265. }
  266. if (type == Texture3D::GetTypeStatic())
  267. cache->BackgroundLoadResource<Texture3D>(name, true, this);
  268. else if (type == Texture2DArray::GetTypeStatic())
  269. cache->BackgroundLoadResource<Texture2DArray>(name, true, this);
  270. else
  271. #endif
  272. cache->BackgroundLoadResource<TextureCube>(name, true, this);
  273. }
  274. else
  275. cache->BackgroundLoadResource<Texture2D>(name, true, this);
  276. textureElem = textureElem.GetNext("texture");
  277. }
  278. }
  279. return true;
  280. }
  281. return false;
  282. }
  283. bool Material::BeginLoadJSON(Deserializer& source)
  284. {
  285. // Attempt to load a JSON file
  286. ResetToDefaults();
  287. loadXMLFile_.Reset();
  288. // Attempt to load from JSON file instead
  289. loadJSONFile_ = new JSONFile(context_);
  290. if (loadJSONFile_->Load(source))
  291. {
  292. // If async loading, scan the XML content beforehand for technique & texture resources
  293. // and request them to also be loaded. Can not do anything else at this point
  294. if (GetAsyncLoadState() == ASYNC_LOADING)
  295. {
  296. auto* cache = GetSubsystem<ResourceCache>();
  297. const JSONValue& rootVal = loadJSONFile_->GetRoot();
  298. JSONArray techniqueArray = rootVal.Get("techniques").GetArray();
  299. for (unsigned i = 0; i < techniqueArray.Size(); i++)
  300. {
  301. const JSONValue& techVal = techniqueArray[i];
  302. cache->BackgroundLoadResource<Technique>(techVal.Get("name").GetString(), true, this);
  303. }
  304. JSONObject textureObject = rootVal.Get("textures").GetObject();
  305. for (JSONObject::ConstIterator it = textureObject.Begin(); it != textureObject.End(); it++)
  306. {
  307. String unitString = it->first_;
  308. String name = it->second_.GetString();
  309. // Detect cube maps and arrays by file extension: they are defined by an XML file
  310. if (GetExtension(name) == ".xml")
  311. {
  312. #ifdef DESKTOP_GRAPHICS
  313. StringHash type = ParseTextureTypeXml(cache, name);
  314. if (!type && !unitString.Empty())
  315. {
  316. TextureUnit unit = ParseTextureUnitName(unitString);
  317. if (unit == TU_VOLUMEMAP)
  318. type = Texture3D::GetTypeStatic();
  319. }
  320. if (type == Texture3D::GetTypeStatic())
  321. cache->BackgroundLoadResource<Texture3D>(name, true, this);
  322. else if (type == Texture2DArray::GetTypeStatic())
  323. cache->BackgroundLoadResource<Texture2DArray>(name, true, this);
  324. else
  325. #endif
  326. cache->BackgroundLoadResource<TextureCube>(name, true, this);
  327. }
  328. else
  329. cache->BackgroundLoadResource<Texture2D>(name, true, this);
  330. }
  331. }
  332. // JSON material was successfully loaded
  333. return true;
  334. }
  335. return false;
  336. }
  337. bool Material::Save(Serializer& dest) const
  338. {
  339. SharedPtr<XMLFile> xml(new XMLFile(context_));
  340. XMLElement materialElem = xml->CreateRoot("material");
  341. Save(materialElem);
  342. return xml->Save(dest);
  343. }
  344. bool Material::Load(const XMLElement& source)
  345. {
  346. ResetToDefaults();
  347. if (source.IsNull())
  348. {
  349. URHO3D_LOGERROR("Can not load material from null XML element");
  350. return false;
  351. }
  352. auto* cache = GetSubsystem<ResourceCache>();
  353. XMLElement shaderElem = source.GetChild("shader");
  354. if (shaderElem)
  355. {
  356. vertexShaderDefines_ = shaderElem.GetAttribute("vsdefines");
  357. pixelShaderDefines_ = shaderElem.GetAttribute("psdefines");
  358. }
  359. XMLElement techniqueElem = source.GetChild("technique");
  360. techniques_.Clear();
  361. while (techniqueElem)
  362. {
  363. auto* tech = cache->GetResource<Technique>(techniqueElem.GetAttribute("name"));
  364. if (tech)
  365. {
  366. TechniqueEntry newTechnique;
  367. newTechnique.technique_ = newTechnique.original_ = tech;
  368. if (techniqueElem.HasAttribute("quality"))
  369. newTechnique.qualityLevel_ = (MaterialQuality)techniqueElem.GetInt("quality");
  370. if (techniqueElem.HasAttribute("loddistance"))
  371. newTechnique.lodDistance_ = techniqueElem.GetFloat("loddistance");
  372. techniques_.Push(newTechnique);
  373. }
  374. techniqueElem = techniqueElem.GetNext("technique");
  375. }
  376. SortTechniques();
  377. ApplyShaderDefines();
  378. XMLElement textureElem = source.GetChild("texture");
  379. while (textureElem)
  380. {
  381. TextureUnit unit = TU_DIFFUSE;
  382. if (textureElem.HasAttribute("unit"))
  383. unit = ParseTextureUnitName(textureElem.GetAttribute("unit"));
  384. if (unit < MAX_TEXTURE_UNITS)
  385. {
  386. String name = textureElem.GetAttribute("name");
  387. // Detect cube maps and arrays by file extension: they are defined by an XML file
  388. if (GetExtension(name) == ".xml")
  389. {
  390. #ifdef DESKTOP_GRAPHICS
  391. StringHash type = ParseTextureTypeXml(cache, name);
  392. if (!type && unit == TU_VOLUMEMAP)
  393. type = Texture3D::GetTypeStatic();
  394. if (type == Texture3D::GetTypeStatic())
  395. SetTexture(unit, cache->GetResource<Texture3D>(name));
  396. else if (type == Texture2DArray::GetTypeStatic())
  397. SetTexture(unit, cache->GetResource<Texture2DArray>(name));
  398. else
  399. #endif
  400. SetTexture(unit, cache->GetResource<TextureCube>(name));
  401. }
  402. else
  403. SetTexture(unit, cache->GetResource<Texture2D>(name));
  404. }
  405. textureElem = textureElem.GetNext("texture");
  406. }
  407. batchedParameterUpdate_ = true;
  408. XMLElement parameterElem = source.GetChild("parameter");
  409. while (parameterElem)
  410. {
  411. String name = parameterElem.GetAttribute("name");
  412. if (!parameterElem.HasAttribute("type"))
  413. SetShaderParameter(name, ParseShaderParameterValue(parameterElem.GetAttribute("value")));
  414. else
  415. SetShaderParameter(name, Variant(parameterElem.GetAttribute("type"), parameterElem.GetAttribute("value")));
  416. parameterElem = parameterElem.GetNext("parameter");
  417. }
  418. batchedParameterUpdate_ = false;
  419. XMLElement parameterAnimationElem = source.GetChild("parameteranimation");
  420. while (parameterAnimationElem)
  421. {
  422. String name = parameterAnimationElem.GetAttribute("name");
  423. SharedPtr<ValueAnimation> animation(new ValueAnimation(context_));
  424. if (!animation->LoadXML(parameterAnimationElem))
  425. {
  426. URHO3D_LOGERROR("Could not load parameter animation");
  427. return false;
  428. }
  429. String wrapModeString = parameterAnimationElem.GetAttribute("wrapmode");
  430. WrapMode wrapMode = WM_LOOP;
  431. for (int i = 0; i <= WM_CLAMP; ++i)
  432. {
  433. if (wrapModeString == wrapModeNames[i])
  434. {
  435. wrapMode = (WrapMode)i;
  436. break;
  437. }
  438. }
  439. float speed = parameterAnimationElem.GetFloat("speed");
  440. SetShaderParameterAnimation(name, animation, wrapMode, speed);
  441. parameterAnimationElem = parameterAnimationElem.GetNext("parameteranimation");
  442. }
  443. XMLElement cullElem = source.GetChild("cull");
  444. if (cullElem)
  445. SetCullMode((CullMode)GetStringListIndex(cullElem.GetAttribute("value").CString(), cullModeNames, CULL_CCW));
  446. XMLElement shadowCullElem = source.GetChild("shadowcull");
  447. if (shadowCullElem)
  448. SetShadowCullMode((CullMode)GetStringListIndex(shadowCullElem.GetAttribute("value").CString(), cullModeNames, CULL_CCW));
  449. XMLElement fillElem = source.GetChild("fill");
  450. if (fillElem)
  451. SetFillMode((FillMode)GetStringListIndex(fillElem.GetAttribute("value").CString(), fillModeNames, FILL_SOLID));
  452. XMLElement depthBiasElem = source.GetChild("depthbias");
  453. if (depthBiasElem)
  454. SetDepthBias(BiasParameters(depthBiasElem.GetFloat("constant"), depthBiasElem.GetFloat("slopescaled")));
  455. XMLElement alphaToCoverageElem = source.GetChild("alphatocoverage");
  456. if (alphaToCoverageElem)
  457. SetAlphaToCoverage(alphaToCoverageElem.GetBool("enable"));
  458. XMLElement lineAntiAliasElem = source.GetChild("lineantialias");
  459. if (lineAntiAliasElem)
  460. SetLineAntiAlias(lineAntiAliasElem.GetBool("enable"));
  461. XMLElement renderOrderElem = source.GetChild("renderorder");
  462. if (renderOrderElem)
  463. SetRenderOrder((unsigned char)renderOrderElem.GetUInt("value"));
  464. XMLElement occlusionElem = source.GetChild("occlusion");
  465. if (occlusionElem)
  466. SetOcclusion(occlusionElem.GetBool("enable"));
  467. RefreshShaderParameterHash();
  468. RefreshMemoryUse();
  469. return true;
  470. }
  471. bool Material::Load(const JSONValue& source)
  472. {
  473. ResetToDefaults();
  474. if (source.IsNull())
  475. {
  476. URHO3D_LOGERROR("Can not load material from null JSON element");
  477. return false;
  478. }
  479. auto* cache = GetSubsystem<ResourceCache>();
  480. const JSONValue& shaderVal = source.Get("shader");
  481. if (!shaderVal.IsNull())
  482. {
  483. vertexShaderDefines_ = shaderVal.Get("vsdefines").GetString();
  484. pixelShaderDefines_ = shaderVal.Get("psdefines").GetString();
  485. }
  486. // Load techniques
  487. JSONArray techniquesArray = source.Get("techniques").GetArray();
  488. techniques_.Clear();
  489. techniques_.Reserve(techniquesArray.Size());
  490. for (unsigned i = 0; i < techniquesArray.Size(); i++)
  491. {
  492. const JSONValue& techVal = techniquesArray[i];
  493. auto* tech = cache->GetResource<Technique>(techVal.Get("name").GetString());
  494. if (tech)
  495. {
  496. TechniqueEntry newTechnique;
  497. newTechnique.technique_ = newTechnique.original_ = tech;
  498. JSONValue qualityVal = techVal.Get("quality");
  499. if (!qualityVal.IsNull())
  500. newTechnique.qualityLevel_ = (MaterialQuality)qualityVal.GetInt();
  501. JSONValue lodDistanceVal = techVal.Get("loddistance");
  502. if (!lodDistanceVal.IsNull())
  503. newTechnique.lodDistance_ = lodDistanceVal.GetFloat();
  504. techniques_.Push(newTechnique);
  505. }
  506. }
  507. SortTechniques();
  508. ApplyShaderDefines();
  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 animations
  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. URHO3D_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 alphaToCoverageVal = source.Get("alphatocoverage");
  591. if (!alphaToCoverageVal.IsNull())
  592. SetAlphaToCoverage(alphaToCoverageVal.GetBool());
  593. JSONValue lineAntiAliasVal = source.Get("lineantialias");
  594. if (!lineAntiAliasVal.IsNull())
  595. SetLineAntiAlias(lineAntiAliasVal.GetBool());
  596. JSONValue renderOrderVal = source.Get("renderorder");
  597. if (!renderOrderVal.IsNull())
  598. SetRenderOrder((unsigned char)renderOrderVal.GetUInt());
  599. JSONValue occlusionVal = source.Get("occlusion");
  600. if (!occlusionVal.IsNull())
  601. SetOcclusion(occlusionVal.GetBool());
  602. RefreshShaderParameterHash();
  603. RefreshMemoryUse();
  604. return true;
  605. }
  606. bool Material::Save(XMLElement& dest) const
  607. {
  608. if (dest.IsNull())
  609. {
  610. URHO3D_LOGERROR("Can not save material to null XML element");
  611. return false;
  612. }
  613. // Write techniques
  614. for (unsigned i = 0; i < techniques_.Size(); ++i)
  615. {
  616. const TechniqueEntry& entry = techniques_[i];
  617. if (!entry.technique_)
  618. continue;
  619. XMLElement techniqueElem = dest.CreateChild("technique");
  620. techniqueElem.SetString("name", entry.technique_->GetName());
  621. techniqueElem.SetInt("quality", entry.qualityLevel_);
  622. techniqueElem.SetFloat("loddistance", entry.lodDistance_);
  623. }
  624. // Write texture units
  625. for (unsigned j = 0; j < MAX_TEXTURE_UNITS; ++j)
  626. {
  627. Texture* texture = GetTexture((TextureUnit)j);
  628. if (texture)
  629. {
  630. XMLElement textureElem = dest.CreateChild("texture");
  631. textureElem.SetString("unit", textureUnitNames[j]);
  632. textureElem.SetString("name", texture->GetName());
  633. }
  634. }
  635. // Write shader compile defines
  636. if (!vertexShaderDefines_.Empty() || !pixelShaderDefines_.Empty())
  637. {
  638. XMLElement shaderElem = dest.CreateChild("shader");
  639. if (!vertexShaderDefines_.Empty())
  640. shaderElem.SetString("vsdefines", vertexShaderDefines_);
  641. if (!pixelShaderDefines_.Empty())
  642. shaderElem.SetString("psdefines", pixelShaderDefines_);
  643. }
  644. // Write shader parameters
  645. for (HashMap<StringHash, MaterialShaderParameter>::ConstIterator j = shaderParameters_.Begin();
  646. j != shaderParameters_.End(); ++j)
  647. {
  648. XMLElement parameterElem = dest.CreateChild("parameter");
  649. parameterElem.SetString("name", j->second_.name_);
  650. if (j->second_.value_.GetType() != VAR_BUFFER && j->second_.value_.GetType() != VAR_INT && j->second_.value_.GetType() != VAR_BOOL)
  651. parameterElem.SetVectorVariant("value", j->second_.value_);
  652. else
  653. {
  654. parameterElem.SetAttribute("type", j->second_.value_.GetTypeName());
  655. parameterElem.SetAttribute("value", j->second_.value_.ToString());
  656. }
  657. }
  658. // Write shader parameter animations
  659. for (HashMap<StringHash, SharedPtr<ShaderParameterAnimationInfo> >::ConstIterator j = shaderParameterAnimationInfos_.Begin();
  660. j != shaderParameterAnimationInfos_.End(); ++j)
  661. {
  662. ShaderParameterAnimationInfo* info = j->second_;
  663. XMLElement parameterAnimationElem = dest.CreateChild("parameteranimation");
  664. parameterAnimationElem.SetString("name", info->GetName());
  665. if (!info->GetAnimation()->SaveXML(parameterAnimationElem))
  666. return false;
  667. parameterAnimationElem.SetAttribute("wrapmode", wrapModeNames[info->GetWrapMode()]);
  668. parameterAnimationElem.SetFloat("speed", info->GetSpeed());
  669. }
  670. // Write culling modes
  671. XMLElement cullElem = dest.CreateChild("cull");
  672. cullElem.SetString("value", cullModeNames[cullMode_]);
  673. XMLElement shadowCullElem = dest.CreateChild("shadowcull");
  674. shadowCullElem.SetString("value", cullModeNames[shadowCullMode_]);
  675. // Write fill mode
  676. XMLElement fillElem = dest.CreateChild("fill");
  677. fillElem.SetString("value", fillModeNames[fillMode_]);
  678. // Write depth bias
  679. XMLElement depthBiasElem = dest.CreateChild("depthbias");
  680. depthBiasElem.SetFloat("constant", depthBias_.constantBias_);
  681. depthBiasElem.SetFloat("slopescaled", depthBias_.slopeScaledBias_);
  682. // Write alpha-to-coverage
  683. XMLElement alphaToCoverageElem = dest.CreateChild("alphatocoverage");
  684. alphaToCoverageElem.SetBool("enable", alphaToCoverage_);
  685. // Write line anti-alias
  686. XMLElement lineAntiAliasElem = dest.CreateChild("lineantialias");
  687. lineAntiAliasElem.SetBool("enable", lineAntiAlias_);
  688. // Write render order
  689. XMLElement renderOrderElem = dest.CreateChild("renderorder");
  690. renderOrderElem.SetUInt("value", renderOrder_);
  691. // Write occlusion
  692. XMLElement occlusionElem = dest.CreateChild("occlusion");
  693. occlusionElem.SetBool("enable", occlusion_);
  694. return true;
  695. }
  696. bool Material::Save(JSONValue& dest) const
  697. {
  698. // Write techniques
  699. JSONArray techniquesArray;
  700. techniquesArray.Reserve(techniques_.Size());
  701. for (unsigned i = 0; i < techniques_.Size(); ++i)
  702. {
  703. const TechniqueEntry& entry = techniques_[i];
  704. if (!entry.technique_)
  705. continue;
  706. JSONValue techniqueVal;
  707. techniqueVal.Set("name", entry.technique_->GetName());
  708. techniqueVal.Set("quality", (int) entry.qualityLevel_);
  709. techniqueVal.Set("loddistance", entry.lodDistance_);
  710. techniquesArray.Push(techniqueVal);
  711. }
  712. dest.Set("techniques", techniquesArray);
  713. // Write texture units
  714. JSONValue texturesValue;
  715. for (unsigned j = 0; j < MAX_TEXTURE_UNITS; ++j)
  716. {
  717. Texture* texture = GetTexture((TextureUnit)j);
  718. if (texture)
  719. texturesValue.Set(textureUnitNames[j], texture->GetName());
  720. }
  721. dest.Set("textures", texturesValue);
  722. // Write shader compile defines
  723. if (!vertexShaderDefines_.Empty() || !pixelShaderDefines_.Empty())
  724. {
  725. JSONValue shaderVal;
  726. if (!vertexShaderDefines_.Empty())
  727. shaderVal.Set("vsdefines", vertexShaderDefines_);
  728. if (!pixelShaderDefines_.Empty())
  729. shaderVal.Set("psdefines", pixelShaderDefines_);
  730. dest.Set("shader", shaderVal);
  731. }
  732. // Write shader parameters
  733. JSONValue shaderParamsVal;
  734. for (HashMap<StringHash, MaterialShaderParameter>::ConstIterator j = shaderParameters_.Begin();
  735. j != shaderParameters_.End(); ++j)
  736. {
  737. if (j->second_.value_.GetType() != VAR_BUFFER && j->second_.value_.GetType() != VAR_INT && j->second_.value_.GetType() != VAR_BOOL)
  738. shaderParamsVal.Set(j->second_.name_, j->second_.value_.ToString());
  739. else
  740. {
  741. JSONObject valueObj;
  742. valueObj["type"] = j->second_.value_.GetTypeName();
  743. valueObj["value"] = j->second_.value_.ToString();
  744. shaderParamsVal.Set(j->second_.name_, valueObj);
  745. }
  746. }
  747. dest.Set("shaderParameters", shaderParamsVal);
  748. // Write shader parameter animations
  749. JSONValue shaderParamAnimationsVal;
  750. for (HashMap<StringHash, SharedPtr<ShaderParameterAnimationInfo> >::ConstIterator j = shaderParameterAnimationInfos_.Begin();
  751. j != shaderParameterAnimationInfos_.End(); ++j)
  752. {
  753. ShaderParameterAnimationInfo* info = j->second_;
  754. JSONValue paramAnimationVal;
  755. if (!info->GetAnimation()->SaveJSON(paramAnimationVal))
  756. return false;
  757. paramAnimationVal.Set("wrapmode", wrapModeNames[info->GetWrapMode()]);
  758. paramAnimationVal.Set("speed", info->GetSpeed());
  759. shaderParamAnimationsVal.Set(info->GetName(), paramAnimationVal);
  760. }
  761. dest.Set("shaderParameterAnimations", shaderParamAnimationsVal);
  762. // Write culling modes
  763. dest.Set("cull", cullModeNames[cullMode_]);
  764. dest.Set("shadowcull", cullModeNames[shadowCullMode_]);
  765. // Write fill mode
  766. dest.Set("fill", fillModeNames[fillMode_]);
  767. // Write depth bias
  768. JSONValue depthBiasValue;
  769. depthBiasValue.Set("constant", depthBias_.constantBias_);
  770. depthBiasValue.Set("slopescaled", depthBias_.slopeScaledBias_);
  771. dest.Set("depthbias", depthBiasValue);
  772. // Write alpha-to-coverage
  773. dest.Set("alphatocoverage", alphaToCoverage_);
  774. // Write line anti-alias
  775. dest.Set("lineantialias", lineAntiAlias_);
  776. // Write render order
  777. dest.Set("renderorder", (unsigned) renderOrder_);
  778. // Write occlusion
  779. dest.Set("occlusion", occlusion_);
  780. return true;
  781. }
  782. void Material::SetNumTechniques(unsigned num)
  783. {
  784. if (!num)
  785. return;
  786. techniques_.Resize(num);
  787. RefreshMemoryUse();
  788. }
  789. void Material::SetTechnique(unsigned index, Technique* tech, MaterialQuality qualityLevel, float lodDistance)
  790. {
  791. if (index >= techniques_.Size())
  792. return;
  793. techniques_[index] = TechniqueEntry(tech, qualityLevel, lodDistance);
  794. ApplyShaderDefines(index);
  795. }
  796. void Material::SetVertexShaderDefines(const String& defines)
  797. {
  798. if (defines != vertexShaderDefines_)
  799. {
  800. vertexShaderDefines_ = defines;
  801. ApplyShaderDefines();
  802. }
  803. }
  804. void Material::SetPixelShaderDefines(const String& defines)
  805. {
  806. if (defines != pixelShaderDefines_)
  807. {
  808. pixelShaderDefines_ = defines;
  809. ApplyShaderDefines();
  810. }
  811. }
  812. void Material::SetShaderParameter(const String& name, const Variant& value)
  813. {
  814. MaterialShaderParameter newParam;
  815. newParam.name_ = name;
  816. newParam.value_ = value;
  817. StringHash nameHash(name);
  818. shaderParameters_[nameHash] = newParam;
  819. if (nameHash == PSP_MATSPECCOLOR)
  820. {
  821. VariantType type = value.GetType();
  822. if (type == VAR_VECTOR3)
  823. {
  824. const Vector3& vec = value.GetVector3();
  825. specular_ = vec.x_ > 0.0f || vec.y_ > 0.0f || vec.z_ > 0.0f;
  826. }
  827. else if (type == VAR_VECTOR4)
  828. {
  829. const Vector4& vec = value.GetVector4();
  830. specular_ = vec.x_ > 0.0f || vec.y_ > 0.0f || vec.z_ > 0.0f;
  831. }
  832. }
  833. if (!batchedParameterUpdate_)
  834. {
  835. RefreshShaderParameterHash();
  836. RefreshMemoryUse();
  837. }
  838. }
  839. void Material::SetShaderParameterAnimation(const String& name, ValueAnimation* animation, WrapMode wrapMode, float speed)
  840. {
  841. ShaderParameterAnimationInfo* info = GetShaderParameterAnimationInfo(name);
  842. if (animation)
  843. {
  844. if (info && info->GetAnimation() == animation)
  845. {
  846. info->SetWrapMode(wrapMode);
  847. info->SetSpeed(speed);
  848. return;
  849. }
  850. if (shaderParameters_.Find(name) == shaderParameters_.End())
  851. {
  852. URHO3D_LOGERROR(GetName() + " has no shader parameter: " + name);
  853. return;
  854. }
  855. StringHash nameHash(name);
  856. shaderParameterAnimationInfos_[nameHash] = new ShaderParameterAnimationInfo(this, name, animation, wrapMode, speed);
  857. UpdateEventSubscription();
  858. }
  859. else
  860. {
  861. if (info)
  862. {
  863. StringHash nameHash(name);
  864. shaderParameterAnimationInfos_.Erase(nameHash);
  865. UpdateEventSubscription();
  866. }
  867. }
  868. }
  869. void Material::SetShaderParameterAnimationWrapMode(const String& name, WrapMode wrapMode)
  870. {
  871. ShaderParameterAnimationInfo* info = GetShaderParameterAnimationInfo(name);
  872. if (info)
  873. info->SetWrapMode(wrapMode);
  874. }
  875. void Material::SetShaderParameterAnimationSpeed(const String& name, float speed)
  876. {
  877. ShaderParameterAnimationInfo* info = GetShaderParameterAnimationInfo(name);
  878. if (info)
  879. info->SetSpeed(speed);
  880. }
  881. void Material::SetTexture(TextureUnit unit, Texture* texture)
  882. {
  883. if (unit < MAX_TEXTURE_UNITS)
  884. {
  885. if (texture)
  886. textures_[unit] = texture;
  887. else
  888. textures_.Erase(unit);
  889. }
  890. }
  891. void Material::SetUVTransform(const Vector2& offset, float rotation, const Vector2& repeat)
  892. {
  893. Matrix3x4 transform(Matrix3x4::IDENTITY);
  894. transform.m00_ = repeat.x_;
  895. transform.m11_ = repeat.y_;
  896. Matrix3x4 rotationMatrix(Matrix3x4::IDENTITY);
  897. rotationMatrix.m00_ = Cos(rotation);
  898. rotationMatrix.m01_ = Sin(rotation);
  899. rotationMatrix.m10_ = -rotationMatrix.m01_;
  900. rotationMatrix.m11_ = rotationMatrix.m00_;
  901. rotationMatrix.m03_ = 0.5f - 0.5f * (rotationMatrix.m00_ + rotationMatrix.m01_);
  902. rotationMatrix.m13_ = 0.5f - 0.5f * (rotationMatrix.m10_ + rotationMatrix.m11_);
  903. transform = transform * rotationMatrix;
  904. Matrix3x4 offsetMatrix = Matrix3x4::IDENTITY;
  905. offsetMatrix.m03_ = offset.x_;
  906. offsetMatrix.m13_ = offset.y_;
  907. transform = offsetMatrix * transform;
  908. SetShaderParameter("UOffset", Vector4(transform.m00_, transform.m01_, transform.m02_, transform.m03_));
  909. SetShaderParameter("VOffset", Vector4(transform.m10_, transform.m11_, transform.m12_, transform.m13_));
  910. }
  911. void Material::SetUVTransform(const Vector2& offset, float rotation, float repeat)
  912. {
  913. SetUVTransform(offset, rotation, Vector2(repeat, repeat));
  914. }
  915. void Material::SetCullMode(CullMode mode)
  916. {
  917. cullMode_ = mode;
  918. }
  919. void Material::SetShadowCullMode(CullMode mode)
  920. {
  921. shadowCullMode_ = mode;
  922. }
  923. void Material::SetFillMode(FillMode mode)
  924. {
  925. fillMode_ = mode;
  926. }
  927. void Material::SetDepthBias(const BiasParameters& parameters)
  928. {
  929. depthBias_ = parameters;
  930. depthBias_.Validate();
  931. }
  932. void Material::SetAlphaToCoverage(bool enable)
  933. {
  934. alphaToCoverage_ = enable;
  935. }
  936. void Material::SetLineAntiAlias(bool enable)
  937. {
  938. lineAntiAlias_ = enable;
  939. }
  940. void Material::SetRenderOrder(unsigned char order)
  941. {
  942. renderOrder_ = order;
  943. }
  944. void Material::SetOcclusion(bool enable)
  945. {
  946. occlusion_ = enable;
  947. }
  948. void Material::SetScene(Scene* scene)
  949. {
  950. UnsubscribeFromEvent(E_UPDATE);
  951. UnsubscribeFromEvent(E_ATTRIBUTEANIMATIONUPDATE);
  952. subscribed_ = false;
  953. scene_ = scene;
  954. UpdateEventSubscription();
  955. }
  956. void Material::RemoveShaderParameter(const String& name)
  957. {
  958. StringHash nameHash(name);
  959. shaderParameters_.Erase(nameHash);
  960. if (nameHash == PSP_MATSPECCOLOR)
  961. specular_ = false;
  962. RefreshShaderParameterHash();
  963. RefreshMemoryUse();
  964. }
  965. void Material::ReleaseShaders()
  966. {
  967. for (unsigned i = 0; i < techniques_.Size(); ++i)
  968. {
  969. Technique* tech = techniques_[i].technique_;
  970. if (tech)
  971. tech->ReleaseShaders();
  972. }
  973. }
  974. SharedPtr<Material> Material::Clone(const String& cloneName) const
  975. {
  976. SharedPtr<Material> ret(new Material(context_));
  977. ret->SetName(cloneName);
  978. ret->techniques_ = techniques_;
  979. ret->vertexShaderDefines_ = vertexShaderDefines_;
  980. ret->pixelShaderDefines_ = pixelShaderDefines_;
  981. ret->shaderParameters_ = shaderParameters_;
  982. ret->shaderParameterHash_ = shaderParameterHash_;
  983. ret->textures_ = textures_;
  984. ret->depthBias_ = depthBias_;
  985. ret->alphaToCoverage_ = alphaToCoverage_;
  986. ret->lineAntiAlias_ = lineAntiAlias_;
  987. ret->occlusion_ = occlusion_;
  988. ret->specular_ = specular_;
  989. ret->cullMode_ = cullMode_;
  990. ret->shadowCullMode_ = shadowCullMode_;
  991. ret->fillMode_ = fillMode_;
  992. ret->renderOrder_ = renderOrder_;
  993. ret->RefreshMemoryUse();
  994. return ret;
  995. }
  996. void Material::SortTechniques()
  997. {
  998. Sort(techniques_.Begin(), techniques_.End(), CompareTechniqueEntries);
  999. }
  1000. void Material::MarkForAuxView(unsigned frameNumber)
  1001. {
  1002. auxViewFrameNumber_ = frameNumber;
  1003. }
  1004. const TechniqueEntry& Material::GetTechniqueEntry(unsigned index) const
  1005. {
  1006. return index < techniques_.Size() ? techniques_[index] : noEntry;
  1007. }
  1008. Technique* Material::GetTechnique(unsigned index) const
  1009. {
  1010. return index < techniques_.Size() ? techniques_[index].technique_ : nullptr;
  1011. }
  1012. Pass* Material::GetPass(unsigned index, const String& passName) const
  1013. {
  1014. Technique* tech = index < techniques_.Size() ? techniques_[index].technique_ : nullptr;
  1015. return tech ? tech->GetPass(passName) : nullptr;
  1016. }
  1017. Texture* Material::GetTexture(TextureUnit unit) const
  1018. {
  1019. HashMap<TextureUnit, SharedPtr<Texture> >::ConstIterator i = textures_.Find(unit);
  1020. return i != textures_.End() ? i->second_.Get() : nullptr;
  1021. }
  1022. const Variant& Material::GetShaderParameter(const String& name) const
  1023. {
  1024. HashMap<StringHash, MaterialShaderParameter>::ConstIterator i = shaderParameters_.Find(name);
  1025. return i != shaderParameters_.End() ? i->second_.value_ : Variant::EMPTY;
  1026. }
  1027. ValueAnimation* Material::GetShaderParameterAnimation(const String& name) const
  1028. {
  1029. ShaderParameterAnimationInfo* info = GetShaderParameterAnimationInfo(name);
  1030. return info == nullptr ? nullptr : info->GetAnimation();
  1031. }
  1032. WrapMode Material::GetShaderParameterAnimationWrapMode(const String& name) const
  1033. {
  1034. ShaderParameterAnimationInfo* info = GetShaderParameterAnimationInfo(name);
  1035. return info == nullptr ? WM_LOOP : info->GetWrapMode();
  1036. }
  1037. float Material::GetShaderParameterAnimationSpeed(const String& name) const
  1038. {
  1039. ShaderParameterAnimationInfo* info = GetShaderParameterAnimationInfo(name);
  1040. return info == nullptr ? 0 : info->GetSpeed();
  1041. }
  1042. Scene* Material::GetScene() const
  1043. {
  1044. return scene_;
  1045. }
  1046. String Material::GetTextureUnitName(TextureUnit unit)
  1047. {
  1048. return textureUnitNames[unit];
  1049. }
  1050. Variant Material::ParseShaderParameterValue(const String& value)
  1051. {
  1052. String valueTrimmed = value.Trimmed();
  1053. if (valueTrimmed.Length() && IsAlpha((unsigned)valueTrimmed[0]))
  1054. return Variant(ToBool(valueTrimmed));
  1055. else
  1056. return ToVectorVariant(valueTrimmed);
  1057. }
  1058. void Material::ResetToDefaults()
  1059. {
  1060. // Needs to be a no-op when async loading, as this does a GetResource() which is not allowed from worker threads
  1061. if (!Thread::IsMainThread())
  1062. return;
  1063. vertexShaderDefines_.Clear();
  1064. pixelShaderDefines_.Clear();
  1065. SetNumTechniques(1);
  1066. auto* renderer = GetSubsystem<Renderer>();
  1067. SetTechnique(0, renderer ? renderer->GetDefaultTechnique() :
  1068. GetSubsystem<ResourceCache>()->GetResource<Technique>("Techniques/NoTexture.xml"));
  1069. textures_.Clear();
  1070. batchedParameterUpdate_ = true;
  1071. shaderParameters_.Clear();
  1072. SetShaderParameter("UOffset", Vector4(1.0f, 0.0f, 0.0f, 0.0f));
  1073. SetShaderParameter("VOffset", Vector4(0.0f, 1.0f, 0.0f, 0.0f));
  1074. SetShaderParameter("MatDiffColor", Vector4::ONE);
  1075. SetShaderParameter("MatEmissiveColor", Vector3::ZERO);
  1076. SetShaderParameter("MatEnvMapColor", Vector3::ONE);
  1077. SetShaderParameter("MatSpecColor", Vector4(0.0f, 0.0f, 0.0f, 1.0f));
  1078. SetShaderParameter("Roughness", 0.5f);
  1079. SetShaderParameter("Metallic", 0.0f);
  1080. batchedParameterUpdate_ = false;
  1081. cullMode_ = CULL_CCW;
  1082. shadowCullMode_ = CULL_CCW;
  1083. fillMode_ = FILL_SOLID;
  1084. depthBias_ = BiasParameters(0.0f, 0.0f);
  1085. renderOrder_ = DEFAULT_RENDER_ORDER;
  1086. occlusion_ = true;
  1087. RefreshShaderParameterHash();
  1088. RefreshMemoryUse();
  1089. }
  1090. void Material::RefreshShaderParameterHash()
  1091. {
  1092. VectorBuffer temp;
  1093. for (HashMap<StringHash, MaterialShaderParameter>::ConstIterator i = shaderParameters_.Begin();
  1094. i != shaderParameters_.End(); ++i)
  1095. {
  1096. temp.WriteStringHash(i->first_);
  1097. temp.WriteVariant(i->second_.value_);
  1098. }
  1099. shaderParameterHash_ = 0;
  1100. const unsigned char* data = temp.GetData();
  1101. unsigned dataSize = temp.GetSize();
  1102. for (unsigned i = 0; i < dataSize; ++i)
  1103. shaderParameterHash_ = SDBMHash(shaderParameterHash_, data[i]);
  1104. }
  1105. void Material::RefreshMemoryUse()
  1106. {
  1107. unsigned memoryUse = sizeof(Material);
  1108. memoryUse += techniques_.Size() * sizeof(TechniqueEntry);
  1109. memoryUse += MAX_TEXTURE_UNITS * sizeof(SharedPtr<Texture>);
  1110. memoryUse += shaderParameters_.Size() * sizeof(MaterialShaderParameter);
  1111. SetMemoryUse(memoryUse);
  1112. }
  1113. ShaderParameterAnimationInfo* Material::GetShaderParameterAnimationInfo(const String& name) const
  1114. {
  1115. StringHash nameHash(name);
  1116. HashMap<StringHash, SharedPtr<ShaderParameterAnimationInfo> >::ConstIterator i = shaderParameterAnimationInfos_.Find(nameHash);
  1117. if (i == shaderParameterAnimationInfos_.End())
  1118. return nullptr;
  1119. return i->second_;
  1120. }
  1121. void Material::UpdateEventSubscription()
  1122. {
  1123. if (shaderParameterAnimationInfos_.Size() && !subscribed_)
  1124. {
  1125. if (scene_)
  1126. SubscribeToEvent(scene_, E_ATTRIBUTEANIMATIONUPDATE, URHO3D_HANDLER(Material, HandleAttributeAnimationUpdate));
  1127. else
  1128. SubscribeToEvent(E_UPDATE, URHO3D_HANDLER(Material, HandleAttributeAnimationUpdate));
  1129. subscribed_ = true;
  1130. }
  1131. else if (subscribed_ && shaderParameterAnimationInfos_.Empty())
  1132. {
  1133. UnsubscribeFromEvent(E_UPDATE);
  1134. UnsubscribeFromEvent(E_ATTRIBUTEANIMATIONUPDATE);
  1135. subscribed_ = false;
  1136. }
  1137. }
  1138. void Material::HandleAttributeAnimationUpdate(StringHash eventType, VariantMap& eventData)
  1139. {
  1140. // Timestep parameter is same no matter what event is being listened to
  1141. float timeStep = eventData[Update::P_TIMESTEP].GetFloat();
  1142. // Keep weak pointer to self to check for destruction caused by event handling
  1143. WeakPtr<Object> self(this);
  1144. Vector<String> finishedNames;
  1145. for (HashMap<StringHash, SharedPtr<ShaderParameterAnimationInfo> >::ConstIterator i = shaderParameterAnimationInfos_.Begin();
  1146. i != shaderParameterAnimationInfos_.End(); ++i)
  1147. {
  1148. bool finished = i->second_->Update(timeStep);
  1149. // If self deleted as a result of an event sent during animation playback, nothing more to do
  1150. if (self.Expired())
  1151. return;
  1152. if (finished)
  1153. finishedNames.Push(i->second_->GetName());
  1154. }
  1155. // Remove finished animations
  1156. for (unsigned i = 0; i < finishedNames.Size(); ++i)
  1157. SetShaderParameterAnimation(finishedNames[i], nullptr);
  1158. }
  1159. void Material::ApplyShaderDefines(unsigned index)
  1160. {
  1161. if (index == M_MAX_UNSIGNED)
  1162. {
  1163. for (unsigned i = 0; i < techniques_.Size(); ++i)
  1164. ApplyShaderDefines(i);
  1165. return;
  1166. }
  1167. if (index >= techniques_.Size() || !techniques_[index].original_)
  1168. return;
  1169. if (vertexShaderDefines_.Empty() && pixelShaderDefines_.Empty())
  1170. techniques_[index].technique_ = techniques_[index].original_;
  1171. else
  1172. techniques_[index].technique_ = techniques_[index].original_->CloneWithDefines(vertexShaderDefines_, pixelShaderDefines_);
  1173. }
  1174. }