OGLTexture2D.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519
  1. //
  2. // Copyright (c) 2008-2015 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 rightsR
  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 "../../IO/FileSystem.h"
  25. #include "../../Graphics/Graphics.h"
  26. #include "../../Graphics/GraphicsEvents.h"
  27. #include "../../Graphics/GraphicsImpl.h"
  28. #include "../../Resource/Image.h"
  29. #include "../../IO/Log.h"
  30. #include "../../Core/Profiler.h"
  31. #include "../../Graphics/Renderer.h"
  32. #include "../../Resource/ResourceCache.h"
  33. #include "../../Graphics/Texture2D.h"
  34. #include "../../Resource/XMLFile.h"
  35. #include "../../DebugNew.h"
  36. namespace Atomic
  37. {
  38. Texture2D::Texture2D(Context* context) :
  39. Texture(context)
  40. {
  41. target_ = GL_TEXTURE_2D;
  42. }
  43. Texture2D::~Texture2D()
  44. {
  45. Release();
  46. }
  47. void Texture2D::RegisterObject(Context* context)
  48. {
  49. context->RegisterFactory<Texture2D>();
  50. }
  51. bool Texture2D::BeginLoad(Deserializer& source)
  52. {
  53. // In headless mode, do not actually load the texture, just return success
  54. if (!graphics_)
  55. return true;
  56. // If device is lost, retry later
  57. if (graphics_->IsDeviceLost())
  58. {
  59. LOGWARNING("Texture load while device is lost");
  60. dataPending_ = true;
  61. return true;
  62. }
  63. // Load the image data for EndLoad()
  64. loadImage_ = new Image(context_);
  65. if (!loadImage_->Load(source))
  66. {
  67. loadImage_.Reset();
  68. return false;
  69. }
  70. // Precalculate mip levels if async loading
  71. if (GetAsyncLoadState() == ASYNC_LOADING)
  72. loadImage_->PrecalculateLevels();
  73. // Load the optional parameters file
  74. ResourceCache* cache = GetSubsystem<ResourceCache>();
  75. String xmlName = ReplaceExtension(GetName(), ".xml");
  76. loadParameters_ = cache->GetTempResource<XMLFile>(xmlName, false);
  77. return true;
  78. }
  79. bool Texture2D::EndLoad()
  80. {
  81. // In headless mode, do not actually load the texture, just return success
  82. if (!graphics_ || graphics_->IsDeviceLost())
  83. return true;
  84. // If over the texture budget, see if materials can be freed to allow textures to be freed
  85. CheckTextureBudget(GetTypeStatic());
  86. SetParameters(loadParameters_);
  87. bool success = SetData(loadImage_);
  88. loadImage_.Reset();
  89. loadParameters_.Reset();
  90. return success;
  91. }
  92. void Texture2D::OnDeviceLost()
  93. {
  94. GPUObject::OnDeviceLost();
  95. if (renderSurface_)
  96. renderSurface_->OnDeviceLost();
  97. }
  98. void Texture2D::OnDeviceReset()
  99. {
  100. if (!object_ || dataPending_)
  101. {
  102. // If has a resource file, reload through the resource cache. Otherwise just recreate.
  103. ResourceCache* cache = GetSubsystem<ResourceCache>();
  104. if (cache->Exists(GetName()))
  105. dataLost_ = !cache->ReloadResource(this);
  106. if (!object_)
  107. {
  108. Create();
  109. dataLost_ = true;
  110. }
  111. }
  112. dataPending_ = false;
  113. }
  114. void Texture2D::Release()
  115. {
  116. if (object_)
  117. {
  118. if (!graphics_)
  119. return;
  120. if (!graphics_->IsDeviceLost())
  121. {
  122. for (unsigned i = 0; i < MAX_TEXTURE_UNITS; ++i)
  123. {
  124. if (graphics_->GetTexture(i) == this)
  125. graphics_->SetTexture(i, 0);
  126. }
  127. glDeleteTextures(1, &object_);
  128. }
  129. if (renderSurface_)
  130. renderSurface_->Release();
  131. object_ = 0;
  132. }
  133. else
  134. {
  135. if (renderSurface_)
  136. renderSurface_->Release();
  137. }
  138. }
  139. bool Texture2D::SetSize(int width, int height, unsigned format, TextureUsage usage)
  140. {
  141. // Delete the old rendersurface if any
  142. renderSurface_.Reset();
  143. usage_ = usage;
  144. if (usage >= TEXTURE_RENDERTARGET)
  145. {
  146. renderSurface_ = new RenderSurface(this);
  147. // Clamp mode addressing by default, nearest filtering, and mipmaps disabled
  148. addressMode_[COORD_U] = ADDRESS_CLAMP;
  149. addressMode_[COORD_V] = ADDRESS_CLAMP;
  150. filterMode_ = FILTER_NEAREST;
  151. requestedLevels_ = 1;
  152. }
  153. if (usage == TEXTURE_RENDERTARGET)
  154. SubscribeToEvent(E_RENDERSURFACEUPDATE, HANDLER(Texture2D, HandleRenderSurfaceUpdate));
  155. else
  156. UnsubscribeFromEvent(E_RENDERSURFACEUPDATE);
  157. width_ = width;
  158. height_ = height;
  159. format_ = format;
  160. return Create();
  161. }
  162. bool Texture2D::SetData(unsigned level, int x, int y, int width, int height, const void* data)
  163. {
  164. PROFILE(SetTextureData);
  165. if (!object_ || !graphics_)
  166. {
  167. LOGERROR("No texture created, can not set data");
  168. return false;
  169. }
  170. if (!data)
  171. {
  172. LOGERROR("Null source for setting data");
  173. return false;
  174. }
  175. if (level >= levels_)
  176. {
  177. LOGERROR("Illegal mip level for setting data");
  178. return false;
  179. }
  180. if (graphics_->IsDeviceLost())
  181. {
  182. LOGWARNING("Texture data assignment while device is lost");
  183. dataPending_ = true;
  184. return true;
  185. }
  186. if (IsCompressed())
  187. {
  188. x &= ~3;
  189. y &= ~3;
  190. }
  191. int levelWidth = GetLevelWidth(level);
  192. int levelHeight = GetLevelHeight(level);
  193. if (x < 0 || x + width > levelWidth || y < 0 || y + height > levelHeight || width <= 0 || height <= 0)
  194. {
  195. LOGERROR("Illegal dimensions for setting data");
  196. return false;
  197. }
  198. graphics_->SetTextureForUpdate(this);
  199. bool wholeLevel = x == 0 && y == 0 && width == levelWidth && height == levelHeight;
  200. unsigned format = GetSRGB() ? GetSRGBFormat(format_) : format_;
  201. if (!IsCompressed())
  202. {
  203. if (wholeLevel)
  204. glTexImage2D(target_, level, format, width, height, 0, GetExternalFormat(format_), GetDataType(format_), data);
  205. else
  206. glTexSubImage2D(target_, level, x, y, width, height, GetExternalFormat(format_), GetDataType(format_), data);
  207. }
  208. else
  209. {
  210. if (wholeLevel)
  211. glCompressedTexImage2D(target_, level, format, width, height, 0, GetDataSize(width, height), data);
  212. else
  213. glCompressedTexSubImage2D(target_, level, x, y, width, height, format, GetDataSize(width, height), data);
  214. }
  215. graphics_->SetTexture(0, 0);
  216. return true;
  217. }
  218. bool Texture2D::SetData(SharedPtr<Image> image, bool useAlpha)
  219. {
  220. if (!image)
  221. {
  222. LOGERROR("Null image, can not set data");
  223. return false;
  224. }
  225. unsigned memoryUse = sizeof(Texture2D);
  226. int quality = QUALITY_HIGH;
  227. Renderer* renderer = GetSubsystem<Renderer>();
  228. if (renderer)
  229. quality = renderer->GetTextureQuality();
  230. if (!image->IsCompressed())
  231. {
  232. // Convert unsuitable formats to RGBA
  233. unsigned components = image->GetComponents();
  234. if (Graphics::GetGL3Support() && ((components == 1 && !useAlpha) || components == 2))
  235. {
  236. image = image->ConvertToRGBA();
  237. if (!image)
  238. return false;
  239. components = image->GetComponents();
  240. }
  241. unsigned char* levelData = image->GetData();
  242. int levelWidth = image->GetWidth();
  243. int levelHeight = image->GetHeight();
  244. unsigned format = 0;
  245. // Discard unnecessary mip levels
  246. for (unsigned i = 0; i < mipsToSkip_[quality]; ++i)
  247. {
  248. image = image->GetNextLevel();
  249. levelData = image->GetData();
  250. levelWidth = image->GetWidth();
  251. levelHeight = image->GetHeight();
  252. }
  253. switch (components)
  254. {
  255. case 1:
  256. format = useAlpha ? Graphics::GetAlphaFormat() : Graphics::GetLuminanceFormat();
  257. break;
  258. case 2:
  259. format = Graphics::GetLuminanceAlphaFormat();
  260. break;
  261. case 3:
  262. format = Graphics::GetRGBFormat();
  263. break;
  264. case 4:
  265. format = Graphics::GetRGBAFormat();
  266. break;
  267. }
  268. // If image was previously compressed, reset number of requested levels to avoid error if level count is too high for new size
  269. if (IsCompressed() && requestedLevels_ > 1)
  270. requestedLevels_ = 0;
  271. SetSize(levelWidth, levelHeight, format);
  272. if (!object_)
  273. return false;
  274. for (unsigned i = 0; i < levels_; ++i)
  275. {
  276. SetData(i, 0, 0, levelWidth, levelHeight, levelData);
  277. memoryUse += levelWidth * levelHeight * components;
  278. if (i < levels_ - 1)
  279. {
  280. image = image->GetNextLevel();
  281. levelData = image->GetData();
  282. levelWidth = image->GetWidth();
  283. levelHeight = image->GetHeight();
  284. }
  285. }
  286. }
  287. else
  288. {
  289. int width = image->GetWidth();
  290. int height = image->GetHeight();
  291. unsigned levels = image->GetNumCompressedLevels();
  292. unsigned format = graphics_->GetFormat(image->GetCompressedFormat());
  293. bool needDecompress = false;
  294. if (!format)
  295. {
  296. format = Graphics::GetRGBAFormat();
  297. needDecompress = true;
  298. }
  299. unsigned mipsToSkip = mipsToSkip_[quality];
  300. if (mipsToSkip >= levels)
  301. mipsToSkip = levels - 1;
  302. while (mipsToSkip && (width / (1 << mipsToSkip) < 4 || height / (1 << mipsToSkip) < 4))
  303. --mipsToSkip;
  304. width /= (1 << mipsToSkip);
  305. height /= (1 << mipsToSkip);
  306. SetNumLevels(Max((int)(levels - mipsToSkip), 1));
  307. SetSize(width, height, format);
  308. for (unsigned i = 0; i < levels_ && i < levels - mipsToSkip; ++i)
  309. {
  310. CompressedLevel level = image->GetCompressedLevel(i + mipsToSkip);
  311. if (!needDecompress)
  312. {
  313. SetData(i, 0, 0, level.width_, level.height_, level.data_);
  314. memoryUse += level.rows_ * level.rowSize_;
  315. }
  316. else
  317. {
  318. unsigned char* rgbaData = new unsigned char[level.width_ * level.height_ * 4];
  319. level.Decompress(rgbaData);
  320. SetData(i, 0, 0, level.width_, level.height_, rgbaData);
  321. memoryUse += level.width_ * level.height_ * 4;
  322. delete[] rgbaData;
  323. }
  324. }
  325. }
  326. SetMemoryUse(memoryUse);
  327. return true;
  328. }
  329. bool Texture2D::GetData(unsigned level, void* dest) const
  330. {
  331. #ifndef GL_ES_VERSION_2_0
  332. if (!object_ || !graphics_)
  333. {
  334. LOGERROR("No texture created, can not get data");
  335. return false;
  336. }
  337. if (!dest)
  338. {
  339. LOGERROR("Null destination for getting data");
  340. return false;
  341. }
  342. if (level >= levels_)
  343. {
  344. LOGERROR("Illegal mip level for getting data");
  345. return false;
  346. }
  347. if (graphics_->IsDeviceLost())
  348. {
  349. LOGWARNING("Getting texture data while device is lost");
  350. return false;
  351. }
  352. graphics_->SetTextureForUpdate(const_cast<Texture2D*>(this));
  353. if (!IsCompressed())
  354. glGetTexImage(target_, level, GetExternalFormat(format_), GetDataType(format_), dest);
  355. else
  356. glGetCompressedTexImage(target_, level, dest);
  357. graphics_->SetTexture(0, 0);
  358. return true;
  359. #else
  360. LOGERROR("Getting texture data not supported");
  361. return false;
  362. #endif
  363. }
  364. bool Texture2D::Create()
  365. {
  366. Release();
  367. if (!graphics_ || !width_ || !height_)
  368. return false;
  369. if (graphics_->IsDeviceLost())
  370. {
  371. LOGWARNING("Texture creation while device is lost");
  372. return true;
  373. }
  374. unsigned format = GetSRGB() ? GetSRGBFormat(format_) : format_;
  375. unsigned externalFormat = GetExternalFormat(format_);
  376. unsigned dataType = GetDataType(format_);
  377. // Create a renderbuffer instead of a texture if depth texture is not properly supported, or if this will be a packed
  378. // depth stencil texture
  379. #ifndef GL_ES_VERSION_2_0
  380. if (format == Graphics::GetDepthStencilFormat())
  381. #else
  382. if (format == GL_DEPTH_COMPONENT16 || format == GL_DEPTH_COMPONENT24_OES || format == GL_DEPTH24_STENCIL8_OES ||
  383. (format == GL_DEPTH_COMPONENT && !graphics_->GetShadowMapFormat()))
  384. #endif
  385. {
  386. if (renderSurface_)
  387. {
  388. renderSurface_->CreateRenderBuffer(width_, height_, format);
  389. return true;
  390. }
  391. else
  392. return false;
  393. }
  394. glGenTextures(1, &object_);
  395. // Ensure that our texture is bound to OpenGL texture unit 0
  396. graphics_->SetTextureForUpdate(this);
  397. // If not compressed, create the initial level 0 texture with null data
  398. bool success = true;
  399. if (!IsCompressed())
  400. {
  401. glGetError();
  402. glTexImage2D(target_, 0, format, width_, height_, 0, externalFormat, dataType, 0);
  403. if (glGetError())
  404. {
  405. LOGERROR("Failed to create texture");
  406. success = false;
  407. }
  408. }
  409. // Set mipmapping
  410. levels_ = requestedLevels_;
  411. if (!levels_)
  412. {
  413. unsigned maxSize = Max((int)width_, (int)height_);
  414. while (maxSize)
  415. {
  416. maxSize >>= 1;
  417. ++levels_;
  418. }
  419. }
  420. #ifndef GL_ES_VERSION_2_0
  421. glTexParameteri(target_, GL_TEXTURE_BASE_LEVEL, 0);
  422. glTexParameteri(target_, GL_TEXTURE_MAX_LEVEL, levels_ - 1);
  423. #endif
  424. // Set initial parameters, then unbind the texture
  425. UpdateParameters();
  426. graphics_->SetTexture(0, 0);
  427. return success;
  428. }
  429. void Texture2D::HandleRenderSurfaceUpdate(StringHash eventType, VariantMap& eventData)
  430. {
  431. if (renderSurface_ && renderSurface_->GetUpdateMode() == SURFACE_UPDATEALWAYS)
  432. renderSurface_->QueueUpdate();
  433. }
  434. }