OGLTextureCube.cpp 17 KB

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