OGLTextureCube.cpp 17 KB

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