OGLTexture2DArray.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635
  1. //
  2. // Copyright (c) 2008-2016 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/Texture2DArray.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. Texture2DArray::Texture2DArray(Context* context) :
  41. Texture(context),
  42. layers_(0)
  43. {
  44. #ifndef GL_ES_VERSION_2_0
  45. target_ = GL_TEXTURE_2D_ARRAY;
  46. #else
  47. target_ = 0;
  48. #endif
  49. }
  50. Texture2DArray::~Texture2DArray()
  51. {
  52. Release();
  53. }
  54. void Texture2DArray::RegisterObject(Context* context)
  55. {
  56. context->RegisterFactory<Texture2DArray>();
  57. }
  58. bool Texture2DArray::BeginLoad(Deserializer& source)
  59. {
  60. ResourceCache* cache = GetSubsystem<ResourceCache>();
  61. // In headless mode, do not actually load the texture, just return success
  62. if (!graphics_)
  63. return true;
  64. // If device is lost, retry later
  65. if (graphics_->IsDeviceLost())
  66. {
  67. URHO3D_LOGWARNING("Texture load while device is lost");
  68. dataPending_ = true;
  69. return true;
  70. }
  71. cache->ResetDependencies(this);
  72. String texPath, texName, texExt;
  73. SplitPath(GetName(), texPath, texName, texExt);
  74. loadParameters_ = (new XMLFile(context_));
  75. if (!loadParameters_->Load(source))
  76. {
  77. loadParameters_.Reset();
  78. return false;
  79. }
  80. loadImages_.Clear();
  81. XMLElement textureElem = loadParameters_->GetRoot();
  82. XMLElement layerElem = textureElem.GetChild("layer");
  83. while (layerElem)
  84. {
  85. String name = layerElem.GetAttribute("name");
  86. // If path is empty, add the XML file path
  87. if (GetPath(name).Empty())
  88. name = texPath + name;
  89. loadImages_.Push(cache->GetTempResource<Image>(name));
  90. cache->StoreResourceDependency(this, name);
  91. layerElem = layerElem.GetNext("layer");
  92. }
  93. // Precalculate mip levels if async loading
  94. if (GetAsyncLoadState() == ASYNC_LOADING)
  95. {
  96. for (unsigned i = 0; i < loadImages_.Size(); ++i)
  97. {
  98. if (loadImages_[i])
  99. loadImages_[i]->PrecalculateLevels();
  100. }
  101. }
  102. return true;
  103. }
  104. bool Texture2DArray::EndLoad()
  105. {
  106. // In headless mode, do not actually load the texture, just return success
  107. if (!graphics_ || graphics_->IsDeviceLost())
  108. return true;
  109. // If over the texture budget, see if materials can be freed to allow textures to be freed
  110. CheckTextureBudget(GetTypeStatic());
  111. SetParameters(loadParameters_);
  112. SetLayers(loadImages_.Size());
  113. for (unsigned i = 0; i < loadImages_.Size(); ++i)
  114. SetData(i, loadImages_[i]);
  115. loadImages_.Clear();
  116. loadParameters_.Reset();
  117. return true;
  118. }
  119. void Texture2DArray::OnDeviceLost()
  120. {
  121. GPUObject::OnDeviceLost();
  122. if (renderSurface_)
  123. renderSurface_->OnDeviceLost();
  124. }
  125. void Texture2DArray::OnDeviceReset()
  126. {
  127. if (!object_ || dataPending_)
  128. {
  129. // If has a resource file, reload through the resource cache. Otherwise just recreate.
  130. ResourceCache* cache = GetSubsystem<ResourceCache>();
  131. if (cache->Exists(GetName()))
  132. dataLost_ = !cache->ReloadResource(this);
  133. if (!object_)
  134. {
  135. Create();
  136. dataLost_ = true;
  137. }
  138. }
  139. dataPending_ = false;
  140. }
  141. void Texture2DArray::Release()
  142. {
  143. if (object_)
  144. {
  145. if (!graphics_)
  146. return;
  147. if (!graphics_->IsDeviceLost())
  148. {
  149. for (unsigned i = 0; i < MAX_TEXTURE_UNITS; ++i)
  150. {
  151. if (graphics_->GetTexture(i) == this)
  152. graphics_->SetTexture(i, 0);
  153. }
  154. glDeleteTextures(1, &object_);
  155. }
  156. if (renderSurface_)
  157. renderSurface_->Release();
  158. object_ = 0;
  159. }
  160. }
  161. void Texture2DArray::SetLayers(unsigned layers)
  162. {
  163. Release();
  164. layers_ = layers;
  165. }
  166. bool Texture2DArray::SetSize(unsigned layers, int width, int height, unsigned format, TextureUsage usage)
  167. {
  168. if (width <= 0 || height <= 0)
  169. {
  170. URHO3D_LOGERROR("Zero or negative texture array size");
  171. return false;
  172. }
  173. if (usage == TEXTURE_DEPTHSTENCIL)
  174. {
  175. URHO3D_LOGERROR("Depth-stencil usage not supported for texture arrays");
  176. return false;
  177. }
  178. // Delete the old rendersurface if any
  179. renderSurface_.Reset();
  180. usage_ = usage;
  181. if (usage == TEXTURE_RENDERTARGET)
  182. {
  183. renderSurface_ = new RenderSurface(this);
  184. // Nearest filtering and mipmaps disabled by default
  185. filterMode_ = FILTER_NEAREST;
  186. requestedLevels_ = 1;
  187. }
  188. if (usage == TEXTURE_RENDERTARGET)
  189. SubscribeToEvent(E_RENDERSURFACEUPDATE, URHO3D_HANDLER(Texture2DArray, HandleRenderSurfaceUpdate));
  190. else
  191. UnsubscribeFromEvent(E_RENDERSURFACEUPDATE);
  192. width_ = width;
  193. height_ = height;
  194. format_ = format;
  195. if (layers)
  196. layers_ = layers;
  197. layerMemoryUse_.Resize(layers_);
  198. for (unsigned i = 0; i < layers_; ++i)
  199. layerMemoryUse_[i] = 0;
  200. return Create();
  201. }
  202. bool Texture2DArray::SetData(unsigned layer, unsigned level, int x, int y, int width, int height, const void* data)
  203. {
  204. URHO3D_PROFILE(SetTextureData);
  205. if (!object_ || !graphics_)
  206. {
  207. URHO3D_LOGERROR("Texture array not created, can not set data");
  208. return false;
  209. }
  210. if (!data)
  211. {
  212. URHO3D_LOGERROR("Null source for setting data");
  213. return false;
  214. }
  215. if (layer >= layers_)
  216. {
  217. URHO3D_LOGERROR("Illegal layer for setting data");
  218. return false;
  219. }
  220. if (level >= levels_)
  221. {
  222. URHO3D_LOGERROR("Illegal mip level for setting data");
  223. return false;
  224. }
  225. if (graphics_->IsDeviceLost())
  226. {
  227. URHO3D_LOGWARNING("Texture array data assignment while device is lost");
  228. dataPending_ = true;
  229. return true;
  230. }
  231. if (IsCompressed())
  232. {
  233. x &= ~3;
  234. y &= ~3;
  235. }
  236. int levelWidth = GetLevelWidth(level);
  237. int levelHeight = GetLevelHeight(level);
  238. if (x < 0 || x + width > levelWidth || y < 0 || y + height > levelHeight || width <= 0 || height <= 0)
  239. {
  240. URHO3D_LOGERROR("Illegal dimensions for setting data");
  241. return false;
  242. }
  243. graphics_->SetTextureForUpdate(this);
  244. #ifndef GL_ES_VERSION_2_0
  245. bool wholeLevel = x == 0 && y == 0 && width == levelWidth && height == levelHeight && layer == 0;
  246. unsigned format = GetSRGB() ? GetSRGBFormat(format_) : format_;
  247. if (!IsCompressed())
  248. {
  249. if (wholeLevel)
  250. glTexImage3D(target_, level, format, width, height, layers_, 0, GetExternalFormat(format_),
  251. GetDataType(format_), 0);
  252. glTexSubImage3D(target_, level, x, y, layer, width, height, 1, GetExternalFormat(format_),
  253. GetDataType(format_), data);
  254. }
  255. else
  256. {
  257. if (wholeLevel)
  258. glCompressedTexImage3D(target_, level, format, width, height, layers_, 0,
  259. GetDataSize(width, height, layers_), 0);
  260. glCompressedTexSubImage3D(target_, level, x, y, layer, width, height, 1, format,
  261. GetDataSize(width, height), data);
  262. }
  263. #endif
  264. graphics_->SetTexture(0, 0);
  265. return true;
  266. }
  267. bool Texture2DArray::SetData(unsigned layer, Deserializer& source)
  268. {
  269. SharedPtr<Image> image(new Image(context_));
  270. if (!image->Load(source))
  271. return false;
  272. return SetData(layer, image);
  273. }
  274. bool Texture2DArray::SetData(unsigned layer, SharedPtr<Image> image, bool useAlpha)
  275. {
  276. if (!image)
  277. {
  278. URHO3D_LOGERROR("Null image, can not set data");
  279. return false;
  280. }
  281. if (!layers_)
  282. {
  283. URHO3D_LOGERROR("Number of layers in the array must be set first");
  284. return false;
  285. }
  286. if (layer >= layers_)
  287. {
  288. URHO3D_LOGERROR("Illegal layer for setting data");
  289. return false;
  290. }
  291. unsigned memoryUse = 0;
  292. int quality = QUALITY_HIGH;
  293. Renderer* renderer = GetSubsystem<Renderer>();
  294. if (renderer)
  295. quality = renderer->GetTextureQuality();
  296. if (!image->IsCompressed())
  297. {
  298. // Convert unsuitable formats to RGBA
  299. unsigned components = image->GetComponents();
  300. if (Graphics::GetGL3Support() && ((components == 1 && !useAlpha) || components == 2))
  301. {
  302. image = image->ConvertToRGBA();
  303. if (!image)
  304. return false;
  305. components = image->GetComponents();
  306. }
  307. unsigned char* levelData = image->GetData();
  308. int levelWidth = image->GetWidth();
  309. int levelHeight = image->GetHeight();
  310. unsigned format = 0;
  311. // Discard unnecessary mip levels
  312. for (unsigned i = 0; i < mipsToSkip_[quality]; ++i)
  313. {
  314. image = image->GetNextLevel();
  315. levelData = image->GetData();
  316. levelWidth = image->GetWidth();
  317. levelHeight = image->GetHeight();
  318. }
  319. switch (components)
  320. {
  321. case 1:
  322. format = useAlpha ? Graphics::GetAlphaFormat() : Graphics::GetLuminanceFormat();
  323. break;
  324. case 2:
  325. format = Graphics::GetLuminanceAlphaFormat();
  326. break;
  327. case 3:
  328. format = Graphics::GetRGBFormat();
  329. break;
  330. case 4:
  331. format = Graphics::GetRGBAFormat();
  332. break;
  333. default:
  334. assert(false); // Should not reach here
  335. break;
  336. }
  337. // Create the texture array when layer 0 is being loaded, check that rest of the layers are same size & format
  338. if (!layer)
  339. {
  340. // If image was previously compressed, reset number of requested levels to avoid error if level count is too high for new size
  341. if (IsCompressed() && requestedLevels_ > 1)
  342. requestedLevels_ = 0;
  343. // Create the texture array (the number of layers must have been already set)
  344. SetSize(0, levelWidth, levelHeight, format);
  345. }
  346. else
  347. {
  348. if (!object_)
  349. {
  350. URHO3D_LOGERROR("Texture array layer 0 must be loaded first");
  351. return false;
  352. }
  353. if (levelWidth != width_ || levelHeight != height_ || format != format_)
  354. {
  355. URHO3D_LOGERROR("Texture array layer does not match size or format of layer 0");
  356. return false;
  357. }
  358. }
  359. for (unsigned i = 0; i < levels_; ++i)
  360. {
  361. SetData(layer, i, 0, 0, levelWidth, levelHeight, levelData);
  362. memoryUse += levelWidth * levelHeight * components;
  363. if (i < levels_ - 1)
  364. {
  365. image = image->GetNextLevel();
  366. levelData = image->GetData();
  367. levelWidth = image->GetWidth();
  368. levelHeight = image->GetHeight();
  369. }
  370. }
  371. }
  372. else
  373. {
  374. int width = image->GetWidth();
  375. int height = image->GetHeight();
  376. unsigned levels = image->GetNumCompressedLevels();
  377. unsigned format = graphics_->GetFormat(image->GetCompressedFormat());
  378. bool needDecompress = false;
  379. if (!format)
  380. {
  381. format = Graphics::GetRGBAFormat();
  382. needDecompress = true;
  383. }
  384. unsigned mipsToSkip = mipsToSkip_[quality];
  385. if (mipsToSkip >= levels)
  386. mipsToSkip = levels - 1;
  387. while (mipsToSkip && (width / (1 << mipsToSkip) < 4 || height / (1 << mipsToSkip) < 4))
  388. --mipsToSkip;
  389. width /= (1 << mipsToSkip);
  390. height /= (1 << mipsToSkip);
  391. // Create the texture array when layer 0 is being loaded, assume rest of the layers are same size & format
  392. if (!layer)
  393. {
  394. SetNumLevels(Max((levels - mipsToSkip), 1U));
  395. SetSize(0, width, height, format);
  396. }
  397. else
  398. {
  399. if (!object_)
  400. {
  401. URHO3D_LOGERROR("Texture array layer 0 must be loaded first");
  402. return false;
  403. }
  404. if (width != width_ || height != height_ || format != format_)
  405. {
  406. URHO3D_LOGERROR("Texture array layer does not match size or format of layer 0");
  407. return false;
  408. }
  409. }
  410. for (unsigned i = 0; i < levels_ && i < levels - mipsToSkip; ++i)
  411. {
  412. CompressedLevel level = image->GetCompressedLevel(i + mipsToSkip);
  413. if (!needDecompress)
  414. {
  415. SetData(layer, i, 0, 0, level.width_, level.height_, level.data_);
  416. memoryUse += level.rows_ * level.rowSize_;
  417. }
  418. else
  419. {
  420. unsigned char* rgbaData = new unsigned char[level.width_ * level.height_ * 4];
  421. level.Decompress(rgbaData);
  422. SetData(layer, i, 0, 0, level.width_, level.height_, rgbaData);
  423. memoryUse += level.width_ * level.height_ * 4;
  424. delete[] rgbaData;
  425. }
  426. }
  427. }
  428. layerMemoryUse_[layer] = memoryUse;
  429. unsigned totalMemoryUse = sizeof(Texture2DArray) + layerMemoryUse_.Capacity() * sizeof(unsigned);
  430. for (unsigned i = 0; i < layers_; ++i)
  431. totalMemoryUse += layerMemoryUse_[i];
  432. SetMemoryUse(totalMemoryUse);
  433. return true;
  434. }
  435. bool Texture2DArray::GetData(unsigned layer, unsigned level, void* dest) const
  436. {
  437. #ifndef GL_ES_VERSION_2_0
  438. if (!object_ || !graphics_)
  439. {
  440. URHO3D_LOGERROR("Texture array not created, can not get data");
  441. return false;
  442. }
  443. if (!dest)
  444. {
  445. URHO3D_LOGERROR("Null destination for getting data");
  446. return false;
  447. }
  448. if (layer != 0)
  449. {
  450. URHO3D_LOGERROR("Only the full download of the array is supported, set layer=0");
  451. return false;
  452. }
  453. if (level >= levels_)
  454. {
  455. URHO3D_LOGERROR("Illegal mip level for getting data");
  456. return false;
  457. }
  458. if (graphics_->IsDeviceLost())
  459. {
  460. URHO3D_LOGWARNING("Getting texture data while device is lost");
  461. return false;
  462. }
  463. graphics_->SetTextureForUpdate(const_cast<Texture2DArray*>(this));
  464. if (!IsCompressed())
  465. glGetTexImage(target_, level, GetExternalFormat(format_), GetDataType(format_), dest);
  466. else
  467. glGetCompressedTexImage(target_, level, dest);
  468. graphics_->SetTexture(0, 0);
  469. return true;
  470. #else
  471. URHO3D_LOGERROR("Getting texture data not supported");
  472. return false;
  473. #endif
  474. }
  475. bool Texture2DArray::Create()
  476. {
  477. Release();
  478. if (!graphics_ || !width_ || !height_ || !layers_)
  479. return false;
  480. if (graphics_->IsDeviceLost())
  481. {
  482. URHO3D_LOGWARNING("Texture array creation while device is lost");
  483. return true;
  484. }
  485. glGenTextures(1, &object_);
  486. // Ensure that our texture is bound to OpenGL texture unit 0
  487. graphics_->SetTextureForUpdate(this);
  488. unsigned format = GetSRGB() ? GetSRGBFormat(format_) : format_;
  489. unsigned externalFormat = GetExternalFormat(format_);
  490. unsigned dataType = GetDataType(format_);
  491. // If not compressed, create the initial level 0 texture with null data
  492. bool success = true;
  493. if (!IsCompressed())
  494. {
  495. glGetError();
  496. glTexImage3D(target_, 0, format, width_, height_, layers_, 0, externalFormat, dataType, 0);
  497. if (glGetError())
  498. success = false;
  499. }
  500. if (!success)
  501. URHO3D_LOGERROR("Failed to create texture array");
  502. // Set mipmapping
  503. levels_ = requestedLevels_;
  504. if (!levels_)
  505. {
  506. unsigned maxSize = (unsigned)Max(width_, height_);
  507. while (maxSize)
  508. {
  509. maxSize >>= 1;
  510. ++levels_;
  511. }
  512. }
  513. #ifndef GL_ES_VERSION_2_0
  514. glTexParameteri(target_, GL_TEXTURE_BASE_LEVEL, 0);
  515. glTexParameteri(target_, GL_TEXTURE_MAX_LEVEL, levels_ - 1);
  516. #endif
  517. // Set initial parameters, then unbind the texture
  518. UpdateParameters();
  519. graphics_->SetTexture(0, 0);
  520. return success;
  521. }
  522. void Texture2DArray::HandleRenderSurfaceUpdate(StringHash eventType, VariantMap& eventData)
  523. {
  524. if (renderSurface_ && (renderSurface_->GetUpdateMode() == SURFACE_UPDATEALWAYS || renderSurface_->IsUpdateQueued()))
  525. {
  526. Renderer* renderer = GetSubsystem<Renderer>();
  527. if (renderer)
  528. renderer->QueueRenderSurface(renderSurface_);
  529. renderSurface_->ResetUpdateQueued();
  530. }
  531. }
  532. }