Material.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429
  1. //
  2. // Urho3D Engine
  3. // Copyright (c) 2008-2011 Lasse Öörni
  4. //
  5. // Permission is hereby granted, free of charge, to any person obtaining a copy
  6. // of this software and associated documentation files (the "Software"), to deal
  7. // in the Software without restriction, including without limitation the rights
  8. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. // copies of the Software, and to permit persons to whom the Software is
  10. // furnished to do so, subject to the following conditions:
  11. //
  12. // The above copyright notice and this permission notice shall be included in
  13. // all copies or substantial portions of the Software.
  14. //
  15. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21. // THE SOFTWARE.
  22. //
  23. #include "Precompiled.h"
  24. #include "Context.h"
  25. #include "FileSystem.h"
  26. #include "Graphics.h"
  27. #include "Log.h"
  28. #include "Material.h"
  29. #include "Matrix4x3.h"
  30. #include "Profiler.h"
  31. #include "ResourceCache.h"
  32. #include "StringUtils.h"
  33. #include "Technique.h"
  34. #include "Texture2D.h"
  35. #include "TextureCube.h"
  36. #include "XMLFile.h"
  37. #include "DebugNew.h"
  38. static const String textureUnitNames[] =
  39. {
  40. "diffuse",
  41. "normal",
  42. "specular",
  43. "detail",
  44. "environment",
  45. "emissive",
  46. "lightramp", // Not defined by materials
  47. "lightspot", // Not defined by materials
  48. ""
  49. };
  50. static const String cullModeNames[] =
  51. {
  52. "none",
  53. "ccw",
  54. "cw",
  55. ""
  56. };
  57. TechniqueEntry::TechniqueEntry() :
  58. qualityLevel_(0),
  59. lodDistance_(0.0f)
  60. {
  61. }
  62. TechniqueEntry::TechniqueEntry(Technique* technique, unsigned qualityLevel, float lodDistance) :
  63. technique_(technique),
  64. qualityLevel_(qualityLevel),
  65. lodDistance_(lodDistance)
  66. {
  67. }
  68. TechniqueEntry::~TechniqueEntry()
  69. {
  70. }
  71. OBJECTTYPESTATIC(Material);
  72. Material::Material(Context* context) :
  73. Resource(context),
  74. cullMode_(CULL_CCW),
  75. shadowCullMode_(CULL_CCW),
  76. auxViewFrameNumber_(0),
  77. occlusion_(true)
  78. {
  79. SetNumTechniques(1);
  80. textures_.Resize(MAX_MATERIAL_TEXTURE_UNITS);
  81. // Setup often used default parameters
  82. vsParameters_[VSP_UOFFSET] = Vector4(1.0f, 0.0f, 0.0f, 0.0f);
  83. vsParameters_[VSP_VOFFSET] = Vector4(0.0f, 1.0f, 0.0f, 0.0f);
  84. psParameters_[PSP_MATDIFFCOLOR] = Vector4::UNITY;
  85. psParameters_[PSP_MATEMISSIVECOLOR] = Vector4::ZERO;
  86. psParameters_[PSP_MATSPECPROPERTIES] = Vector4::ZERO;
  87. }
  88. Material::~Material()
  89. {
  90. }
  91. void Material::RegisterObject(Context* context)
  92. {
  93. context->RegisterFactory<Material>();
  94. }
  95. bool Material::Load(Deserializer& source)
  96. {
  97. PROFILE(LoadMaterial);
  98. ResourceCache* cache = GetSubsystem<ResourceCache>();
  99. Graphics* graphics = GetSubsystem<Graphics>();
  100. if ((!cache) || (!graphics))
  101. return false;
  102. SharedPtr<XMLFile> xml(new XMLFile(context_));
  103. if (!xml->Load(source))
  104. return false;
  105. XMLElement rootElem = xml->GetRootElement();
  106. XMLElement techniqueElem = rootElem.GetChildElement("technique");
  107. techniques_.Clear();
  108. while (techniqueElem)
  109. {
  110. Technique* technique = cache->GetResource<Technique>(techniqueElem.GetString("name"));
  111. if (technique)
  112. {
  113. TechniqueEntry newTechnique;
  114. newTechnique.technique_ = technique;
  115. if (techniqueElem.HasAttribute("quality"))
  116. newTechnique.qualityLevel_ = techniqueElem.GetInt("quality");
  117. if (techniqueElem.HasAttribute("loddistance"))
  118. newTechnique.lodDistance_ = techniqueElem.GetFloat("loddistance");
  119. techniques_.Push(newTechnique);
  120. }
  121. techniqueElem = techniqueElem.GetNextElement("technique");
  122. }
  123. XMLElement textureElem = rootElem.GetChildElement("texture");
  124. while (textureElem)
  125. {
  126. TextureUnit unit = TU_DIFFUSE;
  127. if (textureElem.HasAttribute("unit"))
  128. {
  129. String unitName = textureElem.GetStringLower("unit");
  130. unit = (TextureUnit)GetStringListIndex(unitName, textureUnitNames, MAX_MATERIAL_TEXTURE_UNITS);
  131. if (unitName == "diff")
  132. unit = TU_DIFFUSE;
  133. if (unitName == "norm")
  134. unit = TU_NORMAL;
  135. if (unitName == "spec")
  136. unit = TU_SPECULAR;
  137. if (unitName == "env")
  138. unit = TU_ENVIRONMENT;
  139. if (unit == MAX_MATERIAL_TEXTURE_UNITS)
  140. LOGERROR("Unknown texture unit " + unitName);
  141. }
  142. if (unit != MAX_MATERIAL_TEXTURE_UNITS)
  143. {
  144. String name = textureElem.GetString("name");
  145. // Detect cube maps by file extension: they are defined by an XML file
  146. if (GetExtension(name) == ".xml")
  147. SetTexture(unit, cache->GetResource<TextureCube>(name));
  148. else
  149. SetTexture(unit, cache->GetResource<Texture2D>(name));
  150. }
  151. textureElem = textureElem.GetNextElement("texture");
  152. }
  153. XMLElement parameterElem = rootElem.GetChildElement("parameter");
  154. while (parameterElem)
  155. {
  156. String name = parameterElem.GetString("name");
  157. Vector4 value = parameterElem.GetVector("value");
  158. VSParameter vsParam = graphics->GetVSParameter(name);
  159. if (vsParam != MAX_VS_PARAMETERS)
  160. SetVertexShaderParameter(vsParam, value);
  161. else
  162. {
  163. PSParameter psParam = graphics->GetPSParameter(name);
  164. if (psParam != MAX_PS_PARAMETERS)
  165. SetPixelShaderParameter(psParam, value);
  166. else
  167. LOGERROR("Unknown shader parameter " + name);
  168. }
  169. parameterElem = parameterElem.GetNextElement("parameter");
  170. }
  171. XMLElement cullElem = rootElem.GetChildElement("cull");
  172. if (cullElem)
  173. SetCullMode((CullMode)GetStringListIndex(cullElem.GetString("value"), cullModeNames, CULL_CCW));
  174. XMLElement shadowCullElem = rootElem.GetChildElement("shadowcull");
  175. if (shadowCullElem)
  176. SetShadowCullMode((CullMode)GetStringListIndex(shadowCullElem.GetString("value"), cullModeNames, CULL_CCW));
  177. // Calculate memory use
  178. unsigned memoryUse = 0;
  179. memoryUse += sizeof(Material);
  180. memoryUse += techniques_.Size() * sizeof(TechniqueEntry);
  181. memoryUse += textures_.Size() * sizeof(SharedPtr<Texture>);
  182. memoryUse += vsParameters_.Size() * (sizeof(VSParameter) + sizeof(Vector4));
  183. memoryUse += psParameters_.Size() * (sizeof(PSParameter) + sizeof(Vector4));
  184. SetMemoryUse(memoryUse);
  185. Update();
  186. return true;
  187. }
  188. bool Material::Save(Serializer& dest)
  189. {
  190. Graphics* graphics = GetSubsystem<Graphics>();
  191. if (!graphics)
  192. return false;
  193. SharedPtr<XMLFile> xml(new XMLFile(context_));
  194. XMLElement materialElem = xml->CreateRootElement("material");
  195. // Write techniques
  196. for (unsigned i = 0; i < techniques_.Size(); ++i)
  197. {
  198. TechniqueEntry& entry = techniques_[i];
  199. if (!entry.technique_)
  200. continue;
  201. XMLElement techniqueElem = materialElem.CreateChildElement("technique");
  202. techniqueElem.SetString("name", entry.technique_->GetName());
  203. techniqueElem.SetInt("quality", entry.qualityLevel_);
  204. techniqueElem.SetFloat("loddistance", entry.lodDistance_);
  205. }
  206. // Write texture units
  207. for (unsigned j = 0; j < MAX_MATERIAL_TEXTURE_UNITS; ++j)
  208. {
  209. Texture* texture = GetTexture((TextureUnit)j);
  210. if (texture)
  211. {
  212. XMLElement textureElem = materialElem.CreateChildElement("texture");
  213. textureElem.SetString("unit", textureUnitNames[j]);
  214. textureElem.SetString("name", texture->GetName());
  215. }
  216. }
  217. // Write shader parameters
  218. for (Map<VSParameter, Vector4>::ConstIterator j = vsParameters_.Begin(); j != vsParameters_.End(); ++j)
  219. {
  220. XMLElement parameterElem = materialElem.CreateChildElement("parameter");
  221. parameterElem.SetString("name", graphics->GetVSParameterName(j->first_));
  222. parameterElem.SetVector4("value", j->second_);
  223. }
  224. for (Map<PSParameter, Vector4>::ConstIterator j = psParameters_.Begin(); j != psParameters_.End(); ++j)
  225. {
  226. XMLElement parameterElem = materialElem.CreateChildElement("parameter");
  227. parameterElem.SetString("name", graphics->GetPSParameterName(j->first_));
  228. parameterElem.SetVector4("value", j->second_);
  229. }
  230. return xml->Save(dest);
  231. }
  232. void Material::SetNumTechniques(unsigned num)
  233. {
  234. if (!num)
  235. return;
  236. techniques_.Resize(num);
  237. }
  238. void Material::SetTechnique(unsigned index, Technique* technique, unsigned qualityLevel, float lodDistance)
  239. {
  240. if (index >= techniques_.Size())
  241. return;
  242. techniques_[index] = TechniqueEntry(technique, qualityLevel, lodDistance);
  243. Update();
  244. }
  245. void Material::SetVertexShaderParameter(VSParameter parameter, const Vector4& value)
  246. {
  247. vsParameters_[parameter] = value;
  248. }
  249. void Material::SetPixelShaderParameter(PSParameter parameter, const Vector4& value)
  250. {
  251. psParameters_[parameter] = value;
  252. }
  253. void Material::SetTexture(TextureUnit unit, Texture* texture)
  254. {
  255. if (unit >= MAX_MATERIAL_TEXTURE_UNITS)
  256. return;
  257. textures_[unit] = texture;
  258. }
  259. void Material::SetUVTransform(const Vector2& offset, float rotation, const Vector2& repeat)
  260. {
  261. Matrix4x3 transform(Matrix4x3::IDENTITY);
  262. transform.m00_ = repeat.x_;
  263. transform.m11_ = repeat.y_;
  264. transform.m03_ = -0.5f * transform.m00_ + 0.5f;
  265. transform.m13_ = -0.5f * transform.m11_ + 0.5f;
  266. Matrix4x3 rotationMatrix(Matrix4x3::IDENTITY);
  267. float angleRad = rotation * M_DEGTORAD;
  268. rotationMatrix.m00_ = cosf(angleRad);
  269. rotationMatrix.m01_ = sinf(angleRad);
  270. rotationMatrix.m10_ = -rotationMatrix.m01_;
  271. rotationMatrix.m11_ = rotationMatrix.m00_;
  272. rotationMatrix.m03_ = 0.5f - 0.5f * (rotationMatrix.m00_ + rotationMatrix.m01_);
  273. rotationMatrix.m13_ = 0.5f - 0.5f * (rotationMatrix.m10_ + rotationMatrix.m11_);
  274. transform = rotationMatrix * transform;
  275. Matrix4x3 offsetMatrix = Matrix4x3::IDENTITY;
  276. offsetMatrix.m03_ = offset.x_;
  277. offsetMatrix.m13_ = offset.y_;
  278. transform = offsetMatrix * transform;
  279. Vector4& uOffset = vsParameters_[VSP_UOFFSET];
  280. Vector4& vOffset = vsParameters_[VSP_VOFFSET];
  281. uOffset.x_ = transform.m00_;
  282. uOffset.y_ = transform.m01_;
  283. uOffset.w_ = transform.m03_;
  284. vOffset.x_ = transform.m10_;
  285. vOffset.y_ = transform.m11_;
  286. vOffset.w_ = transform.m13_;
  287. }
  288. void Material::SetUVTransform(const Vector2& offset, float rotation, float repeat)
  289. {
  290. SetUVTransform(offset, rotation, Vector2(repeat, repeat));
  291. }
  292. void Material::SetCullMode(CullMode mode)
  293. {
  294. cullMode_ = mode;
  295. }
  296. void Material::SetShadowCullMode(CullMode mode)
  297. {
  298. shadowCullMode_ = mode;
  299. }
  300. void Material::ReleaseShaders()
  301. {
  302. for (unsigned i = 0; i < techniques_.Size(); ++i)
  303. {
  304. Technique* technique = techniques_[i].technique_;
  305. if (technique)
  306. technique->ReleaseShaders();
  307. }
  308. }
  309. SharedPtr<Material> Material::Clone(const String& cloneName) const
  310. {
  311. SharedPtr<Material> ret(new Material(context_));
  312. ret->SetName(cloneName);
  313. ret->techniques_ = techniques_;
  314. ret->vsParameters_ = vsParameters_;
  315. ret->psParameters_ = psParameters_;
  316. ret->textures_ = textures_;
  317. ret->occlusion_ = occlusion_;
  318. ret->cullMode_ = cullMode_;
  319. ret->shadowCullMode_ = shadowCullMode_;
  320. return ret;
  321. }
  322. void Material::MarkForAuxView(unsigned frameNumber)
  323. {
  324. auxViewFrameNumber_ = frameNumber;
  325. }
  326. const TechniqueEntry& Material::GetTechniqueEntry(unsigned index) const
  327. {
  328. TechniqueEntry noEntry;
  329. return index < techniques_.Size() ? techniques_[index] : noEntry;
  330. }
  331. Technique* Material::GetTechnique(unsigned index) const
  332. {
  333. return index < techniques_.Size() ? techniques_[index].technique_ : (Technique*)0;
  334. }
  335. Pass* Material::GetPass(unsigned index, PassType pass) const
  336. {
  337. Technique* technique = index < techniques_.Size() ? techniques_[index].technique_ : (Technique*)0;
  338. return technique ? technique->GetPass(pass) : 0;
  339. }
  340. Texture* Material::GetTexture(TextureUnit unit) const
  341. {
  342. return (unsigned)unit < textures_.Size() ? textures_[unit] : (Texture*)0;
  343. }
  344. const String& Material::GetTextureUnitName(TextureUnit unit)
  345. {
  346. return textureUnitNames[unit];
  347. }
  348. void Material::Update()
  349. {
  350. // Determine occlusion by checking the first pass of each technique
  351. occlusion_ = false;
  352. for (unsigned i = 0; i < techniques_.Size(); ++i)
  353. {
  354. Technique* technique = techniques_[i].technique_;
  355. if (!technique)
  356. continue;
  357. const Map<PassType, Pass>& passes = technique->GetPasses();
  358. if (!passes.Empty())
  359. {
  360. // If pass writes depth, enable occlusion
  361. const Pass& pass = passes.Begin()->second_;
  362. if (pass.GetDepthWrite())
  363. {
  364. occlusion_ = true;
  365. break;
  366. }
  367. }
  368. }
  369. }