Material.cpp 45 KB

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