Material.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457
  1. //
  2. // Copyright (c) 2008-2013 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 "Context.h"
  24. #include "FileSystem.h"
  25. #include "Graphics.h"
  26. #include "Log.h"
  27. #include "Material.h"
  28. #include "Matrix3x4.h"
  29. #include "Profiler.h"
  30. #include "ResourceCache.h"
  31. #include "StringUtils.h"
  32. #include "Technique.h"
  33. #include "Texture2D.h"
  34. #include "TextureCube.h"
  35. #include "XMLFile.h"
  36. #include "DebugNew.h"
  37. namespace Urho3D
  38. {
  39. const String textureUnitNames[] =
  40. {
  41. "diffuse",
  42. "normal",
  43. "specular",
  44. "emissive",
  45. "environment",
  46. "lightramp",
  47. "lightshape",
  48. "shadowmap",
  49. "faceselect",
  50. "indirection",
  51. "depth",
  52. "light",
  53. ""
  54. };
  55. static const String cullModeNames[] =
  56. {
  57. "none",
  58. "ccw",
  59. "cw",
  60. ""
  61. };
  62. TextureUnit ParseTextureUnitName(const String& name)
  63. {
  64. TextureUnit unit = (TextureUnit)GetStringListIndex(name, textureUnitNames, MAX_TEXTURE_UNITS);
  65. if (name == "diff")
  66. unit = TU_DIFFUSE;
  67. else if (name == "albedo")
  68. unit = TU_DIFFUSE;
  69. else if (name == "norm")
  70. unit = TU_NORMAL;
  71. else if (name == "spec")
  72. unit = TU_SPECULAR;
  73. else if (name == "env")
  74. unit = TU_ENVIRONMENT;
  75. return unit;
  76. }
  77. static TechniqueEntry noEntry;
  78. TechniqueEntry::TechniqueEntry() :
  79. qualityLevel_(0),
  80. lodDistance_(0.0f)
  81. {
  82. }
  83. TechniqueEntry::TechniqueEntry(Technique* tech, unsigned qualityLevel, float lodDistance) :
  84. technique_(tech),
  85. qualityLevel_(qualityLevel),
  86. lodDistance_(lodDistance)
  87. {
  88. }
  89. TechniqueEntry::~TechniqueEntry()
  90. {
  91. }
  92. OBJECTTYPESTATIC(Material);
  93. Material::Material(Context* context) :
  94. Resource(context),
  95. cullMode_(CULL_CCW),
  96. shadowCullMode_(CULL_CCW),
  97. depthBias_(BiasParameters(0.0f, 0.0f)),
  98. auxViewFrameNumber_(0),
  99. occlusion_(true),
  100. specular_(false)
  101. {
  102. SetNumTechniques(1);
  103. // Setup often used default parameters
  104. SetShaderParameter("UOffset", Vector4(1.0f, 0.0f, 0.0f, 0.0f));
  105. SetShaderParameter("VOffset", Vector4(0.0f, 1.0f, 0.0f, 0.0f));
  106. SetShaderParameter("MatDiffColor", Vector4::ONE);
  107. SetShaderParameter("MatEmissiveColor", Vector4::ZERO);
  108. SetShaderParameter("MatEnvMapColor", Vector4::ONE);
  109. SetShaderParameter("MatSpecColor", Vector4(0.0f, 0.0f, 0.0f, 1.0f));
  110. }
  111. Material::~Material()
  112. {
  113. }
  114. void Material::RegisterObject(Context* context)
  115. {
  116. context->RegisterFactory<Material>();
  117. }
  118. bool Material::Load(Deserializer& source)
  119. {
  120. PROFILE(LoadMaterial);
  121. // In headless mode, do not actually load the material, just return success
  122. Graphics* graphics = GetSubsystem<Graphics>();
  123. if (!graphics)
  124. return true;
  125. ResourceCache* cache = GetSubsystem<ResourceCache>();
  126. SharedPtr<XMLFile> xml(new XMLFile(context_));
  127. if (!xml->Load(source))
  128. return false;
  129. XMLElement rootElem = xml->GetRoot();
  130. XMLElement techniqueElem = rootElem.GetChild("technique");
  131. techniques_.Clear();
  132. while (techniqueElem)
  133. {
  134. Technique* tech = cache->GetResource<Technique>(techniqueElem.GetAttribute("name"));
  135. if (tech)
  136. {
  137. TechniqueEntry newTechnique;
  138. newTechnique.technique_ = tech;
  139. if (techniqueElem.HasAttribute("quality"))
  140. newTechnique.qualityLevel_ = techniqueElem.GetInt("quality");
  141. if (techniqueElem.HasAttribute("loddistance"))
  142. newTechnique.lodDistance_ = techniqueElem.GetFloat("loddistance");
  143. techniques_.Push(newTechnique);
  144. }
  145. techniqueElem = techniqueElem.GetNext("technique");
  146. }
  147. XMLElement textureElem = rootElem.GetChild("texture");
  148. while (textureElem)
  149. {
  150. TextureUnit unit = TU_DIFFUSE;
  151. if (textureElem.HasAttribute("unit"))
  152. {
  153. String unitName = textureElem.GetAttributeLower("unit");
  154. if (unitName.Length() > 1)
  155. {
  156. unit = ParseTextureUnitName(unitName);
  157. if (unit >= MAX_MATERIAL_TEXTURE_UNITS)
  158. LOGERROR("Unknown or illegal texture unit " + unitName);
  159. }
  160. else
  161. unit = (TextureUnit)Clamp(ToInt(unitName), 0, MAX_MATERIAL_TEXTURE_UNITS - 1);
  162. }
  163. if (unit != MAX_MATERIAL_TEXTURE_UNITS)
  164. {
  165. String name = textureElem.GetAttribute("name");
  166. // Detect cube maps by file extension: they are defined by an XML file
  167. if (GetExtension(name) == ".xml")
  168. SetTexture(unit, cache->GetResource<TextureCube>(name));
  169. else
  170. SetTexture(unit, cache->GetResource<Texture2D>(name));
  171. }
  172. textureElem = textureElem.GetNext("texture");
  173. }
  174. XMLElement parameterElem = rootElem.GetChild("parameter");
  175. while (parameterElem)
  176. {
  177. String name = parameterElem.GetAttribute("name");
  178. Vector4 value = parameterElem.GetVector("value");
  179. SetShaderParameter(name, value);
  180. parameterElem = parameterElem.GetNext("parameter");
  181. }
  182. XMLElement cullElem = rootElem.GetChild("cull");
  183. if (cullElem)
  184. SetCullMode((CullMode)GetStringListIndex(cullElem.GetAttribute("value"), cullModeNames, CULL_CCW));
  185. XMLElement shadowCullElem = rootElem.GetChild("shadowcull");
  186. if (shadowCullElem)
  187. SetShadowCullMode((CullMode)GetStringListIndex(shadowCullElem.GetAttribute("value"), cullModeNames, CULL_CCW));
  188. XMLElement depthBiasElem = rootElem.GetChild("depthbias");
  189. if (depthBiasElem)
  190. SetDepthBias(BiasParameters(depthBiasElem.GetFloat("constant"), depthBiasElem.GetFloat("slopescaled")));
  191. // Calculate memory use
  192. unsigned memoryUse = sizeof(Material);
  193. memoryUse += techniques_.Size() * sizeof(TechniqueEntry);
  194. memoryUse += MAX_MATERIAL_TEXTURE_UNITS * sizeof(SharedPtr<Texture>);
  195. memoryUse += shaderParameters_.Size() * sizeof(MaterialShaderParameter);
  196. SetMemoryUse(memoryUse);
  197. CheckOcclusion();
  198. return true;
  199. }
  200. bool Material::Save(Serializer& dest)
  201. {
  202. SharedPtr<XMLFile> xml(new XMLFile(context_));
  203. XMLElement materialElem = xml->CreateRoot("material");
  204. // Write techniques
  205. for (unsigned i = 0; i < techniques_.Size(); ++i)
  206. {
  207. TechniqueEntry& entry = techniques_[i];
  208. if (!entry.technique_)
  209. continue;
  210. XMLElement techniqueElem = materialElem.CreateChild("technique");
  211. techniqueElem.SetString("name", entry.technique_->GetName());
  212. techniqueElem.SetInt("quality", entry.qualityLevel_);
  213. techniqueElem.SetFloat("loddistance", entry.lodDistance_);
  214. }
  215. // Write texture units
  216. for (unsigned j = 0; j < MAX_MATERIAL_TEXTURE_UNITS; ++j)
  217. {
  218. Texture* texture = GetTexture((TextureUnit)j);
  219. if (texture)
  220. {
  221. XMLElement textureElem = materialElem.CreateChild("texture");
  222. textureElem.SetString("unit", textureUnitNames[j]);
  223. textureElem.SetString("name", texture->GetName());
  224. }
  225. }
  226. // Write shader parameters
  227. for (HashMap<StringHash, MaterialShaderParameter>::ConstIterator j = shaderParameters_.Begin(); j != shaderParameters_.End(); ++j)
  228. {
  229. XMLElement parameterElem = materialElem.CreateChild("parameter");
  230. parameterElem.SetString("name", j->second_.name_);
  231. parameterElem.SetVector4("value", j->second_.value_);
  232. }
  233. // Write culling modes
  234. XMLElement cullElem = materialElem.CreateChild("cull");
  235. cullElem.SetString("value", cullModeNames[cullMode_]);
  236. XMLElement shadowCullElem = materialElem.CreateChild("shadowcull");
  237. shadowCullElem.SetString("value", cullModeNames[shadowCullMode_]);
  238. // Write depth bias
  239. XMLElement depthBiasElem = materialElem.CreateChild("depthbias");
  240. depthBiasElem.SetFloat("constant", depthBias_.constantBias_);
  241. depthBiasElem.SetFloat("slopescaled", depthBias_.slopeScaledBias_);
  242. return xml->Save(dest);
  243. }
  244. void Material::SetNumTechniques(unsigned num)
  245. {
  246. if (!num)
  247. return;
  248. techniques_.Resize(num);
  249. }
  250. void Material::SetTechnique(unsigned index, Technique* tech, unsigned qualityLevel, float lodDistance)
  251. {
  252. if (index >= techniques_.Size())
  253. return;
  254. techniques_[index] = TechniqueEntry(tech, qualityLevel, lodDistance);
  255. CheckOcclusion();
  256. }
  257. void Material::SetShaderParameter(const String& name, const Vector4& value)
  258. {
  259. MaterialShaderParameter newParam;
  260. newParam.name_ = name;
  261. newParam.value_ = value;
  262. StringHash stringHash(name);
  263. shaderParameters_[stringHash] = newParam;
  264. if (stringHash == PSP_MATSPECCOLOR)
  265. specular_ = value.x_ > 0.0f || value.y_ > 0.0f || value.z_ > 0.0f;
  266. }
  267. void Material::SetTexture(TextureUnit unit, Texture* texture)
  268. {
  269. if (unit < MAX_MATERIAL_TEXTURE_UNITS)
  270. textures_[unit] = texture;
  271. }
  272. void Material::SetUVTransform(const Vector2& offset, float rotation, const Vector2& repeat)
  273. {
  274. Matrix3x4 transform(Matrix3x4::IDENTITY);
  275. transform.m00_ = repeat.x_;
  276. transform.m11_ = repeat.y_;
  277. transform.m03_ = -0.5f * transform.m00_ + 0.5f;
  278. transform.m13_ = -0.5f * transform.m11_ + 0.5f;
  279. Matrix3x4 rotationMatrix(Matrix3x4::IDENTITY);
  280. float angleRad = rotation * M_DEGTORAD;
  281. rotationMatrix.m00_ = cosf(angleRad);
  282. rotationMatrix.m01_ = sinf(angleRad);
  283. rotationMatrix.m10_ = -rotationMatrix.m01_;
  284. rotationMatrix.m11_ = rotationMatrix.m00_;
  285. rotationMatrix.m03_ = 0.5f - 0.5f * (rotationMatrix.m00_ + rotationMatrix.m01_);
  286. rotationMatrix.m13_ = 0.5f - 0.5f * (rotationMatrix.m10_ + rotationMatrix.m11_);
  287. transform = rotationMatrix * transform;
  288. Matrix3x4 offsetMatrix = Matrix3x4::IDENTITY;
  289. offsetMatrix.m03_ = offset.x_;
  290. offsetMatrix.m13_ = offset.y_;
  291. transform = offsetMatrix * transform;
  292. SetShaderParameter("UOffset", Vector4(transform.m00_, transform.m01_, transform.m02_, transform.m03_));
  293. SetShaderParameter("VOffset", Vector4(transform.m10_, transform.m11_, transform.m12_, transform.m13_));
  294. }
  295. void Material::SetUVTransform(const Vector2& offset, float rotation, float repeat)
  296. {
  297. SetUVTransform(offset, rotation, Vector2(repeat, repeat));
  298. }
  299. void Material::SetCullMode(CullMode mode)
  300. {
  301. cullMode_ = mode;
  302. }
  303. void Material::SetShadowCullMode(CullMode mode)
  304. {
  305. shadowCullMode_ = mode;
  306. }
  307. void Material::SetDepthBias(const BiasParameters& parameters)
  308. {
  309. depthBias_ = parameters;
  310. depthBias_.Validate();
  311. }
  312. void Material::RemoveShaderParameter(const String& name)
  313. {
  314. StringHash stringHash(name);
  315. shaderParameters_.Erase(stringHash);
  316. if (stringHash == PSP_MATSPECCOLOR)
  317. specular_ = false;
  318. }
  319. void Material::ReleaseShaders()
  320. {
  321. for (unsigned i = 0; i < techniques_.Size(); ++i)
  322. {
  323. Technique* tech = techniques_[i].technique_;
  324. if (tech)
  325. tech->ReleaseShaders();
  326. }
  327. }
  328. SharedPtr<Material> Material::Clone(const String& cloneName) const
  329. {
  330. SharedPtr<Material> ret(new Material(context_));
  331. ret->SetName(cloneName);
  332. ret->techniques_ = techniques_;
  333. ret->shaderParameters_ = shaderParameters_;
  334. for (unsigned i = 0; i < MAX_MATERIAL_TEXTURE_UNITS; ++i)
  335. ret->textures_[i] = textures_[i];
  336. ret->occlusion_ = occlusion_;
  337. ret->cullMode_ = cullMode_;
  338. ret->shadowCullMode_ = shadowCullMode_;
  339. return ret;
  340. }
  341. void Material::MarkForAuxView(unsigned frameNumber)
  342. {
  343. auxViewFrameNumber_ = frameNumber;
  344. }
  345. const TechniqueEntry& Material::GetTechniqueEntry(unsigned index) const
  346. {
  347. return index < techniques_.Size() ? techniques_[index] : noEntry;
  348. }
  349. Technique* Material::GetTechnique(unsigned index) const
  350. {
  351. return index < techniques_.Size() ? techniques_[index].technique_ : (Technique*)0;
  352. }
  353. Pass* Material::GetPass(unsigned index, StringHash passType) const
  354. {
  355. Technique* tech = index < techniques_.Size() ? techniques_[index].technique_ : (Technique*)0;
  356. return tech ? tech->GetPass(passType) : 0;
  357. }
  358. Texture* Material::GetTexture(TextureUnit unit) const
  359. {
  360. return unit < MAX_MATERIAL_TEXTURE_UNITS ? textures_[unit] : (Texture*)0;
  361. }
  362. const Vector4& Material::GetShaderParameter(const String& name) const
  363. {
  364. HashMap<StringHash, MaterialShaderParameter>::ConstIterator i = shaderParameters_.Find(StringHash(name));
  365. return i != shaderParameters_.End() ? i->second_.value_ : Vector4::ZERO;
  366. }
  367. const String& Material::GetTextureUnitName(TextureUnit unit)
  368. {
  369. return textureUnitNames[unit];
  370. }
  371. void Material::CheckOcclusion()
  372. {
  373. // Determine occlusion by checking the base pass of each technique
  374. occlusion_ = false;
  375. for (unsigned i = 0; i < techniques_.Size(); ++i)
  376. {
  377. Technique* tech = techniques_[i].technique_;
  378. if (tech)
  379. {
  380. Pass* pass = tech->GetPass(PASS_BASE);
  381. if (pass && pass->GetDepthWrite() && !pass->GetAlphaMask())
  382. occlusion_ = true;
  383. }
  384. }
  385. }
  386. }