OGLTextureCube.cpp 18 KB

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