OGLTexture2D.cpp 14 KB

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