OGLTexture2D.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479
  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 "Graphics.h"
  25. #include "GraphicsEvents.h"
  26. #include "GraphicsImpl.h"
  27. #include "Log.h"
  28. #include "Profiler.h"
  29. #include "Renderer.h"
  30. #include "ResourceCache.h"
  31. #include "Texture2D.h"
  32. #include "DebugNew.h"
  33. namespace Urho3D
  34. {
  35. Texture2D::Texture2D(Context* context) :
  36. Texture(context)
  37. {
  38. target_ = GL_TEXTURE_2D;
  39. }
  40. Texture2D::~Texture2D()
  41. {
  42. Release();
  43. }
  44. void Texture2D::RegisterObject(Context* context)
  45. {
  46. context->RegisterFactory<Texture2D>();
  47. }
  48. bool Texture2D::Load(Deserializer& source)
  49. {
  50. PROFILE(LoadTexture2D);
  51. // In headless mode, do not actually load the texture, just return success
  52. if (!graphics_)
  53. return true;
  54. // If device is lost, retry later
  55. if (graphics_->IsDeviceLost())
  56. {
  57. LOGWARNING("Texture load while device is lost");
  58. dataPending_ = true;
  59. return true;
  60. }
  61. // If over the texture budget, see if materials can be freed to allow textures to be freed
  62. CheckTextureBudget(GetTypeStatic());
  63. SharedPtr<Image> image(new Image(context_));
  64. if (!image->Load(source))
  65. return false;
  66. // Before actually loading the texture, get optional parameters from an XML description file
  67. LoadParameters();
  68. return Load(image);
  69. }
  70. void Texture2D::OnDeviceLost()
  71. {
  72. GPUObject::OnDeviceLost();
  73. if (renderSurface_)
  74. renderSurface_->OnDeviceLost();
  75. }
  76. void Texture2D::OnDeviceReset()
  77. {
  78. // If has a file name, reload through the resource cache. Otherwise just recreate.
  79. if (!object_)
  80. {
  81. if (!GetName().Trimmed().Empty())
  82. dataLost_ = !GetSubsystem<ResourceCache>()->ReloadResource(this);
  83. else
  84. {
  85. Create();
  86. dataLost_ = true;
  87. }
  88. }
  89. else if (dataPending_)
  90. {
  91. if (!GetName().Trimmed().Empty())
  92. dataLost_ = !GetSubsystem<ResourceCache>()->ReloadResource(this);
  93. else
  94. dataLost_ = true;
  95. }
  96. dataPending_ = false;
  97. }
  98. void Texture2D::Release()
  99. {
  100. if (object_)
  101. {
  102. if (!graphics_ || graphics_->IsDeviceLost())
  103. return;
  104. for (unsigned i = 0; i < MAX_TEXTURE_UNITS; ++i)
  105. {
  106. if (graphics_->GetTexture(i) == this)
  107. graphics_->SetTexture(i, 0);
  108. }
  109. if (renderSurface_)
  110. renderSurface_->Release();
  111. glDeleteTextures(1, &object_);
  112. object_ = 0;
  113. }
  114. else
  115. {
  116. if (renderSurface_)
  117. renderSurface_->Release();
  118. }
  119. }
  120. bool Texture2D::SetSize(int width, int height, unsigned format, TextureUsage usage)
  121. {
  122. // Delete the old rendersurface if any
  123. renderSurface_.Reset();
  124. usage_ = usage;
  125. if (usage >= TEXTURE_RENDERTARGET)
  126. {
  127. renderSurface_ = new RenderSurface(this);
  128. // Clamp mode addressing by default, nearest filtering, and mipmaps disabled
  129. addressMode_[COORD_U] = ADDRESS_CLAMP;
  130. addressMode_[COORD_V] = ADDRESS_CLAMP;
  131. filterMode_ = FILTER_NEAREST;
  132. requestedLevels_ = 1;
  133. }
  134. if (usage == TEXTURE_RENDERTARGET)
  135. SubscribeToEvent(E_RENDERSURFACEUPDATE, HANDLER(Texture2D, HandleRenderSurfaceUpdate));
  136. else
  137. UnsubscribeFromEvent(E_RENDERSURFACEUPDATE);
  138. width_ = width;
  139. height_ = height;
  140. format_ = format;
  141. return Create();
  142. }
  143. bool Texture2D::SetData(unsigned level, int x, int y, int width, int height, const void* data)
  144. {
  145. if (!object_ || !graphics_)
  146. {
  147. LOGERROR("No texture created, can not set data");
  148. return false;
  149. }
  150. if (!data)
  151. {
  152. LOGERROR("Null source for setting data");
  153. return false;
  154. }
  155. if (level >= levels_)
  156. {
  157. LOGERROR("Illegal mip level for setting data");
  158. return false;
  159. }
  160. if (graphics_->IsDeviceLost())
  161. {
  162. LOGWARNING("Texture data assignment while device is lost");
  163. dataPending_ = true;
  164. return true;
  165. }
  166. if (IsCompressed())
  167. {
  168. x &= ~3;
  169. y &= ~3;
  170. }
  171. int levelWidth = GetLevelWidth(level);
  172. int levelHeight = GetLevelHeight(level);
  173. if (x < 0 || x + width > levelWidth || y < 0 || y + height > levelHeight || width <= 0 || height <= 0)
  174. {
  175. LOGERROR("Illegal dimensions for setting data");
  176. return false;
  177. }
  178. graphics_->SetTextureForUpdate(this);
  179. bool wholeLevel = x == 0 && y == 0 && width == levelWidth && height == levelHeight;
  180. unsigned format = GetSRGB() ? GetSRGBFormat(format_) : format_;
  181. if (!IsCompressed())
  182. {
  183. if (wholeLevel)
  184. glTexImage2D(target_, level, format, width, height, 0, GetExternalFormat(format_), GetDataType(format_), data);
  185. else
  186. glTexSubImage2D(target_, level, x, y, width, height, GetExternalFormat(format_), GetDataType(format_), data);
  187. }
  188. else
  189. {
  190. if (wholeLevel)
  191. glCompressedTexImage2D(target_, level, format, width, height, 0, GetDataSize(width, height), data);
  192. else
  193. glCompressedTexSubImage2D(target_, level, x, y, width, height, format, GetDataSize(width, height), data);
  194. }
  195. graphics_->SetTexture(0, 0);
  196. return true;
  197. }
  198. bool Texture2D::Load(SharedPtr<Image> image, bool useAlpha)
  199. {
  200. if (!image)
  201. {
  202. LOGERROR("Null image, can not load texture");
  203. return false;
  204. }
  205. unsigned memoryUse = sizeof(Texture2D);
  206. int quality = QUALITY_HIGH;
  207. Renderer* renderer = GetSubsystem<Renderer>();
  208. if (renderer)
  209. quality = renderer->GetTextureQuality();
  210. if (!image->IsCompressed())
  211. {
  212. unsigned char* levelData = image->GetData();
  213. int levelWidth = image->GetWidth();
  214. int levelHeight = image->GetHeight();
  215. unsigned components = image->GetComponents();
  216. unsigned format = 0;
  217. // Discard unnecessary mip levels
  218. for (unsigned i = 0; i < mipsToSkip_[quality]; ++i)
  219. {
  220. image = image->GetNextLevel();
  221. levelData = image->GetData();
  222. levelWidth = image->GetWidth();
  223. levelHeight = image->GetHeight();
  224. }
  225. switch (components)
  226. {
  227. case 1:
  228. format = useAlpha ? Graphics::GetAlphaFormat() : Graphics::GetLuminanceFormat();
  229. break;
  230. case 2:
  231. format = Graphics::GetLuminanceAlphaFormat();
  232. break;
  233. case 3:
  234. format = Graphics::GetRGBFormat();
  235. break;
  236. case 4:
  237. format = Graphics::GetRGBAFormat();
  238. break;
  239. }
  240. SetSize(levelWidth, levelHeight, format);
  241. if (!object_)
  242. return false;
  243. for (unsigned i = 0; i < levels_; ++i)
  244. {
  245. SetData(i, 0, 0, levelWidth, levelHeight, levelData);
  246. memoryUse += levelWidth * levelHeight * components;
  247. if (i < levels_ - 1)
  248. {
  249. image = image->GetNextLevel();
  250. levelData = image->GetData();
  251. levelWidth = image->GetWidth();
  252. levelHeight = image->GetHeight();
  253. }
  254. }
  255. }
  256. else
  257. {
  258. int width = image->GetWidth();
  259. int height = image->GetHeight();
  260. unsigned levels = image->GetNumCompressedLevels();
  261. unsigned format = graphics_->GetFormat(image->GetCompressedFormat());
  262. bool needDecompress = false;
  263. if (!format)
  264. {
  265. format = Graphics::GetRGBAFormat();
  266. needDecompress = true;
  267. }
  268. unsigned mipsToSkip = mipsToSkip_[quality];
  269. if (mipsToSkip >= levels)
  270. mipsToSkip = levels - 1;
  271. while (mipsToSkip && (width / (1 << mipsToSkip) < 4 || height / (1 << mipsToSkip) < 4))
  272. --mipsToSkip;
  273. width /= (1 << mipsToSkip);
  274. height /= (1 << mipsToSkip);
  275. SetNumLevels(Max((int)(levels - mipsToSkip), 1));
  276. SetSize(width, height, format);
  277. for (unsigned i = 0; i < levels_ && i < levels - mipsToSkip; ++i)
  278. {
  279. CompressedLevel level = image->GetCompressedLevel(i + mipsToSkip);
  280. if (!needDecompress)
  281. {
  282. SetData(i, 0, 0, level.width_, level.height_, level.data_);
  283. memoryUse += level.rows_ * level.rowSize_;
  284. }
  285. else
  286. {
  287. unsigned char* rgbaData = new unsigned char[level.width_ * level.height_ * 4];
  288. level.Decompress(rgbaData);
  289. SetData(i, 0, 0, level.width_, level.height_, rgbaData);
  290. memoryUse += level.width_ * level.height_ * 4;
  291. delete[] rgbaData;
  292. }
  293. }
  294. }
  295. SetMemoryUse(memoryUse);
  296. return true;
  297. }
  298. bool Texture2D::GetData(unsigned level, void* dest) const
  299. {
  300. #ifndef GL_ES_VERSION_2_0
  301. if (!object_ || !graphics_)
  302. {
  303. LOGERROR("No texture created, can not get data");
  304. return false;
  305. }
  306. if (!dest)
  307. {
  308. LOGERROR("Null destination for getting data");
  309. return false;
  310. }
  311. if (level >= levels_)
  312. {
  313. LOGERROR("Illegal mip level for getting data");
  314. return false;
  315. }
  316. if (graphics_->IsDeviceLost())
  317. {
  318. LOGWARNING("Getting texture data while device is lost");
  319. return false;
  320. }
  321. graphics_->SetTextureForUpdate(const_cast<Texture2D*>(this));
  322. if (!IsCompressed())
  323. glGetTexImage(target_, level, GetExternalFormat(format_), GetDataType(format_), dest);
  324. else
  325. glGetCompressedTexImage(target_, level, dest);
  326. graphics_->SetTexture(0, 0);
  327. return true;
  328. #else
  329. LOGERROR("Getting texture data not supported");
  330. return false;
  331. #endif
  332. }
  333. bool Texture2D::Create()
  334. {
  335. Release();
  336. if (!graphics_ || !width_ || !height_)
  337. return false;
  338. if (graphics_->IsDeviceLost())
  339. {
  340. LOGWARNING("Texture creation while device is lost");
  341. return true;
  342. }
  343. unsigned format = GetSRGB() ? GetSRGBFormat(format_) : format_;
  344. unsigned externalFormat = GetExternalFormat(format_);
  345. unsigned dataType = GetDataType(format_);
  346. // Create a renderbuffer instead of a texture if depth texture is not properly supported, or if this will be a packed
  347. // depth stencil texture
  348. #ifndef GL_ES_VERSION_2_0
  349. if (format == Graphics::GetDepthStencilFormat())
  350. #else
  351. if (!graphics_->GetShadowMapFormat() && externalFormat == GL_DEPTH_COMPONENT)
  352. #endif
  353. {
  354. if (renderSurface_)
  355. {
  356. renderSurface_->CreateRenderBuffer(width_, height_, format);
  357. return true;
  358. }
  359. else
  360. return false;
  361. }
  362. glGenTextures(1, &object_);
  363. // Ensure that our texture is bound to OpenGL texture unit 0
  364. graphics_->SetTextureForUpdate(this);
  365. // If not compressed, create the initial level 0 texture with null data
  366. bool success = true;
  367. if (!IsCompressed())
  368. {
  369. glGetError();
  370. glTexImage2D(target_, 0, format, width_, height_, 0, externalFormat, dataType, 0);
  371. if (glGetError())
  372. {
  373. LOGERROR("Failed to create texture");
  374. success = false;
  375. }
  376. }
  377. // Set mipmapping
  378. levels_ = requestedLevels_;
  379. if (!levels_)
  380. {
  381. unsigned maxSize = Max((int)width_, (int)height_);
  382. while (maxSize)
  383. {
  384. maxSize >>= 1;
  385. ++levels_;
  386. }
  387. }
  388. #ifndef GL_ES_VERSION_2_0
  389. glTexParameteri(target_, GL_TEXTURE_BASE_LEVEL, 0);
  390. glTexParameteri(target_, GL_TEXTURE_MAX_LEVEL, levels_ - 1);
  391. #endif
  392. // Set initial parameters, then unbind the texture
  393. UpdateParameters();
  394. graphics_->SetTexture(0, 0);
  395. return success;
  396. }
  397. void Texture2D::HandleRenderSurfaceUpdate(StringHash eventType, VariantMap& eventData)
  398. {
  399. if (renderSurface_ && renderSurface_->GetUpdateMode() == SURFACE_UPDATEALWAYS)
  400. renderSurface_->QueueUpdate();
  401. }
  402. }