OGLTexture3D.cpp 16 KB

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