Material.cpp 46 KB

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