Material.cpp 46 KB

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