OGLTextureCube.cpp 16 KB

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