Material.cpp 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874
  1. //
  2. // Copyright (c) 2008-2015 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 "../IO/FileSystem.h"
  26. #include "../Graphics/Graphics.h"
  27. #include "../IO/Log.h"
  28. #include "../IO/VectorBuffer.h"
  29. #include "../Graphics/Material.h"
  30. #include "../Math/Matrix3x4.h"
  31. #include "../Core/Profiler.h"
  32. #include "../Resource/ResourceCache.h"
  33. #include "../Scene/Scene.h"
  34. #include "../Scene/SceneEvents.h"
  35. #include "../Core/StringUtils.h"
  36. #include "../Graphics/Technique.h"
  37. #include "../Graphics/Texture2D.h"
  38. #include "../Graphics/Texture3D.h"
  39. #include "../Graphics/TextureCube.h"
  40. #include "../Scene/ValueAnimation.h"
  41. #include "../Resource/XMLFile.h"
  42. #include "../DebugNew.h"
  43. namespace Atomic
  44. {
  45. extern const char* wrapModeNames[];
  46. static const char* textureUnitNames[] =
  47. {
  48. "diffuse",
  49. "normal",
  50. "specular",
  51. "emissive",
  52. "environment",
  53. #ifdef DESKTOP_GRAPHICS
  54. "volume",
  55. "custom1",
  56. "custom2",
  57. "lightramp",
  58. "lightshape",
  59. "shadowmap",
  60. "faceselect",
  61. "indirection",
  62. "depth",
  63. "light",
  64. "zone",
  65. 0
  66. #else
  67. "lightramp",
  68. "lightshape",
  69. "shadowmap",
  70. 0
  71. #endif
  72. };
  73. static const char* cullModeNames[] =
  74. {
  75. "none",
  76. "ccw",
  77. "cw",
  78. 0
  79. };
  80. static const char* fillModeNames[] =
  81. {
  82. "solid",
  83. "wireframe",
  84. "point",
  85. 0
  86. };
  87. TextureUnit ParseTextureUnitName(String name)
  88. {
  89. name = name.ToLower().Trimmed();
  90. TextureUnit unit = (TextureUnit)GetStringListIndex(name.CString(), textureUnitNames, MAX_TEXTURE_UNITS);
  91. if (unit == MAX_TEXTURE_UNITS)
  92. {
  93. // Check also for shorthand names
  94. if (name == "diff")
  95. unit = TU_DIFFUSE;
  96. else if (name == "albedo")
  97. unit = TU_DIFFUSE;
  98. else if (name == "norm")
  99. unit = TU_NORMAL;
  100. else if (name == "spec")
  101. unit = TU_SPECULAR;
  102. else if (name == "env")
  103. unit = TU_ENVIRONMENT;
  104. // Finally check for specifying the texture unit directly as a number
  105. else if (name.Length() < 3)
  106. unit = (TextureUnit)Clamp(ToInt(name), 0, MAX_TEXTURE_UNITS - 1);
  107. }
  108. if (unit == MAX_TEXTURE_UNITS)
  109. LOGERROR("Unknown texture unit name " + name);
  110. return unit;
  111. }
  112. static TechniqueEntry noEntry;
  113. bool CompareTechniqueEntries(const TechniqueEntry& lhs, const TechniqueEntry& rhs)
  114. {
  115. if (lhs.lodDistance_ != rhs.lodDistance_)
  116. return lhs.lodDistance_ > rhs.lodDistance_;
  117. else
  118. return lhs.qualityLevel_ > rhs.qualityLevel_;
  119. }
  120. TechniqueEntry::TechniqueEntry() :
  121. qualityLevel_(0),
  122. lodDistance_(0.0f)
  123. {
  124. }
  125. TechniqueEntry::TechniqueEntry(Technique* tech, unsigned qualityLevel, float lodDistance) :
  126. technique_(tech),
  127. qualityLevel_(qualityLevel),
  128. lodDistance_(lodDistance)
  129. {
  130. }
  131. TechniqueEntry::~TechniqueEntry()
  132. {
  133. }
  134. ShaderParameterAnimationInfo::ShaderParameterAnimationInfo(Material* target, const String& name, ValueAnimation* attributeAnimation, WrapMode wrapMode, float speed) :
  135. ValueAnimationInfo(target, attributeAnimation, wrapMode, speed),
  136. name_(name)
  137. {
  138. }
  139. ShaderParameterAnimationInfo::ShaderParameterAnimationInfo(const ShaderParameterAnimationInfo& other) :
  140. ValueAnimationInfo(other),
  141. name_(other.name_)
  142. {
  143. }
  144. ShaderParameterAnimationInfo::~ShaderParameterAnimationInfo()
  145. {
  146. }
  147. void ShaderParameterAnimationInfo::ApplyValue(const Variant& newValue)
  148. {
  149. static_cast<Material*>(target_.Get())->SetShaderParameter(name_, newValue);
  150. }
  151. Material::Material(Context* context) :
  152. Resource(context),
  153. auxViewFrameNumber_(0),
  154. shaderParameterHash_(0),
  155. occlusion_(true),
  156. specular_(false),
  157. subscribed_(false),
  158. batchedParameterUpdate_(false)
  159. {
  160. ResetToDefaults();
  161. }
  162. Material::~Material()
  163. {
  164. }
  165. void Material::RegisterObject(Context* context)
  166. {
  167. context->RegisterFactory<Material>();
  168. }
  169. bool Material::BeginLoad(Deserializer& source)
  170. {
  171. // In headless mode, do not actually load the material, just return success
  172. Graphics* graphics = GetSubsystem<Graphics>();
  173. if (!graphics)
  174. return true;
  175. loadXMLFile_ = new XMLFile(context_);
  176. if (loadXMLFile_->Load(source))
  177. {
  178. // If async loading, scan the XML content beforehand for technique & texture resources
  179. // and request them to also be loaded. Can not do anything else at this point
  180. if (GetAsyncLoadState() == ASYNC_LOADING)
  181. {
  182. ResourceCache* cache = GetSubsystem<ResourceCache>();
  183. XMLElement rootElem = loadXMLFile_->GetRoot();
  184. XMLElement techniqueElem = rootElem.GetChild("technique");
  185. while (techniqueElem)
  186. {
  187. cache->BackgroundLoadResource<Technique>(techniqueElem.GetAttribute("name"), true, this);
  188. techniqueElem = techniqueElem.GetNext("technique");
  189. }
  190. XMLElement textureElem = rootElem.GetChild("texture");
  191. while (textureElem)
  192. {
  193. String name = textureElem.GetAttribute("name");
  194. // Detect cube maps by file extension: they are defined by an XML file
  195. /// \todo Differentiate with 3D textures by actually reading the XML content
  196. if (GetExtension(name) == ".xml")
  197. {
  198. #ifdef DESKTOP_GRAPHICS
  199. TextureUnit unit = TU_DIFFUSE;
  200. if (textureElem.HasAttribute("unit"))
  201. unit = ParseTextureUnitName(textureElem.GetAttribute("unit"));
  202. if (unit == TU_VOLUMEMAP)
  203. cache->BackgroundLoadResource<Texture3D>(name, true, this);
  204. else
  205. #endif
  206. cache->BackgroundLoadResource<TextureCube>(name, true, this);
  207. }
  208. else
  209. cache->BackgroundLoadResource<Texture2D>(name, true, this);
  210. textureElem = textureElem.GetNext("texture");
  211. }
  212. }
  213. return true;
  214. }
  215. else
  216. {
  217. ResetToDefaults();
  218. loadXMLFile_.Reset();
  219. return false;
  220. }
  221. }
  222. bool Material::EndLoad()
  223. {
  224. // In headless mode, do not actually load the material, just return success
  225. Graphics* graphics = GetSubsystem<Graphics>();
  226. if (!graphics)
  227. return true;
  228. bool success = false;
  229. if (loadXMLFile_)
  230. {
  231. // If async loading, get the techniques / textures which should be ready now
  232. XMLElement rootElem = loadXMLFile_->GetRoot();
  233. success = Load(rootElem);
  234. }
  235. loadXMLFile_.Reset();
  236. return success;
  237. }
  238. bool Material::Save(Serializer& dest) const
  239. {
  240. SharedPtr<XMLFile> xml(new XMLFile(context_));
  241. XMLElement materialElem = xml->CreateRoot("material");
  242. Save(materialElem);
  243. return xml->Save(dest);
  244. }
  245. bool Material::Load(const XMLElement& source)
  246. {
  247. ResetToDefaults();
  248. if (source.IsNull())
  249. {
  250. LOGERROR("Can not load material from null XML element");
  251. return false;
  252. }
  253. ResourceCache* cache = GetSubsystem<ResourceCache>();
  254. XMLElement techniqueElem = source.GetChild("technique");
  255. techniques_.Clear();
  256. while (techniqueElem)
  257. {
  258. Technique* tech = cache->GetResource<Technique>(techniqueElem.GetAttribute("name"));
  259. if (tech)
  260. {
  261. TechniqueEntry newTechnique;
  262. newTechnique.technique_ = tech;
  263. if (techniqueElem.HasAttribute("quality"))
  264. newTechnique.qualityLevel_ = techniqueElem.GetInt("quality");
  265. if (techniqueElem.HasAttribute("loddistance"))
  266. newTechnique.lodDistance_ = techniqueElem.GetFloat("loddistance");
  267. techniques_.Push(newTechnique);
  268. }
  269. techniqueElem = techniqueElem.GetNext("technique");
  270. }
  271. SortTechniques();
  272. XMLElement textureElem = source.GetChild("texture");
  273. while (textureElem)
  274. {
  275. TextureUnit unit = TU_DIFFUSE;
  276. if (textureElem.HasAttribute("unit"))
  277. unit = ParseTextureUnitName(textureElem.GetAttribute("unit"));
  278. if (unit < MAX_TEXTURE_UNITS)
  279. {
  280. String name = textureElem.GetAttribute("name");
  281. // Detect cube maps by file extension: they are defined by an XML file
  282. /// \todo Differentiate with 3D textures by actually reading the XML content
  283. if (GetExtension(name) == ".xml")
  284. {
  285. #ifdef DESKTOP_GRAPHICS
  286. if (unit == TU_VOLUMEMAP)
  287. SetTexture(unit, cache->GetResource<Texture3D>(name));
  288. else
  289. #endif
  290. SetTexture(unit, cache->GetResource<TextureCube>(name));
  291. }
  292. else
  293. SetTexture(unit, cache->GetResource<Texture2D>(name));
  294. }
  295. textureElem = textureElem.GetNext("texture");
  296. }
  297. batchedParameterUpdate_ = true;
  298. XMLElement parameterElem = source.GetChild("parameter");
  299. while (parameterElem)
  300. {
  301. String name = parameterElem.GetAttribute("name");
  302. SetShaderParameter(name, ParseShaderParameterValue(parameterElem.GetAttribute("value")));
  303. parameterElem = parameterElem.GetNext("parameter");
  304. }
  305. batchedParameterUpdate_ = false;
  306. XMLElement parameterAnimationElem = source.GetChild("parameteranimation");
  307. while (parameterAnimationElem)
  308. {
  309. String name = parameterAnimationElem.GetAttribute("name");
  310. SharedPtr<ValueAnimation> animation(new ValueAnimation(context_));
  311. if (!animation->LoadXML(parameterAnimationElem))
  312. {
  313. LOGERROR("Could not load parameter animation");
  314. return false;
  315. }
  316. String wrapModeString = parameterAnimationElem.GetAttribute("wrapmode");
  317. WrapMode wrapMode = WM_LOOP;
  318. for (int i = 0; i <= WM_CLAMP; ++i)
  319. {
  320. if (wrapModeString == wrapModeNames[i])
  321. {
  322. wrapMode = (WrapMode)i;
  323. break;
  324. }
  325. }
  326. float speed = parameterAnimationElem.GetFloat("speed");
  327. SetShaderParameterAnimation(name, animation, wrapMode, speed);
  328. parameterAnimationElem = parameterAnimationElem.GetNext("parameteranimation");
  329. }
  330. XMLElement cullElem = source.GetChild("cull");
  331. if (cullElem)
  332. SetCullMode((CullMode)GetStringListIndex(cullElem.GetAttribute("value").CString(), cullModeNames, CULL_CCW));
  333. XMLElement shadowCullElem = source.GetChild("shadowcull");
  334. if (shadowCullElem)
  335. SetShadowCullMode((CullMode)GetStringListIndex(shadowCullElem.GetAttribute("value").CString(), cullModeNames, CULL_CCW));
  336. XMLElement fillElem = source.GetChild("fill");
  337. if (fillElem)
  338. SetFillMode((FillMode)GetStringListIndex(fillElem.GetAttribute("value").CString(), fillModeNames, FILL_SOLID));
  339. XMLElement depthBiasElem = source.GetChild("depthbias");
  340. if (depthBiasElem)
  341. SetDepthBias(BiasParameters(depthBiasElem.GetFloat("constant"), depthBiasElem.GetFloat("slopescaled")));
  342. RefreshShaderParameterHash();
  343. RefreshMemoryUse();
  344. CheckOcclusion();
  345. return true;
  346. }
  347. bool Material::Save(XMLElement& dest) const
  348. {
  349. if (dest.IsNull())
  350. {
  351. LOGERROR("Can not save material to null XML element");
  352. return false;
  353. }
  354. // Write techniques
  355. for (unsigned i = 0; i < techniques_.Size(); ++i)
  356. {
  357. const TechniqueEntry& entry = techniques_[i];
  358. if (!entry.technique_)
  359. continue;
  360. XMLElement techniqueElem = dest.CreateChild("technique");
  361. techniqueElem.SetString("name", entry.technique_->GetName());
  362. techniqueElem.SetInt("quality", entry.qualityLevel_);
  363. techniqueElem.SetFloat("loddistance", entry.lodDistance_);
  364. }
  365. // Write texture units
  366. for (unsigned j = 0; j < MAX_TEXTURE_UNITS; ++j)
  367. {
  368. Texture* texture = GetTexture((TextureUnit)j);
  369. if (texture)
  370. {
  371. XMLElement textureElem = dest.CreateChild("texture");
  372. textureElem.SetString("unit", textureUnitNames[j]);
  373. textureElem.SetString("name", texture->GetName());
  374. }
  375. }
  376. // Write shader parameters
  377. for (HashMap<StringHash, MaterialShaderParameter>::ConstIterator j = shaderParameters_.Begin(); j != shaderParameters_.End(); ++j)
  378. {
  379. XMLElement parameterElem = dest.CreateChild("parameter");
  380. parameterElem.SetString("name", j->second_.name_);
  381. parameterElem.SetVectorVariant("value", j->second_.value_);
  382. }
  383. // Write shader parameter animations
  384. for (HashMap<StringHash, SharedPtr<ShaderParameterAnimationInfo> >::ConstIterator j = shaderParameterAnimationInfos_.Begin(); j != shaderParameterAnimationInfos_.End(); ++j)
  385. {
  386. ShaderParameterAnimationInfo* info = j->second_;
  387. XMLElement parameterAnimationElem = dest.CreateChild("parameteranimation");
  388. parameterAnimationElem.SetString("name", info->GetName());
  389. if (!info->GetAnimation()->SaveXML(parameterAnimationElem))
  390. return false;
  391. parameterAnimationElem.SetAttribute("wrapmode", wrapModeNames[info->GetWrapMode()]);
  392. parameterAnimationElem.SetFloat("speed", info->GetSpeed());
  393. }
  394. // Write culling modes
  395. XMLElement cullElem = dest.CreateChild("cull");
  396. cullElem.SetString("value", cullModeNames[cullMode_]);
  397. XMLElement shadowCullElem = dest.CreateChild("shadowcull");
  398. shadowCullElem.SetString("value", cullModeNames[shadowCullMode_]);
  399. // Write fill mode
  400. XMLElement fillElem = dest.CreateChild("fill");
  401. fillElem.SetString("value", fillModeNames[fillMode_]);
  402. // Write depth bias
  403. XMLElement depthBiasElem = dest.CreateChild("depthbias");
  404. depthBiasElem.SetFloat("constant", depthBias_.constantBias_);
  405. depthBiasElem.SetFloat("slopescaled", depthBias_.slopeScaledBias_);
  406. return true;
  407. }
  408. void Material::SetNumTechniques(unsigned num)
  409. {
  410. if (!num)
  411. return;
  412. techniques_.Resize(num);
  413. RefreshMemoryUse();
  414. }
  415. void Material::SetTechnique(unsigned index, Technique* tech, unsigned qualityLevel, float lodDistance)
  416. {
  417. if (index >= techniques_.Size())
  418. return;
  419. techniques_[index] = TechniqueEntry(tech, qualityLevel, lodDistance);
  420. CheckOcclusion();
  421. }
  422. void Material::SetShaderParameter(const String& name, const Variant& value)
  423. {
  424. MaterialShaderParameter newParam;
  425. newParam.name_ = name;
  426. newParam.value_ = value;
  427. StringHash nameHash(name);
  428. shaderParameters_[nameHash] = newParam;
  429. if (nameHash == PSP_MATSPECCOLOR)
  430. {
  431. VariantType type = value.GetType();
  432. if (type == VAR_VECTOR3)
  433. {
  434. const Vector3& vec = value.GetVector3();
  435. specular_ = vec.x_ > 0.0f || vec.y_ > 0.0f || vec.z_ > 0.0f;
  436. }
  437. else if (type == VAR_VECTOR4)
  438. {
  439. const Vector4& vec = value.GetVector4();
  440. specular_ = vec.x_ > 0.0f || vec.y_ > 0.0f || vec.z_ > 0.0f;
  441. }
  442. }
  443. if (!batchedParameterUpdate_)
  444. {
  445. RefreshShaderParameterHash();
  446. RefreshMemoryUse();
  447. }
  448. }
  449. void Material::SetShaderParameterAnimation(const String& name, ValueAnimation* animation, WrapMode wrapMode, float speed)
  450. {
  451. ShaderParameterAnimationInfo* info = GetShaderParameterAnimationInfo(name);
  452. if (animation)
  453. {
  454. if (info && info->GetAnimation() == animation)
  455. {
  456. info->SetWrapMode(wrapMode);
  457. info->SetSpeed(speed);
  458. return;
  459. }
  460. if (shaderParameters_.Find(name) == shaderParameters_.End())
  461. {
  462. LOGERROR(GetName() + " has no shader parameter: " + name);
  463. return;
  464. }
  465. StringHash nameHash(name);
  466. shaderParameterAnimationInfos_[nameHash] = new ShaderParameterAnimationInfo(this, name, animation, wrapMode, speed);
  467. UpdateEventSubscription();
  468. }
  469. else
  470. {
  471. if (info)
  472. {
  473. StringHash nameHash(name);
  474. shaderParameterAnimationInfos_.Erase(nameHash);
  475. UpdateEventSubscription();
  476. }
  477. }
  478. }
  479. void Material::SetShaderParameterAnimationWrapMode(const String& name, WrapMode wrapMode)
  480. {
  481. ShaderParameterAnimationInfo* info = GetShaderParameterAnimationInfo(name);
  482. if (info)
  483. info->SetWrapMode(wrapMode);
  484. }
  485. void Material::SetShaderParameterAnimationSpeed(const String& name, float speed)
  486. {
  487. ShaderParameterAnimationInfo* info = GetShaderParameterAnimationInfo(name);
  488. if (info)
  489. info->SetSpeed(speed);
  490. }
  491. void Material::SetTexture(TextureUnit unit, Texture* texture)
  492. {
  493. if (unit < MAX_TEXTURE_UNITS)
  494. {
  495. if (texture)
  496. textures_[unit] = texture;
  497. else
  498. textures_.Erase(unit);
  499. }
  500. }
  501. void Material::SetUVTransform(const Vector2& offset, float rotation, const Vector2& repeat)
  502. {
  503. Matrix3x4 transform(Matrix3x4::IDENTITY);
  504. transform.m00_ = repeat.x_;
  505. transform.m11_ = repeat.y_;
  506. transform.m03_ = -0.5f * transform.m00_ + 0.5f;
  507. transform.m13_ = -0.5f * transform.m11_ + 0.5f;
  508. Matrix3x4 rotationMatrix(Matrix3x4::IDENTITY);
  509. rotationMatrix.m00_ = Cos(rotation);
  510. rotationMatrix.m01_ = Sin(rotation);
  511. rotationMatrix.m10_ = -rotationMatrix.m01_;
  512. rotationMatrix.m11_ = rotationMatrix.m00_;
  513. rotationMatrix.m03_ = 0.5f - 0.5f * (rotationMatrix.m00_ + rotationMatrix.m01_);
  514. rotationMatrix.m13_ = 0.5f - 0.5f * (rotationMatrix.m10_ + rotationMatrix.m11_);
  515. transform = rotationMatrix * transform;
  516. Matrix3x4 offsetMatrix = Matrix3x4::IDENTITY;
  517. offsetMatrix.m03_ = offset.x_;
  518. offsetMatrix.m13_ = offset.y_;
  519. transform = offsetMatrix * transform;
  520. SetShaderParameter("UOffset", Vector4(transform.m00_, transform.m01_, transform.m02_, transform.m03_));
  521. SetShaderParameter("VOffset", Vector4(transform.m10_, transform.m11_, transform.m12_, transform.m13_));
  522. }
  523. void Material::SetUVTransform(const Vector2& offset, float rotation, float repeat)
  524. {
  525. SetUVTransform(offset, rotation, Vector2(repeat, repeat));
  526. }
  527. void Material::SetCullMode(CullMode mode)
  528. {
  529. cullMode_ = mode;
  530. }
  531. void Material::SetShadowCullMode(CullMode mode)
  532. {
  533. shadowCullMode_ = mode;
  534. }
  535. void Material::SetFillMode(FillMode mode)
  536. {
  537. fillMode_ = mode;
  538. }
  539. void Material::SetDepthBias(const BiasParameters& parameters)
  540. {
  541. depthBias_ = parameters;
  542. depthBias_.Validate();
  543. }
  544. void Material::SetScene(Scene* scene)
  545. {
  546. UnsubscribeFromEvent(E_UPDATE);
  547. UnsubscribeFromEvent(E_ATTRIBUTEANIMATIONUPDATE);
  548. subscribed_ = false;
  549. scene_ = scene;
  550. UpdateEventSubscription();
  551. }
  552. void Material::RemoveShaderParameter(const String& name)
  553. {
  554. StringHash nameHash(name);
  555. shaderParameters_.Erase(nameHash);
  556. if (nameHash == PSP_MATSPECCOLOR)
  557. specular_ = false;
  558. RefreshShaderParameterHash();
  559. RefreshMemoryUse();
  560. }
  561. void Material::ReleaseShaders()
  562. {
  563. for (unsigned i = 0; i < techniques_.Size(); ++i)
  564. {
  565. Technique* tech = techniques_[i].technique_;
  566. if (tech)
  567. tech->ReleaseShaders();
  568. }
  569. }
  570. SharedPtr<Material> Material::Clone(const String& cloneName) const
  571. {
  572. SharedPtr<Material> ret(new Material(context_));
  573. ret->SetName(cloneName);
  574. ret->techniques_ = techniques_;
  575. ret->shaderParameters_ = shaderParameters_;
  576. ret->textures_ = textures_;
  577. ret->occlusion_ = occlusion_;
  578. ret->specular_ = specular_;
  579. ret->cullMode_ = cullMode_;
  580. ret->shadowCullMode_ = shadowCullMode_;
  581. ret->fillMode_ = fillMode_;
  582. ret->RefreshMemoryUse();
  583. return ret;
  584. }
  585. void Material::SortTechniques()
  586. {
  587. Sort(techniques_.Begin(), techniques_.End(), CompareTechniqueEntries);
  588. }
  589. void Material::MarkForAuxView(unsigned frameNumber)
  590. {
  591. auxViewFrameNumber_ = frameNumber;
  592. }
  593. const TechniqueEntry& Material::GetTechniqueEntry(unsigned index) const
  594. {
  595. return index < techniques_.Size() ? techniques_[index] : noEntry;
  596. }
  597. Technique* Material::GetTechnique(unsigned index) const
  598. {
  599. return index < techniques_.Size() ? techniques_[index].technique_ : (Technique*)0;
  600. }
  601. Pass* Material::GetPass(unsigned index, const String& passName) const
  602. {
  603. Technique* tech = index < techniques_.Size() ? techniques_[index].technique_ : (Technique*)0;
  604. return tech ? tech->GetPass(passName) : 0;
  605. }
  606. Texture* Material::GetTexture(TextureUnit unit) const
  607. {
  608. HashMap<TextureUnit, SharedPtr<Texture> >::ConstIterator i = textures_.Find(unit);
  609. return i != textures_.End() ? i->second_.Get() : (Texture*)0;
  610. }
  611. const Variant& Material::GetShaderParameter(const String& name) const
  612. {
  613. HashMap<StringHash, MaterialShaderParameter>::ConstIterator i = shaderParameters_.Find(name);
  614. return i != shaderParameters_.End() ? i->second_.value_ : Variant::EMPTY;
  615. }
  616. ValueAnimation* Material::GetShaderParameterAnimation(const String& name) const
  617. {
  618. ShaderParameterAnimationInfo* info = GetShaderParameterAnimationInfo(name);
  619. return info == 0 ? 0 : info->GetAnimation();
  620. }
  621. WrapMode Material::GetShaderParameterAnimationWrapMode(const String& name) const
  622. {
  623. ShaderParameterAnimationInfo* info = GetShaderParameterAnimationInfo(name);
  624. return info == 0 ? WM_LOOP : info->GetWrapMode();
  625. }
  626. float Material::GetShaderParameterAnimationSpeed(const String& name) const
  627. {
  628. ShaderParameterAnimationInfo* info = GetShaderParameterAnimationInfo(name);
  629. return info == 0 ? 0 : info->GetSpeed();
  630. }
  631. Scene* Material::GetScene() const
  632. {
  633. return scene_;
  634. }
  635. String Material::GetTextureUnitName(TextureUnit unit)
  636. {
  637. return textureUnitNames[unit];
  638. }
  639. Variant Material::ParseShaderParameterValue(const String& value)
  640. {
  641. String valueTrimmed = value.Trimmed();
  642. if (valueTrimmed.Length() && IsAlpha(valueTrimmed[0]))
  643. return Variant(ToBool(valueTrimmed));
  644. else
  645. return ToVectorVariant(valueTrimmed);
  646. }
  647. void Material::CheckOcclusion()
  648. {
  649. // Determine occlusion by checking the base pass of each technique
  650. occlusion_ = false;
  651. for (unsigned i = 0; i < techniques_.Size(); ++i)
  652. {
  653. Technique* tech = techniques_[i].technique_;
  654. if (tech)
  655. {
  656. Pass* pass = tech->GetPass("base");
  657. if (pass && pass->GetDepthWrite() && !pass->GetAlphaMask())
  658. occlusion_ = true;
  659. }
  660. }
  661. }
  662. void Material::ResetToDefaults()
  663. {
  664. // Needs to be a no-op when async loading, as this does a GetResource() which is not allowed from worker threads
  665. if (!Thread::IsMainThread())
  666. return;
  667. SetNumTechniques(1);
  668. SetTechnique(0, GetSubsystem<ResourceCache>()->GetResource<Technique>("Techniques/NoTexture.xml"));
  669. textures_.Clear();
  670. batchedParameterUpdate_ = true;
  671. shaderParameters_.Clear();
  672. SetShaderParameter("UOffset", Vector4(1.0f, 0.0f, 0.0f, 0.0f));
  673. SetShaderParameter("VOffset", Vector4(0.0f, 1.0f, 0.0f, 0.0f));
  674. SetShaderParameter("MatDiffColor", Vector4::ONE);
  675. SetShaderParameter("MatEmissiveColor", Vector3::ZERO);
  676. SetShaderParameter("MatEnvMapColor", Vector3::ONE);
  677. SetShaderParameter("MatSpecColor", Vector4(0.0f, 0.0f, 0.0f, 1.0f));
  678. batchedParameterUpdate_ = false;
  679. cullMode_ = CULL_CCW;
  680. shadowCullMode_ = CULL_CCW;
  681. fillMode_ = FILL_SOLID;
  682. depthBias_ = BiasParameters(0.0f, 0.0f);
  683. RefreshShaderParameterHash();
  684. RefreshMemoryUse();
  685. }
  686. void Material::RefreshShaderParameterHash()
  687. {
  688. VectorBuffer temp;
  689. for (HashMap<StringHash, MaterialShaderParameter>::ConstIterator i = shaderParameters_.Begin(); i != shaderParameters_.End(); ++i)
  690. {
  691. temp.WriteStringHash(i->first_);
  692. temp.WriteVariant(i->second_.value_);
  693. }
  694. shaderParameterHash_ = 0;
  695. const unsigned char* data = temp.GetData();
  696. unsigned dataSize = temp.GetSize();
  697. for (unsigned i = 0; i < dataSize; ++i)
  698. shaderParameterHash_ = SDBMHash(shaderParameterHash_, data[i]);
  699. }
  700. void Material::RefreshMemoryUse()
  701. {
  702. unsigned memoryUse = sizeof(Material);
  703. memoryUse += techniques_.Size() * sizeof(TechniqueEntry);
  704. memoryUse += MAX_TEXTURE_UNITS * sizeof(SharedPtr<Texture>);
  705. memoryUse += shaderParameters_.Size() * sizeof(MaterialShaderParameter);
  706. SetMemoryUse(memoryUse);
  707. }
  708. ShaderParameterAnimationInfo* Material::GetShaderParameterAnimationInfo(const String& name) const
  709. {
  710. StringHash nameHash(name);
  711. HashMap<StringHash, SharedPtr<ShaderParameterAnimationInfo> >::ConstIterator i = shaderParameterAnimationInfos_.Find(nameHash);
  712. if (i == shaderParameterAnimationInfos_.End())
  713. return 0;
  714. return i->second_;
  715. }
  716. void Material::UpdateEventSubscription()
  717. {
  718. if (shaderParameterAnimationInfos_.Size() && !subscribed_)
  719. {
  720. if (scene_)
  721. SubscribeToEvent(scene_, E_ATTRIBUTEANIMATIONUPDATE, HANDLER(Material, HandleAttributeAnimationUpdate));
  722. else
  723. SubscribeToEvent(E_UPDATE, HANDLER(Material, HandleAttributeAnimationUpdate));
  724. subscribed_ = true;
  725. }
  726. else if (subscribed_)
  727. {
  728. UnsubscribeFromEvent(E_UPDATE);
  729. UnsubscribeFromEvent(E_ATTRIBUTEANIMATIONUPDATE);
  730. subscribed_ = false;
  731. }
  732. }
  733. void Material::HandleAttributeAnimationUpdate(StringHash eventType, VariantMap& eventData)
  734. {
  735. // Timestep parameter is same no matter what event is being listened to
  736. float timeStep = eventData[Update::P_TIMESTEP].GetFloat();
  737. Vector<String> finishedNames;
  738. for (HashMap<StringHash, SharedPtr<ShaderParameterAnimationInfo> >::ConstIterator i = shaderParameterAnimationInfos_.Begin(); i != shaderParameterAnimationInfos_.End(); ++i)
  739. {
  740. if (i->second_->Update(timeStep))
  741. finishedNames.Push(i->second_->GetName());
  742. }
  743. // Remove finished animations
  744. for (unsigned i = 0; i < finishedNames.Size(); ++i)
  745. SetShaderParameterAnimation(finishedNames[i], 0);
  746. }
  747. }