Material.cpp 43 KB

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