OGLTexture2D.cpp 14 KB

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