OGLTexture2D.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497
  1. //
  2. // Copyright (c) 2008-2020 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 rightsR
  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/Profiler.h"
  25. #include "../../Graphics/Graphics.h"
  26. #include "../../Graphics/GraphicsEvents.h"
  27. #include "../../Graphics/GraphicsImpl.h"
  28. #include "../../Graphics/Renderer.h"
  29. #include "../../Graphics/Texture2D.h"
  30. #include "../../IO/FileSystem.h"
  31. #include "../../IO/Log.h"
  32. #include "../../Resource/ResourceCache.h"
  33. #include "../../Resource/XMLFile.h"
  34. #include "../../DebugNew.h"
  35. namespace Urho3D
  36. {
  37. void Texture2D::OnDeviceLost()
  38. {
  39. if (object_.name_ && !graphics_->IsDeviceLost())
  40. glDeleteTextures(1, &object_.name_);
  41. GPUObject::OnDeviceLost();
  42. if (renderSurface_)
  43. renderSurface_->OnDeviceLost();
  44. }
  45. void Texture2D::OnDeviceReset()
  46. {
  47. if (!object_.name_ || dataPending_)
  48. {
  49. // If has a resource file, reload through the resource cache. Otherwise just recreate.
  50. auto* cache = GetSubsystem<ResourceCache>();
  51. if (cache->Exists(GetName()))
  52. dataLost_ = !cache->ReloadResource(this);
  53. if (!object_.name_)
  54. {
  55. Create();
  56. dataLost_ = true;
  57. }
  58. }
  59. dataPending_ = false;
  60. }
  61. void Texture2D::Release()
  62. {
  63. if (object_.name_)
  64. {
  65. if (!graphics_)
  66. return;
  67. if (!graphics_->IsDeviceLost())
  68. {
  69. for (unsigned i = 0; i < MAX_TEXTURE_UNITS; ++i)
  70. {
  71. if (graphics_->GetTexture(i) == this)
  72. graphics_->SetTexture(i, nullptr);
  73. }
  74. glDeleteTextures(1, &object_.name_);
  75. }
  76. if (renderSurface_)
  77. renderSurface_->Release();
  78. object_.name_ = 0;
  79. }
  80. else
  81. {
  82. if (renderSurface_)
  83. renderSurface_->Release();
  84. }
  85. resolveDirty_ = false;
  86. levelsDirty_ = false;
  87. }
  88. bool Texture2D::SetData(unsigned level, int x, int y, int width, int height, const void* data)
  89. {
  90. URHO3D_PROFILE(SetTextureData);
  91. if (!object_.name_ || !graphics_)
  92. {
  93. URHO3D_LOGERROR("No texture created, can not set data");
  94. return false;
  95. }
  96. if (!data)
  97. {
  98. URHO3D_LOGERROR("Null source for setting data");
  99. return false;
  100. }
  101. if (level >= levels_)
  102. {
  103. URHO3D_LOGERROR("Illegal mip level for setting data");
  104. return false;
  105. }
  106. if (graphics_->IsDeviceLost())
  107. {
  108. URHO3D_LOGWARNING("Texture data assignment while device is lost");
  109. dataPending_ = true;
  110. return true;
  111. }
  112. if (IsCompressed())
  113. {
  114. x &= ~3u;
  115. y &= ~3u;
  116. }
  117. int levelWidth = GetLevelWidth(level);
  118. int levelHeight = GetLevelHeight(level);
  119. if (x < 0 || x + width > levelWidth || y < 0 || y + height > levelHeight || width <= 0 || height <= 0)
  120. {
  121. URHO3D_LOGERROR("Illegal dimensions for setting data");
  122. return false;
  123. }
  124. graphics_->SetTextureForUpdate(this);
  125. bool wholeLevel = x == 0 && y == 0 && width == levelWidth && height == levelHeight;
  126. unsigned format = GetSRGB() ? GetSRGBFormat(format_) : format_;
  127. if (!IsCompressed())
  128. {
  129. if (wholeLevel)
  130. glTexImage2D(target_, level, format, width, height, 0, GetExternalFormat(format_), GetDataType(format_), data);
  131. else
  132. glTexSubImage2D(target_, level, x, y, width, height, GetExternalFormat(format_), GetDataType(format_), data);
  133. }
  134. else
  135. {
  136. if (wholeLevel)
  137. glCompressedTexImage2D(target_, level, format, width, height, 0, GetDataSize(width, height), data);
  138. else
  139. glCompressedTexSubImage2D(target_, level, x, y, width, height, format, GetDataSize(width, height), data);
  140. }
  141. graphics_->SetTexture(0, nullptr);
  142. return true;
  143. }
  144. bool Texture2D::SetData(Image* image, bool useAlpha)
  145. {
  146. if (!image)
  147. {
  148. URHO3D_LOGERROR("Null image, can not set data");
  149. return false;
  150. }
  151. // Use a shared ptr for managing the temporary mip images created during this function
  152. SharedPtr<Image> mipImage;
  153. unsigned memoryUse = sizeof(Texture2D);
  154. MaterialQuality quality = QUALITY_HIGH;
  155. auto* renderer = GetSubsystem<Renderer>();
  156. if (renderer)
  157. quality = renderer->GetTextureQuality();
  158. if (!image->IsCompressed())
  159. {
  160. // Convert unsuitable formats to RGBA
  161. unsigned components = image->GetComponents();
  162. if (Graphics::GetGL3Support() && ((components == 1 && !useAlpha) || components == 2))
  163. {
  164. mipImage = image->ConvertToRGBA(); image = mipImage;
  165. if (!image)
  166. return false;
  167. components = image->GetComponents();
  168. }
  169. unsigned char* levelData = image->GetData();
  170. int levelWidth = image->GetWidth();
  171. int levelHeight = image->GetHeight();
  172. unsigned format = 0;
  173. // Discard unnecessary mip levels
  174. for (unsigned i = 0; i < mipsToSkip_[quality]; ++i)
  175. {
  176. mipImage = image->GetNextLevel(); image = mipImage;
  177. levelData = image->GetData();
  178. levelWidth = image->GetWidth();
  179. levelHeight = image->GetHeight();
  180. }
  181. switch (components)
  182. {
  183. case 1:
  184. format = useAlpha ? Graphics::GetAlphaFormat() : Graphics::GetLuminanceFormat();
  185. break;
  186. case 2:
  187. format = Graphics::GetLuminanceAlphaFormat();
  188. break;
  189. case 3:
  190. format = Graphics::GetRGBFormat();
  191. break;
  192. case 4:
  193. format = Graphics::GetRGBAFormat();
  194. break;
  195. default:
  196. assert(false); // Should not reach here
  197. break;
  198. }
  199. // If image was previously compressed, reset number of requested levels to avoid error if level count is too high for new size
  200. if (IsCompressed() && requestedLevels_ > 1)
  201. requestedLevels_ = 0;
  202. SetSize(levelWidth, levelHeight, format);
  203. if (!object_.name_)
  204. return false;
  205. for (unsigned i = 0; i < levels_; ++i)
  206. {
  207. SetData(i, 0, 0, levelWidth, levelHeight, levelData);
  208. memoryUse += levelWidth * levelHeight * components;
  209. if (i < levels_ - 1)
  210. {
  211. mipImage = image->GetNextLevel(); image = mipImage;
  212. levelData = image->GetData();
  213. levelWidth = image->GetWidth();
  214. levelHeight = image->GetHeight();
  215. }
  216. }
  217. }
  218. else
  219. {
  220. int width = image->GetWidth();
  221. int height = image->GetHeight();
  222. unsigned levels = image->GetNumCompressedLevels();
  223. unsigned format = graphics_->GetFormat(image->GetCompressedFormat());
  224. bool needDecompress = false;
  225. if (!format)
  226. {
  227. format = Graphics::GetRGBAFormat();
  228. needDecompress = true;
  229. }
  230. unsigned mipsToSkip = mipsToSkip_[quality];
  231. if (mipsToSkip >= levels)
  232. mipsToSkip = levels - 1;
  233. while (mipsToSkip && (width / (1u << mipsToSkip) < 4 || height / (1u << mipsToSkip) < 4))
  234. --mipsToSkip;
  235. width /= (1u << mipsToSkip);
  236. height /= (1u << mipsToSkip);
  237. SetNumLevels(Max((levels - mipsToSkip), 1U));
  238. SetSize(width, height, format);
  239. for (unsigned i = 0; i < levels_ && i < levels - mipsToSkip; ++i)
  240. {
  241. CompressedLevel level = image->GetCompressedLevel(i + mipsToSkip);
  242. if (!needDecompress)
  243. {
  244. SetData(i, 0, 0, level.width_, level.height_, level.data_);
  245. memoryUse += level.rows_ * level.rowSize_;
  246. }
  247. else
  248. {
  249. auto* rgbaData = new unsigned char[level.width_ * level.height_ * 4];
  250. level.Decompress(rgbaData);
  251. SetData(i, 0, 0, level.width_, level.height_, rgbaData);
  252. memoryUse += level.width_ * level.height_ * 4;
  253. delete[] rgbaData;
  254. }
  255. }
  256. }
  257. SetMemoryUse(memoryUse);
  258. return true;
  259. }
  260. bool Texture2D::GetData(unsigned level, void* dest) const
  261. {
  262. if (!object_.name_ || !graphics_)
  263. {
  264. URHO3D_LOGERROR("No texture created, can not get data");
  265. return false;
  266. }
  267. #ifndef GL_ES_VERSION_2_0
  268. if (!dest)
  269. {
  270. URHO3D_LOGERROR("Null destination for getting data");
  271. return false;
  272. }
  273. if (level >= levels_)
  274. {
  275. URHO3D_LOGERROR("Illegal mip level for getting data");
  276. return false;
  277. }
  278. if (graphics_->IsDeviceLost())
  279. {
  280. URHO3D_LOGWARNING("Getting texture data while device is lost");
  281. return false;
  282. }
  283. if (multiSample_ > 1 && !autoResolve_)
  284. {
  285. URHO3D_LOGERROR("Can not get data from multisampled texture without autoresolve");
  286. return false;
  287. }
  288. if (resolveDirty_)
  289. graphics_->ResolveToTexture(const_cast<Texture2D*>(this));
  290. graphics_->SetTextureForUpdate(const_cast<Texture2D*>(this));
  291. if (!IsCompressed())
  292. glGetTexImage(target_, level, GetExternalFormat(format_), GetDataType(format_), dest);
  293. else
  294. glGetCompressedTexImage(target_, level, dest);
  295. graphics_->SetTexture(0, nullptr);
  296. return true;
  297. #else
  298. // Special case on GLES: if the texture is a rendertarget, can make it current and use glReadPixels()
  299. if (usage_ == TEXTURE_RENDERTARGET)
  300. {
  301. graphics_->SetRenderTarget(0, const_cast<Texture2D*>(this));
  302. // Ensure the FBO is current; this viewport is actually never rendered to
  303. graphics_->SetViewport(IntRect(0, 0, width_, height_));
  304. glReadPixels(0, 0, width_, height_, GetExternalFormat(format_), GetDataType(format_), dest);
  305. return true;
  306. }
  307. URHO3D_LOGERROR("Getting texture data not supported");
  308. return false;
  309. #endif
  310. }
  311. bool Texture2D::Create()
  312. {
  313. Release();
  314. if (!graphics_ || !width_ || !height_)
  315. return false;
  316. if (graphics_->IsDeviceLost())
  317. {
  318. URHO3D_LOGWARNING("Texture creation while device is lost");
  319. return true;
  320. }
  321. #ifdef GL_ES_VERSION_2_0
  322. if (multiSample_ > 1)
  323. {
  324. URHO3D_LOGWARNING("Multisampled texture is not supported on OpenGL ES");
  325. multiSample_ = 1;
  326. autoResolve_ = false;
  327. }
  328. #endif
  329. unsigned format = GetSRGB() ? GetSRGBFormat(format_) : format_;
  330. unsigned externalFormat = GetExternalFormat(format_);
  331. unsigned dataType = GetDataType(format_);
  332. // Create a renderbuffer instead of a texture if depth texture is not properly supported, or if this will be a packed
  333. // depth stencil texture
  334. #ifndef GL_ES_VERSION_2_0
  335. if (format == Graphics::GetDepthStencilFormat())
  336. #else
  337. if (format == GL_DEPTH_COMPONENT16 || format == GL_DEPTH_COMPONENT24_OES || format == GL_DEPTH24_STENCIL8_OES ||
  338. (format == GL_DEPTH_COMPONENT && !graphics_->GetShadowMapFormat()))
  339. #endif
  340. {
  341. if (renderSurface_)
  342. {
  343. renderSurface_->CreateRenderBuffer(width_, height_, format, multiSample_);
  344. return true;
  345. }
  346. else
  347. return false;
  348. }
  349. else
  350. {
  351. if (multiSample_ > 1)
  352. {
  353. if (autoResolve_)
  354. {
  355. // Multisample with autoresolve: create a renderbuffer for rendering, but also a texture
  356. renderSurface_->CreateRenderBuffer(width_, height_, format, multiSample_);
  357. }
  358. else
  359. {
  360. // Multisample without autoresolve: create a texture only
  361. #ifndef GL_ES_VERSION_2_0
  362. if (!Graphics::GetGL3Support() && !GLEW_ARB_texture_multisample)
  363. {
  364. URHO3D_LOGERROR("Multisampled texture extension not available");
  365. return false;
  366. }
  367. target_ = GL_TEXTURE_2D_MULTISAMPLE;
  368. if (renderSurface_)
  369. renderSurface_->target_ = GL_TEXTURE_2D_MULTISAMPLE;
  370. #endif
  371. }
  372. }
  373. }
  374. glGenTextures(1, &object_.name_);
  375. // Ensure that our texture is bound to OpenGL texture unit 0
  376. graphics_->SetTextureForUpdate(this);
  377. // If not compressed, create the initial level 0 texture with null data
  378. bool success = true;
  379. if (!IsCompressed())
  380. {
  381. glGetError();
  382. #ifndef GL_ES_VERSION_2_0
  383. if (multiSample_ > 1 && !autoResolve_)
  384. {
  385. glTexImage2DMultisample(target_, multiSample_, format, width_, height_, GL_TRUE);
  386. }
  387. else
  388. #endif
  389. {
  390. glTexImage2D(target_, 0, format, width_, height_, 0, externalFormat, dataType, nullptr);
  391. }
  392. if (glGetError())
  393. {
  394. URHO3D_LOGERROR("Failed to create texture");
  395. success = false;
  396. }
  397. }
  398. // Set mipmapping
  399. if (usage_ == TEXTURE_DEPTHSTENCIL || usage_ == TEXTURE_DYNAMIC)
  400. requestedLevels_ = 1;
  401. else if (usage_ == TEXTURE_RENDERTARGET)
  402. {
  403. #if defined(__EMSCRIPTEN__) || defined(IOS) || defined(TVOS)
  404. // glGenerateMipmap appears to not be working on WebGL or iOS/tvOS, disable rendertarget mipmaps for now
  405. requestedLevels_ = 1;
  406. #else
  407. if (requestedLevels_ != 1)
  408. {
  409. // Generate levels for the first time now
  410. RegenerateLevels();
  411. // Determine max. levels automatically
  412. requestedLevels_ = 0;
  413. }
  414. #endif
  415. }
  416. levels_ = CheckMaxLevels(width_, height_, requestedLevels_);
  417. #ifndef GL_ES_VERSION_2_0
  418. glTexParameteri(target_, GL_TEXTURE_BASE_LEVEL, 0);
  419. glTexParameteri(target_, GL_TEXTURE_MAX_LEVEL, levels_ - 1);
  420. #endif
  421. // Set initial parameters, then unbind the texture
  422. UpdateParameters();
  423. graphics_->SetTexture(0, nullptr);
  424. return success;
  425. }
  426. }